text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Ever since I started using constructor dependency injection in my .NET/.NET Core projects, there has been essentially a three step process to adding a new dependency into a class. Create a private readonly field in my class, with an underscore prefix on the variable name Edit the constructor of my class to accept the same type, but name the parameter without a prefix Set the private readonly field to be the passed in parameter in the constructor In the end, we want something that looks like this : public class UserService { private readonly IUserRepository _userRepository; public UserService(IUserRepository userRepository) { _userRepository = userRepository; } } Well at least, this used to be the process. For a few years now, I’ve been using a nice little “power user” trick in Visual Studio to do the majority of this work for me. It looks a bit like this : The feature of auto creating variables passed into a constructor is actually turned on by default in Visual Studio, however the private readonly with an underscore naming convention is not (Which is slightly annoying because that convention is now in Microsoft’s own standards for C# code!). To add this, we need do the following in Visual Studio. The exact path to the setting is : Tools => Options => Text Editor => C# => Code Style => Naming That should land you on this screen : The first thing we need to do is click the “Manage naming styles” button, then click the little cross to add. We should fill it out like so : I would add that in our example, we are doing a camelCase field with an underscore prefix, but if you have your own naming conventions you use, you can also do it here. So if you don’t use the underscore prefix, or you use kebab casing (ew!) or snake casing (double ew!), you can actually set it up here too! Then on the naming screen, add a specification for Private or Internal, using your _fieldName style. Move this all the way to the top : And we are done! Now, simply add parameters to the constructor and move your mouse to the left of the code window to pop the Quick Actions option, and use the “Create and Assign Field” option. Again, you can actually do this for lots of other types of fields, properties, events etc. And you can customize all of the naming conventions to work how you like. I can’t tell you how many times I’ve been sharing my screen while writing code, and people have gone “What was that?! How did you do that?!”, and by the same token, how many times I’ve been watching someone else code and felt how tedious it is to slowly add variables one by one and wire them up! The post Auto Creating Private Readonly Fields In Visual Studio appeared first on .NET Core Tutorials.
https://online-code-generator.com/auto-creating-private-readonly-fields-in-visual-studio/
CC-MAIN-2021-43
refinedweb
479
65.66
Constructing your First PowerShell Provider Introduction I think it's safe to say that PowerShell will be a staple on the Microsoft platform for the foreseeable future. Version 2.0 is shipping standard with Windows 7 and Windows Server 2008 R2. Exchange leverages PowerShell, SQL Server 2008 leverages Powershell, and future server products will be leveraging PowerShell. If you're not building a product's administration features on top of PowerShell you soon will be. There is, however, a PowerShell learning curve. As a developer you need to master two major PowerShell concepts. The first is familiarity with the PowerShell environment. The second is learning how to build CmdLets and Providers, the components that plug into PowerShell. Much has already been written about building CmdLets. So, in this article, I'm going to demonstrate some basic Provider construction. Provider Overview A complete introduction to PowerShell and PowerShell Providers is beyond the scope of this article. So I'll focus on a few of the major PowerShell Provider concepts. First, I think of a Provider as a storage place for an application's data. A Provider plugs into PowerShell and through the standard or custom CmdLets navigates and modifies the application's data. Typically a Provider is represented by a path which looks similar to the one you would see from the Windows command line. Most of the Microsoft Server products have some type of Provider. Like CmdLets, Providers can emit .NET Objects. Because Providers and CmdLets are using the Common Language Runtime and the .NET Framework, objects from different providers can interact in new and interesting ways. PowerShell commands can be joined through a Pipeline, so the results of a particular command can feed the input to another command. When you consider the ecosystem of PowerShell providers already shipping with many Microsoft products and the extensibility provided by the .NET Framework; it shouldn't be hard to justify PowerShell support for your product. Sample Overview I developed the sample in Visual Studio 2008 and targeted PowerShell 1.0. Like any software application a Provider's complexity depends on the problem it solves and how the provider solves the problem. The first step to building a provider is to understand how CmdLets interacting with the Provider are translated into function calls in your code. This sample arose from a need to study the Cmdlet to Provider to code interaction. Aside from dishing up .NET objects, a Provider is responsible for validating the path information input by the user. The sample does some simple validation and emits Win32 debugging information you can view inside of the DebugView utility. Sources at the end of the article include DebugView information for downloading DebugView. The animation below shows the sample code in action. There are many styles of Providers. Styles are in a hierarchy of Provider functionality. The hierarchy appears below. Figure 1: PowerShell Sample in action - DriveCmdLetProvider - ItemCmdLetProvider - ContainerCmdLetProvider - NavigationCmdLetProvider The lowest level of functionality is a Drive Provider and the highest is a Navigation Provider. I chose a Navigation Provider so I could explore all possible functionality. Since each level of Provider must supply all the functionally of the Provider a level up, I partitioned the sample code into regions so you can browse all the functions related to a particular Provider in the hierarchy. Later in the article I'll refer to the regions. Before looking at Navigation Provider code, I want to explain how I utilized DebugView. Trace and DebugView .NET Trace and Debug statements are great for troubleshooting real-time software. Basically, they're useful anytime it's not feasible to step through an application with the Debugger. I built the following class to handle writing Trace statements targeted for DebugView. public class TraceTest { public TraceTest(string area, string application) { _application = application; _area = area; } public void WriteLine(string application, string area, string message) { if (TraceTest.Activated) { Trace.WriteLine(application + ":" + area + ":" + message); } } public void WriteLine(string area, string message) { this.WriteLine(_application, area, message); } public void WriteLine(string message) { this.WriteLine(_application, _area, message); } } Though PowerShell has its own Trace and Debug statements, I realized that I wouldn't always have the foresight to activate PowerShell verbose mode. I also realized that what I display in PowerShell may be different than what I want to display when I'm debugging. In addition, I thought it would be faster to do unit testing from a Console Application and hook my code into PowerShell once I had my code debugged. Therefore, I wouldn't always be running from within PowerShell. Finally, with DebugView filtering, I felt I had more selective control over what was displayed. With some background on PowerShell Providers and some of the tools I used to debug my Provider, I'm ready to explain how the sample provider works.
http://www.developer.com/net/article.php/3841976/Constructing-your-First-PowerShell-Provider.htm
CC-MAIN-2013-20
refinedweb
799
56.45
Snowplow Java Tracker 0.2.0 released We are pleased to announce the release of the Snowplow Java Tracker version 0.2.0. This release comes shortly after we introduced the community-contributed event tracker a little more than a week ago. In that previous post, we also mentioned our roadmap for the Java Tracker to include Android support as well as numerous other features. This release doesn’t directly act on that roadmap, but is largely a refactoring for future releases of the tracker with a few minor features. I’ll talk more about the new additions made further down in this post: - Tracker constructor - Renamed method calls - Jackson JSON Processor support - TransactionItem class - Constant & Parameter classes - Miscellaneous - Support 1. Tracker constructor One of the TrackerC constructors seemed unnecessary so we decided to remove it. The only way to construct a Tracker object now is with the following signature: public TrackerC(String collector_uri, String namespace, String app_id, boolean base64_encode, boolean contracts) 2. Renamed method calls We wanted the Java tracker to follow the more native naming convention of Java classes, so method names have been renamed from using underscores for word separators into the camel casing convention. Here are a few examples of renamed method calls: // Previous public void track_page_view(String page_url, String page_title, String referrer, String context) public void track_unstruct_event(String eventVendor, String eventName, String dictInfo, String context) // Now public void trackPageView(String page_url, String page_title, String referrer, String context) public void trackUnstructEvent(String eventVendor, String eventName, String dictInfo, String context) 3. Jackson JSON Processor support We are standardizing on Jackson for all JSON manipulation on the JVM, so it made sense to do so on the Java Tracker as well. Uses of JSONObject have been replaced with JsonNode with futher changes coming to newer releases. 4. TransactionItem class Previously, when calling trackEcommerceTransactionItem, you needed to pass in a List<Map<String, String>> that represented all transaction items. This was weakly typed, and we felt it would be better to provide a TransactionItem class that can be used to create individual items. With this change, you now pass a List<TransactionItem> to the tracker instead. 5. Constant & Parameter classes An early introduction of a Constant & Parameter class that would be used to store various string constants and keys from the Snowplow Tracker Protocol respectively. We wanted to keep a unified place to keep code clean and place for users to add their own keys for unstructured events. 6. Miscellaneous Some minor changes include initial unit tests, Travis build support, renamed classes, and general code clean up. For more details on this release, please check out the 0.2.0 Release Notes on GitHub. 7. Support The Snowplow Java Tracker is quite new and is rapidly being developed. We’d love to hear of any feature suggestions from you, or even help setting up the tracker. Feel free to get in touch with us, or raise an issue if you find any bugs.
https://snowplowanalytics.com/blog/2014/07/02/snowplow-java-tracker-0.2.0-released/
CC-MAIN-2019-18
refinedweb
494
50.46
Given JavaScript is loosely typed, it can be amazingly productive language for prototyping. The problems begin once your project grows in complexity. It is very easy to end up with a runtime error if you miss a simple check at the right place. Testing can help to control the situation, but it's not the only way. Typing systems, like tcomb by Giulio Canti, can help. Read on to learn more.. Two years ago I started to do open source, which I genuinely love, with a precise goal: bring type safety to JavaScript. tcomb is a library for checking the types of JavaScript values at runtime with a simple and concise syntax. It's great for Domain Driven Design and for adding safety to your internal code. It has solid mathematical foundations, being based on set theory. Type instances are not boxed, meaning tcomb works great with existing libraries (lodash, Ramda, ...). You can of course use them as props to React components and it works great paired with tcomb-react, an alternative to PropTypes. It's enforces immutability, using the native Object.freeze on type instances. Finally, it's performance friendly, since asserts and "freezes" are only present in development mode and stripped out in production builds. tcomb defines a set of basic types (e.g. t.String, t.Number, t.Boolean, ...) and a set of type combinators, i.e. functions that return a new type (e.g. t.list, t.maybe, t.interface, ...). The power of tcomb, comes from the composition of combinators: import t from 'tcomb'; // the maybe combinator returns a new type // that represents an optional value const MyOptString = t.maybe(t.String); // an optional string // the list combinator returns a new type // that represents a list of values const MyList = t.list(MyOptString); // a list of optional strings Using combinators like t.interface or utilities like t.assert, you can model your own domain and its invariants: import t from 'tcomb'; // a domain model const Person = t.interface({ name: t.String, surname: t.maybe(t.String), age: t.Number, tags: t.list(t.String) }, 'Person'); function getFullName(person) { // an invariant t.assert( Person.is(person), 'Invalid argument person supplied to getFullName' ); return `${this.name} ${this.surname}`; } When an assert fails, the default behavior throws a TypeError with a descriptive message, so you can leverage the power of the debugger, inspect the stack and find out what's wrong with little effort. For a start, tcomb is a mature project: it's five years old, battle tested and deployed in several production environments (it recently hit 70K/month downloads). It's also an extremely flexible tool and its strength comes from two unique features: refinements and runtime type introspection: A refinement type is a type endowed with a predicate which must hold for all instances of the refined type. Here's a simple example: import t from 'tcomb'; const Integer = t.refinement(t.Number, (n) => n % 1 === 0); const PositiveInteger = t.refinement(Integer, (n) => n >= 0); const Person = t.interface({ name: t.String, surname: t.maybe(t.String), age: PositiveInteger, // <= much better! tags: t.list(t.String) }, 'Person'); This means you can narrow your types defining precise invariants, something that static type checkers can do only partially. All models are inspectable at runtime. You can read and reuse the informations stored in your types. For example, you can build a validation library on top of tcomb with a few lines of code; or maybe a form generator library like tcomb-form. In my day to day work I make many mistakes. I mean many mistakes. I wanted a tool which would allow me to speed up the development phase, bringing in solid type safety, yet flexible enough to define my own types and progressively introduce them in the code base. I'm really excited about my last project, a babel plugin for combining static and runtime type checking using Flow and tcomb. It allows to define your tcomb types (refinements included!) as type annotations fully compatible with Flow. This means you can run them side by side, statically checking your code with Flow and catching the remaining mistakes with tcomb at runtime: the best of the two worlds! Here's the first example we've seen above, rewritten leveraging the plugin: type Person = { name: string, surname: ?string age: number tags: Array<string> }; function getFullName(person: Person): string { return `${this.name} ${this.surname}`; } Flow can typecheck this, but you can also turn it off and let tcomb check it at runtime. This simple example may not be particularly useful, but, once you start using type refinements, the mixed approach really starts to shine! Now that we have static type checkers for JavaScript like Flow or TypeScript one could think that tcomb will be irrelevant in the long run. Far from it, there are features that I want (namely refinements, IO validation and runtime type introspection) which are either too hard or impossible for a static type checker to provide. Static and runtime type checking are complementary and both useful. More in general, I'm pleased to see functional programming going mainstream in many communities, included the frontend one. I think smart type checkers and functional techniques are going to become common tools for a growing number of frontend developers. I'd like to read what Phil Freeman has to say about the future of PureScript. Thanks for the interview Giulio! I've definitely seen the light with types after getting familiar with languages like Haskell myself. Even though you can manage without a strong typing system, it can still be highly useful to document your types when you know them. Particularly the new babel plugin seems interesting to me and no doubt I'll be giving it a good go in the near future and integrate it to the material. Perhaps we will see something similar with types and JavaScript as we saw with CoffeeScript and JavaScript. The current standard integrated the best ideas from there and as a result we have a stronger language. I hope we see stronger options for typing in the language itself in the future. Projects like tcomb are important in that they allow us to experiment with these ideas.
https://survivejs.com/blog/tcomb-interview/
CC-MAIN-2020-40
refinedweb
1,037
65.22
Many. Why IoT Devices Aren't Always Secure Internet of things devices are low-cost, internet-connected pieces of hardware which often straddle the line between great idea and completely unnecessary. The trend of putting a Wi-Fi card in objects which are made only marginally more useful, if at all, by connecting them to the internet, means that many different manufacturers are baking in their own version of security into these devices. Many of these Wi-Fi-enabled products, like light bulbs, thermostats, and speakers, have become mainstream products, trickling down to reach even the least tech-savvy of users. Because of how widespread the adoption of IoT devices has been, the belief among IoT device manufacturers is that their gear must be, above all, easy to use, which means lax security. The majority of IoT devices use poorly secured APIs that assume that if you are on allowed on the same local Wi-Fi network as the device, you must have permission to be interacting with it. As a result, many IoT devices allow anyone on the local Wi-Fi network to control them with the right commands, without ever asking a user for a password or login of any kind. SoCo, SoCos & API Libraries for IoT Devices Some of the most popular types of IoT devices are Sonos connected speakers, which allow anyone on the local network to control them through a mobile or desktop application. Because of how widespread and easy-to-control Sonos speakers are, they make a perfect example to examine how we can influence them. Unlike mobile applications communicating with remote servers, running the Sonos app on your phone or desktop sends commands directly to the Sonos on your home network. Because these commands can be sent by anyone, not just the Sonos app, we can make application calls from a Python program if we know the API that the Sonos device uses. - Don't Miss: Python Scripting for the Aspiring Hacker Luckily for hackers, the API for many common IoT devices are well known and documented unofficially. The Sonos API has even been turned into a library for Python! The SoCo and SoCos libraries allow a Python programmer to discover and issue commands to Sonos devices on a local network, either via a command line interface or via a Python script written in an IDE. To show how this works, we'll analyze the way Sonos devices can be controlled o build a denial-of-service script to disable any Sonos system on the network. Designing Your Own Behaviors with Python Using the SoCo (Sonos Controller) library for Python, we can start to look at what kind of behaviors we would want to script in an IoT device. While we could change the song repeatedly to a classic anthem of intense sensual power like "Never Gonna Give You Up," this behavior would immediately tip off everyone nearby that someone was messing with the speaker. Instead, reviewing the available commands to us, it seems like a denial-of-service attack would be trivially easy to perform.. What You'll Need To get started, you'll need a Sonos device on your network that you have permission to connect to. While the point of this article is that simply being connected to the same network as the device gives you permission to mess with it, doing so could get you in trouble if the owner doesn't approve of what you're doing. Next, you'll need a Python IDE to write your code. IDEs are helpful because they let us work on our code in an optimized environment and give us a lot of feedback about what's happening with our code along the way. I recommend PyCharm, especially if you're a student, as they give free licenses of their professional product to students. Once you've set up PyCharm, make sure your computer has Python installed. The best way to do this is to go to a terminal window, type python3, and press return. If you get a command prompt, you have Python3, and you're ready to begin. If you don't, you may need to download Python3 before continuing from the official website. - Don't Miss: Building a Simple Hacking Tool in Python Step 1: Start a New Python Project Once you have PyCharm download, open the file, and follow the installation steps to set it up. If you already have it set up, just open the PyCharm application. The first time you open PyCharm, you should see a screen like this: Click "Create New Project," then name the project something memorable if you want. Click on "Create" to open a new project window. Within the new project window, we'll need to start a new Python file. Right-click on the project screen on the left side, then select the "New" drop-down menu. From that menu, select "Python File" to create a blank Python file. Name it something you'll remember. There we go! We should now have a Python file open and ready to run. To make sure your Python is working, you can go ahead and throw a simple script into it. Paste the following into the text editor, right-click in the Project area, then click "Run." for i in range (20): print("It works!") It should produce a result like the one below. If you see the script working, you're ready to move on to installing the SoCo library. Step 2: Install the SoCos Library There are two different ways of controlling a Sonos device on the network. The first we'll explore is SoCos, which is the command line version of SoCo. To install SoCos, go to a terminal window, and type the following. pip install socos This should install the command line version of Socos. To use it, go ahead and run socos in your terminal window. When in the socos tool, type help to see what's available. help Available commands: * list List available devices * partymode Put all the speakers in the same group, a.k.a Party Mode. * info Information about a speaker * play Start playing * pause Pause * stop Stop * next Play the next track * previous Play the previous track * mode Change or show the play mode of a device * current Show the current track * queue Show the current queue * remove Remove track from queue by index * volume Change or show the volume of a device * bass Change or show the bass value of a device * treble Change or show the treble value of a device * state Get the current state of a device / group * tracks Public convenience method for `_search_and_play` * albums Public convenience method for `_search_and_play` * artists Public convenience method for `_search_and_play` * playlists Public convenience method for `_search_and_play` * sonos_playlists Public convenience method for `_search_and_play` * exit Exit socos * set Set the current speaker for the shell session by ip or speaker * unset Resets the current speaker for the shell session * help Print a list of commands with short description Above, we can see that we have commands available for locating devices on the network, playing them, stopping them, and doing a variety of other useful things from the command line. If simply controlling your Sonos from the command line is what interests you, then you can stop here and play around with SoCos for a while before moving on. For our purposes, we'll move on to installing SoCo in PyCharm so that we can start scripting behaviors, rather than relying on a command prompt. Step 3: Install the SoCo Library In PyCharm, look at the bottom of the window to find the "Terminal" icon at the bottom. Click it, and it will open up a terminal prompt in the bottom of you PyCharm screen, allowing you to install libraries for PyCharm to use. Once this window is open, you can type pip install soco to install the SoCo library to PyCharm. You can type the same command in a system terminal window to install the library to your system overall. pip install soco Requirement already satisfied: soco in /Users/skickar/venv/lib/python3.6/site-packages Requirement already satisfied: xmltodict in /Users/skickar/venv/lib/python3.6/site-packages (from soco) Requirement already satisfied: requests in /Users/skickar/venv/lib/python3.6/site-packages (from soco) Requirement already satisfied: idna<2.8,>=2.5 in /Users/skickar/venv/lib/python3.6/site-packages (from soco) Requirement already satisfied: urllib3<1.24,>=1.21.1 in /Users/skickar/venv/lib/python3.6/site-packages (from soco) Requirement already satisfied: certifi>=2017.4.17 in /Users/skickar/venv/lib/python3.6/site-packages (from soco) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /Users/skickar/venv/lib/python3.6/site-packages (from soco) You are using pip version 9.0.1, however version 18.1 is available You should consider upgrading via the 'pip install --upgrade pip' command Once PyCharm confirms that SoCo is installed, we can get started writing our first script for the Sonos! Step 4: Locate a Device on the Network Now that we have SoCo set up in PyCharm, let's write the first part of our script. To learn about the way SoCo can interact with Sonos speakers, we can refer to the documentation page for the project. In the documentation, we see that there are a few commands for discovering Sonos devices on the network. The most useful one is to grab all Sonos devices using the soco.discover() function. The function will put the information needed to control the Sonos device into a variable called "devices." >>> import soco >>> devices = soco.discover() >>> devices set(SoCo("192.168.0.10"), SoCo("192.168.0.30"), SoCo("192.168.0.17")) >>> device = devices.pop() >>> device SoCo("192.168.0.16") Now that we can target any Sonos devices on the network, let's try an API call. Step 5: Try Out an API Call Next, we'll actually get the Sonos device to do something using our Python code. In PyCharm, let's make any Sonos devices we've detected do something. Referring to the documentation, there are a number of things we can do. The normal play, pause and stop functionality is provided with similarly named methods (play(), pause() and stop()) on the SoCo instance and the current state is included in the output of get_current_transport_info(): For our purposes, we'll be using the stop() function. By repeating this function directed at all Sonos devices we detect, we'll essentially be creating a denial-of-service attack. Step 6: Write a Python Script Now, to create our Python code, we'll need to import the SoCo library. Next, we'll need to detect any Sonos devices on the network and dump them into a variable called "device." import soco device = soco.discovery.any_soco() Next, we'll need to test to see if we got a result, and use a while loop to define what to do. We'll check to see if the variable "device" contains anything. If it does, we'll send the stop command. If it's empty, we'll say "No device found." while len(str(device)) != 0: print("Denial of Service Attack in progress on: ", device) device.stop() else: print("No device found.") This simple code should do everything we need, so the only thing we need to do next is test it out, and see if we can connect to and control a Sonos device. Below is the 7 lines together that you can easily copy and paste. import soco device = soco.discovery.any_soco() while len(str(device)) != 0: print("Denial of Service Attack in progress on: ", device) device.stop() else: print("No device found.") Step 7: Find Sonos Devices with Ports Open To discover a Sonos device outside of SoCos, we can run an Nmap scan with the following ports specified to search the network. Sonos devices will have ports 1400, 1420, and 1443 open, so to detect them, we'll scan for these. You'll need to find the IP address range for your network, which you can do by taking your IP address and typing it after the command ipcalc in a terminal window. ipcalc 172.16.42.61 Address: 172.16.42.61 10101100.00010000.00101010. 00111101 Netmask: 255.255.255.0 = 24 11111111.11111111.11111111. 00000000 Wildcard: 0.0.0.255 00000000.00000000.00000000. 11111111 => Network: 172.16.42.0/24 10101100.00010000.00101010. 00000000 HostMin: 172.16.42.1 10101100.00010000.00101010. 00000001 HostMax: 172.16.42.254 10101100.00010000.00101010. 11111110 Broadcast: 172.16.42.255 10101100.00010000.00101010. 11111111 Hosts/Net: 254 Class B, Private Internet Once you know your network range, you can run the following command to scan for Sonos devices on the same network. nmap -p 1400, 1420, 1443 172.16.42.0/24 If you see devices that say these ports are open, then you should be ready to continue to the next step. However, there might be a lot of devices with those open ports from different manufacturers, but you can whittle the results down to just Sonos devices using the grep command. Make sure Sonos is capitalized as that's how it will likely be listed on the scan. nmap -p 1400, 1420, 1443 172.16.42.0/24 | grep 'Sonos' MAC Address: 94:9F:3E:f$:04:3C (Sonos) MAC Address: 94:9F:3E:F5:96:0A (Sonos) Step 8: Assume Direct Control of the Device Back in PyCharm, it's time to try our Python script. Press the green play button in the top menu to run our Python script. If nothing happens, right-click the project window, select "Run," then the name of your project. Sometimes, PyCharm will try to run the wrong project, so make sure it's the right one. If the script succeeds, you should hear an immediate stop to any music playing and see an output like the one below stating the IP address of the Sonos device being affected. Other users will not be able to regain control of the device from the mobile or desktop app due to the intensity of the stop commands being sent to the device. Until you stop the loop, the device will continue to stop any playback, rendering the Sonos useless. This sort of attack can be modified to perform any creative action you could want, even doing things like changing the song when a specific device joins the network. Keeping Your IoT Devices Safe It's important to remember that IoT devices are increasingly designed for convenience, not security. This can be frustrating for anyone wanting to keep their devices safe, but there are a few ways you can still take device security into your own hands. Be careful who you give access to your Wi-Fi network. This gives them access to every device on your network, some of which may not have the best security set up. You should also never set up IoT devices on an open network. Instead, consider setting up a guest network which does not allow devices to connect with each other. Restricting guests to their own subnet on a Wi-Fi network prevents them from communicating with anything else on the network, eliminating the problem of guests on the Wi-Fi interacting with the Sonos. In general, you should be careful when connecting new devices to a network before you fully understand how they work. Because most IoT devices don't check too hard to see who is controlling them, they're frequently a target of malware and other types of abuse. You can do your part by making sure to connect IoT devices in a way that doesn't allow random outsiders to configure or access them. I hope you enjoyed this guide to controlling IoT devices with Python API calls! If you have any questions about this tutorial on IoT security or if you have a comment, feel free to ask it below or reach out to me on Twitter @KodyKinzie. 1 Comment Hmmm... interesting. I wonder if this method could be applied to lets say, Cisco IP Phones? ;) Share Your Thoughts
https://null-byte.wonderhowto.com/how-to/take-control-sonos-iot-devices-with-python-0191144/
CC-MAIN-2019-30
refinedweb
2,704
70.43
Using a Windows service in your .NET project part 1: foundations October 6, 2014 3 Comments Introduction As the title suggests we’ll discuss Windows services in this new series and how they can be used in your .NET project. We’ll take up the following topics: - What is a Windows service? - How can it be (un)installed using scripts? - What’s the use of a Windows Service? - How can it be taken advantage of in a .NET project? - Simplified layered architecture with OOP principles: we’ll see a lot of abstractions and dependency injection We’ll also build a small demo application with the following components: - A Windows service - A Console-based consumer with a simplified layered architecture - A MongoDb database If you’re not familiar with MongoDb, don’t worry. You can read about it on this blog starting here. Just make sure you read at least the first 2 posts so that you know how to install MongoDb as a Windows service on your PC. Otherwise we won’t see much MongoDb related code in the demo project. A warning: it’s not possible to create Windows services in the Express edition of Visual Studio. I’ll be building the project in VS 2013 Professional. Windows services Windows services are executable assemblies that run in the background without the user’s ability to interact with them directly. They are often used for long running or periodically recurring activities such as polling, monitoring, listening to network connections and the like. Windows services have no user interface and have their own user session. It’s possible to start a Windows service without the user logging on to the computer. An average Windows PC has a large number of pre-installed Windows services, like: - ASP.NET State Service - Windows Event Log - Windows Firewall …and many more. You can view the services by opening the Services window: We’ll go through the different categories like “Name” and “Status” when we create the Windows service project. There are some special considerations about Windows services: - A Windows service project cannot be started directly in Visual Studio and step through its code with F11 - Instead the service must be installed and started in order to see it in action - An installer must be attached to the Windows service so that it can registered with the Windows registry - Windows services cannot communicate directly with the logged-on user. E.g. it cannot write to a Console that the user can read. Instead it must write messages to another source: a log file, the Windows event log, a web service, email etc. - A Windows service runs under a user context different from that of the logged-on user. It’s possible to give a different role to the Windows service than the role of the user. Normally you’ll run the service with roles limited to the tasks of the service Demo project description In the demo project we’ll simulate a service that analyses web sites for us: makes a HTTP call, takes note of the response time and also registers the contents of the web site. This operation could take a long time especially of the user is allowed to enter a range of URIs that should be carried out in succession. Think of a recorded session in Selenium where each step is carried out sequentially, like… - Go to login page - Reserve a product - Pay It is not too wise to make these URL calls directly from a web page and present the results at the end. The HTTP communication may take far too much time to get the final status and the end user won’t see any intermediate results, such as “initialising”, “starting step 1”, “step 2 complete” etc. Websites are simply not designed to carry out long-running processes and wait for the response. Instead it’s better to just create a “job” in some data storage that a continuous process, like a Windows service, is monitoring. This service can then carry out the job and update the data storage with information. The web site receives a correlation ID for the job which it can use to query the data store periodically. The most basic solution for the web page is to have a timer which automatically refreshes the window and runs the code that retrieves the latest status of the job using the correlation ID. An alternative here is web sockets. You could even hide the data store and the Windows service setup behind a web service so that the web site only communicates with this web service using the correlation ID. To keep this series short and concise I’ll skip the web page. I’m not exactly a client-side wizard and it would only create unnecessary noise to build a web side with all the elements to enter the URLs and show the job updates. Instead, we’ll replace it with a Console based consumer. At the end we’ll have a console app where you can enter a series of URLs which are then entered in the MongoDb data store as a job. The Console will receive a job correlation ID. The Windows Service will monitor this data store and act upon every new job. It will call the URLs in succession and take note of the response time and string content of each URL. It will also update the status message of the job. The console will in turn monitor the job status and print the messages so that the user can track the status. We’ll also put in place a simple file-based logging system to see what the Windows service is actually doing. Start: infrastructure Open Visual Studio 2012/2013 Pro and create a blank solution called WindowsServiceDemo. Make sure to select .NET4.5 as the framework for all layers we create within this solution. We’ll start from the very end of the project and create an abstraction for the planned HTTP calls. We’ve discussed a lot on this blog why it’s important to factor out dependencies such as file system operations, emailing, service calls etc. If you’re not sure why this is a good idea then go through the series on SOLID starting here, where especially Dependency Injection is most relevant. We’ve also gone through a range of examples of cross cutting concerns in this series where we factored out the common concerns into an Infrastructure project. We’ll do it here as well and describe the HTTP communication service in an interface first. Insert a new C# class library called Demo.Infrastructure into the blank solution. Add a folder called HttpCommunication to it. Making a HTTP call can require a large amount of inputs: the URI, the HTTP verb, a HTTP body, the headers etc. Instead of creating a long range of overloaded methods we’ll gather them in an object which will be used as the single input parameter. Let’s keep this simple and insert the following interface into the folder: public interface IHttpService { Task<MakeHttpCallResponse> MakeHttpCallAsync(MakeHttpCallRequest request); } The HTTP calls will be carried out asynchronously. If you’re not familiar with asynchronous method calls in .NET4.5 then start here. MakeHttpCallResponse and MakeHttpCallRequest have the following form: public class MakeHttpCallResponse { public int HttpResponseCode { get; set; } public string HttpResponse { get; set; } public bool Success { get; set; } public string ExceptionMessage { get; set; } } - HttpResponseCode: the HTTP response code from the server, such as 200, 302, 400 etc. - HttpResponse: the string contents of the URL - Success: whether the HTTP call was successful - ExceptionMessage: any exception message in case Success was false public class MakeHttpCallRequest { public Uri Uri { get; set; } public HttpMethodType HttpMethod { get; set; } public string PostPutPayload { get; set; } } - Uri: the URI to be called - HttpMethodType: the HTTP verb - PostPutPayload: the string HTTP body for POST and PUT operations HttpMethodType is an enumeration which you can also insert into HttpCommunication: public enum HttpMethodType { Get , Post , Put , Delete , Head , Options , Trace } That should be straightforward. Both MakeHttpCallRequest and MakeHttpCallResponse are admittedly oversimplified in their current forms but they suffice for the demo. For the implementation we’ll use the HttpClient class in the System.Net library. Add the following .NET libraries to the Infrastructure layer: - System.Net version 4.0.0.0 - System.Net.Http version 4.0.0.0 Insert a class called HttpClientService to the HttpCommunication folder, which will implement IHttpService as follows: public class HttpClientService : IHttpService { public async Task<MakeHttpCallResponse> MakeHttpCallAsync(MakeHttpCallRequest request) { MakeHttpCallResponse response = new MakeHttpCallResponse(); using (HttpClient httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.ExpectContinue = false; HttpRequestMessage requestMessage = new HttpRequestMessage(Translate(request.HttpMethod), request.Uri); if (!string.IsNullOrEmpty(request.PostPutPayload)) { requestMessage.Content = new StringContent(request.PostPutPayload); } try { HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage, HttpCompletionOption.ResponseContentRead, CancellationToken.None); HttpStatusCode statusCode = responseMessage.StatusCode; response.HttpResponseCode = (int)statusCode; response.HttpResponse = await responseMessage.Content.ReadAsStringAsync(); response.Success = true; } catch (Exception ex) { Exception inner = ex.InnerException; if (inner != null) { response.ExceptionMessage = inner.Message; } else { response.ExceptionMessage = ex.Message; } } } return response; } public HttpMethod Translate(HttpMethodType httpMethodType) { switch (httpMethodType) { case HttpMethodType.Delete: return HttpMethod.Delete; case HttpMethodType.Get: return HttpMethod.Get; case HttpMethodType.Head: return HttpMethod.Head; case HttpMethodType.Options: return HttpMethod.Options; case HttpMethodType.Post: return HttpMethod.Post; case HttpMethodType.Put: return HttpMethod.Put; case HttpMethodType.Trace: return HttpMethod.Trace; } return HttpMethod.Get; } } So we simply call the URI using the HttpClient and HttpRequestMessage objects. We get the HttpResponseMessage by awaiting the asynchronous SendAsync method of HttpClient. We save the Http status code as an integer and the string content of the URI in the MakeHttpCallResponse object. We also store any exception message in this response object to indicate that the HTTP call failed. In the next part of the series we’ll build the domain and repository layer. View the list of posts on Architecture and Patterns here.
https://dotnetcodr.com/category/windows-service/page/2/
CC-MAIN-2020-24
refinedweb
1,640
55.95
You've probably heard the buzz about DB2's V9 -- IBM's first database management system to support both tabular (SQL-based) and hierarchical (XML-based) data structures. Previous articles in the series have summarized DB2's new XML features, described how to create database objects and populate them with XML data, and explained how to work with XML data using SQL and SQL/XML. This article continues to explore DB2 XML capabilities by focusing on its new support for XQuery. DB2 treats XQuery as a first-class language, allowing users to write XQuery expressions directly rather than requiring that users embed or wrap XQueries in SQL statements. Furthermore, DB2's query engine processes XQueries natively, meaning that it parses, evaluates, and optimizes XQueries without ever translating them into SQL behind the scenes. Of course, if you choose to write bilingual queries that include both XQuery and SQL expressions, DB2 will process and optimize these queries, too. As with SQL/XML in Part 3 of the series, this article explores several common query tasks and looks at how you can use XQuery to accomplish your goals. First, briefly consider how XQuery differs from SQL. About XQuery XQuery differs from SQL in a number of key respects, largely because the languages were designed to work with different data models that have different characteristics. XML documents contain hierarchies and possess an inherent order. Tabular data structures supported by SQL-based DBMSs are flat and set based. As such, rows are unordered. The differences between these data models yield a number of fundamental differences in their respective query languages, including: -, while SQL returns result sets of various SQL data types. This is a subset of the fundamental differences between XQuery and SQL. It is beyond the scope of this introductory article to provide an exhaustive list, but an IBM Systems Journal article discusses language differences in more detail. This article focuses on some basic aspects of the XQuery language and how you can use it to query XML data in DB2 V9. Sample database The queries in this article access the sample tables created in Part 1 of this series. For a quick review, Listing 1 defines the sample items and clients tables.> Query environment All the queries in this article are designed to be issued interactively. You can do this through the DB2 command line processor or the DB2 Command Editor of the DB2 Control Center. The screen images and instructions in this article focus on the latter. (IBM Data Studio and IBM Optim Development Studio ship with an Eclipse-based Developer Workbench that can help programmers graphically construct queries as well. This article does not discuss application development issues or the Development Studio.) To use the DB2 Command Editor, launch the Control Center, and select Tools > Command Editor. A window similar to Figure 1 appears. Figure 1. The DB2 Command Editor, which can be launched from the DB2 Control Center Type your queries in the upper pane, click on the green arrow in the upper left corner to run them, and view your output in the lower pane or in the separate Query Results tab. XQuery examples Just as in Part 3 of the series, this article steps through several common business scenarios and shows how to use XQuery to satisfy requests for XML data. It also explores more complex situations that involve embedding SQL within XQuery. XQuery provides several different kinds of expressions that can be combined in any way you like. Each expression returns a list of values that can be used as input to other expressions. The result of the outermost expression is the result of the query. This article focuses on two important kinds of XQuery expressions: FLWOR expressions and path expressions. A FLWOR expression is much like a SELECT-FROM-WHERE expression in SQL: it is used to iterate through a list of items and to optionally return something that is computed from each item. A path expression, on the other hand, navigates through a hierarchy of XML elements and returns the elements that are found at the end of the path. Like a SELECT-FROM-WHERE expression in SQL, an XQuery FLWOR expression can contain several clauses that begin with certain keywords. The following keywords are used to begin clauses in a FLWOR expression: for: Iterates through an input sequence, binding a variable to each input item in turn let: Declares a variable and assigns it a value, which can be a list containing multiple items where: Specifies criteria for filtering query results order by: Specifies the sort order of the result return: Defines the result to be returned A path expression in XQuery consists of a series of steps, separated by slash characters. In its simplest form, each step navigates downward in an XML hierarchy to find the children of the elements returned by the previous step. Each step in a path expression can also contain a predicate that filters the elements that are returned by that step, retaining only elements that satisfy some condition. For example, assuming that the variable $clients is bound to a list of XML documents containing <Client> elements, the four-step path expression $clients/Client/Address[state = "CA"]/zip will return the list of zip codes for clients whose addresses are in California. In many cases, it is possible to write a query by using either a FLWOR expression or a path expression. Using DB2 XQuery as a top-level query language To execute an XQuery directly in DB2 V9 (as opposed to embedding it in an SQL statement), you must preface the query with the keyword xquery. This instructs DB2 to invoke its XQuery parser to process your request. Note that you only need to do this if you are using XQuery as the outermost (or top level) language. If you embed XQuery expressions in SQL, you don't need to preface them with the xquery keyword. However, this article uses XQuery as the primary language, so all the queries are prefaced with xquery. When running as a top-level language, XQuery needs to have a source of input data. One way in which an XQuery can obtain input data is to call a function named db2-fn:xmlcolumn with a parameter that identifies the table name and column name of an XML column in a DB2 table. The db2-fn:xmlcolumn function returns the sequence of XML documents that is stored in the given column. For example, the following query in Listing 4 returns a sequence of XML documents containing customer contact information. Listing 4. Simple XQuery to return customer contact data xquery db2-fn:xmlcolumn('CLIENTS.CONTACTINFO') As you might recall from our database schema (see "Sample database" section), XML documents are stored in the Contactinfo column of the Clients table. Note that the column and table names are specified in uppercase here. This is because table and column names are typically folded into uppercase before being written to DB2's internal catalog. Because XQuery is case-sensitive, lowercase table and column names would fail to match upper-case names in the DB2 catalog. Retrieving specific XML elements Now, explore a basic task. Suppose you want to retrieve the fax numbers of all clients who have provided you with this information. Listing 5 shows one way you can write this query. Listing 5. Listing 6. Listing 6. Sample output for previous query As an aside, the output will also contain some information that's not of great interest in this article: XML version and encoding data, such as <?xml version="1.0" encoding="windows-1252" ?>, and XML namespace information, such as To make the output easier for you to follow, that information is omitted from this article. However, it can be important for a number of XML applications. If you use the DB2 command line processor to run your queries, you can use the -d option to suppress the XML declaration information and the -i option to print the results in an attractive manner. The query shown in Listing 5 could be expressed somewhat more concisely as a three-step path expression, as shown in Listing 7. Listing 7. Path expression to retrieve client fax data xquery db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/fax The first step of the path expression calls the db2-fn:xmlcolumn function to obtain a list of XML documents from the CONTACTINFO column of the CLIENTS table. The second step returns all the Client elements in these documents, and the third step returns the fax elements nested inside these Client elements. If you're not interested in obtaining XML fragments from your query but instead want just a text representation of qualifying XML element values, you can invoke the text() function in your return clause, as shown in Listing 8. Listing 8. Two queries to retrieve text representation of client fax data xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/fax return $y/text() (or) xquery db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/fax/text() The output of these queries will be similar to that shown in Listing 9. Listing 9. Sample output from previous queries 4081112222 5559998888 The results of the sample queries are relatively simple because the fax element is based on a primitive data type. Of course, elements can be based on complex types, which means they might contain sub-elements (or nested hierarchies). The Address element of our client contact information is one example of this. According to the schema defined in Part 2 of this series, it can contain a street address, apartment number, city, state, and zip code. Consider what the XQuery in Listing 10 would return. Listing 10. FLWOR expression to retrieve complex XML type xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/Address return $y If you guessed a sequence of XML fragments containing Address elements and all their sub-elements, you're right. Listing 11 shows an example: Listing 11. Sample> Note: This sample output is formatted to make it easier for you to read. The DB2 Command Editor displays each customer address record on one line. Filtering on XML element values You can refine the previous XQuery examples to be more selective. For example, consider how to return the mailing addresses of all customers who live in U.S. zip code 95116. As you might imagine, the XQuery where clause enables you to filter results based on the value of the zip element in your XML documents. Listing 12 shows how to add a where clause to the previous FLWOR expression in Listing 10 to obtain only the addresses that interest you. Listing 12. FLWOR expression with a new "where" clause xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/Address where $y/zip="95116" return $y The added where clause is pretty easy to understand.. The same result could be obtained by adding a predicate to the path expression, as shown in Listing 13. Listing 13. Path expression with additional filtering predicate xquery db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/Address[zip="95116"] Of course, you can filter on zip code values and return elements unrelated to street addresses. Furthermore, you can also filter on multiple XML element values in a single query. The query in Listing 14 returns e-mail information for customers who live in a specific zip code in New York City (10011) or anywhere in the city of San Jose. Listing 14. Filtering on multiple XML element values with a FLWOR expression xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client where $y/Address/zip="10011" or $y/Address/city="San Jose" return $y/email Note that the for clause is changed so that it binds variable $y to Client elements rather than to Address elements. This enables you can be expressed somewhat more concisely as a path expression, as shown in Listing 15. Listing 15. Filtering on multiple XML element values with a path expression xquery db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client[Address/zip="10011" or Address/city="San Jose"]/email; What's not as obvious from reviewing either form of this query is that the returned results will differ in two significant ways from what a SQL programmer might expect: - You won't get XML data returned for qualifying customers who didn't give you their e-mail addresses. In other words, if you have 1000 customers who live in San Jose or zip code 10011, and 700 customers each gave you one e-mail address, you'd get a list of these 700 e-mail addresses returned. This is due to a fundamental difference between XQuery and SQL mentioned earlier: XQuery doesn't use nulls. - You won't know which e-mail addresses were derived from the same XML document. In other words, if you have 700 customers who live in San Jose or zip code 10011, and each gave you two e-mail addresses, you'd get a list of 1400 email elements returned. You would not get a sequence 700 records, each consisting of two e-mail addresses. Both situations can be desirable under some circumstances and undesirable under others. For example, if you need to e-mail a notice to every qualifying account you have on record, then iterating through a list of customer e-mail addresses in XML format is easy to do in an application. However, if you want to e-mail only one notice to every customer, including those who only provided you with their street addresses, then the XQuery previously shown won't be sufficient. There are multiple ways you can rewrite this query so that the returned results represent missing information in some fashion and indicate when multiple e-mail addresses were derived from the same customer record, that is, the same XML document (more on this later). However, if all you want to do is retrieve a list containing one e-mail address per qualifying customer, you could modify the return clause of the previous query slightly. Listing 16. Retrieving only the first email element per customer xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client where $y/Address/zip="10011" or $y/Address/city="San Jose" return $y/email[1] This query causes DB2 to return the first e-mail element it finds within each qualifying XML document (customer contact record). If it doesn't find an e-mail address for a qualifying customer, it won't return anything for that customer. Transforming XML output A powerful aspect of XQuery is its ability to transform XML output from one form of XML into another. For example, you can use XQuery to retrieve all or part of your stored XML documents and convert the output into HTML for easy display in a Web browser. The query in Listing 17 retrieves the addresses of the clients, sorts the results by zip code, and converts the output into XML elements that are part of an unordered HTML list. Listing 17. Querying DB2 XML data and returning results as HTML xquery <ul> { for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client/Address order by $y/zip return <li>{$y}</li> } </ul> The query can be dissected this way: - The query begins simply enough with the xquerykeyword a new order byclause, specifying that results must be returned in ascending order (the default order) based on customer zip codes (the zip sub-element of each address bound to $y). - The returnclause indicates that the Address elements are to be surrounded by HTML list item tags before return. - The final line concludes the query and completes the HTML unordered list tag. The output appears similar to that in Listing 18. Listing 18. Sample> Now consider a topic raised earlier: how to write an XQuery that will indicate missing values in the returned results as well as indicate when a single XML document (such as a single customer record) contains repeating elements (such as multiple email addresses). One way to do so involves wrapping the returned output in a new XML element, as shown in the query in Listing 19: Listing 19. Indicating missing values and repeating elements in an XQuery result xquery for $y in db2-fn:xmlcolumn('CLIENTS.CONTACTINFO')/Client where $y/Address[zip="10011"] or $y/Address[city="San Jose"] return <emailList> {$y/email} </emailList> Running this query causes a sequence of emailList elements to be returned, one per qualifying customer record. Each emailList element contains e-mail data. If DB2 finds a single e-mail address in a customer's record, it returns that element and its value. If it finds multiple e-mail addresses, it returns all e-mail elements and their values. Finally, if it finds no e-mail address, it will return an empty emailList element. Thus, the output might appear as shown in Listing 20. Listing 20. Sample output of previous query <emailList> <email>love2shop@yahoo.com</email> </emailList> <emailList/> <emailList> <email>beatlesfan36@hotmail.com</email> <email>lennonfan36@hotmail.com</email> </emailList> . . . Using conditional logic XQuery's ability to transform XML output can be combined with its built-in support for conditional logic to reduce the complexity of application code. Consider a simple example. The Items table includes an XML column containing comments customers have made about products. For customers who have requested a response to their comments, you might want to create new Action elements containing the product ID, customer ID, and message so you can route this information to the appropriate person for handling. However, comments that don't require a response are still important to the business, and you don't want to just ignore them. Instead, create an Info element with just the product ID and message. Here's how you can use an XQuery if-then-else expression to accomplish this task: Listing 21. Using an "if-then-else" expression in an XQuery xquery for $y in db2-fn:xmlcolumn('ITEMS.COMMENTS')/Comments/Comment return ( if ($y/ResponseRequested = 'Yes') then <action> {$y/ProductID, $y/CustomerID, $y/Message} </action> else ( <info> {$y/ProductID, $y/Message} </info> ) ) Most aspects of this query should be familiar to you by now, so concentrate on the conditional logic. The if clause determines whether the value of the ResponseRequested sub-element for a given comment is equal to Yes. If so, the then clause is evaluated, causing DB2 to return a new element (action) that contains three sub-elements: ProductID, CustomerID, and Message. Otherwise, the else clause is evaluated, and DB2 returns an Info element containing only product ID and message data. Using the let clause You have now seen how to use all the parts of a FLWOR expression except for the let clause. This clause is used to assign a value (possibly containing a list of several items) to a variable that can be used in other clauses of the FLWOR expression. Suppose you want to make a list of how many comments were received for each product. This can be done with the query in Listing 22. Listing 22. Using the "let" clause xquery for $p in distinct-values (db2-fn:xmlcolumn('ITEMS.COMMENTS')/Comments/Comment/ProductID) let $pc := db2-fn:xmlcolumn('ITEMS.COMMENTS') /Comments/Comment[ProductID = $p] return <product> <id> { $p } </id> <comments> { count($pc) } </comments> </product> The distinct-values function in the for clause returns a list of all the distinct values of ProductID that are found inside comments in the Comments column of the Items table. The for clause binds variable $p to each of these ProductID values in turn. For each value of $p, the let clause scans the Items column again and binds the variable $pc to a list containing all the comments whose ProductID matches the ProductID in $p. The return clause constructs a new product element for each distinct ProductID value. Each of these product elements contains two sub-elements: an id element containing the ProductID value and a comments element containing a count of how many The result of this example query might look something similar to Listing 23. Listing 23. Sample output for the previous query <product> <id>3926</id> <comments>28</comments> </product> <product> <id>4097</id> <comments>13</comments> </product> XQueries with embedded SQL By now, you've seen how to write XQueries that retrieve XML document fragments, create new forms of XML output, and return different output based on conditions specified in queries themselves. In short, you've learned a few ways to use XQuery to query XML data stored in DB2. To be sure, there's more to learn about XQuery than this brief article covers. But there is one more broad topic not covered yet: how to embed SQL within XQuery. Doing so can be useful if you need to write queries that filter data based on XML and non-XML column values. You might recall from Part 3 of this series how to embed simple XQuery expressions within an SQL statement to accomplish this task. Here, look at how to do the opposite: embed SQL within XQuery to restrict results based on both traditional SQL data values and specific XML element values. In place of the db2-fn:xmlcolumn function, which returns all the XML data in a column of a table, you can call the db2-fn:sqlquery function, which executes an SQL query and returns only the selected data. The SQL query passed to db2-fn:sqlquery must return XML data. This XML data can then be further processed by XQuery. The query in Listing 24 retrieves information about comments involving products with a suggested retail price (srp) of more than $100 USD that include a customer request for a response. Recall that pricing data is stored in an SQL decimal column, while customer comments are stored as XML. The returned data, including the product ID, customer ID, and customer message, are included in a single XML action element for each qualifying comment stored in the database. Listing 24. Embedding SQL within an XQuery xquery for $y in db2-fn:sqlquery('select comments from items where srp > 100')/Comments/Comment where $y/ResponseRequested="Yes" return ( <action> {$y/ProductID, $y/CustomerID, $y/Message} </action> ) Most of this query should look familiar to you by now, so take a look at the new function: db2-fn:sqlquery. DB2 processes the SQL SELECT statement supplied to this function to determine which rows contain information about items priced at more than $100 USD. The documents stored in these rows serve as inputs to a path expression that returns all the nested Comment elements. Subsequent portions of the query use the XQuery where clause to filter returned data further and to transform portions of the selected comments into new XML fragments. With this in mind, consider how you might solve a slightly different problem. Imagine that you want a list of all e-mail addresses for Gold clients who live in San Jose. Furthermore, if you have multiple e-mail addresses for a single client, you want all of them to be included in the output as part of a single client record. Finally, if a qualifying Gold client didn't give you an e-mail address, you want to retrieve his or her mailing address. Listing 25 shows one way to write such a query: Listing 25. ) Two aspects of this query deserve some explanation. First, the SELECT statement embedded in the second line contains a query predicate based on the Status column, comparing the value of this VARCHAR column to the string Gold. In SQL, such strings are surrounded by single quotes. Note that although the example might appear to use double quotes, it actually uses two single quotes before and after the comparison value (''Gold''). The extra single quotes are escape characters. If you use double quotes around your string-based query predicate, instead of pairs of single quotes, you'll get a syntax error. In addition, the return clause in this query contains conditional logic to determine if an e-mail element is present in a given customer's record. If so, the query returns a new emailList element containing all the customer's e-mail addresses (that is, all the e-mail elements for that customer). If not, it returns the customer's mailing address (that is, the Address element for that customer). Indexing It's worth noting that you can create specialized XML indexes to speed access to data stored in XML columns. Because this is an introductory article and the sample data is small, the topic is not covered here. However, in production environments, defining appropriate indexes can be critical to achieving optimal performance. See Resources for more info about DB2's indexing technology. Summary XQuery differs from SQL in significant ways, several of which are highlighted in this article. Learning more about the language helps you determine when it can be most beneficial to your work, as well as help you understand when it can be useful to combine XQuery with SQL. Other articles in this series describe how to develop Java applications that exploit DB2 XML capabilities. For now though, this article includes a simple Java example, which depicts how a Java application might embed an XQuery. Acknowledgments Thanks to George Lapis, Matthias Nicola, and Gary Robinson for reviewing this article. Resources Learn - IBM DB2 e-kit for Database Professionals: Grow your skills, and quickly and easily become certified for DB2 for Linux, UNIX, and Windows. - DB2 pureXML Web site: Learn more about DB2's XML support. - "Get off to a fast start with DB2 V9 pureXML, Part 1" (developerWorks, February 2006, updated March 2010): Get an overview of the new XML technologies now in beta in DB2. - "Get off to a start start with DB2 V9, Part 2" (developerWorks, March 2006, updated March 2010): Learn how to insert, import, and validate XML data. - "Get off to a start start with DB2 V9, Part 3: Query XML Data in DB2 with SQL" (developerWorks, March 2006, updated March 2010): Learn how to query DB2 XML data using SQL and SQL/XML. - XQuery from the Experts, (Howard Katz, et. al., Addison-Wesley, 2003): Learn about the XQuery language. A book excerpt is available online. - "Firing up the Hybrid Engine" (DB2. - developerWorks Information Management zone: Find more resources for DB2 UDB developers and administrators. - Stay current with developerWorks technical events and webcasts..
http://www.ibm.com/developerworks/data/library/techarticle/dm-0604saracco/?S_TACT=105AGY75
CC-MAIN-2014-52
refinedweb
4,394
59.23
Good afternoon Akron. Again thank you all for attending the event in Akron. I am glad you enjoyed the event as much as I did, I look forward to the next time I am in town. There were a lot of great question so without any further delay here are the Questions and Answers from the event. As always feel free to comment if I missed any question or if you need additional information, enjoy! Q: What are the requirements for DFS in Windows 2003 R2?A: This is a great question I got this week, the main question is: Can Non Windows 2003 R2 systems participate in the new DFS replication model. The answer is a definitive and official yes. Here are some additional requirements:DFS Replication requirements Before DFS Replication can be deployed, administrators must configure servers and storage as follows: · The Active Directory schema must be updated to include the new DFS Replication objects. · Anti-virus software must be compatible with DFS Replication; contact your anti-virus software vendor to check for compatibility. · Servers in a replication group must be in the same forest. You cannot enable replication across servers in different forests. · Replicated folders must be stored on NTFS volumes. · On server clusters, replicated folders should be located in the local storage of a node because the Distributed File System Replication service is not cluster aware and the service will not fail over to another node. Important-exist on the same member server or domain controller. DFS Namespaces requirements To enable all features in DFS Namespaces, you must configure lab servers and clients as follows: · Servers where namespace management tasks are performed must run Windows Server 2003 SP1 and Windows Server 2003 R2. · To take advantage of new namespace features, all servers that host namespaces must run Windows Server 2003 SP1. · To take advantage of new namespace features, all domain controllers must run Windows Server 2003 with SP1. · Namespaces must be created on NTFS volumes. · Clients that access namespaces can run any of the supported client operating systems, but only clients running the following operating systems, service packs, and the appropriate client fail-back hotfix can be configured for client fail back: · Windows® XP with Service Pack 2 and the Windows XP Client Failback hotfix. · Windows Server 2003 SP1 and the Windows Server 2003 Client Failback hotfix. (This hotfix does not yet have a release date.) For a great overview document on more information on DFS take a look at the overview document on the DVD from the event or take a look at this link: Q: Can you set the default printer with a Microsoft Group Policy (GPO)A: There is no default set Group Policy to accomplish this however, there are a couple of ways to set this. One way is to create a script with the following commands to set the printer, there is some good information here: The other way to accomplish is to modify the registry of the system you are working with. Take a look here for the registry locations: The great thing about knowing the registry entry is that you can create a custom policy .ADM file to actually accomplish this via group policy. Take a look here on how to create custom .adm files: Q: Is there a remote administration package for Windows XP for Windows 2003 R2?A: There is still the ability to load the adminpak.msi file on the Windows XP desktop, however I do know for some of the specific like the print management console, it will only work on Windows 2003 R2 servers. On a side note the great thing about the new print management console is that you can use Print Management to monitor printers that are on print servers running Microsoft Windows XP, Microsoft® Windows® 2000 Server, Windows Server 2003, and Windows Server 2003 R2 operating systems. Q: Can you view Access Based Enumeration with DFS and shares?A: This is a question based on some of the tools that other operating systems had. Inside Microsoft Windows Technologies, this is look at the, discretionary access control lists DACLS of the files themselves, the only way I have ever processed this information was with some scripts. Please take a look here: This site will show you how to look at this at the file and folder level. Q: How do you upgrade to Windows 2003 R2?A: This is a great question and there is a ton of information on the main web site here: With a Windows Server 2003 R2 license, you can upgrade to Windows Server 2003 R2 if your computer is running one of the following operating systems: Windows Server 2003 with SP1 Windows Server 2003 without SP1 Windows 2000 Server Windows NT Server 4.0 with Service Pack 5 or later Windows NT Server 4.0, Terminal Server Edition, with Service Pack 5 or later The process is fairly straight forward for all the OS’s listed. For more detail take a look here: Q: Can you put a pure Print Server in the new Print Management Console (PMC) in Windows 2003 R2?A: This question is in relation to the all in one types of printers, where they are their own server as well as printer. Yes you can, just when you add in the server just put in the IP address of the print server. Although I have not tried this, all the docs indicate that you can. So if someone has tried this please comment and I will update the post, my only concern is how the print management will handle the driver for the printer. Q: What are the requirements for the Windows 2003 R2 file screening technology?A: This is a great new technology in Windows 2003 R2. It does require the File Server Resource Manager (FSRM). There is some great information for FSRM here: File screening allows you to do the following:. Q: How do you configure Windows Mobile 5 devices for the direct push technology?A: I had some great feedback during the session on this particular topic. I know there was some rumors that we were holding the mobility features due to recent lawsuits. I am happy to report that this is not TRUE! I checked with some friends in the product group as well as my good friend Harold Wong. Right now accomplishing a lot of the fantastic things I showed are not quite possible yet. A lot of the device manufactures are in the process of getting the mobile 5 security update tested. The new mobility features require quite a bit of work on the devices and the servers to work. Harold Wong. actually put a FANTASTIC post together on this very topic, please check out his post:. Hopefully this will clear up some confusion. However, there is a device out right now that does have the MSFP bits already incorporated. This device is the Gigabyte g-Smart:. It's a pretty cool device!!!
http://blogs.technet.com/b/matthewms/archive/2006/02/09/419173.aspx
CC-MAIN-2014-41
refinedweb
1,166
69.31
#include <Server.hpp> A server. The Server is an abstract class providing methods for opening a server and accepting clients. The server opened by this Server class follows the protocol of Samchon Framework's own. To open a server, extends the Server class and overrides addClient() method to define what to do with a newly connected remote clients. At last, call open() method with the specified port number. Below codes and classes will be good examples for comprehending how to open a server and handle remote clients. Note that, this Server class follows the protocol of Samchon Framework's own. If you want to provide a realtime web-service, then use WebServer instead, that is following the web-socket protocol. Definition at line 45 of file Server.hpp. Default Constructor. Definition at line 54 of file Server.hpp. Default Destructor. Reimplemented in samchon::templates::service::Server. Definition at line 61 of file Server.hpp. Open server. Definition at line 74 of file Server.hpp. Referenced by samchon::templates::parallel::MediatorServer::start(). Close the server. Definition at line 100 of file Server.hpp. References addClient(). Add a newly connected remote client. The addClient() is an abstract method being called when a remote client is newly connected with IClientDriver object who communicates with the remote system. Overrides this method and defines what to do with the driver, a newly connected remote client. Below methods and example codes may be good for comprehending how to utilizing this addClient method. Referenced by close(), and samchon::protocol::WebServer::WebServer().
http://samchon.github.io/framework/api/cpp/de/d12/classsamchon_1_1protocol_1_1Server.html
CC-MAIN-2022-27
refinedweb
254
51.75
Results 1 to 1 of 1 Thread: script help? - Join Date - Nov 2011 - 154 - Thanks - 5 - Thanked 0 Times in 0 Posts script help? Hello, I have this script, which allows for multiple songs to play. I just need to get it working with my graphical interface, which is just simply a play/pause button. But I'm having trouble getting the script (SongPlayer.as) to work with my button. Code: package { import flash.display.*; import flash.media.*; import flash.events.*; public class SongPlayer extends Sprite { private var s:Sound; private var sc:SoundChannel; private var isPlaying:Boolean; private var songs:Array; public function SongPlayer() { songs = [Song1, Song2, Song3, Song4, Song5]; playSong(); } private function playSong():void { var index:int = Math.floor(Math.random() * songs.length); s = new songs[index]() as Sound; sc = new SoundChannel(); sc = s.play(0,0); sc.addEventListener(Event.SOUND_COMPLETE, songComplete); songs.splice(index, 1); trace(s); } private function songComplete(e:Event):void { sc.stop(); if(songs.length > 0) { playSong(); } else { trace("all songs played"); } } } }
http://www.codingforums.com/flash-and-actionscript/267231-script-help.html?s=d0796047f89706ff5c00495a5e0b903e
CC-MAIN-2015-48
refinedweb
168
68.47
Open End JavaScript testing and utility kit jskit contains infrastructure and in particular a py.test plugin to enable running tests for JavaScript code inside browsers directly using py.test as the test driver. Running inside the browsers comes with some speed cost, on the other hand it means for example the code is tested against the real-world DOM implementations. The approach also enables to write integration tests such that the JavaScript code is tested against server-side Python code mocked as necessary. Any server-side framework that can already be exposed through WSGI (or for which a subset of WSGI can be written to accommodate the jskit own needs) can play along. jskit has also some support to run JavaScript tests from unittest.py based test suites. jskit also contains code to help modularizing JavaScript code which can be used to describe and track dependencies dynamically during development and that can help resolving them statically when deploying/packaging. Known supported browsers are Firefox, Internet Explorer >=7, and WebKit browsers. jskit now supports both py.test 2.0 and late py.test 1.x. jskit requires Python 2.6 or 2.7. It also uses MochiKit - of which it ships a version within itself for convenience - for its own working though in does not imposes its usage on tested code. jskit was initially developed by Open End AB and is released under the MIT license. Europython 2009 talk with examples The project repository lives at Discussions and feedback should go to py-dev at codespeak.net Changelog 0.9.0 make reusing one tab/window and the corresponding browser test object for all tests using the same setup in a session the default, this is enforced when using py.test 2.0 which collects all tests first py.test 2.0 is now supported! py.test 1.x still works as well display during the test runs a list of links on the upper right corner of the pages to jump to the outcome sections corresponding to the JavaScript test files or python modules various internal cleanups and simplifications some light refreshing and editing of the docs fix the looking up of jstests_setup values to consider the chain of conftest.py correctly MochiKit usage is really an implementation detail, switch to by default in tests importing it with __export__=false, which means the name MochiKit alone is defined in the global (window) namespace, use in a jstests_setup: class jstests_setup: MochiKit__export__ = True to get the old behavior. 0.8.9 - optionally delegate to the serverSide how the baseurl from which tests will be served should look like, useful when doing proxying for functional testing abuse of oejskit - change packaging to just offer a source tar file, so that makes it easier to package - requires Python 2.6 or 2.7 0.8.8 - improved code to check for the presence of browsers which is used to skip tests, this means that listing non-present browsers in browser specs should not provoke problems - workaround to bug in FF3.5 triggered by the global var leak detection code, no leak detection with FF3.5 :( 0.8.7 - flexible user-defined-name=commandline control over browser names for browser.py server with documentation - document the glue to standard library unittest.py - better error reporting when a browser cannot be started - use json module included in Python >=2.6, simplejson otherwise - move the py.test plugin into the oejskit package, expose it through a pytest11 setuptools entry point - fix own-tests-only issues and warnings with py.test 1.1.x 0.8.6 - fixes for py.test 1.0 final compatibility - experimental glue to standard library unittest.py (no docs yet) Download Files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/oejskit/
CC-MAIN-2017-43
refinedweb
639
63.49
On Sun, Apr 5, 2009 at 8:46 PM, Adam Vogt <vogt.adam at gmail.com> wrote: > Fixed. I'm attaching a darcs patch and a screenshot of my IM workspace. All the windows found their placement automatically. >. I don't know how to implement it this way, without any access to Combo's internal state. I could duplicate it's windows management logic and so maintain a mirror of it's state, but I really hate both high coupling and code duplication. To my mind a better idea would be to explicitly specify all the components invariants about applying combinators, processing messages and stack management, like requirement to send ReleaseResources to all the sublayouts etc. I had to spend quite a lot of time reading sources to get some bits of knowledge about it (esp. taking into account my modest Haskell experience). >>-. Exactly. I've switched from Ion which always has black background and immediately put some fancy picture in the root window, that's why it was so noticeable to me. I even thought that Ion does some kind of double buffering, but I've just checked - it doesn't, it's only a background colour which makes such a difference. By the way, is it possible to implement this in WM: save old window bitmaps and show them instead of background image while windows are redrawing? >>-. I meant reflection, I haven't even tried rotation. Reflecting a 1/3 division converts it to 2/3, but dragging the splitter doesn't work anymore. > In any case, if you run across an issue, file a bug and/or notify the > maintainers: it could be that such a combination has not been tried before > and maybe the solution isn't difficult at all. OK, I'll file a couple of reports. Thank you. -------------- next part -------------- Tue Apr 7 17:43:14 EDT 2009 konstantin.sobolev at gmail.com * comobP Adda a new comboP layout that combines multiple layouts and allows to specify where to put new windows. New patches: [comobP konstantin.sobolev at gmail.com**20090407214314 Ignore-this: a2da3d0e165d70f6ccb07ff5b5a44685 Adda a new comboP layout that combines multiple layouts and allows to specify where to put new windows. ] { addfile ./XMonad/Layout/ComboP.hs hunk ./XMonad/Layout/ComboP.hs 1 +{-# LANGUAGE TypeSynonymInstances, DeriveDataTypeable, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances, PatternGuards #-} +----------------------------------------------------------------------------- +-- | +-- Module : XMonad.Layout.ComboP +-- Copyright : (c) Konstantin Sobolev <konstantin.sobolev at gmail.com> +-- License : BSD-style (see LICENSE) +-- +-- Maintainer : Konstantin Sobolev <konstantin.sobolev at gmail.com> +-- Stability : unstable +-- Portability : unportable +-- +-- A layout that combines multiple layouts and allows to specify where to put +-- new windows. +-- +----------------------------------------------------------------------------- + +module XMonad.Layout.ComboP ( + -- * Usage + -- $usage + combineTwoP, + CombineTwoP, + SwapWindow(..) + ) where + +import Data.List ( delete, intersect, (\\) ) +import Data.Maybe ( isJust ) +import Control.Monad +import XMonad hiding (focus) +import XMonad.StackSet ( integrate, Workspace (..), Stack(..) ) +import XMonad.Layout.WindowNavigation +import XMonad.Layout.ResizableTile +import XMonad.Util.WindowProperties +import qualified XMonad.StackSet as W + +-- $usage +-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: +-- +-- > import XMonad.Layout.ComboP +-- > import XMonad.Util.WindowProperties +-- +--#Editing_the_layout_hook" +-- +--#Editing_key_bindings". + +data SwapWindow = SwapWindow -- ^ Swap window between panes + | SwapWindowN Int -- ^ Swap window between panes in the N-th nested ComboP. SwapWindowN 0 equals to SwapWindow + deriving (Read, Show, Typeable) +instance Message SwapWindow + +data CombineTwoP l l1 l2 a = C2P [a] [a] [a] l (l1 a) (l2 a) Property + deriving (Read, Show) + +combineTwoP :: (LayoutClass super(), LayoutClass l1 Window, LayoutClass l2 Window) => + super () -> l1 Window -> l2 Window -> Property -> CombineTwoP (super ()) l1 l2 Window +combineTwoP = C2P [] [] [] + +instance (LayoutClass l (), LayoutClass l1 Window, LayoutClass l2 Window) => + LayoutClass (CombineTwoP (l ()) l1 l2) Window where + doLayout (C2P f w1 w2 super l1 l2 prop) rinput s = + let origws = W.integrate s + w1c = w1 `intersect` origws + w2c = w2 `intersect` origws + new = origws \\ (w1c ++ w2c) + superstack = Just Stack { focus=(), up=[], down=[()] } + f' = focus s:delete (focus s) f + in do + matching <- (hasProperty prop) `filterM` new + let w1' = w1c ++ matching + w2' = w2c ++ (new \\ matching) + s1 = differentiate f' w1' + s2 = differentiate f' w2' + ([((),r1),((),r2)], msuper') <- runLayout (Workspace "" super superstack) rinput + (wrs1, ml1') <- runLayout (Workspace "" l1 s1) r1 + (wrs2, ml2') <- runLayout (Workspace "" l2 s2) r2 + return (wrs1++wrs2, Just $ C2P f' w1' w2' (maybe super id msuper') + (maybe l1 id ml1') (maybe l2 id ml2') prop) + + + handleMessage us@(C2P f ws1 ws2 super l1 l2 prop) m + -- unsuccessful attempt to workaround ResizableTile + | Just Shrink <- fromMessage m = forwardToFocused us m + | Just Expand <- fromMessage m = forwardToFocused us m + | Just MirrorShrink <- fromMessage m = forwardToFocused us m + | Just MirrorExpand <- fromMessage m = forwardToFocused us m + + | Just SwapWindow <- fromMessage m = swap us m + | Just (SwapWindowN 0) <- fromMessage m = swap us m + | Just (SwapWindowN n) <- fromMessage m = forwardToFocused us $ SomeMessage $ SwapWindowN $ n-1 + + | Just (MoveWindowToWindow w1 w2) <- fromMessage m, + w1 `elem` ws1, + w2 `elem` ws2 = return $ Just $ C2P f (delete w1 ws1) (w1:ws2) super l1 l2 prop + + | Just (MoveWindowToWindow w1 w2) <- fromMessage m, + w1 `elem` ws2, + w2 `elem` ws1 = return $ Just $ C2P f (w1:ws1) (delete w1 ws2) super l1 l2 prop + + -- code from CombineTwo + | otherwise = do ml1' <- broadcastPrivate m [l1] + ml2' <- broadcastPrivate m [l2] + msuper' <- broadcastPrivate m [super] + if isJust msuper' || isJust ml1' || isJust ml2' + then return $ Just $ C2P f ws1 ws2 + (maybe super head msuper') + (maybe l1 head ml1') + (maybe l2 head ml2') prop + else return Nothing + + description (C2P _ _ _ super l1 l2 prop) = "combining " ++ description l1 ++ " and "++ + description l2 ++ " with " ++ description super ++ " using "++ (show prop) + +swap :: (LayoutClass t Window, LayoutClass t1 Window, LayoutClass s a) => + CombineTwoP (s a) t t1 Window -> SomeMessage -> X (Maybe (CombineTwoP (s a) t t1 Window)) +swap us@(C2P f ws1 ws2 super l1 l2 prop) m = do + mst <- gets (W.stack . W.workspace . W.current . windowset) + let (ws1', ws2') = case mst of + Nothing -> (ws1, ws2) + Just st -> if foc `elem` ws1 + then (foc `delete` ws1, foc:ws2) + else if foc `elem` ws2 + then (foc:ws1, foc `delete` ws2) + else (ws1, ws2) + where foc = W.focus st + if (ws1,ws2) == (ws1',ws2') + then forwardToFocused us m + else return $ Just $ C2P f ws1' ws2' super l1 l2 prop + + +forwardToFocused :: (LayoutClass l1 Window, LayoutClass l2 Window, LayoutClass s a) => + CombineTwoP (s a) l1 l2 Window -> SomeMessage -> X (Maybe (CombineTwoP (s a) l1 l2 Window)) +forwardToFocused (C2P f ws1 ws2 super l1 l2 prop) m = do + ml1 <- forwardIfFocused l1 ws1 m + ml2 <- forwardIfFocused l2 ws2 m + ms <- if isJust ml1 || isJust ml2 + then return Nothing + else handleMessage super m + if isJust ml1 || isJust ml2 || isJust ms + then return $ Just $ C2P f ws1 ws2 (maybe super id ms) (maybe l1 id ml1) (maybe l2 id ml2) prop + else return Nothing + +forwardIfFocused :: (LayoutClass l Window) => l Window -> [Window] -> SomeMessage -> X (Maybe (l Window)) +forwardIfFocused l w m = do + mst <- gets (W.stack . W.workspace . W.current . windowset) + case mst of + Nothing -> return Nothing + Just st -> if (W.focus st) `elem` w + then handleMessage l m + else return Nothing + +-- code from CombineTwo +differentiate :: Eq q => [q] -> [q] -> Maybe (Stack q) +differentiate (z:zs) xs | z `elem` xs = Just $ Stack { focus=z + , up = reverse $ takeWhile (/=z) xs + , down = tail $ dropWhile (/=z) xs } + | otherwise = differentiate zs xs +differentiate [] xs = W.differentiate xs + +broadcastPrivate :: LayoutClass l b => SomeMessage -> [l b] -> X (Maybe [l b]) +broadcastPrivate a ol = do nml <- mapM f ol + if any isJust nml + then return $ Just $ zipWith ((flip maybe) id) ol nml + else return Nothing + where f l = handleMessage l a `catchX` return Nothing + +-- vim:ts=4:shiftwidth=4:softtabstop=4:expandtab:foldlevel=20: hunk ./xmonad-contrib.cabal 137 XMonad.Layout.Circle XMonad.Layout.Cross XMonad.Layout.Combo + XMonad.Layout.ComboP XMonad.Layout.Decoration XMonad.Layout.DecorationMadness XMonad.Layout.Dishes } Context: [More configurability for Layout.NoBorders (typeclass method) Adam Vogt <vogt.adam at gmail.com>**20090325050206 Ignore-this: 91fe0bc6217b910b7348ff497b922e11 This method uses a typeclass to pass a function to the layoutmodifier. It is flexible, but a bit indirect and perhaps the flexibility is not required. ] [Add XMonad.Actions.PhysicalScreens nelhage at mit.edu**20090321001320 Add an XMonad.Actions.PhysicalScreens contrib module that allows addressing of screens by physical ordering, rather than the arbitrary ScreenID. ] [pointWithin has moved to the core Joachim Breitner <mail at joachim-breitner.de>**20081008154245] [UpdatePointer even to empty workspaces Joachim Breitner <mail at joachim-breitner.de>**20081007080041 This makes UpdatePointer more Xinerama-compatible: If the user switches to a screen with an empty workspace, the pointer is moved to that workspace, which I think is expected behavoiur. ] [More predictable aspect ratio in GridVariants.Grid Norbert Zeh <nzeh at cs.dal.ca>**20090311013617. ] [X.L.Master: fix number of windows Ismael Carnales <icarnales at gmail.com>**20090301051509 Ignore-this: 2af132159450d4fb72eb52024eda71b5 ] [U.EZConfig: add xK_Print <Print> to special keys wirtwolff at gmail.com**20090302230741 Ignore-this: 9560b7c7c4424edb5cea6eec45e2b41d Many setups are expecting xK_Print rather than xK_Sys_Req, so make it available in additionalKeysP. ] [More flexibility for H.FadeInactive Daniel Schoepe <asgaroth_ at gmx.de>**20090309160020 Ignore-this: ebfa2eadb439763276b372107cdf8d6c ] [Prompt.Shell: escape ampersand Valery V. Vorotyntsev <valery.vv at gmail.com>**20090312091314 Ignore-this: 7200b76af8109bab794157da46cb0030 Ampersand (&) is a special character and should be escaped. ] [Cleanup X.L.Mosaic, without breaking it Adam Vogt <vogt.adam at gmail.com>**20090219022417 Ignore-this: d49ed55fe8dc2204256dff9252384745 ] [X.L.Mosaic: prevent users from causing non-termination with negative elements Adam Vogt <vogt.adam at gmail.com>**20090210022727 Ignore-this: 370a7d6249906f1743c6692758ce5aeb ] [better Layout.NoBorders.smartBorders behavior on xinerama Adam Vogt <vogt.adam at gmail.com>**20090314170058 Ignore-this: 36737ce2fa2087c4a16ddf226d3b0f0a Now smartBorders shows borders when you have multiple screens with one window each. In the case where only one window is visible, no borders are drawn. ] [H.DynamicLog: revised dzenStrip and xmobarStrip functions wirtwolff at gmail.com**20090314041517 Ignore-this: 9897c60b8dfc59344939b7aebc370953 Reconcile darcswatch patch with pushed version of dzenStrip. ] [X.H.DynamicLog: Add dzenStrip to remove formatting, for use in dzenPP's ppUrgent. Braden Shepherdson <Braden.Shepherdson at gmail.com>**20090314032818 Ignore-this: fd96a1a4b112d0f71589b639b83ec3e This function was written by Wirt Wolff. This change should allow UrgencyHook to work out of the box with dzen and dzenPP, rather than the colours being overridden so even though UrgencyHook is working, it doesn't change colours. ] [X.H.ManageHelpers: export isInProperty Roman Cheplyaka <roma at ro-che.info>**20090308201112] [L.Cross: clarify documentation wirtwolff at gmail.com**20090222042220 Ignore-this: 4a5dcf71e63d045f27e2340e1def5cc8 Amend-record earlier patch to work with byorgey's fix, this one is just the documentation typo fixes and clarifications. ] [documentation for IndependentScreens daniel at wagner-home.com**20090221235959] [eliminate a haddock warning in BoringWindows daniel at wagner-home.com**20090221235836] [merge IndependentScreens daniel at wagner-home.com**20090221232142] [add IndependentScreens to xmonad-contrib.cabal daniel at wagner-home.com**20090221231632] [add type information for IndependentScreens daniel at wagner-home.com**20090221231525] [add some boilerplate comments at the top of IndependentScreens Brent Yorgey <byorgey at cis.upenn.edu>**20090221230850] [IndependentScreens, v0.0 daniel at wagner-home.com**20090221225229] [U.Run: remove waitForProcess to close Issue 268 wirtwolff at gmail.com**20090220214153 Ignore-this: a6780565fde40a4aac9023cc55fc2273 Submitting with some trepidation, since I've nearly no understanding of process handling. Should be ok, no warnings by sjanssen when asking about it in hpaste or earlier email, and tested locally by spawning excessive numbers of dzens: did not leave zombies or raise exceptions. ] [change Cross data declaration into a record so that Haddock will parse the per-argument comments Brent Yorgey <byorgey at cis.upenn.edu>**20090221224742] [X.L.Master: turn it to a Layout modifier and update the code Ismael Carnales <icarnales at gmail.com>**20090213020453 Ignore-this: 69513ad2b60dc4aeb49d64ca30e6f9f8 ] [Use doShift in my config Spencer Janssen <spencerjanssen at gmail.com>**20090219042040 Ignore-this: 1f103d21bbceec8d48384f975f18eaec ] [SpawnOn: use doShift. This resolves problems where SpawnOn would shift the wrong window Spencer Janssen <spencerjanssen at gmail.com>**20090219041856 Ignore-this: 6ae639a638db8eff77203f3f2e481a4e ] [SpawnOn: delete seen pids Spencer Janssen <spencerjanssen at gmail.com>**20090213013011 Ignore-this: 8b15a60bba1edf1bab5fb77ac54eb12f ] [X.U.Loggers: handle possible EOF (reported by dyfrgi) Roman Cheplyaka <roma at ro-che.info>**20090216213842] [U.Scratchpad: add general spawn action to close issue 249 wirtwolff at gmail.com**20090214003642 Ignore-this: 925ad9db4ecc934dcd86320f383ed44a Adds scratchpadSpawnActionCustom where user specifies how to set resource to "scratchpad". This allows use of gnome-terminal, etc. Add detail to RationalRectangle documentation; strip trailing spaces. ] [SpawnOn: add 'exec' to shell strings where possible Spencer Janssen <spencerjanssen at gmail.com>**20090212234608 Ignore-this: c7de4e05803d60b10f38004dcbda4732 ] [Add Cross Layout 'Luis Cabellos <zhen.sydow at gmail.com>'**20090209174802] [Fix an undefined in EwmhDesktops Daniel Schoepe <asgaroth_ at gmx.de>**20090209152308 Ignore-this: f60a43d7ba90164ebcf700090dfb2480 ] [X.U.WindowProperties: docs (description and sections) Roman Cheplyaka <roma at ro-che.info>**20090208231422] [X.U.WindowProperties: Add getProp32 and getProp32s, helpers to get properties from windows Ismael Carnales <icarnales at gmail.com>**20090205013031 Ignore-this: c5481fd5d97b15ca049e2da2605f65c1 ] [cleanup and make X.L.Mosaic behavior more intuitive wrt. areas Adam Vogt <vogt.adam at gmail.com>**20090208221629 Ignore-this: 3c3c6faa203cbb1c1db909e5bf018b6f ] [minor typo in XMonad/Util/EZConfig.hs Joachim Breitner <mail at joachim-breitner.de>**20090208192224 Ignore-this: 7ffee60858785c3e31fdd5383c9bb784 ] [Multimedia keys support for EZConfig Khudyakov Alexey <alexey.skladnoy at gmail.com>**20090207173330 Ignore-this: 21183dd7c192682daa18e3768828f88d ] [+A.CycleWindows: bindings to cycle windows in new ways wirtwolff at gmail.com**20090207170622 Ignore-this: 51634299addf224cbbc421adb4b048f5. ] [XMonad.Actions.CopyWindow: fmt & qualify stackset import gwern0 at gmail.com**20090206171833 Ignore-this: 4d08f5a7627020b188f59fc637b53ae8 ] [XMonad.Actions.CopyWindow runOrCopy lan3ny at gmail.com**20080602205742] [ManageHelpers: reduce duplicated code in predicates Ismael Carnales <icarnales at gmail.com>**20090204021847 Ignore-this: e28a912d4f897eba68ab3edfddf9f26b ] [Remove X.U.SpawnOnWorkspace (superseded by X.A.SpawnOn) Roman Cheplyaka <roma at ro-che.info>**20090204103635] [X.A.SpawnOn: add docs Roman Cheplyaka <roma at ro-che.info>**20090204102424 Add more documentation, including documentation from X.U.SpawnOnWorkspace by Daniel Schoepe. ] [Remove silliness from XMonad.Doc.Configuring Spencer Janssen <spencerjanssen at gmail.com>**20090204055626] [Adjustments to use the new event hook feature instead of Hooks.EventHook Daniel Schoepe <asgaroth_ at gmx.de>**20090203160046 Ignore-this: f8c239bc8e301cbd6fa509ef748af542 ] [Easier Colorizers for X.A.GridSelect quentin.moser at unifr.ch**20090128001702 Ignore-this: df3e0423824e40537ffdb4bc7363655d ] [X.A.SpawOn: fix usage doc Roman Cheplyaka <roma at ro-che.info>**20090202102042] [Added GridVariants.SplitGrid Norbert Zeh <nzeh at cs.dal.ca>**20090129152146 GridVariants.TallGrid behaved weird when transformed using Mirror or Reflect. The new layout SplitGrid does away with the need for such transformations by taking a parameter to specify horizontal or vertical splits. ] [FixedColumn: added missing nmaster to the usage doc Ismael Carnales <icarnales at gmail.com>**20090130195239 Ignore-this: 642aa0bc9e68e7518acc8af30324b97a ] [XMonad.Actions.Search: fix whitespace & tabs gwern0 at gmail.com**20090129025246 Ignore-this: 894e479ccc46160848c4d70c2361c929 ] [xmonad-action-search-intelligent-searchengines Michal Trybus <komar007 at gmail.com>**20090128101938 Changed the XMonad.Action.Search to use a function instead of String to prepare the search URL.Added a few useful functions used to connect many search engines together and do intelligent prefixed searches (more doc in haddock)The API has not changed with the only exception of search function, which now accepts a function instead of String. ] [XMonad.Prompt autocompletion fix quentin.moser at unifr.ch**20090127184145 Ignore-this: 635cbf6420722a4edef1ae9c40b36e1b ] [X.A.SinkAll: re-add accidentally deleted usage documentation Brent Yorgey <byorgey at cis.upenn.edu>**20090127222533] [move XMonad.Actions.SinkAll functionality to more general XMonad.Actions.WithAll, and re-export sinkAll from X.A.SinkAll for backwards compatibility Brent Yorgey <byorgey at cis.upenn.edu>**20090127222355] [adds generic 'all windows on current workspace' functionality loupgaroublond at gmail.com**20081221224850] [placement patch to XMonad.Layout.LayoutHints quentin.moser at unifr.ch**20090126195950 Ignore-this: 87a5efa9c841d378a808b1a4309f18 ] [XMonad.Actions.MessageFeedback module quentin.moser at unifr.ch**20090126181059 Ignore-this: 82e58357a44f98c35ccf6ad0ef98b552 ] [submapDefault Anders Engstrom <ankaan at gmail.com>**20090118152933 Ignore-this: c8958d47eb584a7de04a81eb087f05d1 Add support for a default action to take when the entered key does not match any entry. ] [X.A.CycleWS: convert tabs to spaces (closes #266) Roman Cheplyaka <roma at ro-che.info>**20090127185604] [Mosaic picks the middle aspect layout, unless overriden Adam Vogt <vogt.adam at gmail.com>**20090126032421 Ignore-this: aaa31da14720bffd478db0029563aea5 ] [Mosaic: stop preventing access to the widest layouts Adam Vogt <vogt.adam at gmail.com>**20090125045256 Ignore-this: c792060fe2eaf532f433cfa8eb1e8fe3 ] [X.L.Mosaic add documentation, update interface and aspect ratio behavior Adam Vogt <vogt.adam at gmail.com>**20090125041229 Ignore-this: e78027707fc844b3307ea87f28efed73 ] [Use currentTag, thanks asgaroth Spencer Janssen <spencerjanssen at gmail.com>**20090125213331 Ignore-this: dd1a3d96038de6479eca3b9798d38437 ] [Support for spawning most applications on a specific workspace Daniel Schoepe <asgaroth_ at gmx.de>**20090125191045 Ignore-this: 26076d54b131e037b42c87e4fde63200 ] [X.L.Mosaic: haddock fix Roman Cheplyaka <roma at ro-che.info>**20090124235908] [A mosaic layout based on MosaicAlt Adam Vogt <vogt.adam at gmail.com>**20090124022058 Ignore-this: 92bad7498f1ac402012e3eba6cbb2693 The position of a window in the stack determines its position and layout. And the overall tendency to make wide or tall windows can be changed, though not all of the options presented by MosaicAlt can be reached, the layout changes with each aspect ratio message. ] [uninstallSignalHandlers in spawnPipe Spencer Janssen <spencerjanssen at gmail.com>**20090122002745 Ignore-this: e8cfe0f18f278c95d492628da8326fd7 ] [Create a new session for spawnPiped processes Spencer Janssen <spencerjanssen at gmail.com>**20090122000441 Ignore-this: 37529c5fe8b4bf1b97fffb043bb3dfb0 ] [TAG 0.8.1 Spencer Janssen <spencerjanssen at gmail.com>**20090118220647] [Use spawnOn in my config Spencer Janssen <spencerjanssen at gmail.com>**20090117041026 Ignore-this: 3f92e4bbe4f2874b86a6c7ad66a31bbb ] [Add XMonad.Actions.SpawnOn Spencer Janssen <spencerjanssen at gmail.com>**20090117040432 Ignore-this: 63869d1ab11f2ed5aab1690763065800 ] [Bump version to 0.8.1 Spencer Janssen <spencerjanssen at gmail.com>**20090116223607 Ignore-this: 1c201e87080e4404f51cadc108b228a1 ] [Compile without optimizations on x86_64 and GHC 6.10 Spencer Janssen <spencerjanssen at gmail.com>**20090108231650 Ignore-this: a803235b8022793f648e8953d9f05e0c This is a workaround for ] [Update all uses of doubleFork/waitForProcess Spencer Janssen <spencerjanssen at gmail.com>**20090116210315 Ignore-this: 4e15b7f3fd6af3b7317449608f5246b0 ] [Update to my config Spencer Janssen <spencerjanssen at gmail.com>**20090116204553 Ignore-this: 81017fa5b99855fc8ed1fe8892929f53 ] [Adjustments to new userCode function Daniel Schoepe <asgaroth_ at gmx.de>**20090110221310] [X.U.EZConfig: expand documentation Brent Yorgey <byorgey at cis.upenn.edu>**20090116153143] [add a bit of documentation to HintedTile Brent Yorgey <byorgey at cis.upenn.edu>**20090114065126] [ManageHelpers: add isDialog johanngiwer at web.de**20090108232505] [CenteredMaster portnov84 at rambler.ru**20090111134513 centerMaster layout modifier places master window at top of other, at center of screen. Other windows are managed by base layout. topRightMaster is similar, but places master window at top right corner. ] [XMonad.Util.XSelection: update maintainer information gwern0 at gmail.com**20090110213000 Ignore-this: 1592ba07f2ed5d2258c215c2d175190a ] âworkspace flickerâ: 5ebd2916c6728033f4a01cea8490f2ab65594e36 -------------- next part -------------- A non-text attachment was scrubbed... Name: comboP.png Type: image/png Size: 166801 bytes Desc: not available Url :
http://www.haskell.org/pipermail/xmonad/2009-April/007689.html
CC-MAIN-2014-35
refinedweb
3,025
51.34
#include <VolVolume.hpp> List of all members. 143 of file VolVolume.hpp. Construct a vector of size s. The content of the vector is undefined. Definition at line 152 of file VolVolume.hpp. References sz, v, and VOL_TEST_SIZE. Default constructor creates a vector of size 0. Definition at line 157 of file VolVolume.hpp. Copy constructor makes a replica of x. Definition at line 159 of file VolVolume.hpp. The destructor deletes the data array. Definition at line 167 of file VolVolume.hpp. Return the size of the vector. Definition at line 170 of file VolVolume.hpp. Return a reference to the i-th entry. Definition at line 173 of file VolVolume.hpp. References sz, v, and VOL_TEST_INDEX. Return the i-th entry. Definition at line 179 of file VolVolume.hpp. References sz, v, and VOL_TEST_INDEX. Delete the content of the vector and replace it with a vector of length 0. Definition at line 186 of file VolVolume.hpp. Convex combination. Replace the current vector v with v = (1-gamma) v + gamma w. Definition at line 193 of file VolVolume.hpp. Referenced by VOL_primal::cc(). delete the current vector and allocate space for a vector of size s. Definition at line 209 of file VolVolume.hpp. References sz, v, and VOL_TEST_SIZE. swaps the vector with w. Definition at line 216 of file VolVolume.hpp. Copy w into the vector. Replace every entry in the vector with w. The array holding the vector. Definition at line 146 of file VolVolume.hpp. Referenced by allocate(), cc(), clear(), operator[](), swap(), VOL_dvector(), and ~VOL_dvector(). The size of the vector. Definition at line 148 of file VolVolume.hpp. Referenced by allocate(), cc(), clear(), operator[](), size(), swap(), and VOL_dvector().
http://www.coin-or.org/Doxygen/CoinAll/class_v_o_l__dvector.html
crawl-003
refinedweb
283
64.47
What is new in Java 14 (for Developers) Java JDK 14 was released on March 2020 as part of the new release cycle (a new Java version every 6 months). In this article we will learn what are the new features available for developers. What’s new in Java 14? Java JDK 14 is one of the releases I’ve personally been waiting for. It includes Switch Expressions (introduced in Java 12) - now as a complete feature, Text Blocks, Pattern Matching for instanceof (Preview) and my two favorite features: Helpful NullPointerExceptions and Records (Preview). Althought JDK 14 is not LTS (Long Term Support) it’s exciting to see the language evolving with features will have an impact in our daily professional lives as developers. Below is a list of all features included in Java 14 (from Oracle blog): - JEP 305 – Pattern Matching for instanceof (Preview): This preview feature enhances Java with pattern matching for the instanceof operator. This improves developer productivity by eliminating the need for common boiler plate code and allows more concise type-safe code. - JEP 343 – Packaging Tool (Incubator): This incubator tool provides a way for developers to package Java applications for distribution in platform-specific formats. The tool helps developers with modern applications where constraints require runtimes and applications to be bundled in a single deliverable. - JEP 345 – NUMA-Aware Memory Allocation for G1: This feature improves overall performance of the G1 garbage collector on Non-uniform memory access (NUMA) systems. - JEP 349 – JFR Event Streaming: This feature exposes JDK Flight Recorder (JFR) data for continuous monitoring, which will simplify access to JFR data to various tools and applications. - JEP 352 – Non-Volatile Mapped Byte Buffers: This feature adds a file mapping mode for the JDK when using non-volatile memory. The persistent nature of non-volatile memory changes various persistence and performance assumptions which can be leveraged with this feature. - JEP 358 – Helpful NullPointerExceptions: This feature improves the usability of NullPointerExceptionsby describing precisely which variable was null and other helpful information. This will improve developer productivity and improve the quality of many development and debugging tools. - JEP 359 – Records (Preview): This preview feature provides a compact syntax for declaring classes which hold shallowly immutable data. Superficially, this feature greatly reduces boilerplate code in classes of this type, but ultimately its goal is to better allow the modeling of data as data. It should be easy, clear, and concise to declare shallowly-immutable nominal data aggregates. - JEP 361 – Switch Expressions: This was a preview feature in JDK 12 and JDK 13 and is now a completed feature. It allows switch to be used as either a statement or an expression. This feature simplifies every day coding and prepared the way for the pattern matching (JEP 305) feature previewed in this release. - JEP 362 – Deprecate the Solaris and SPARC Ports: This JEP deprecates the Solaris and SPARC ports with the intent to remove them in a future release. - JEP 363 – Remove the Concurrent Mark Sweep (CMS) Garbage Collector: The CMS garbage collector was deprecated over two years ago and G1, which has been the intended successor to CMS since JDK 6, has been the default GC and used at scale for many years. We have also seen the introduction of two new collectors, ZGC and Shenandoah, along with many improvements to G1 over the same time. - JEP 364 – ZGC on macOS: While most users that require ZGC also require the scalability of Linux-based environments, it is also often needs, for deployment and testing, in Windows and macOS. There are also certain desktop applications which will benefit from ZGC capabilities. Therefore, the ZGC feature was ported to Windows and macOS. - JEP 365 – ZGC on Windows. - JEP 366 – Deprecate the ParallelScavenge + SerialOld GC Combination: This deprecates the combination of the Parallel Scavenge and Serial Old garbage collection algorithms, which is rarely used, with the intent to remove it in a future release. - JEP 367 – Remove the Pack200 Tools and API: This removes the pack200and unpack200tools, and the Pack200 API in the java.util.jarpackage. These tools and API were deprecated for removal in Java SE 11. - JEP 368 – Text Blocks (Second Preview): After receiving feedback when Text Blocks was first introduced as a preview feature (JEP 355) as part of Java 13, two new escape sequences have been added, and Text Blocks is being offered as a preview feature for a second time. Benefits of Text Blocks include: simplified writing of programs using strings that span several lines of source code, while avoiding escape sequences in common cases; enhanced readability of strings in Java programs that denote code written in non-Java languages; supports the migration from string literals by stipulating that any new construct can express the same set of strings as a string literal, interpret the same escape sequences, and be manipulated in the same ways as a string literal. - JEP 370 – Foreign-Memory Access API (Incubator): This incubator module introduces an API to allow Java programs to safely and efficiently access foreign memory outside of the Java heap. Let’s take a look at Switch Expressions, new features from Text Blocks, Helpful NullPointerExceptions, Pattern Matching for instanceof and the new Records. Before you try these new features, don’t forget to download and install the latest JDK. Also, don’t forget to download the latest version of your favorite IDE (latest Eclipse version or IntelliJ IDEA 2020.1). Pattern Matching for instanceof (from JEP 305 - Preview Feature) Consider the following code, and nothe the instanceof code inside the equals method: public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof Person) { Person person = (Person) obj; return age == person.age && name.equals(person.name); } return false; } } Code such as Person person = (Person) obj is very common in Java projects. Pattern Matching for instanceof allows us to simplify this code. After refactoring with Java 14, this is what we have: if (obj instanceof Person person) { // we can declare the variable person here // Person person = (Person) obj; return age == person.age && name.equals(person.name); } Although this is a very simple change, the code is more concise. And any refactoring we can do to improve our code, we’ll take it! :) Text Blocks - String Literals (from JEP 368 - Second Preview) A text block is a multi-line string literal that avoids the need for most escape sequences, automatically formats the string in a predictable way, and gives the developer control over format when desired. The first preview of this feature was introduced in Java 13. Below is a snippet comparing how we used to declare multiple line string and from first preview); } The second preview of this feature introduced two escape sequence we can use. First, the \ escape sequence explicitly suppresses the insertion of a newline character. The \s escape sequence can be used in both text blocks and traditional string literals. Applying these two new escape sequence: String updateQuery2 = """ update products \ set quantityInStock = ? ,modifiedDate = ? ,modifiedBy = ? \s \ where productCode = ? """; System.out.println(updateQuery2); We’ll have the following output: update products set quantityInStock = ? ,modifiedDate = ? ,modifiedBy = ? where productCode = ? These two new escape sequence give us a little bit more flexiblity to write readable code without comprimising the way we want the output to be! Switch Expressions (from JEP 361 - Complete Feature) Switch Expressions are now much more optimized (syntax wise) than before. I have published details in these two blogs posts: To summarize, we can use yield to return a value from switch instead of break: as preview): private String enhancedSwitchCase(DAY_OF_WEEK dayOfWeek) { return switch (dayOfWeek) { case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Weekday"; case SATURDAY, SUNDAY -> "Weekend"; }; } Helpful NullPointerExceptions (from JEP 358) This is one of my favortite JEPs this release! Given the code below, we’re going to get a NullPointerException because matrix[1][0] is null. private static void helpfulNullPointerExceptions(){ String[][] matrix = new String[5][5]; matrix[1] = new String[5]; if (matrix[1][0].toUpperCase().equals("S")) { // some code here } } If we run code above with Java 13 or before, we’ll get the following exception: Exception in thread "main" java.lang.NullPointerException at com.loiane.Java14Features.helpfulNullPointerExceptions(Java14Features.java:33) at com.loiane.Java14Features.main(Java14Features.java:20) This stack trace is helpful, but not that helpful. We don’t know if the exception was thrown because matrix[1] is null or matrix[1][0], and to find it out it requires some debugging. This JEP introduces a JVM parameter that can show the exact reason of this exception. By default, this feature is set to false, but we can enable it by adding -XX:+ShowCodeDetailsInExceptionMessages to the JVM options as showed below: According to the JEP details: “The option will first have default ‘false’ so that the message is not printed. It is intended to enable code details in exception messages by default in a later release.”. Executing the code again, we’ll get the helpfull NullPointerException: Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "matrix[1][0]" is null at com.loiane.Java14Features.helpfulNullPointerExceptions(Java14Features.java:33) at com.loiane.Java14Features.main(Java14Features.java:20) Much better! Records (from JEP 359 - Preview Feature) This is another one of my favorites JEPs from this release! From the JEP.”. When we create a class to represent something in Java, we usually declare all the atributes/properties, then create the getters and setters, contructors, and methods toString, equals, hashCode. Altough the IDE can create the methods for us, when reading the code later, it’s too many lines, and sometimes what we need is something very simple just to represent something. There is an alternative to declutter the classes, which is done by project Lombok. Some developers like it, others don’t like it. However, with the new Records, decluttering our code into a more elegant code is possible throuhg records! Let’s take a look how we can declare a Record: public record Product(String name,int quantity,double price) {} That’s awesome! Now, this is what we get once the code is compiled: public final class Product extends java.lang.Record { private final java.lang.String name; private final int quantity; private final double price; public Product(java.lang.String name, int quantity, double price) { /* compiled code */ } public java.lang.String toString() { /* compiled code */ } public final int hashCode() { /* compiled code */ } public final boolean equals(java.lang.Object o) { /* compiled code */ } public java.lang.String name() { /* compiled code */ } public int quantity() { /* compiled code */ } public double price() { /* compiled code */ } } All properties are private and final, which makes our properties immutable. We don’t get setters, and the getters don’t have the get or is prefix. We also get by default the methods toString, hashCode and equals. Our Record is compiled into a class that extends the class Record and it’s also a final class, meaning we cannot declare an abstract Record. And all the properties are declared within parenthesis (), meaning we cannot declare instance properties inside a Record. Because of this new type, some new methods were also added into the Java API. The Class class has two methods for the new Record feature: isRecord() and getRecordComponents() (used to retrive details of annotations and the generic type),. The ElementType enumeration has a new constant for Records: RECORD_TYPE. If we need to, we can override the default contructor to add any specific logic required: public record Product(String name,int quantity,double price) { public Product { if (quantity < 1) { throw new IllegalArgumentException("Product needs to have at least 1 quantity"); } } } The constructor can also declare arguments/parameters: public record Product(String name,int quantity,double price) { public Product(String name, int quantity, double price) { if (quantity < 1) { throw new IllegalArgumentException("Product needs to have at least 1 quantity"); } this.name = name; this.quantity = quantity; this.price = price; } } But that’s now all we can do with a Record. We can also declare static properties and methods: public record Product(String name,int quantity,double price) { private static int COUNT = 0; static int count() { return COUNT; } } A Record cannot extend another class (as the compiled code is a class that exteds Record and Java does not allow multiple inheritance with classes), but a Record can implement interfaces: public record Product(String name,int quantity,double price) implements Comparable<Product> { @Override public int compareTo(Product o) { return 0; // code here } } And finally, we can also add annotations to the Record’s properties: public record Product( @NotNull String name, int quantity, @Min(1) double price) {} Personally, I can’t wait for this JEP to be a complete feature so I can start refactoring existing projects! Conclusion This was a big release for Java in number of JEPs, with some important features for developers. Now let’s wait for Java 15 (September 2020) with more new features! View the full source code on GitHub. References: - The arrival of Java 14 - Oracle blog - OpenJDK JDK 13 project page - What’s New In JDK 14 Latest Release? 80 New Features & APIs Happy Coding!
http://loiane.com/2020/04/what-is-new-in-java-14-api-for-developers/
CC-MAIN-2020-29
refinedweb
2,195
51.38
Next: Complex Multi-Dimensional DFTs, Previous: Tutorial, Up: Tutorial Plan: To bother about the best method of accomplishing an accidental result. [Ambrose Bierce, The Enlarged Devil's Dictionary.] The basic usage of FFTW to compute a one-dimensional DFT of size N is simple, and it typically looks something like this code: ); } (When you compile, you must also link with the fftw3 library, e.g. -lfftw3 -lm on Unix systems.) First you allocate the input and output arrays. You can allocate them in any way that you like, but we recommend using fftw_malloc, which behaves like malloc except that it properly aligns the array when SIMD instructions (such as SSE and Altivec) are available (see SIMD alignment and fftw_malloc). The data is an array of type fftw_complex, which is by default a double[2] composed of the real ( in[i][0]) and imaginary ( in[i][1]) parts of a complex number. The next step is to create a plan, which is an object that contains all the data that FFTW needs to compute the FFT. This function creates the plan: fftw_plan fftw_plan_dft_1d(int n, fftw_complex *in, fftw_complex *out, int sign, unsigned flags); The first argument, n, is the size of the transform you are trying to compute. The size n can be any positive integer, but sizes that are products of small factors are transformed most efficiently (although prime sizes still use an O(n log n) algorithm). The next two arguments are pointers to the input and output arrays of the transform. These pointers can be equal, indicating an in-place transform. The fourth argument, sign, can be either FFTW_FORWARD ( -1) or FFTW_BACKWARD ( +1), and indicates the direction of the transform you are interested in; technically, it is the sign of the exponent in the transform. The flags argument is usually either FFTW_MEASURE or FFTW_ESTIMATE. FFTW_MEASURE instructs FFTW to run and measure the execution time of several FFTs in order to find the best way to compute the transform of size n. This process takes some time (usually a few seconds), depending on your machine and on the size of the transform. FFTW_ESTIMATE, on the contrary, does not run any computation and just builds a reasonable plan that is probably sub-optimal. In short, if your program performs many transforms of the same size and initialization time is not important, use FFTW_MEASURE; otherwise use the estimate.); If you want to transform a different array of the same size, you can create a new plan with fftw_plan_dft_1d and FFTW automatically reuses the information from the previous plan, if possible. (Alternatively, with the “guru” interface you can apply a given plan to a different array, if you are careful. See FFTW computes an unnormalized DFT. Thus, computing a forward followed by a backward transform (or vice versa) results in the original array scaled by n. For the definition of the DFT, see What FFTW Really Computes. If you have a C compiler, such as gcc, that supports the recent C99 standard, and you #include <complex.h> before <fftw3.h>, then fftw_complex is the native double-precision complex type and you can manipulate it with ordinary arithmetic. Otherwise, FFTW defines its own complex type, which is bit-compatible with the C99 complex type. See.
http://www.fftw.org/doc/Complex-One_002dDimensional-DFTs.html
crawl-001
refinedweb
542
60.24
We recommend that you use the latest version of this feature, which is renamed to Cloud Endpoints Frameworks for App Engine. This new version supports App Engine standard environment, provides lower latency, and has better integration with App Engine. For more details, see Migrating to 2.0. This code walkthrough shows a pre-built Maven project containing a simple Cloud Endpoints backend API that you can run and test locally without having to build a client. The purpose is to show the basic structure and behavior of a backend API. Objectives In this tutorial, you'll learn how to: - Set up your development environment for Cloud Endpoints. - Run and test a simple backend API. - Learn the basics of backend API construction. Costs App Engine has free a level of usage. If your total usage of App Engine is less than the limits specified in the App Engine free quota, there is no charge for doing this tutorial. Before you begin Install the Java 7 SDK and set up your environment as described in Configuring Java. Install Maven 3.1 or greater as described in Installing Maven 3.1+. Create or select a Cloud Platform project in the Cloud Platform Console and then ensure that an App Engine application exists and billing is enabled: The Dashboard opens if an App Engine application already exists in your project and billing is enabled. Otherwise, follow the prompts for choosing a region and enabling billing. Cloning the tutorial project Clone the HelloWorld sample from GitHub: git clone Alternatively, you can download the sample as a zip file and extract it. Viewing the project layout and files If you execute a tree command or equivalent on the directory appengine-endpoints-helloworld-java-maven, this is what the structure of the project looks like: We'll cover the contents of MyBean.java and YourFirstAPI.java in detail during the tutorial. To give you a quick synopsis of these files for now, here's a brief inventory: Building and running locally In the root directory of the project, appengine-endpoints-helloworld In a terminal window, start a new Chrome session as follows: <Full-Path-to-Chrome> --user-data-dir=test --unsafely-treat-insecure-origin-as-secure= For example, on Mac OS X, /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir=test --unsafely-treat-insecure-origin-as-secure= Start the API in the development server by invoking the command mvn appengine:devserver Wait for the dev server to start up. When the server is ready, you will see a message similar to this one: [INFO] INFO: Module instance default is running at [INFO] April 13, 2016 9:44:47 AM com.google.appengine.tools.development.AbstractModule startup [INFO] INFO: The admin console is running at [INFO] April 13, 2016 9:44:47 AM com.google.appengine.tools.development.DevAppServerImpl doStart [INFO] INFO: Dev App Server is now running Visit the APIs Explorer at this URL: (The Google APIs Explorer is a built-in tool that lets you send requests to a backend service without using a client app.) Click myApi API V1 to display the methods available from this API. Click myApi.sayHi to display the Explorer for this method: Supply any name you want in the name field, then click Execute without OAuth When finished, stop the browser you started with the command line above, because you should not use it for normal browsing for safety reasons. Configuration files In this simple tutorial, we won't cover the configuration files, such as pom.xml, appengine-web.xml, and web.xml. These are covered in more detail in the more advanced Backend API with Maven sample. MyBean.java walkthrough The following code shows the contents of the file MyBean.java: /** The object model for the data we are sending through endpoints */ public class MyBean { private String myData; public String getData() { return myData; } public void setData(String data) { myData = data; } } This class is used to return data from the backend API to the caller. Note that you need to use a JavaBean object to send data through the backend API. YourFirstAPI.java walkthrough The following code shows some of the contents of the file YourFirstAPI.java: /**}) /** A simple endpoint method that takes a name and says Hi back */ @ApiMethod(name = "sayHi") public MyBean sayHi(@Named("name") String name) { MyBean response = new MyBean(); response.setData("Hi, " + name); return response; } Notice the annotation @Api; this is where you set the configuration of the backend API, such as its name and version, along with other possible settings. (See Endpoint Annotations for all of the available attributes of this annotation.) This is where you specify the name and version of the API, both of which show up in the API Explorer Notice the @ApiMethod annotation; it allows you to configure your methods at a finer level than the API-wide configuration. Finally, notice the use of the javax.inject.Named annotation ( @Named) in the sayHi method definition. You must supply this annotation for all parameters passed to server-side methods, unless the parameter is an entity type.. What's next This tutorial walked you through the process of building a simplistic backend API. For a more complete example of building a backend API, including GET/POST methods and OAuth authentication, see Backend API with Maven.
https://cloud.google.com/appengine/docs/java/endpoints/helloworld-java-maven
CC-MAIN-2017-04
refinedweb
885
51.99
Alex Martelli <aleax at aleax.it> wrote in message news:<gq4tb.20498$9_.728759 at news1.tin.it>... > > You want to HIDE (shudder) the fact that a function is being called, > ensuring, instead, that just coding: > print f.someattr > will call f secretly, behind the scenes. > > If one was truly intent on perpetrating this horror, then: > > class DontLetKidsSeeThisPlease(object): > def __init__(self, f): self.__f = f > def __getattr__(self, name): return getattr(self.__f(), name) > f = DontLetKidsSeeThisPlease(f) I think the original poster was not very clear in his writing. But he did give an analogy. Let me try to guess what he wants. For a property implemented with getter and setter accessor methods, you can do a lot of things when the user accesses the property. A few examples are: (a) dynamically retrieve/store the value from/to a database, (b) do some logging or access security control, (c) return different values depending on environmental circumstances, etc. The original poster seems to want the same level of control for access to a global object inside a module. That's all. That is, he probably would like to: (a) dynamically assemble the object on the flight, perhaps from a database, perhaps some meta-programming, notice that a simple Python namespace entry CANNOT do this trick, because it always points to the same object. Sure, one way out in Python is to make a wrapper, but that's exactly what the original poster's "f" is about, (b) do some logging or security control everytime the object is accessed, (c) return different objects depending on environmental circumstances, etc. regards, Hung Jung
https://mail.python.org/pipermail/python-list/2003-November/224341.html
CC-MAIN-2014-15
refinedweb
270
55.64
.. For information on setting the value in ansible.cfg to master. - name: - Download the role to a specific name. Defaults to the Galaxy name when downloading from Galaxy, otherwise it defaults to the name of the repository. Use the following example as a guide for specifying roles in requirements.yml: # from galaxy - src: yatesr.timezone # from GitHub - src: # from GitHub, overriding the name and specifying a specific tag - src: version: master name: nginx_role # from a webserver, where the role is packaged in a tar.gz - src: name: http-role # Roles can also be dependent on other roles, and when you install a role that has dependencies, those dependenices Playbook Roles and Include Statements.. This will create the same directory structure as above, but populate it with default files appropriate for a Container Enabled role. For instance, the README.md has a slightly different structure, the .travis.yml file tests the role using Ansible Container, and the meta directory includes a container.yml file. Using the import, delete and setup commands to manage your roles on the Galaxy website requires authentication, and the login command can be used to do just that. Before you can use the login command, you must create an account on the Galaxy website. The login command requires using your GitHub credentials. You can use your username and password, or you can create a personal access token. If you choose to create a token, grant minimal access to the token, as it is used just to verify identify. The following shows authenticating with the Galaxy website using a GitHub username and password: $ ansible-galaxy login We need your GitHub login to identify you. This information will not be sent to Galaxy, only to api.github.com. The password will not be displayed. Use --github-token if you do not want to enter your password. Github Username: dsmith Password for dsmith: Successfully logged into Galaxy as dsmith When you choose to use your username and password, your password is not sent to Galaxy. It is used to authenticates with GitHub and create a personal access token. It then sends the token to Galaxy, which in turn verifies that your identity and returns a Galaxy access token. After authentication completes the GitHub token is destroyed. If you do not wish to use your GitHub password, or if you have two-factor authentication enabled with GitHub, use the –github-token option to pass a personal access token that you create. The import command requires that you first authenticate using the login command. Once authenticated you can import any GitHub repository that you own or have been granted access. Use the following to import to role: $ ansible-galaxy import github_user github_repo By default the command will wait for Galaxy to complete the import process, displaying the results as the import progresses: Successfully submitted import request 41 Starting import 41: role_name=myrole repo=githubuser/ansible-role-repo ref= Retrieving GitHub repo githubuser/ansible-role-repo Accessing branch: master Parsing and validating meta/main.yml Parsing galaxy_tags Parsing platforms Adding dependencies Parsing and validating README.md Adding repo tags as role versions Import completed Status SUCCESS : warnings=0 errors=0. The delete command requires that you first authenticate using the login command. Once authenticated you can remove a role from the Galaxy web site. You are only allowed to remove roles where you have access to the repository in GitHub. Use the following to delete a role: $ ansible-galaxy delete github_user github_repo This only removes the role from Galaxy. It does not remove or alter the actual GitHub repository. You can create an integration or connection between a role in Galaxy and Travis. Once the connection is established, a build in Travis will automatically trigger an import in Galaxy, updating the search index with the latest information about the role. You create the integration using the setup command, but before an integration can be created, you must first authenticate using the login command; you will also need an account in Travis, and your Travis token. Once you’re ready, use the following command to create the integration: $ ansible-galaxy setup travis github_user github_repo xxx-travis-token-xxx The setup command requires your Travis token, however the token is not stored in Galaxy. It is used along with the GitHub username and repo to create a hash as described in the Travis documentation. The hash is stored in Galaxy and used to verify notifications received from Travis. The setup command enables Galaxy to respond to notifications. To configure Travis to run a build on your repository and send a notification, follow the Travis getting started guide. To instruct Travis to notify Galaxy when a build completes, add the following to your .travis.yml file: notifications: webhooks:
http://docs.ansible.com/ansible/latest/galaxy.html
CC-MAIN-2017-34
refinedweb
792
54.73
] Solution #2: Solution #3: In the project right click -> new -> module -> import jar/AAR package -> import select the jar file to import -> click ok -> done Follow the screenshots below: 1: 2: 3: You will see this: Solution #4: Solution #5: IIRC, simply using “Add as library” isn’t enough for it to compile with the project. Check Intellij’s help about adding libraries to a project The part that should interest you the most is this: (In File > Project Structure) Open the module settings and select the Dependencies tab. On the Dependencies tab, click add and select Library. In the Choose Libraries dialog, select one or more libraries and click Add Selected. If the library doesn’t show up in the dialog, add it in the Libraries settings, right below Modules. You shouldn’t need to add compile files() anymore, and the library should be properly added to your project. Solution #6: All these solutions are outdated. It’s really easy now in Android Studio: File > New Module… The next screen looks weird, like you are selecting some widget or something but keep it on the first picture and below scroll and find “Import JAR or .AAR Package” Then take Project Structure from File menu.Select app from the opened window then select dependencies ,then press green plus button ,select module dependency then select module you imported then press OK Solution #7: Easy steps to add external library in Android Studio - If you are in Android View in project explorer, change it to Project view as below - Right click the desired module where you would like to add the external library, then select New > Directroy and name it as ‘libs‘ - Now copy the blah_blah.jar into the ‘libs‘ folder - Right click the blah_blah.jar, Then select ‘Add as Library..‘. This will automatically add and entry in build.gradle as compile files(‘libs/blah_blah.jar’) and sync the gradle. And you are done Please Note : If you are using 3rd party libraries then it is better to use dependencies where Gradle script automatically downloads the JAR and the dependency JAR when gradle script run. Ex : compile ‘com.google.android.gms:play-services-ads:9.4.0’ Read more about Gradle Dependency Mangement Solution #8: ‘compile: I found Dependency Manager of Android Studio quite handy and powerful for managing 3rd party dependencies (like gson mentioned here). Providing step by step guide which worked for me (NOTE: These steps are tested for Android Studio 1.6 and onward versions on Windows platform). Step-1: Goto “Build > Edit Libraries and Dependencies…” it would open up the dialog “Project Structure” Step-2: Select “app” and then select “Dependencies” tab. Then select “Add > 1 Library dependency” Step-3: “Choose Library Dependency” dialog would be shown, specify “gson” in search and press the “search button” Step-4: The desired dependency would be shown in search list, select com.google.code.gson:gson:2.7 (this is the latest version at the time when I wrote the answer), press OK Press OK on “Project Structure” dialog. Gradle would update your build scripts accordingly. Hope this would help 🙂 Solution #12: 1. Put the jar (in my case, gson-2.2.4.jar) into the libs folder. 2. Ensure that compile files ( libs/gson-2.2.4.jar) is in your build.gradle file. 3. Now Click on the “Sync Project with Gradle files”(Left to AVD manager Button on the topbar). After I did the above three, it started working fine. Solution #13: Download & Copy Your .jar file in libs folder then adding these line to build.gradle: dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.google.code.gson:gson:2.3.1' } Do not forget to click “Sync now” Solution #14: You can do this with two options. first simple way. Copy the .jar file to clipboard then add it to libs folder. To see libs folder in the project, choose the project from combobox above the folders. then right click on the .jar file and click add as a library then choose a module then ok. You can see the .jar file in build.gradle file within dependencies block. dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.3' implementation project(':okhttp-2.0.0') implementation 'com.google.code.gson:gson:2.3.1' } Second way is that: We can add a .jar file to a module by importing this .jar file as a .jar module then add this module to any module we want. import module —> choose your .jar file –> than import as a .jar — Then CTRL+ALT+SHIFT+S –> project sturure –>choose the module you want ato add a jar –>Dependencendies –> Module Dependency. build.gradle of the module will updated automatically. Solution #15: Ive done above 3 steps and its work charm for me. (I am using Android Studio 2.1.2) Step 1 - Add your jar package name (as an example compile 'com.squareup.okhttp3:okhttp:3.3.1') into gradle build script under build.gradle(Module:app). Step 2: Right click on app folder -> New -> Module Step 3: Click Import JAR/.AAR Package Then browse your package. as an example: OkHttp.jar Solution #16: With Android Studio 3+: You should just be able to simply copy the jar file to the libs folder right under the app folder. … myprojectapplibsmy ‘com: Step 1 : Now under your app folder you should see libs, if you don’t see it, then create it . Step 2 : Drag & Drop the .jar file here, you may be get a prompt "This file does not belong to the project", just click OK Button . Step 3 : Now you should see the jar file under libs folder, right click on the jar file and select "Add as library", Click OK for prompt "Create Library" Step 4 : Now this jar has been added. Solution #21: Create a folder libs. Add your .jar file. Right click on it and you will find add jar as dependency. Click on it. Its all you need to do. You can find the dependencies added to your build.gradle file. Solution #22: 1) create an ‘your_libs’ folder inside the Project/app/src folder. 2) Copy your jar file into this ‘your_libs’ folder 3) In Android Studio, go to File -> Project Structure -> Dependencies -> Add -> File Dependency and navigate to your jar file, which should be under ‘src/your_libs’ 3) Select your jar file and click ‘Ok’ and then you can see on your build.gradle like this : compile files(‘src/your_libs/your.jar’) Solution #23: In android Studio 1.1.0 . I solved this question by following steps: 1: Put jar file into libs directory. (in Finder) 2: Open module settings , go to Dependencies ,at left-bottom corner there is a plus button. Click plus button then choose “File Dependency” .Here you can see you jar file. Select it and it’s resolved. Solution #24: Add the following: dependencies { compile 'com.android.support:appcompat-v7:19.+' compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.google.code.gson:gson:2.3' } This will allow support for two different ways of adding dependencies. The compile fileTree(dir: 'libs', include: ['*.jar'])(as @Binod mentioned) tells the compiler to look under the folder libs for ANY jar. It is a good practice to create such a folder ‘libs’ which will contain the jar packages that our application needs to use. But this will also allow support for Maven dependency. The compile 'com.google.code.gson:gson:2.3' (as mentioned by @saneryee) it is another recommended way to add dependencies that are in a central remote repository and not in our /libs “local repository”. It is basically telling gradle to look for that version of that package and it’s telling the compiler to consider it when compiling the project (having it in the classpath) PS: I use both Solution #27: Like many before pointed out you shall add compile files('libs/gson-2.2.3.jar') to your build.gradle file. However I have a project in Android Studio that was migrated from Eclipse and in this case the “libs” folder is named “lib” so for me removing the “s” solved the problem.. I observed CTRL + ALT + SHIFT + S –> project structure –> app-module –>Dependencies” already had an entry as (dir: 'libs', include: '*.jar') under compile-option, initially. And after adding the jar’s as per the steps stated above, the build.gradle got the entries for the new added jar’s, fileTree(include: ['*.jar'], dir: 'libs') Add the library jar to your libs folder -> right click the library -> click add as a library -> it asks you for the project to add it for -> select your project-> click ok The following line is automatically added to build.gradle implementation files('libs/android-query.jar') That did it for me. nothing more was required. i have shown this for android aquery another third party library for android.
https://techstalking.com/programming/question/solved-android-studio-add-jar-as-library/
CC-MAIN-2022-40
refinedweb
1,490
66.74
Spring MVC Login Form is a basic example for all spring based applications. We can hardly imagine any web application without forms in it, because forms has its own importance in web application develpment. In this tutorial, we are going to see how forms are used in Spring Framework, and how spring forms are different then normal HTML forms. Prerequisites for Spring MVC Login Form: As part of this tutorial, I am going to implement a simple Spring based Login Form. Though it is a simple login form, it requires more understanding about each and every newer things init. Spring offers different types of annotations to handling forms. Here are the typical annotations @Controller : - @Controller is an annotation, used in Spring MVC Framework. - @Controller annotation is a sub annotation of @Cmponent annotation. - We can use @Controller annotation on top of the class only. - It indicates that a particular class serves the role of controller in MVC parttern. - @Controller annotation acts as a stereotype for the annotated class, indicating its roles. @RequestMapping : - Like @Controller annotation, @RequestMapping annotation is also used in Spring MVC Framework. - @RequestMapping annotation can be applied on top of the class and/or methods, and it should be used along with the @Controller annotation. - It is used to bind a http request to spring components or handler methods. - Class level mapping binds a specific request to the Spring component (class), whereas method level mapping binds a specific request to a specific handler method. @ModelAttribute : - @ModelAttribute annotation can be used on top of a method or method arguments. - An @ModelAttribute on a method is used to populate the model with commonly needed attributes for example to fill a drop-down with states. - @ModelAttribute on method arguments refers a specific property in Model class (MVC). - Used to bind the data from form to controller - It should be used along with @RequestMapping in Controllers - @ModelAttribute is invoked before the actual controller method starts execution along with @RequestMapping Recommended: Spring with Hibernate Integration Complete Example Example for Spring MVC Login Form: Here we are going to implement Spring MVC Login form in step by step. Download Example : Spring MVC Login Form Example with STS (NEW) Project Structure: Follow below project structure to add described files below. <%@ page <html> <head> <meta http- <title>Spring Login Form</title> </head> <body> <form:form <div align="center"> <table> <tr> <td>User Name</td> <td><input type="text" name="userName" /></td> </tr> <tr> <td>Password</td> <td><input type="password" name="password" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" /></td> </tr> </table> <div style="color: red">${error}</div> </div> </form:form> </body> </html> Points To Note : - On the above login form, we used <form:form> tag. Which is given by the spring framework. To use this tag, we need to include the below taglib directory on top of the jsp page. <%@taglib uri=”” prefix=”form”%> - The main advantage of using the <form: form> is, spring automatically binds the form data to the model bean whenever we submit this form. To make it work, the properties in model class should be equal to the name of form data elements. - For instance, we have created a text box field with name userName and password field with the name password. The same names should be used as part of the Model class attributes. Create a Login Model : package com.spring.controller; public class LoginBean { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Recommended: Spring Boot MVC Login Form Example <="com.spring.controller" /> </beans:beans> Points To Note : - <annotation-driven />, informs Spring container that we are going to use annotations in this application and can be used to identify annotations and to perform respective functions. - Created a ViewResolver bean and mapped with the folder name where our actual views (jsp) are present as prefix and extension as suffix - Component scanning with <context:component-scan base-package=”com.spring.controller” />, is telling spring that it should search the classpath for all the classes under com.spring.controller and look at each class to see if it has a @Controller, or @Repository, or @Service, or @Component and if it does then Spring will register the class with the bean factory as if you had typed <bean class=”…” /> in the XML configuration files. Configure the web.xml File : <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns: <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> > Points To Note : - Define DispatcherServlet, that will act as front controller to route the requests Create a Spring Controller : package com.spring.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller public class LoginController { @RequestMapping(value = "/login", method = RequestMethod.GET) public String init(Model model) { model.addAttribute("msg", "Please Enter Your Login Details"); return "login"; } @RequestMapping(method = RequestMethod.POST) public String submit(Model model, @ModelAttribute("loginBean") LoginBean loginBean) { if (loginBean != null && loginBean.getUserName() != null & loginBean.getPassword() != null) { if (loginBean.getUserName().equals("chandra") && loginBean.getPassword().equals("chandra123")) { model.addAttribute("msg", loginBean.getUserName()); return "success"; } else { model.addAttribute("error", "Invalid Details"); return "login"; } } else { model.addAttribute("error", "Please enter Details"); return "login"; } } } Points To Note : We have created two handler methods - init This is a default handler method for HTTP GET requests. The RequestMapping url is “/login”. - submit This method is called whenever the form get submitted because the HTTP type for this method is POST. All the form elements are feeded into LoginBean object and we retrieve them using @ModelAttribute annotation Run It : To run this application, we can make use of the bellow URL. data-orig-src= alt=zip> Spring MVC Login Form Example with STS (NEW) good one..here in the example there is one user where he is logging and getting the result.my query is if there are multiple users and each users are having different permisions and with specified page.please share such examples. Hi Vishwanath, Thank you for your comment. Can you please explain your query in detail, so that I can help you better. Thankyou, Chandrashekhar Very well demonstrated by you Mr. Chandrashekhar… Nice to have it. 🙂 Hi Chandra…. Very good example for beginners to understand spring MVC…. but can you explain us how to connect it with data base like HSQLDB like that…. because working with data base is necessary in projects…. @Vishwanath I think you are wondering about the system which have users with multiple role types such as client, admin, superadmin for example. For such scenario you have to follow the same steps as Mr. Chandrashekhar has described, addition to that follow as, Step 1: Retrieve user roles from DB as per authentication from your DAO layer. Step 2: In Service layer, filter the return value for your view page based on the the user role you retrieved from DB for specific login credentials to your controller class. E.g. if(users.getUserRole.equals("amin")) { return "Admin"; } if(users.getUserRole.equals("client")) { return "Client"; } Step 3: And eventually, just return that same view name to ViewResolver which you received from Service layer. Step4; DONE… ViewResolver will properly navigate the user depending on its user type to its respective pages. Like Admin = Admin.jsp, Client= Client.jsp etc. Where all users will have their respective permissions to work in your system. i am getting Error-The request sent by the client was syntactically incorrect. why you added applicationcontext. xml in web.xml param name I just downloaded the “Spring MVC Login Form Example With Netbeans” example.In the project itself there was no pom.xml.But in your project structure I am seeing the pom.xml.Am i missing something here. Thank you for your help. Hi Tejeswar, Thanks for following us. The example you have downloaded “Spring MVC Login Form Example With Netbeans” was written based on Ant build. For maven you can download the latest one “Spring MVC Login Form Example with STS (NEW)”. It is completely implemented in maven. Please don’t hesitate to write comment us, if you find any problem. Thanks. can u please give example first register then login and then CRUD operation in single project When i submit page i got ” WARN : org.springframework.web.servlet.PageNotFound – Request method ‘POST’ not supported ” this exception and it shows “HTTP Status 405 – Request method ‘POST’ not supported” error at main page. Please explain exception .. Hey i am not finding source file for root-context.xml…. can please send the code .. I am doing project in Maven Very Well explained.. Thank you @chandrashekhar I want login and registration example with spring +hibernate in with explanation… Your explaining way is very impressed me if possible please send fastly Hi, I am new to Spring. I understood the .files which is explained in above post.But I need what are the software requirements and how to add these files in a project. Please need an explanation in Eclipse. I am getting an error HTTP status 405 “Request method ‘GET’ not supported”. Why i’m getting this? I am getting an error HTTP status 405 “Request method ‘GET’ not supported” can anyone explain why? Hi ! I just had a look at the demo. I have an inventory app developed in spring mvc and security. it takes ages to load login p[age and navigate to other functionalities. I have googled many a times bt there is no conclusive answere I am also getting an error HTTP status 405 “Request method ‘GET’ not supported” can anyone help me please. nice tutorial what i have to do to handle the session Hello Sir,….Your tutorial is really Good…. But Netbeans project size is 0 bytes…Please share the login form using netbeans zip file to my email… I am also getting an error HTTP status 405 “Request method ‘GET’ not supported” hello did u solve the problem of getting an error HTTP status 405 “Request method ‘GET’ not supported” ??i m using eclipse Hi, Nice tutorial.
https://www.onlinetutorialspoint.com/spring/spring-mvc-login-form-example.html
CC-MAIN-2020-29
refinedweb
1,719
57.16
From our sponsor: Grow with Mailchimp's All-in-One Marketing Platform There are many ways of displaying text inside a Three.js application: drawing text to a canvas and use it as a texture, importing a 3D model of a text, creating text geometry, and using bitmap fonts — or BMFonts. This last one has a bunch of helpful properties on how to render text into a scene. Text in WebGL opens many possibilities to create amazing things on the web. A great example is Sorry, Not Sorry by awesome folks at Resn or this refraction experiment by Jesper Vos. Let’s use Three.js with three-bmfont-text to create text in 3D and give it a nice look using shaders. Three-bmfont-text is a tool created by Matt DesLauriers and Jam3 that renders BMFont files in Three.js, allowing to batch glyphs into a single geometry. It also supports things like word-wrapping, kerning, and msdf — please watch Zach Tellman’s talk on distance fields, he explains it very good. With all that said, let’s begin. Getting started Before everything, we need to load a font file to create a geometry three-bmfont-text provides packed with bitmap glyphs. Then, we load a texture atlas of the font which is a collection of all characters inside a single image. After loading is done, we’ll pass the geometry and material to a function that will initialize a Three.js setup. To generate these files check out this repository. const createGeometry = require('three-bmfont-text'); const loadFont = require('load-bmfont'); loadFont('fonts/Lato.fnt', (err, font) => { // Create a geometry of packed bitmap glyphs const geometry = createGeometry({ font, text: 'OCEAN' }); // Load texture containing font glyphs const loader = new THREE.TextureLoader(); loader.load('fonts/Lato.png', (texture) => { // Start and animate renderer init(geometry, texture); animate(); }); }); Creating the text mesh It’s time to create the mesh with the msdf shader three-bmfont-text comes with. This module has a default vertex and fragment shader that forms sharp text. We’ll change them later to produce a wavy effect. const MSDFShader = require('three-bmfont-text/shaders/msdf'); function init(geometry, texture) { // Create material with msdf shader from three-bmfont-text const material = new THREE.RawShaderMaterial(MSDFShader({ map: texture, color: 0x000000, // We'll remove it later when defining the fragment shader side: THREE.DoubleSide, transparent: true, negate: false, })); // Create mesh of text const mesh = new THREE.Mesh(geometry, material); mesh.position.set(-80, 0, 0); // Move according to text size mesh.rotation.set(Math.PI, 0, 0); // Spin to face correctly scene.add(mesh); } And now the text should appear on screen. Cool, right? You can zoom and rotate with the mouse to see how crisp the text is. Let’s make it more interesting in the next step. GLSL Vertex shader To oscillate the text, trigonometry is our best friend. We want to make a sinusoidal movement along the Y and Z axis — up and down, inside and outside the screen. A vertex shader fits the bill for this since it handles the position of the vertices of the mesh. But before this, let’s add the shaders to the material and create a time uniform that will fuel them. function init(geometry, texture) { // Create material with msdf shader from three-bmfont-text const material = new THREE.RawShaderMaterial(MSDFShader({ vertexShader, fragmentShader, map: texture, side: THREE.DoubleSide, transparent: true, negate: false, })); // Create time uniform from default uniforms object material.uniforms.time = { type: 'f', value: 0.0 }; } function animate() { requestAnimationFrame(animate); render(); } function render() { // Update time uniform each frame mesh.material.uniforms.time.value = this.clock.getElapsedTime(); mesh.material.uniformsNeedUpdate = true; renderer.render(scene, camera); } Then we’ll pass it to the vertex shader: // Variable qualifiers that come with the msdf shader attribute vec2 uv; attribute vec4 position; uniform mat4 projectionMatrix; uniform mat4 modelViewMatrix; varying vec2 vUv; // We passed this one uniform float time; void main() { vUv = uv; vec3 p = vec3(position.x, position.y, position.z); float frequency1 = 0.035; float amplitude1 = 20.0; float frequency2 = 0.025; float amplitude2 = 70.0; // Oscillate vertices up/down p.y += (sin(p.x * frequency1 + time) * 0.5 + 0.5) * amplitude1; // Oscillate vertices inside/outside p.z += (sin(p.x * frequency2 + time) * 0.5 + 0.5) * amplitude2; gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0); } Frequency and amplitude are properties of a wave that determine their quantity and their “height”. Because we are using a sine wave to move the vertices, these properties can help control the behavior of the wave. I encourage you to tweak the values to observe different results. Okay, so here is the tidal movement: Fragment shader For the fragment shader, I thought about just interpolating between two shades of blue – a light and a dark one. Simple as that. The built-in GLSL function mix helps interpolating between two values. We can use it along with a cosine function mapped from 1 to 0, so it can go back and forth these values and change the color of the text — a value of 1 will give a dark blue and 0 a light blue, interpolating the colors between. #ifdef GL_OES_standard_derivatives #extension GL_OES_standard_derivatives : enable #endif // Variable qualifiers that come with the shader precision highp float; uniform float opacity; uniform vec3 color; uniform sampler2D map; varying vec2 vUv; // We passed this one uniform float time; // HSL to RGB color conversion module #pragma glslify: hsl2rgb = require(glsl-hsl2rgb) float median(float r, float g, float b) { return max(min(r, g), min(max(r, g), b)); } void main() { // This is the code that comes to produce msdf vec3 sample = texture2D(map, vUv).rgb; float sigDist = median(sample.r, sample.g, sample.b) - 0.5; float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0); // Colors vec3 lightBlue = hsl2rgb(202.0 / 360.0, 1.0, 0.5); vec3 navyBlue = hsl2rgb(238.0 / 360.0, 0.47, 0.31); // Goes from 1.0 to 0.0 and vice versa float t = cos(time) * 0.5 + 0.5; // Interpolate from light to navy blue vec3 newColor = mix(lightBlue, navyBlue, t); gl_FragColor = vec4(newColor, alpha * opacity); if (gl_FragColor.a < 0.0001) discard; } And here it is! The final result: Other examples There is plenty of stuff one can do with three-bmfont-text. You can make words fall: Enter and leave: Distortion: Water blend: Or mess with noise: I encourage you to explore more to create something that gets you excited, and please share it with me via twitter or email. You can reach me there, too if you got any questions, or comment below. Hope you learned something new. Cheers! Really(!) cool! Thank you for sharing! Anytime! Glad you liked it 🙂
https://tympanus.net/codrops/2019/10/10/create-text-in-three-js-with-three-bmfont-text/
CC-MAIN-2020-05
refinedweb
1,117
57.77
- Training Library - DevOps - Courses - Kubernetes Patterns for Application Developers Networking Kubernetes has several concepts relevant to networking. As an application developer, you should know about the concepts and how they can be used to securely provide access to applications running in a cluster. This lesson will begin by reviewing the basic networking model employed by Kubernetes. Then we will discuss more about services. The Networking Basics and Services topics are also covered in other content here on Cloud Academy so we will only review the key concepts of each. After, we will discuss Kubernetes network policies for controlling traffic that is allowed to and from pods. The basic building block in Kubernetes is a pod. The network model for a pod is IP per pod meaning each pod is assigned one unique IP in the cluster. Containers in the pod share the same IP address and can communicate with each other's ports using localhost. A pod is of course scheduled onto a node in the cluster. Any node can reach the pod by using its pod IP address. Other pods in the cluster can also reach the pod using the pod's IP address. This is thanks to whatever Kubernetes networking plugin you choose. The network plugin implements the container network interface standard and enables pod-to-pod communication. But pods should be seen as ephemeral. They can be killed and restarted with a different IP. You may also have multiple replicas of a pod running. You can't rely on a single pod IP to get the benefits of replication. This is where services come in. The service maintains a logical set of pod replicas. Usually these sets of pods are identified with labels. The diagram only includes one replica but there could be many spread over many nodes. The service maintains a list of endpoints as pods are added and removed from the set. The service can send requests to any of the pods in the set. Clients of the service now only need to know about the service rather than specific pods. Pods can discover services using environment variables as long as the pod was created after the service, or by using the DNS add-on in a cluster. The DNS can resolve the service name or the namespace qualified service name to the IP associated with the service. The IP given to a service is called the cluster IP. Cluster IP is the most basic type of service. The cluster IP is only reachable from within the cluster. The kube-proxy cluster component that runs on each node is responsible for proxying requests for the service to one of the service's endpoints. The other types of services allow clients outside of the cluster to connect to the service. The first of those types of services is node port. Node port causes a given port to be opened on every node in the cluster. The cluster IP is still given to the service. Any requests to the node port of any node are routed to the cluster IP. The next type of service that allows external access is load balancer. The load balancer type exposes the service externally through a cloud provider's load balancer. A load balancer type also creates a cluster IP and a node port for the service. Requests to the load balancer are sent to the node port and routed to the cluster IP. Different features of cloud provider load balancers, such as connection draining and health checks, are configured using annotations on a load balancer. The final type of service is the external name and it is different in that it is enabled by DNS, not proxying. You configure an external name service with the DNS name and requests for the service return a CNAME record with the external DNS name. This can be used for services running outside of Kubernetes, such as a database as a service offering. Network policies in Kubernetes are rules that determine which group of pods are allowed to communicate with each other and to other network endpoints. Network policies are similar to simple firewalls or security groups that control access to virtual machines running in a cloud. Network policies are namespace resources meaning that you can configure network policies independently for each Kubernetes namespace. Before we get into the details there is an important caveat when it comes to network policies. The container network plugin running in your cluster must support network policies to get any of their benefits. Otherwise, you will create network policies and there won't be anything to enforce them. In the worse case, you might think that you have secured access to an application but the pods are actually still open to request from anywhere. There won't be any error messages when you create the policy. It will be created successfully but we'll simply have no effect. The cluster administrator can tell you if the network plugin in your cluster supports network policy or not. Some examples of network plugins that support network policy are Calico and Romana. With that caveat out of the way, we can talk about two kinds of pods, isolated and non-isolated. A pod that is non-isolated allows traffic from any source. This is the default behavior. Once a pod is selected by a network policy it becomes isolated. The pods are selected using labels, which are the core grouping primitive in Kubernetes. Let's see how to use network policies in a demo by writing several network policies and observing their effects. To begin with, I am running a cluster with the Calico network plugin installed. You can see that by checking the pods in the kube-system namespace, and observe there're several pods beginning with calico. Calico is one of the network plugins that support network policy. I have created three pods in the network policy namespace. One is a server and the other two are clients that send requests to the server every second. Client one is in the U.S. East region, while client two is in the U.S. West region. Both clients are able to send requests and get responses from the server. This can be seen by watching the logs of each client. I use the -f option to follow or stream the logs for each pod. New logs are generated every second acknowledging response was received from the server. Let's take a look at our first policy. Working our way down from the top, network policies are included in the networking API. This policy is made to allow traffic from the U.S. East region and is scoped to the network policy namespace. In the spec, first there is a pod selector that selects the pods that the policy applies to. Here we are using the match labels selector to select any pod with the app server label. This applies to the single server pod that is running in the cluster. If the pod selector were empty the policy would apply to all pods in the namespace. Next is the policy types list. The two allowed values are ingress to indicate the policy applies to incoming traffic, and egress to indicate the policy applies to outgoing traffic. You can include one or the other, or both as in this case. If, for example, you only included egress, then all ingress traffic would be allowed by the policy. Corresponding to the ingress policy type is the ingress list, which specifies rules for where the traffic is allowed. Each rule includes a from list specifying sources and a ports list specifying allowed ports. If the from list is omitted, all sources of traffic are allowed on the specified ports. If the ports list is omitted, traffic on all ports is allowed from the specified sources. If both are omitted, all traffic on all ports is allowed. Source rules can be made of pod selectors to select traffic based on pod labels, namespace selectors to select based on the namespace of pods or IP block to select based on a range of IP addresses. This policy uses a pod selector to allow ingress traffic from pods with the us-east region label. Each item in the ports list can restrict the allowed traffic to a given port and protocol. In this example, TCP port 8888 is allowed because that is the port the server listens to. The egress mapping includes a "to" map that lists rules in the same format as the ingress rules. In this case, no rules are specified so all outbound traffic is allowed. Let's create the policy and then check to verify that client one in the U.S. East region is allowed to communicate with the server. And it is because responses are still being received. What if we check client two, which is in the U.S. West region? There're no new log messages being received. The policy is doing its job. Besides doing some basic tests like this, you can always use the describe command to check that the policy is doing what you expect. It outputs a description of the policy in a relatively easy to understand format. Now let's look at one more policy to see how IP block rules are configured. This policy is constructed to block outgoing traffic to a single IP address from app server pods. This policy is an egress-only policy so there is no ingress included in the policy types list. The egress list has a single IP block rule. There're two parts to the rule. The cidr field is required and sets a range of allowed IP addresses. Cidr is a notation for representing a block of IP addresses. 0.0.0.0/0 represents all IP addresses. If that was the complete rule all outgoing traffic would be allowed. However, there is an except list. The except field is optional but when included, it acts as a blacklist within the white list that the cidr field specifies. In this case, there's a single exception which represents one IP address. That IP address happens to be the IP address of the client one pod. This is for demonstration purposes only. In general, you should use labels when selecting pods in your cluster because pods should be treated as ephemeral. They can be terminated and brought up again with a different IP address, or as labels remain the same. No port list is specified so all ports are allowed. Let's go ahead and create the policy. Now there're two policies being enforced. One allows incoming traffic from the U.S. East region, which allows client one traffic in the current cluster. And the second policy denies outgoing traffic from the server to client one. Think about what you might expect to observe. Will either client pod receive responses from the server? Let's check. Client two still doesn't receive responses. What about client one? It is still receiving responses. That may come as a surprise. We never discussed how policies are combined. For network policies you should think of them as sets of allow rules that are added together. If any rule allows traffic, even if others deny it, the traffic is allowed. In this case, the default allow egress rule and the first policy allows all egress, even though the second policy has blacklisted a specific IP. So to see the effect of the IP block rule, we can delete the first policy with the default allow egress rule. Now, if we check the logs for client one, which is not allow egress according to the policy that is being enforced, it is still able to receive responses. What is happening now? The rules apply to new connections. In the case of a client sending a request to the server, the connection is already in place and the response is sent back through the same existing connection. There is no new connection so the network policy can't block the egress. However, if we create a connection from the server, say by running the ping command, to ping the client one pod, we can see that there is no response. Contrast that with client two which we can see that we get a response. To have a clear picture of how network policies work, it is important to remember how multiple policies are combined and that the rules apply to creating connections, not traffic sent over established connections. That's all for this lesson on Kubernetes networking. We began with a review of basic networking principles. Then we paid some extra attention to the different types of services available in Kubernetes. Lastly, we discussed network policies and how they can restrict traffic that is allowed to and from pods. In the next lesson, you will continue with the theme of security in Kubernetes and learn about service accounts. Start the next lesson when you are ready..
https://cloudacademy.com/course/kubernetes-patterns-for-application-developers/networking/
CC-MAIN-2020-24
refinedweb
2,176
65.52
View Full Document This preview has intentionally blurred sections. Unformatted text preview: Chapter 20 Hybrid Financing: Preferred Stock, Warrants, and Convertibles ANSWERS TO BEGINNING-OF-CHAPTER QUESTIONS 20-1 Both companies and investors have different preferences regarding risks, maturities, and so forth. Companies offer different types of securities in order to get the features they like and also to provide features that investors desire so as to minimize the cost of funds. 20-2 Preferred dividends are not normally deductible by the issuing corporation, so they have a higher after-tax cost than debt. Companies normally plan to pay dividends on preferred stocks, and investors expect to collect them. However, the non-payment of preferred cannot throw a firm into bankruptcy, whereas failure pay interest on debt does lead to bankruptcy. Therefore, preferred is riskier than debt to investors, but less risky to the issuer, and preferred provides only a fixed return (except that some preferred stock has, in effect, a floating dividend rate). Corporate investors can exclude 70% of preferred dividends from taxable income, so for such investors preferred stock provides a relatively high after-tax rate of return. Also, preferred stocks can be made convertible. Today, non-convertible preferred stock is not used very often, and when it is, it is typically has a floating rate and is bought by corporate investors or money market funds. 20-3 A warrant is a long-term option to purchase a share of common stock. Generally, warrants are issued with bonds and serve as “sweeteners” to induce investors to buy the bonds. Because of the possibility of profits from the warrant, investors will buy the bond at a coupon rate that is below the rate on straight debt of comparable risk and maturity. The terms on a bond-with-warrants would be set such that the expected rate of return on the package is somewhat above the straight debt interest rate but below the required return on the common stock. The bond would produce a stream of cash flows from the coupons and eventually the maturity value. The warrants would produce an expected cash flow in Year N equal to: Number of warrants * (P (1+g) N- P exercise ). We could find the IRR of this cash flow stream, and it would be the expected rate of return on the bonds-plus-warrants package. This IRR should be between r d and r s , and the investment bankers could “tinker” with the coupon rate, the number of warrants offered, the exercise price, and the life of the warrants to increase or decrease the IRR and make the offering sufficiently attractive to induce investors to buy the issue. See the tab labeled “Warrants” on the BOC model for an illustration. Answers and Solutions: 20- 1 20-4 A convertible is a bond or preferred stock that can be converted into common stock of the issuing company at the holder’s option. The bond will specify a coupon rate, maturity, call protection period, and number of shares to be received upon conversion. Investors will expect the stock to grow at some rate, and they can use that growth rate to forecast... View Full Document - Summer '12 - Picou - Corporate Finance, Dividend Click to edit the document details
https://www.coursehero.com/file/6864438/Chapter20/
CC-MAIN-2017-51
refinedweb
543
56.69
In my previous blog post Writing a Custom Cypress Command I have shown a simple custom Cypress custom command for finding a form element by its label. In this blog post I will show how to correctly publish this custom command to the NPM registry. - The command - Continuous integration - Command source refactoring - Publishing to NPM - Better registration - Using an example - Types - ES6 import and export - Examples 🔎 You can find the source code for this blog post in bahmutov/cypress-get-by-label repo. The command I usually start by developing the code in-place and writing the custom command in the spec file. Given an HTML file: The following spec file tests the custom command The spec passes. Continuous integration As soon as we have the first test, I set up continuous integration pipeline. I can pick amongst various CI providers, but perhaps GitHub Actions is the simplest to set up right now. We can run Cypress via cypress-io/github-action with ease: The test passes on CI. Command source refactoring Now let's refactor our command to be usable from any spec. Our users should be able to register the custom command in a particular spec or in all specs by importing the command from their support file. Let's move the command source code into its own file src/index.js The spec file requires the src/index.js file Great, but when we distribute this NPM package, our users will require it by name. Thus instead of require('../../src/index') let's require the top level package folder. We can set the main field to point at the src/index in our package.json file. While we are there, let's set the list of files to be published to NPM, our users only will need the src folder. Time to publish! Publishing to NPM Let's verify the files we are about to publish to NPM So we are going to include three files in the distributable archive: the README file, the package.json, and src/index.js. Seems right. As always I will use semantic-release following How I publish to NPM approach. Since GitHub Actions will have GH token set, we can grab a new NPM token using the command: Set the NPM_TOKEN as a secret when running the GitHub Action To do semantic release, I like using cycjimmy/semantic-release-action. The ci.yml file is now: In order to actually release, let's update our README file. We need to explain how to use this package and commit with a feature or fix release. The GitHub action runs and publishes "cypress-get-by-label v1.0.0", which we can find at. Better registration Currently we have published our command that registers itself immediately whenever some runs require('cypress-get-by-label') code. What if we want to customize the custom command? What if we want to register it under a different name? It makes sense to export a registration function, instead of immediately modifying the global state by running Cypress.Commands.add('getByLabel', ...) function. Let's modify our package. Let's update our spec file to test this: The commands work, notice both "getByLabel" and "getFormField" log messages. Because we have changed the public API of our package, we have to publish this change as a breaking change. Since we use the semantic versioning that analyzes the commit messages, we can simply do: Semantic release publishes v2 Oops, we forgot to update the README when we published the new release. ## use Include from your Cypress support file or individual spec const { registerCommand } = require('cypress-get-by-label') registerCommand() // or we could register under a different name registerCommand('getFormField') Then use the command `cy.getByLabel` (default) or the custom name // if used registerCommand() cy.getByLabel('First name:') // if used registerCommand('getFormField') cy.getFormField('First name:') We should commit this change with fix: ... prefix. For example Which publishes v2.0.1 of the package. Using an example At this point I like creating a separate repo to show the custom command in action and to verify everything works when a user tries to install and use cypress-use-by-label. You can find my example in the repo bahmutov/cypress-get-by-label-example. When installing the new package, I recommend following the README file, just to "test" the installation instructions. In the spec file (I have copied the spec and example from cypress-get-by-label) I will use the name of the package. The example works. We can set up the CI, RenovateBot, and even self-updating README badges to keep this example repo up-to-date. I then link the new repo from the cypress-get-by-label README file Types When the user uses the cy.getByLabel command, there is no IntelliSense information, unlike cy.visit and other built-in Cypress commands. Note: we are only going to provide type for the default cy.getByLabel command, and we also assume command has been registered by the user's test code. If the user uses a different command name, they could write a similar typescript file locally. Let's follow Cypress TypeScript guide and add src/index.d.ts file Now we need to point at this types file from other specs and distribute this file with the source code. Types in the project To tell your specs about your new custom command, instead of loading the reference types="cypress" from the spec file. Notice how we switched from loading types from node_modules/cypress folder to a relative path using reference path=.... Types for other projects In order to describe the types for the default cy.getByLabel command we need to include types file with our NPM package. In the package.json file add the "types" field pointing at the src/index.d.ts file Publish the new version of the package - it is a new feature, so it becomes v2.1.0, and the example project should use the types by loading them like this: ES6 import and export If we register the custom command, and try to avoid modifying the global state using require, we might as well declare our registration function using the ES6 export keyword. The cypress-get-by-label project still works like before. Let's publish our change, it becomes v2.2.0. Let's upgrade cypress-get-by-label-example to use v2.2.0 - all working the same. The top-level export keyword did not affect the project. We can also replace the require with import keyword in the user project Even if we refactor the internals of cypress-get-by-label to use import and export keywords, the user package should be able to bundle them correctly using Cypress v6+. Examples You can find example Cypress commands in the following modules:
https://glebbahmutov.com/blog/publishing-cypress-command/
CC-MAIN-2022-05
refinedweb
1,141
56.25
Up to [cvs.netbsd.org] / pkgsrc / devel / allegro Request diff between arbitrary revisions Default branch: MAIN Revision 1.20 / (download) - annotate - [select for diffs], Mon Feb 20 15:39:37 2012 UTC (3 months ago) by reinoud Branch: MAIN CVS Tags: pkgsrc-2012Q1-base, pkgsrc-2012Q1, HEAD Changes since 1.19: +7 -11 lines Diff to previous 1.19 (colored) Bump devel/allegro to version 4.2.2 from pkgsrc-wip. Revision 1.19 / (download) - annotate - [select for diffs], Sat Aug 20 15:28:09 2011 UTC (9 months ago) by joerg Branch: MAIN CVS Tags: pkgsrc-2011Q4-base, pkgsrc-2011Q4, pkgsrc-2011Q3-base, pkgsrc-2011Q3 Changes since 1.18: +2 -1 lines Diff to previous 1.18 (colored) Deal with C99 vs GNU89 inline semantic Revision 1.18 / (download) - annotate - [select for diffs], Sat Sep 18 08:02:29 2010 UTC (20 months ago) by obache Branch: MAIN CVS Tags:.17: +2 -2 lines Diff to previous 1.17 (colored) replace spaces with tabs for recent gmake. Revision 1.17 / (download) - annotate - [select for diffs], Wed Feb 20 10:04:24 2008 UTC (4 years, 3 months ago) by rill.16: +2 -1 lines Diff to previous 1.16 (colored) Don't install the library stripped when the pkgsrc user says INSTALL_UNSTRIPPED=yes. Revision 1.16 / (download) - annotate - [select for diffs], Thu Nov 29 22:45:23 2007 UTC (4 years, 5 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2007Q4-base, pkgsrc-2007Q4 Changes since 1.15: +5 -6 lines Diff to previous 1.15 (colored) Update to 4.2.2: ===================================================================== ============ Changes from 4.2.2 RC1 to 4.2.2 (July 2007) ============ ===================================================================== Matthew Leverton added build instructions for DMC and updated the MSVC project files and instructions. Matthew Leverton added a shell script wrapper around gcc to build universal binaries (i386 + PPC) on Mac OS X and made the Allegro makefile use it. Peter Hull reenabled the Quit menu option on Mac OS X when set_close_button_callback is used. Rikard Peterson fixed the Mac OS X joystick driver so that HID_ELEMENT_STANDALONE_AXIS axes correctly got the flag JOYFLAG_UNSIGNED and not JOYFLAG_DIGITAL. Matthew Leverton fixed a problem with the GDI driver blitting a rectangle smaller than the bitmap's height that touches the bottom left corner of a bitmap. Some minor changes. ===================================================================== ============ Changes from 4.2.1 to 4.2.2 RC1 (July 2007) ============ ===================================================================== Matthew Leverton added project files for MSVC 6/7/8 (see the build directory and Allegro Wiki for instructions). Matthew Leverton added initial support for the Digital Mars C compiler (for the Windows port). It only works with the C-only port and obj\dmc\plugins.h needs to be built by hand. Peter Wang cleaned up most of the autoconf namespace pollution. Matthew Smith made a fix for C locking code in GDI. Trent Gamblin made the fullscreen DirectX driver save and restore the palette when switching away and back in 8-bit video modes. Elias Pschernig added missing documentation for pack_ungetc(). Trent Gamblin fixed the C version of stretch_blit so it now draws correctly. He also made it about 20% faster along the way. orz and Matthew Leverton made the ALLEGRO_USE_C=1 option to work under MinGW and MSVC. Erno Schwetter fixed a long-standing bug in polygon() where the bottom-most pixels would not be drawn. Anthony 'Timorg' Cassidy made d_menu_proc fill up its assigned area with the gui_bg_color. Phil Krylov fixed a bug that prevented load_bios_font() from loading 8x16 fonts. Etienne Vouga fixed a bug with the reset_controllers MIDI command. Milan Mimica fixed a double SWITCH_IN event callback bug when de-minimizing an Allegro program in Windows. Erno Schwetter fixed a bug where __al_linux_console_fd was used in display_switch_lock() without the console being initialized first. Erno Schwetter fixed an unbalanced __al_linux_console_graphics() call. Ryan Patterson fixed a crash in free_config_entries. Elias Pschernig added support for horizontal wheel mice (so far, only the X11 driver reports any horizontal wheel movement though). Also increased the number of supported mouse buttons from 3 to 5 for the X11 driver. Jon Rafkind and Karthik Kumar fixed a problem where allegro-config would respect neither --libdir nor --includedir. Peter Wang fixed some problems with the ALSA MIDI driver in the case of failure. torhu fixed a bug in akaitest where an array was indexed with -1. Trent Gamblin implemented set_mouse_speed under X11. Peter Wang made setting stick only while the cursor is in the Allegro window. Evert Glebbeek added desktop_color_depth and get_desktop_resolution to the Linux fbcon driver. Matthew Leverton fixed building of universal binaries on MacOS X. This currently requires OS X 10.4 on both PPC and Intel. Milan Miminca made the fbcon driver initialization fail if an unsupported color depth was set. Michal Molhanec and Milan Mimica simplified the MSVC build process and updated the documentation. Andrei Ellman made the MSVC makefile compatible with cygwin port of make-3.81 (and newer?). makefile.vc now uses cygpath tool to convert DOS 8.3 paths to unix-style paths. Daniel Schlyder added a functions is_trans_font, font_has_alpha. Daniel Schlyder made load_txt_font() additionally search for files referenced in the font script in the same directory as the script itself. It still searches in the current working directory first (for relative paths). Daniel Schlyder documented that register_assert_handler() and register_trace_handler() can be called before initialising Allegro. Daniel Schlyder prevented the Windows port from registering its default trace handler on initialisation if the user had previously registered a custom trace handler. Andrei Ellman modified the 6-to-8 bit value scaling tables to be more evenly distributed, and changed the implementation of create_blender_table() to create a more evenly distributed distribution of the lower 2 bits. It should be faster as well. Other minor bug fixes and documentation updates. Revision 1.15 / (download) - annotate - [select for diffs], Thu Mar 15 22:38:55 2007 UTC (5 years, 2 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2007Q3-base, pkgsrc-2007Q3, pkgsrc-2007Q2-base, pkgsrc-2007Q2, pkgsrc-2007Q1-base, pkgsrc-2007Q1 Changes since 1.14: +6 -7 lines Diff to previous 1.14 (colored) Update to 4.2.1: ========================================================================= ============ Changes from 4.2.1 RC1 to 4.2.1 (November 2006) ============ ========================================================================= Peter Wang made the Unix ports query the memory page size with sysconf() when necessary, instead of using the PAGE_SIZE constant, which seems to be Linux-specific. Matthew Leverton gave the STATICRUNTIME builds of MSVC new names by appending _crt (c run time) to the libraries. He also fixed the problem of incorrectly setting the EMBED_MANIFEST variable when using the STATICRUNTIME. Andrei Ellman fixed an inverted test in pack_fopen_chunk on Windows. Peter Hull made 32-bit icon generation by fixbundle endian-independent (colours were incorrect on Intel Macs). Peter Wang fixed a long standing bug where some compressed packfiles would not be read back properly (premature EOF). Reported by jman2050. Andrei Ellman spotted a free() of an internal buffer returned by tmpnam(). Peter Hull fixed a problem with mouse-related deadlock on MacOS X as reported by Mike Farrell. Peter Hull implemented simulation of video bitmaps on MacOS X, so that page flipping will work. Peter Hull fixed an endian problem in the digital sound driver on MacOS X. Elias Pschernig and Chris Robinson fixed problems with UTF-8 filenames under Unix, as reported by Grzegorz. Non-ASCII non-UTF-8 filenames remain broken. Chris Robinson fixed some problems with non-ASCII filenames under Windows. Elias Pschernig made the X11 driver call XInitThreads, to make Mesa-OpenGL work together with Allegro. It can be disabled at runtime through a config variable. Andrei Ellman fixed a bug in datedit.c that could crash the grabber. Elias Pschernig added file_size_ex(), which returns a 64 bit integer to handle large files. Ron Novy made improvements to the test program. Peter Hull fixed problems with set_mouse_sprite() on Intel Macs. Peter Hull added universal binary support to the MacOS X port. Peter Wang and Evert Glebbeek independently fixed a problem with dependency generation for MacOS X on non-Mac systems. Many smaller fixes and updates by Peter Hull, Elias Pschernig, Peter Wang and Milan Mimica. ==================================================================== ============ Changes from 4.2.0 to 4.2.1 RC1 (May 2006) ============ ==================================================================== Michal Molhanec made msvchelp.exe work on Cygwin, where there was a problem with the case-insensitivity of environment variables. Reported by Milan Mimica. Peter Hull fixed a bug where Allegro detected keypresses on KEY_MINUS_PAD as KEY_PLUS_PAD. Peter Hull made OSX work correctly with Logitech sticks, as discussed with Ultio. Milan Mimica fixed some spin loops in the test program. Chris Robinson added UTF8/Unicode support for filenames in Windows. Milan Mimica made the Linux console driver more robust: set_gfx_mode used to get stuck in a infinite loop when there wasn't a console available. Evert Glebbeek made the C blitter use memmove for normal blits, with a bugfix by Milan Mimica. This can be disabled by removing a #define USE_MEMMOVE at the top of cblit.h so that it can easliy be tested against the older versions of the code. Christer Sandberg worked around a problem where one-line high bitmaps would crash with Electric Fence. Chris Robinson fixed a crash that occurred if the sound mixer quality level was set to 0 after the mixer was already initialised. Evert Glebbeek fixed the window title under X11, which was broken by a previous change. Peter Hull updated the endian detection under OSX as recommended by Apple. Miguel A. Gavidia and Jay Bernardo made qtmidi.m work on both PPC and Intel. Milan Mimica fixed a crash when vsync() on certain drivers. Elias Pschernig replaced the ALLEGRO_USE_C define with ALLEGRO_NO_ASM. Peter Wang restored the JACK driver to compiling state. Milan Mimica made the new transparent fonts be recognized as color fonts with is_color_font. Elias Pschernig made the modules path WIP version specific, for enhanced binary compatibility. Stijn Wolters clarified the documentation of init_dialog. Hans de Goede fixed a problem with dynamically generated stretcher code not being properly marked as executable on Linux (esp. SELinux). Hans de Goede fixed a busy wait in the X11 vsync simulation. Elias Pschernig makde it so modules under Unix are now searched in libdir as passed by the build machinery. Closes bug #1401840 from SF, reported by Paul Eipper. Milan Mimica added a get_volume and a get_hardware_volume function, to work as pendants to set_volume and set_hardware_volume. Milan Mimica corrected a case where a wrong structure on the stack was being cleared in the DirectSound input driver. Hans de Goede added a fullscreen driver for X11 which does not need XVidMode extension, and instead simply centers the window on the desktop and draws a black border around. Hans de Goede fixed a problem where switching to fullscreen mode under X11. Serge Semashko added Enter as a fire key in the demo game. Serge Semashko added fixed problems with Allegro working on Nokia 770. Peter Wang fixed some problems with binary compatibility checking in the 4.2 branch. Catatonic Porpoise added OpenBSD detection (in addition to FreeBSD and NetBSD) and fixed an issue with executable rights not set on the memory for the i386 stretcher on UNIX systems. Hans de Goede fixed a bug preventing the ALSA driver to work on big endian systems. Elias Pschernig and Chris Robinson fixed binary compatibility checking in allegro_init and install_allegro. Catatonic Porpoise fixed the example in the documentation of stretch_sprite. Hans de Goede made DIGMID work with absolute paths in the patches.cfg file. Peter Hull added code to make Allegro work better with user-supplied Nibs under OSX, as discussed with Thomas Harte. Matthew Leverton added embedding of manifests to the MSVC 8 build process. Neil Walker and Thomas Harte implemented a hardware accelerated stretch_blit() for the Windows DX port. Evert Glebbeek corrected a bug when destroying sub-bitmaps under Windows. Evert Glebbeek fixed a bug in pack_fopen_chunk() where a temporary file would be created in a non-writable location. Peter Wang changed a "/lib" option to MSVC's link utility to "-lib" as reported to be problematic by Karthik Kumar. Peter Wang fixed a crash in dat and grabber due to the return value of pack_fopen_chunk() not being checked. Elias Pschernig added support for anti-aliased bitmap fonts. Dennis Busch fixed the short description of add_clip_rect. Thomas Harte and Neil Walker fixed a problem with draw_sprite() and sub-bitmaps. Peter Wang fixed scancode_to_name(KEY_NUMLOCK) returning "PAUSE" in Windows. Peter Wang fixed page flipping and triple buffering in the demo game. Elias Pschernig added list_config_sections and list_config_entries functions. Hrvoje Ban added create_datafile_index and load_datafile_object_indexed functions. Peter Hull allowed use of "mingw" instead of "mingw32" in fix.bat and fix.sh. Peter Wang fixed a bug with SWITCH_BACKAMNESIA mode with the fbcon graphics driver. Peter Wang made the svgalib driver save and restore the palette on VT switches. Peter Wang fixed a problem with the fbcon driver and VT switching. Milan Mimica delayed Linux console initialisation until it is required. This way the user can write command-line programs using timers without needing a real console. Chris Jones fixed behavior of numeric keys when NumLock is on. Vincent Penecherc'h worked around a problem with 24-bit bitmaps in the assembler code. Tobias Dammers fixed a problem with the DirectSound input driver. Matthew Leverton fixed Ctrl-Alt-Del mistakenly being captured by Allegro under Windows Vincent Penecherc'h improved the implementation of set_ramp_cmap in the fbcon driver. Vincent Penecherc'h implemented get_refresh_rate for the fbcon driver. Vincent Penecherc'h fixed problems with the fbcon driver not restoring the original video mode when the driver exits. Victor Williams Stafusa da Silva made OS type detection handle Windows 2003 and Windows Vista. Chris Jones and Vincent Penecherc'h fixed load_wav to handle degenerate stereo wave files with an odd length. Annie Testes fixed all sorts of problems with the linux evdev mouse driver when using a tablet as the mouse. Annie Testes made the linux evdev mouse driver use the correct device files. Vincent Penecherc'h made the linux fbcon driver set a ramp colourmap for directcolor modes, otherwise colours in those modes were all wrong. Vincent Penecherc'h fixed a problem with the linux fbcon driver, where it would keep using the old pitch after changing resolutions. Serge Semashko fixed a typo causing crashs in _linear_draw_trans_rgba_rle_sprite24. Annie Testes fixed cursor speed and incorrect mickey computation bugs in the Linux evdev mouse driver. Vincent Penecherc'h made the Linux PS/2 mouse driver try /dev/input/mice by default, in addition to /dev/mouse. Warnings, code formatting and minor changes to code and build system by Milan Mimica, Evert Glebbeek, Elias Pschernig, Peter Wang, Peter Hull, Thomas Harte, Vincent Penecherc'h and Chris Robinson. Documentation updates by Tore Halse, Elias Pschernig, Milan Mimica, Peter Wang, Physics Dave, Ryan Patterson, Grzegorz Adam Hankiewicz, Andrei Ellman and Evert Glebbeek. Revision 1.14 / (download) - annotate - [select for diffs], Thu Jan 4 00:15:03 2007 UTC (5 years, 4 months ago) by wiz Branch: MAIN Changes since 1.13: +3 -3 lines Diff to previous 1.13 (colored) Look for config files and esd module in pkgsrc path. From Tatsuya Kobayashi in PR 31236. Bump PKGREVISION. Revision 1.13 / (download) - annotate - [select for diffs], Thu Oct 12 17:20:19 2006 UTC (5 years, 7 months ago) by rillig Branch: MAIN CVS Tags: pkgsrc-2006Q4-base, pkgsrc-2006Q4 Changes since 1.12: +2 -2 lines Diff to previous 1.12 (colored) Fixed "test ==". Revision 1.12 / (download) - annotate - [select for diffs], Tue Jul 4 06:27:39 2006 UTC (5 years, 10 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2006Q3-base, pkgsrc-2006Q3 Changes since 1.11: +2 -2 lines Diff to previous 1.11 (colored) Better fix for assembler problem from mrg@. Revision 1.11 / (download) - annotate - [select for diffs], Sat Jul 1 09:59:49 2006 UTC (5 years, 10 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2006Q2-base, pkgsrc-2006Q2 Changes since 1.10: +2 -1 lines Diff to previous 1.10 (colored) Add patch for gcc-4.1, provided by mrg@. Revision 1.10 / (download) - annotate - [select for diffs], Wed Mar 22 23:53:33 2006 UTC (6 years, 2 months ago) by jlam Branch: MAIN CVS Tags: pkgsrc-2006Q1-base, pkgsrc-2006Q1 Changes since 1.9: +4 -4 lines Diff to previous 1.9 (colored) * Fix PLIST in the "esound" PKG_OPTION case. * Avoid hardcoding paths with sed when using the preprocessor is much nicer. * We don't need to explicitly add ${LIBOSSAUDIO} to LIBS since the configure script already knows to search for -lossaudio. * Directly list the info files in the PLIST. Bump PKGREVISION to 2. Revision 1.9 / (download) - annotate - [select for diffs], Sun Jan 22 13:55:20 2006 UTC (6 years, 4 months ago) by wiz Branch: MAIN Changes since 1.8: +8 -9 lines Diff to previous 1.8 (colored) Update to 4.2.0: ======================================================================== ============ Changes from 4.2.0 RC2 to 4.2.0 (October 2005) ============ ======================================================================== Peter Wang made fixmul() detect overflows as it used to do in the 4.0.x branch. Dennis Busch found a bug where d_clear_proc would not work properly if the GUI target bitmap is different from screen. Grzegorz Adam Hankiewicz made Allegro log all TRACE output with a prefix in the format "al-system level: ". This makes it easier to grep debug logs. Grzegorz Adam Hankiewicz made dialogs with MSG_CHAR/MSG_UCHAR handlers honor a D_CLOSE return flag without a D_USED_CHAR. Peter Hull fixed problems with the mouse position as reported by Allegro and the mouse position as known to OS X. Peter Hull made Command-Q not close the application if no exit-button callback is registered. Peter Hull fixed problems with joysticks under MacOS X as reported by Thomas Harte. Peter Hull fixed a bug preventing more than one Allegro application from being run at a time on Mac OS X. Reported by Thomas Harte. Peter Hull did a lot of other things for the MacOS X port too. Jiri Gabriel fixed loading of multiple ranges in a single bitmap with txt fonts. Milan Mimica and Jiri Gabriel fixed several bugs in extract_font_range. Dennis Busch fixed a Unicode bug in the mode selector. Evert Glebbeek added FA_ALL and FA_NONE file attribute flags. Peter Hull fixed a deadlock in OS X when calling vsync() while the screen was acquired. Robert Alfonso fixed a grabber crash when importing a new font range into an existing font. Reported by Milan Mimica. Chris Robinson fixed the fileselector in UNIXnot properly recognising filenames containing UTF-8 characters. Hrvoje Ban and Peter Wang wrote a documentation section that explains several common mistakes. Elias Pschernig disabled DGA auto-detection under X11 i_am_drv added support for .rmi midis to the midi reader Elias Pschernig fixed a fix-point overflow in pivot_sprite. Michal Molhanec fixed several problems with the Watcom compiler. Peter Hull fixed an error with 'make uninstall' on MacOS X. Matthew Leverton added a programs: makefile target. Many small fixes and improvements by Michal Molhanec, Peter Hull, Chris Robinson, Peter Wang and Elias Pschernig. Documentation improvements by Grzegorz Adam Hankiewicz, Tore Halse and Peter Hull. =========================================================================== ============ Changes from 4.2.0 RC1 to 4.2.0 RC2 (August 2005) ============ =========================================================================== Grady Martin made the grabber consider deleting object properties as a change to the datafile. Milan Mimica fixed numerous bugs in extract_font_range(). Peter Hull moved the 'magic chdir' in the MacOS X port to earlier in the startup process, so that the config file will be looked for in the resource directory if is present. Chris Robinson made create_bitmap(0,0) not return a bitmap that would later crash destroy_bitmap(). Zero-sized bitmaps are still not allowed so the assertions for debug mode have not changed. Elias Pschernig patched the Windows keyboard driver to get key_shifts working again with KB_SHIFT_FLAG, KB_CTRL_FLAG, KB_ALT_FLAG on Win98. Peter Wang changed hline and vline into aliases for internal symbols to avoid a conflict with the curses API. This change should be transparent for users. Matthew Leverton and Michal Molhanec updated the build system for MSVC 8. Grzegorz Adam Hankiewicz prevented make_relative_filename() from crashing with malformed parameters. Hrvoje Ban made ASSERT() actually abort in Windows. Chris Robinson made GUI menus work with gui_screen. Evert Glebbeek fixed reading of 32 bit Windows .bmp files, which was not supported. These files seem to be not very standard though, so it's unclear if it will always do the right thing. Alpha channels also seem not to be standard in 32 bit BMP files, so it's possible they're not read in correctly. Peter Wang and Peter Hull updated the ABI compatibility document. This documents our policy for the 4.2.x series. Extensive documentation updates from Grzegorz Adam Hankiewicz and minor updates due to Michael Faerber, Robert Ohannessian and Milan Mimica. ============================================================================== ============ Changes from 4.2.0 beta 4 to 4.2.0 RC1 (August 2005) ============ ============================================================================== Peter Hull fixed the MacOS X port to avoid an issue with the dead bootstrap context and cleaned up the dock notification. This means command line apps (with SYSTEM_NONE) run without the dock being notified. Peter Wang Added a COLORCONV_KEEP_ALPHA flag, as suggested by Gideon Weems. Peter Wang fixed issues with OSS in OpenBSD and made the configure script print a warning if Allegro is compiled without X11 support. Peter Hull set the compatibility version to 4.2.0 for MacOS X and added a MacOS X help file. Peter Wang made the Mode-X and VBE/AF drivers fail if Allegro is compiled as a C-only library in Linux and made the Unix port install liballeg*.so and the alleg-*.so modules with the execute permission enabled. Grady Martin standardised some of the grabber dialog boxes and added a `move' command to the grabber. Evert Glebbeek fixed a bug when loading some old datafiles containing monochrome fonts. Evert Glebbeek fixed a bug that prevented system cursors from working correctly in Windows. Olivier Blin fixed compilation problems for the ModeX driver with newer binutils. Shawn Walker fixed a bug in get_executable_name under some UNIX systems. Shawn Walker worked around a problem with some versions of GNU AS and fixed some errors in the configure script when not using GCC. Elias Pschernig made create_sample not unnecessarily clear the sample to 0. Bobby Ferris fixed the makedoc SciTE API output. Elias Pschernig fixed a too strict assert that prevented set_volume from working in debug mode. Paavo Ahola helped fix a problem with BCC and the C implementations of fixmul. Elias Pschernig fixed a cosmetic bug where the listbox was drawing a too big selection rectangle, reported by dthompson. Documentation and example updates by Grzegorz Adam Hankiewicz, Peter Wang, Elias Pschernig Michal Molhanec and Evert Glebbeek. =============================================================================== ============ Changes from 4.2.0 beta 3 to 4.2.0 beta 4 (June 2005) ============ =============================================================================== Matthew Leverton changed the default behavior of the grabber: default color depth is now the desktop, default mode is windowed and if fullscreen is specified, then desktop resolution is used by default. Peter Wang fixed compilation problems related to get_modex_screen() on UNIX and deprecated it. Robert Ohannessian fixed compilation problems for the assembler code with newer binutils. Peter Wang, Thomas Harte and Evert Glebbeek optimised fixmul() for different platforms. Robert Alfonso fixed a couple of warnings that with DJGPP. Grzegorz Adam Hankiewicz made the FLIC player yield. Miran Amon fixed an arbitrary limit in get_config_argv(). Evert Glebbeek fixed a memory leak in same. Thomas Klausner fixed a problem in allegro.m4 and automake 1.8+. Charles Wardlaw fixed some warnings with gcc 4 on MacOS X. Elias Pschernig removed the `256 items' limit from the dat utility. Julien Cugniere fixed a crash in the GUI if a new dialog was opened while a menu was still open. Shawn Walker fixed crashes with the keyboard driver under Solaris. Elias Pschernig split the demo game into multiple files and made the makefile handle a multi-file demo game. Evert Glebbeek fixed a bug where the hardware mouse wasn't displayed in Windows until the mouse was moved. J.P. Morris fixed rest_callback() under UNIX. Shawn Walker and Evert Glebbeek fixed get_executable_name() under Solaris and OpenBSD. Peter Hull fixed compilation problems with setAppleMenu under Tiger. Peter Hull fixed a deadlock on MacOS X related to mouse updating. Peter Wang fixed a problem with compiling the VBE/AF driver using newer binutils. Evert Glebbeek fixed a bug with colour conversions when loading a font from a datafile. Many code, example and documentation updates by Grzegorz Adam Hankiewicz, Elias Pschernig, Peter Wang, Evert Glebbeek, Andrei Ellman, Victor Williams Stafusa da Silva, Matthew Leverton, AJ, Michal Molhanec and Hrvoje Ban. ============================================================================== ============ Changes from 4.2.0 beta 2 to 4.2.0 beta 3 (May 2005) ============ ============================================================================== Grzegorz Adam Hankiewicz did several documentation updates. Evert Glebbeek cleaned up some of the global namespace pollution in the Windows port. Chris Robinson made improvements to the Windows sound driver. Chris Robinson made the GUI multi-selection box behave a bit nicer. Grzegorz Adam Hankiewicz added a bunch of ASSERTs to the code to check for out-of-range arguments. Jakub Wasilewski fixed a bug when loading greyscale TGA images. Evert Glebbeek fixed a bug where the bottom and right line of pixels was not updated on show_video_bitmap, as pointed out by Thomas Harte. Evert Glebbeek documented JOY_TYPE_* defines for Windows and Linux. Dark Nation restored the ability to read old-style encrypted packfiles, i.e. those produced before Allegro 3.9.30. This was silently removed from 4.1.18 when custom packfile support / decoupled compression routines were added. Evert Glebbeek made the grabber and dat utilities now use Allegro's builtin load_font() function and made datafiles properly store truecolour fonts and added a datedit_select() callback to datedit. Evert Glebbeek fixed some unsafe assumptions on the size of integer datatypes. Arthur Huillet fixed a typo in the docs. Elias Pschernig restored Alt+key = ASCII code 0 behavior for the Windows keyboard driver Evert Glebbeek fixed a bug that caused a crash when loading Allegro 1.x datafiles containing 4 bit bitmaps. Peter Wang clarified the mode select documentation and made the mode selector clear the input variables before passing them on to the filter. Peter Wang fixed a bug in the mode selector where disabled drivers were still shown with empty resolution lists. Pointed out by Hrvoje Ban. Elias Pschernig fixed Allegro's internal multithreading in Windows. This fixes a deadlock on exit. Robert Alfonso made the MSVC makefile call `link /lib' rather than `lib', which doesn't work for the free toolkit. Peter Hull fixed a problem with hardware cursors not working properly in MacOS X. Peter Hull added a missing enable_hardware_cursor vtable entry and added OS native cursors for the MacOS X port. Grzegorz Adam Hankiewicz documented the online Allegro patch generator. Evert Glebbeek renamed datafiles._tx -> datafile._tx StApostol updated the FAQ to use rest(0) instead of the deprecated yield_timeslice(). Evert Glebbeek silenced some GCC4 warnings in MacOS X. Peter Wang fixed warnings and errors with gcc 4.0.0 on the Unix port; reported by Milan Mimica. Peter Wang added the preprocessor symbol ALLEGRO_NO_FIX_CLASS that the user can define to not pull in the `fix' class in C++ programs. Peter Wang removed the exdodgy example. Elias Pschernig fixed another X11 async reply bug. Elias Pschernig made the seek in expackf test work with CR/LF line endings. Evert Glebbeek fixed a small bug that prevented the Allegro template for Project Builder from installing correctly on MacOSX. Elias Pschernig enabled warnings about unused variables with --enable-strictwarn in unix. Peter Wang fixed a warning with Watcom 1.3. ================================================================================ ============ Changes from 4.2.0 beta 1 to 4.2.0 beta 2 (April 2005) ============ ================================================================================ Daniel Schlyder fixed a problem with the makefile in Windows. Evert Glebbeek fixed a bug that prevented true colour fonts from working. Peter Wang fixed a possible deadlock in dialog_message. Elias Pschernig fixed a bug where the DJGPP version would choke on a missing variable. Peter Hull made makedoc return an error code if it failed to build the SciTE documentation. Evert Glebbeek fixed a problem with incorrect dependencies being generated for MacOS X. Tobi Vollebregt fixed a problem in X11 if the XRGBACursor extension was missing. Evert Glebbeek made configure use k8 rather than athlon64 as a compiler switch on AMD64. Peter Wang and Elias Pschernig added a packfile example. Michal Molhanec fixed a problem in the MSVC makefile. Evert Glebbeek removed void*-arithmetic from the colour converter. Evert Glebbeek fixed a bug where hardware cursors would stop working. Elias Pschernig, Andrew Chew fixed and Tobi Vollebregt fixed several problems with the Windows keyboard driver. Elias Pschernig fixed bug in unix dependency generation. Elias Pschernig made the GUI not mess up the hardware cursor. Elias Pschernig removed pckeys.c and keyconf from the windows port, since the dinput driver no longer needs pckeys.c nor uses keyboard.dat. Daniel Schlyder fixed a problem with the -mtune switch on older gcc based compilers. Matthew Leverton figured out which versions of Watcom have inttypes.h and stdint.h. V Karthik Kumar added a password to the Windows screensaver example. Cosmetic fixes, example bugfixes and spelling corrections by Jon Rafkind, Evert Glebbeek, Peter Wang, StApostol and Elias Pschernig. ======================================================================== ============ Changes from 4.1.18 to 4.2.0 beta (March 2005) ============ ======================================================================== Peter Wang fixed many problems on AMD64 in Linux - it should now work fine. Peter Hull added CPU detection to the MacOS X port. Peter Hull fixed some problems related to /usr/local/bin not existing in recent versions of MacOS X. Elias Pschernig and Peter Wang rewrote the Windows keyboard driver so it no longer needs keyboard.dat. Elias Pschernig added a show_os_cursor function as an alternative to show_mouse() for system cursors. Evert Glebbeek and Peter Wang added an example programme for system cursors. Elias Pschernig fixed a deadlocks in X11 related to scare_mouse() and keyboard repeats and fixed async replies. Daniel Schlyder fixed the gcc -mcpu is deprecated warnings. Peter Wang added an astdint.h, which provides C99 typedefs for pre-C99 compilers. AJ added detection for DirectX 8 and 9 to the Windows port. Evert Glebbeek added detection for AMD64 to the UNIX port and test programme. Elias Pschernig added a get_midi_length function and a midi_time variable. Elias Pschernig fixed a problem where Allegro would ignore a user-specified configuration file if set_config_file() was called before allegro_init(). Evert Glebbeek added a transpose_font function. Evert Glebbeek added support for true colour fonts and a font example. Elias Pschernig fixed a problem in shutdown_dialog() reported by Tobi Vollebregt. Marcio Fialho fixed some issues with displaying author names in the demo game. Andrei Ellman fixed a problem in the MSVC makefile when building Allegro with Cygwin. Daniel Schlyder fixed (again) problems with creating directories in different setups in Windows. Elias Pschernig added documentation for the custom packfile functions. Jeff Mitchell fixed the location of grabber.txt in the spec file. Harshavardhana Reddy added a Kannada greeting to exunicod. Elias Pschernig cleaned up the example programmes. Peter Wang made it possible to disable the hardware cursor in X by passing an option to the configure script. AJ and Michal Molhanec added an MSVC 7 configure option and added an msvc7 switch to fix.bat. Karthik Kumar did the same for the Intel compiler icl. Mr_Bones fixed compilation of setup.c when --disable-ossdigi is used AJ fixed a beep being generated in Windows when alt+character was pressed in Windowed mode. Peter Wang fixed many oversights and problems in the library and examples and allowed the code to be build with stricter warnings. Peter Wang fixed problems compiling the Windows port with WARNMODE=1 Tore Halse fixed compilation problems in Windows related to TITLEBARINFO. Daniel Schlyder made the Windows port use TITLEBARINFO if it is available. Grzegorz Adam Hankiewicz made many improvements to the documentation. Revision 1.8 / (download) - annotate - [select for diffs], Sun Sep 11 14:17:44 2005 UTC (6 years, 8 months ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2005Q4-base, pkgsrc-2005Q4, pkgsrc-2005Q3-base, pkgsrc-2005Q3 Changes since 1.7: +3 -1 lines Diff to previous 1.7 (colored). Revision 1.7 / (download) - annotate - [select for diffs], Mon May 23 12:05:46 2005 UTC (7 years ago) by wiz Branch: MAIN CVS Tags: pkgsrc-2005Q2-base, pkgsrc-2005Q2 Changes since 1.6: +4 -3 lines Diff to previous 1.6 (colored) Fix autoconf argument quoting. Revision 1.6 / (download) - annotate - [select for diffs], Wed Feb 23 22:24:09 2005 UTC (7 years, 2 months ago) by agc Branch: MAIN CVS Tags: pkgsrc-2005Q1-base, pkgsrc-2005Q1 Changes since 1.5: +2 -1 lines Diff to previous 1.5 (colored) Add RMD160 digests. Revision 1.5 / (download) - annotate - [select for diffs], Wed Feb 9 20:16:34 2005 UTC (7 years, 3 months ago) by wiz Branch: MAIN Changes since 1.4: +3 -3 lines Diff to previous 1.4 (colored). Revision 1.4 / (download) - annotate - [select for diffs], Mon Nov 22 16:39:50 2004 UTC (7 years, 6 months ago) by kristerw Branch: MAIN CVS Tags: pkgsrc-2004Q4-base, pkgsrc-2004Q4 Changes since 1.3: +2 -1 lines Diff to previous 1.3 (colored) Add a missing include to make this pkg build on NetBSD 1.6. Revision 1.3 / (download) - annotate - [select for diffs], Tue Nov 9 10:48:02 2004 UTC (7 years, 6 months ago) by adam Branch: MAIN Changes since 1.2: +6 -4 lines Diff to previous 1.2 (colored) Changes 4.1.16: * Fixed two problems with the keyboard driver on Windows. * Added a set_allegro_resource_path() function. * Added hardware cursor support to the X11 and DirectX window drivers. * Fixed a crash when initializing, deinitializing and reinitializing Allegro on Windows. * New MIDI input driver for the Windows port. * Improved the speed of drawing primitives on X11 and implemented locking/unlocking for video bitmaps. * Fixed bugs in set_palette() and remove_int(). * Fixed a bug where the X11 fullscreen driver would fail if no virtual screen was reported. * Many fixes to source, examples and documentation. Revision 1.2 / (download) - annotate - [select for diffs], Thu Jun 3 23:29:53 2004 UTC (7 years, 11 months ago) by xtraeme Branch: MAIN CVS Tags: pkgsrc-2004Q3-base, pkgsrc-2004Q3, pkgsrc-2004Q2-base, pkgsrc-2004Q2 Changes since 1.1: +4 -6 lines Diff to previous 1.1 (colored) Update devel/allegro to 4.1.14. Changes: # Fixed a couple of problems in dat2c. # Polished the MacOS X package builder script. # Added a Jack sound driver to the Unix port. # Added support for debugging with DMalloc under Unix. # Fixed detection of the ALSA 1.0 MIDI driver. # Fixed compilation with --enable-color8=no under Unix. # Now it is possible to link against the Allegro framework with the allegro-config script under MacOS X. # Fixed a bug in fixbundle with 32bpp icons and alpha channel under MacOS X. # Restored the compensation code for end-of-frame in the FLI player. Revision 1.1.1.1 / (download) - annotate - [select for diffs] (vendor branch), Mon Apr 5 05:02:41 2004 UTC (8 years, 1 month ago) by xtraeme Branch: TNF CVS Tags: pkgsrc-base Changes since 1.1: +0 -0 lines Diff to previous 1.1 (colored) Initial import of allegro-4.1.13 from pkgsrc-wip, Initial work by Thomas Klausner plus minor changes by me.". It is also a recursive acronym which stands for "Allegro Low LEvel Game ROutines". Cross-platform support o Dos (DJGPP, Watcom) o Unix (Linux, *BSD, Irix, Solaris, Darwin) o Windows (MSVC, MinGW, Cygwin, Borland) o BeOS o QNX o MacOS X Revision 1.1 / (download) - annotate - [select for diffs], Mon Apr 5 05:02:41 2004 UTC (8 years, 1 month.
http://cvsweb.netbsd.org/bsdweb.cgi/pkgsrc/devel/allegro/distinfo
crawl-003
refinedweb
5,951
67.35
Created on 2008-02-24 05:09 by belopolsky, last changed 2008-03-24 17:19 by belopolsky. This issue is now closed. Attached patch improves pydoc UserDict presentation. One of the problems with the current documentation in comments is that order of methods is not preserved and thus the method level comments in DictMixin implementation are meaningless in pydoc. (In any case the If this patch is accepted in principle, the original level comments should be removed. I am leaving them intact to simplify the review. Fixed an error in lavels doc. Needs review. I'm not sure the class docstring approach is suitable for a mixin. It seems fine to me that pydoc strips the commentary on the mixin as a standalone class; instead it appropriately focuses on the client class that uses the mixin as part of its API. FWIW, all of this code goes away in Py3.0. On Mon, Mar 24, 2008 at 4:53 AM, Raymond Hettinger <report@bugs.python.org> wrote: > I'm not sure the class docstring approach is suitable for a mixin. It > seems fine to me that pydoc strips the commentary on the mixin as a > standalone class; My main point was not that some commentary was stripped by pydoc, but that the commentary that is not stripped is misleading: The beginning of pydoc UserDict.DictMixin is rendered as follows: UserDict.DictMixin = class DictMixin | Methods defined here: | | __cmp__(self, other) | | __contains__(self, key) | | __iter__(self) | # second level definitions support higher levels | | __len__(self) .. What does "second level definitions support higher levels" comment below __iter__ means? Does it apply to all methods above or all methods below but above the "third level ..." comment or just to __iter__? All of these plausible interpretations are wrong. Furthemore, pydoc UserDict is rendered as follows: NAME UserDict - A more or less complete user-defined wrapper around dictionary objects. FILE /bnv/home/abelopolsky/Work/python-svn/trunk/Lib/UserDict.py CLASSES DictMixin UserDict IterableUserDict class DictMixin ... Which is not helpful at all in understanding of what DictMixin is for. > instead it appropriately focuses on the client class > that uses the mixin as part of its API. I assume you refer to UserDict as the "client class". In what sense does it use "mixin as part of its API"? In 2.x, UserDict does not derive from DictMixin. To the contrary, UserDict and DictMixin present quite different APIs to the users of derived classes. For example, overriding __getitem__ does not affect has_key, __contains__ or iter* methods of the class deriving from UserDict, which is different from the way DictMixin descendants work. .. that's why I selected version 2.6 when I submitted this issue. :-) However, AFAICT, not all this code goes away, just UserDict is moved to collections and DictMixin functionality is replaced with ABCs. This is a welcome change because with abstract methods the classes become self-documenting, but I have to note that UserDict will behave differently in 3.0: the following code print 1 in 2.x and 42 in 3.0: class X(UserDict): def __getitem__(self, _): return 42 print(X(a=1).pop('a')) This change should probably be reflected in the docs somewhere.
https://bugs.python.org/issue2172
CC-MAIN-2021-04
refinedweb
533
57.67
tml> Sugar Bowl 1993 Alabama 34 Miami 13 Alabama Fight Song By MALCOLM MORAN Gene Stallings went for the ride of his life tonight. Sitting atop crimson shoulders and bathing in the bright light of the flashbulbs before him, the football descendant of Alabama legend Paul (Bear) Bryant led the second-ranked Crimson Tide to a virtually certain national championship. Three interceptions by Miami quarterback Gino Torretta led to Alabama touchdowns in an improbable 34-13 Crimson Tide victory over the top-ranked Hurricanes in the 59th Sugar Bowl. With Derrick Lassic rushing for 135 yards and two touchdowns, and Alabama's defense smothering Miami's rushing game and confusing Torretta, the Heisman Trophy winner, Alabama (13-0) made certain that when final polls are released Saturday, it will clinch its sixth outright national championship since The Associated Press news media poll began in 1936. The title will be Alabama's first since Bryant's 1979 team won in the Sugar Bowl. "We said we would make 55 or 56 plays for the privilege of making a difference," Stallings said. "We had a lot of guys that made the difference." Miami (11-1) lost for the first time since a 29-20 defeat at Notre Dame in October 1990. Alabama's 23rd consecutive victory ended Miami's 29-game streak to become the longest current streak among major colleges. Six years after Vinny Testaverde, Miami's first Heisman winner, threw five interceptions in a shocking Fiesta Bowl loss to Penn State, Torretta's nightmare played a critical role in a game that was nearly as much of a surprise. "He made some good throws," Stallings said, "and we got some of them." Torretta's interceptions -- after he had thrown only seven all season -- did not hold the final-second shock that another Miami generation suffered that 1987 night in the Arizona desert. They only compounded Miami's desperation before a raucous Alabama-partisan crowd of 76,789 in the Louisiana Superdome. A Sugar Bowl-record 78-yard punt return by Miami junior Kevin Williams brought the Hurricanes within 14 points with 12 minutes 8 seconds left in the game. But the Tide gained 67 more rushing yards than any team had gained against Miami this season. Miami's attempt to complete a second consecutive perfect season, and an unprecedented fifth unofficial national championship in 10 years, came apart when two of the three interceptions thrown by Torretta led to two Alabama touchdowns within 16 seconds early in a shocking third quarter. Alabama was outgained, 326 yards to 285. Tide quarterback Jay Barker, who has led his team to 17 victories in 17 starts, completed just 4 of 13 passes for 18 yards, with 2 interceptions. Torretta threw for 278 yards on 24 completions in 56 attempts. His decisive mistakes were the result of an overwhelming Alabama defensive effort that all but eliminated Miami's ability to run. Miami was held to 48 rushing yards, 42 of which came during an inconsequential final drive long after a Crimson celebration had begun. Cornerback Tommy Johnson intercepted Torretta's quick pass towards Kevin Williams, and returned the ball 23 yards to the Miami 20. That led to a 1-yard touchdown run by Lassic, who scored the fifth rushing touchdown against the Hurricanes. Then just 16 seconds later, on first down following the kickoff, George Teague's aggressiveness and anticipation created the fourth Alabama interception return for a touchdown this season. Teague was matched against Miami sophomore tailback Jonathan Harris, who was lined up in a slot to the right. Teague jammed Harris as he tried to come off the line of scrimmage. Torretta, who was pressured all night by the Alabama defense, chose to force a throw towards Harris. But Teague stepped in front of the sophomore, caught the pass at the 31, took off toward the right sideline and high-stepped the last five yards into the end zone for a 21-point lead (video). The biggest challenge facing the Hurricanes was the necessity of dealing with the most forceful part of the Alabama defensive unit, its bookend all-america ends Eric Curry and John Copeland. "If I had three and a half seconds to throw in the Sugar Bowl," Torretta had said before the game, "I'd take it any day of the week." Those opportunities did not seem to come very often. Curry and Copeland became a force from the start, leading a defense that limited Miami to two first downs in the first quarter and minus-13 rushing yards in the first half. The Crimson Tide outgained Miami, 70 yards to 55 in the first quarter on the strength of a defense. But Alabama wasted several opportunities to take advantage of the momentum created by its stifling defense and the boisterous pro-Tide crowd. And a controversial unsportsmanlike conduct penalty, after the Tide had reached the Miami 1-yard line, stalled another Alabama drive. The first Tide opportunity came after Miami was held without a yard on its first possession, and Paul Snyder's line-drive punt helped set up Tide sophomore David Palmer for a 38-yard return to the Miami 24. Alabama moved to the 6 on a 14-yard run by Lassic. On first down, Barker appeared to have Lassic open in the right side of the end zone. But Hurricane defensive back Casey Greer, whose last-second tackle had saved the victory at Syracuse, leaped to bat the pass away with his right hand. Two plays later, on third down from the 3, Barker rolled to his right and was met by Robert Bass and Darren Krein at the 2. Alabama was forced to settle for a 19-yard field goal by freshman kicker Michael Proctor, just the second time this season that a Miami opponent scored first in a game this season. Dane Prewitt, the Miami kicker who was a high school teammate of Barker, tied the score with a career-long 49-yard kick. Then Alabama, which had built its perfect record with a cautious offense, stepped out of character and suffered the consequences. On third-and-16 from its 45, a spot that normally called for a draw play and a punt, Barker's overthrown pass for Kevin Lee was intercepted by Greer and returned 26 yards to the Alabama 39. On Miami's second play, Lamar Thomas gained 13 yards on a quick-forming middle screen to the Tide 23. But Tide cornerback Tommy Johnson stripped the ball, and cornerback Willie Gaston recovered the fumble to end the Hurricane threat. Barker's second interception, a dangerously high, looping pass for Prince Wimbley, became Alabama's second turnover when Miami cornerback Ryan McNeil gained position and outleaped Wimbley at the Miami 23. The controversial Alabama penalty was assessed at the start of the second quarter. After a Miami punt, the Tide had driven to the Miami 11 on the strength of a 24-yard run by Lassic, who gained 106 of Alabama's 152 first-half rushing yards. Lassic then gained 10 yards to the Hurricane 1, was met when Darrin Smith grabbed his facemask, and a flag was thrown against Miami. But then a second was thrown at a ball that was spinning on the goalline near where Lassic had been downed. Because of the location of the ball, the facemask penalty was for zero yardage. But the second flag -- an unsportsmanlike conduct penalty -- pushed the Tide back to the 15, and they were forced to settle for a 23-yard field goal by Proctor. A Torretta interception, and a 33-yard return by safety Sam Shade, led to a 2-yard touchdown run by Sherman Williams and a 13-3 Alabama lead. Note: As Miami wideout Lamar Thomas sprinted toward completing an 89-yard touchdown pass in the 1993 Sugar Bowl, Alabama safety George Teague, five yards behind, didn't give up. Teague caught Thomas inside the Tide 10, and with a windmill swipe, turned upfield with ball in hand (video). An Alabama penalty nullified the play, which means the most celebrated play in the No. 2 Tide's 34-13 rout of the No. 1 'Canes never really happened. Alabama quarterback Jay Barker. Alabama Coach Gene Stallings. Teague was the sensational hero for Alabama. Here he scores on a interception return. Attendance- 76,789 Scoring Summary First Quarter UA- FG Proctor 19 UM- FG Prewitt 49 Second Quarter UA- FG Proctor 23 UA- Williams 2 run (Proctor kick) UM- FG Prewitt 42 Third Quarter UA- Lassic 1 run (Proctor kick) UA- Teague 31 interception return (Proctor kick) Fourth Quarter UM- S.Williams 78 punt return (Prewitt kick) UA- Lassic 4 run (Proctor kick) Individual Statistics Rushing UM- Bennett 5-28, L Jones 3-26 UA- Lassic 28-135, Lynch 5-39, Houston 6-23, Palmer 2-22, Barker 7-20, S.Williams 7-18 Passing UM- Torretta 24-56-278 UA- Barker 4-13-18 Receiving UM- Thomas 6-52, Bennett 4-17, C.Jones 3-64, K.Williams 3-49, H Copeland 2-21, J.Harris 2-16 UA- Wimbley 2-11
http://web.archive.org/web/20080908044115/http:/www.mmbolding.com/bowls/Sugar_1993.htm
CC-MAIN-2014-52
refinedweb
1,525
58.72
3. Basics of C There are certain rules in every language; certain grammar which dictates the way language will be spoken and written. It has a script to write with. Similarly, programming languages have BNF (Backus-Naur Form) context-free grammar. There are valid characters in a programming language and a set of keywords. However, programming language ruleset is very small compared to a natural programming language. Also, when using natural programming language like talking to someone or writing something the other person can understand your intent but in programming you cannot violate rules. The grammar is context-free. Compilers or interpreters cannot deduce your intent by reading code. They are not intelligent. You make a mistake and it will refuse to listen to you no matter what you do. Therefore, it is very essential to understand these rules very clearly and correctly. Note that C language is governed by ISO specification ISO/IEC 9899:2011. As much as I would like to refer to specification there are financial reasons why I will not because it is expensive and I do not expect all of readers to buy this. Thus I would use n1570.pdf mentioned in previous chapter. Sections of this document will be referred like \(\S(\text{iso.section number})\). 3.1. The C Character Set The following form the C character set you are allowed to use in it: [a-z] [A-Z] [0-9] ~ ! # % ^ & * ( ) - = [ ] \ ; ' , . / _ + { } | : " < > ? This means along with other symbols you can use all English alphabets (both uppercase and lowercase) and Arabic numerals. However, English is not the only spoken language in the world. Therefore in other non-English speaking counties there are keyboard where certain characters present in above set are not present. The inventors of C were wise enough to envision this and provide the facility in form of trigraph sequences. Here, I am presenting table of trigraph sequences. 3.2. Keywords The following are reserved keywords for C programming language which you are not allows to use other than what they are meant for: Following keywords were added in C11 specification: These keywords serve specific purpose. You will come to know about all of them as you progress through the book. Next we look at identifiers. 3.3. Identifiers The names which we give to our variables are known as \(\S(\text{iso.6.4.2})\). Something with which we identify. As you have already seen what is allowed in C’s character set but not all are allowed in an identifiers name. Only alphabets from English language both lowercase and uppercase, Arabic digits from zero to nine and underscore (_) are allowed in an identifiers name. The rule for constructing names is that among the allowed characters it can only begin with only English alphabets and underscore. Numbers must not be first character. For example, x, _myVar, varX, yourId78 are all valid names. However, take care with names starting from underscore as they are mostly used by different library authors. Invalid identifier examples are 9x, my$, your age. Invalid identifier examples are 9x, my$} and your age. If the identifier name contains extended characters(i.e. other than what is mentioned for simplicity like, Chinese, European, Japanese etc) then it will be replaced with an encoding of universal character set, however, it cannot be first character. Length of an identifer for 31 characters, which, acts as minimum limits, as specified in \(\S(\text{iso.5.2.4.1})\), is guaranteed across all platforms. 3.4. Programming Now is time for some programming. Let us revisit our first program and try to understand what it does. Here I am giving code once again for quick reference: // My first program // Description: This program does nothing. #include <stdio.h> int main(int argc, char* argv[]) { return 0; } You can now issue a command as $gcc nothing.c where nothing.c is the filename by which you saved the source code. Note that $ is the prompt not part of command itself. Then you can do an ls and you will find that a.out is a file which has been produced by gcc. Now you can run this program by saying ./a.out and nothing will happen. But if you type echo $? then you will find that 0 is printed on screen which is nothing but 0 after return of our program. As you can see this program does almost nothing but it is fairly complete program and we can learn a lot from it about C. The first line is a comment. Whenever C compiler parses C programs and it encounters // it ignores rest of line as code i.e. it does not compile them. This type of single line comment were introduced in C99 standard and if your compiler is really old the compiler may give you error message about it. The second and third lines are also /* and */ is ignored like //. However, be careful of something like /* some comment */ more comment */. Such comments will produce error messages and your program will fail to compile. Comments are very integral part of programming. They are used to describe various things. You can write whatever you want. They may also be used to generate documentation with tools like doxygen. Typically comments tell what the program is doing. Sometimes how, when the logic is really complex. One should be generous while commenting the code. #include is a pre-processor directive. It will look for whatever is contained in angular brackets in the INCLUDEPATH of compiler. For now you can assume that /usr/include is in include path of compiler. Basically what it does is that it looks for a file names stdio.h in the INCLUDEPATH. If that is found the content of that file is pasted here in our program.If you really want to see what happens then you can type $gcc -E nothing.c. You will see lots of text scrolling on your screen. The -E switch tells gcc that just preprocess the file, do not compile it, and send the resulting output to standard output (we will know about this more later), which happens to be your monitor in this case.. Next line is int main(int argc, char* argv[]). Now this is very special function. Every complete executable(shared objects or dlls do not have main even though they are C programs) C program will have one main function unless you do assembly hacking. This function is where the programs start. The first word int is a keyword which stands for integer. This signifies the return type of function. main is the name of the function. Inside parenthesis you see int argc which tells how many arguments were passed to program. While char* argv[] is a pointer to array which we will see later. For now it holds all the arguments to the program. Next is a brace. The scope in C is determined by braces. Something outside any brace has global scope (we will see these later), something inside first level of brace has function or local scope. Something inside second or more level of braces have got that particular block scope. Scope here means that when there will be a closing brace that particular variable which is valid in that scope will cease to exist. However, we do not have to worry about that yet as we do not have any variable. Just note that a corresponding closing brace will be the end of main function. Next line is return 0; This means whoever has called main() will get a 0 as return is returning 0. In this case, receiver is the shell or operating system which has invoked the very program. The semicolon is called the terminator and used also on Java or C++ for example. The very requirement of semicolon is to terminate the statement and move on to next statement. However, the program shown does not do much. Let us write a program which has some more functionality and we can explore more of C. So here is a program which takes two integers as input from users and presents their sum as output. Here is the program: // My second program // Description: It adds two numbers #include <stdio.h> int main() { int x=0, y=0, sum=0; printf("Please enter an integer:\n"); scanf("%d", &x); printf("Please enter another integer:\n"); scanf("%d", &y); sum = x + y; printf("%d + %d = %d\n", x, y, sum); return 0; } and the output is: shiv@shiv:~/book/code$ ./addition Please enter an integer: 7 Please enter another integer: 8 7 + 8 = 15 shiv@shiv:~/book/code$ Note that shiv@shiv:~/book/code$ is the prompt. The Makefile is also updated: check-syntax: gcc -o nul -Wall -S $ (CHK_SOURCES) nothing:nothing.c gcc nothing.c -o nothing addition:addition.c gcc addition.c -o addition You can choose Tools->Compile then enter make -k addition as make commands in the Emacs’s minibuffer and execute like $./addition. Let us discuss new lines one by one. The line int x=0, y=0, z=0; is declaration and definition or initialization of three ints. int keyword in C is used to represent integers. Now we have three integers with there values set to 0. Note that how the variables are separated by commas and terminated by semicolon(as we saw in last program also). We could have also written it like this: int x; int y; int z; x = 0; y = 0; z = 0; or int x, y, z; x = y = z = 0; However, the first method is best and most preferred as it prevents use before definition. int is a data-type in C. x, y, and z are variables of type int. This means that the size of these variables will be same as int. Note that C is a statically typed language and all types have predefined memory requirements. In cour case, int requires 4 bytes on 32-bit systems. Now I will talk about printf() function. This function is declared in stdio.h. The prototype of printf() is int printf(const char *restrict format, ...); The first argument format is what we have in first two function calls. The second is a ... which means it can take variable number of arguments known as variable-list. We have seen this in the third call.This means it will take a string with optional variable no. of arguments. The string is called the format-string and determines what can be printed with supplied arguments. These ... are used to supply variable no. of arguments. In the first two printf() statements we just print the format-string so that is simple. However, in the last one, we have format as %d which signifies a decimal integer. The integers printed are in the same order in which they were supplied. Time for some input. scanf() is scan function which scans for keyboard input. As by now you know that %d is for decimal integer but we have not said x or y. The reason is x and y are values while &x and &y are the addresses of x and y in memory. scanf() needs the memory address to which it can write the contents to. You will see & operator in action later when we deal with pointers. Just remember for now that to use a simple variable with scanf() requires & before its name. Now I am going to take you on a tour of data types. Till now we have just seen only int. So onward to data types. 3.5. Data Types C is a statically typed language that is every variable has a type associated with it. Types are discussed in specification in great length in \(\S(\text{iso.6.2.5})\) to \(\S(\text{iso.6.2.8})\). These types determine what kind of values these variables can hold and how they will be interpreted. For example, say you are given a sequence of 0s and 1s how much can you work with them. We as humans are not very versed with 0s and 1s. Also, say we encode character ‘A’ for 10101 will it be easy for you to see A or numbers. Also, numbers range from \(-\infty\) to \(\infty\). Also, since C is statically typed the sizes of data types have to be known at compile time. There are four types of data types. Integral, floating-point, arrays and pointers. Here, I will deal with the two former types and leave latter two for later. The integral types are char, short int, int, long and long long and floating-point types are float, double and long double. signed and unsigned are sign modifiers which also modified the range of data types but do not affect their memory requirements. By default all basic data types are signed in nature and you must qualify you variables with unsigned if you want that behavior. short and long are modifiers for size which the data type occupies but I consider them as different types because memory requirements are different. The ranges of integral data types directly reflect their memory requirements and if you know how much memory they are going to occupy you can easily compute their ranges. The range of floating-point comes from IEEE specification. The range of data types is given in Numerical limits \(\S(\text{iso.5.2.4.2})\). For example, in the range program given below size of int is 4 bytes which is double than what is specified by specification i.e. 2 bytes. Given below is the table for numerical limits for reference from specification. Note that these are in 1’s complement form thus you have to adjust for 2’s complement. Note that these limits are minimum limits imposed by specification and actual limits of data types may be different on your particular platform. The actual values of these limits can be found in headers <limits.h>, <float.h> and <stdint.h>. The values given below are replaced by constant expressions suitable for use in #if preprocessing directives. Moreover, except for CHAR_BIT and MB_LEN_MAX, the following are replaced by expressions that have the same type as an expression that is an object of the corresponding type converted according to the integer promotions. Their implementation-defined values are equal or greater in magnitude (absolute value) to those shown, with the same sign. Note that these ranges are for 1’s complement. While most probably your computer uses 2’s complement so you should add -1 to the negative range. Thus MINs are greater than MAXes. number of bits for smallest object that is not a bit-field (byte) CHAR_BIT8 minimum value for an object of type signed char SCHAR_MIN-127 \(~~~~-2^7 - 1\) maximum value for an object of type signed char SCHAR_MAX127 \(~~~~2^7 - 1\) maximum value for an object of type unsigned char UCHAR_MAX255 \(2^8 - 1\) minimum value for an object of type char CHAR_MINsee below maximum value for an object of type char CHAR_MAXsee below maximum number of bytes in a multibyte character, for any supported locale MB_LEN_MAX1 minimum value for an object of type short int SHRT_MIN-32767 \(-2^{15} - 1\) Let us write a program to find out memory required for various data types: // My range program // Description: It gives ranges of integral data types #include <stdio.h> #include <limits.h> int main() { printf("Size of char is..........%d\n", sizeof(char)); printf("Size of short int is.....%d\n", sizeof(short int)); printf("Size of int is...........%d\n", sizeof(int)); printf("Size of long is..........%d\n", sizeof(long)); printf("Size of long long is.....%d\n", sizeof(long long)); printf("Size of float is.........%d\n", sizeof(float)); printf("Size of double is........%d\n", sizeof(double)); printf("Size of long double is...%d\n", sizeof(long double));c return 0; } and the output will be: Size of char is..........1 Size of short int is.....2 Size of int is...........4 Size of long is..........4 Size of long long is.....8 Size of float is.........4 Size of double is........8 Size of long double is...12 Based on this it is left as an exercise to reader to compute the ranges of these data types. 3.5.1. Integers Integers are probably simplest to understand of all data types in C so I am discussing them before any other type. As you have seen the keyword for declaring integer type is int. An integer can be 2 bytes or 4 bytes. A 16-bit compiler will have integer of 2 bytes while a 32-bit or 64-bit compiler will have a 4 byte integer. The specified minimum size of an integer is 2 bytes. Since most modern computers are either 32-bit with 64-bit becoming more dominant we will assume in this book that integer’s size is 4 bytes or 32-bit implicitly because 32-bit gcc gives a 32-bit integer. There is a keyword signed which when applied to a data type splits the range into two parts. Since integer is 32 bit so it will be split in the range from \(-2^{31}\) to \(2^{31} - 1\). By default integers, characters and long are signed. Floats and doubles are always signed and have no unsigned counterpart. When the integer will be texttt{unsigned} then the positive range doubles and it becomes $0$ to \(2^{32} - 1\). When the value of intger is more than its range then the values rotate in the using modulus with the largest value of the range which is also known as INT_MAX or INT_MIN. For unsigned types it is UINT_MAX. These are macros and are defined in limits.h which you can find in /usr/include or /usr/local/include by default. There are four different types of integers based on their storage requirement. short int, int, long and long long. Short integers are always two bytes. Signed short integer has a range of -32768 to 32767 while unsigned of that has a range of 0 to 65535. Plain integers i.e. int have already been discussed. long are having a minimum storage requirement of 4 bytes. Usually it is large enough to represent all memory addresses of the system because size_t is unsigned long. short, long and long long qualifiers decrease/increase the range of plain integers. On a 64-bit compiler short int will be 2 bytes while long int will be 8 bytes, which, will be equal to long longint. unsigned long int is chose in such a way that it should be capable of representing all memory addresses because it has a typedef to size_t which is the type of argument received by many functions including memory allocation functions. 3.5.2. Characters A char is 1 byte i.e. 8 bits or CHAR_BIT bits. So its signed version i.e. 2’s complement where half the range is negative and half is positive will have value from -128 to 127. Well that is not exactly opposite because we have only one zero for positive and negative numbers. If it would have been 1’s complement then range would have been from -127 to 127 but since computers follow 2’s complement the specification clearly mentions that range should be from \(-2^7\) to \(2^7 - 1\). Note that chars are fundamentally integral types and ASCII symbols are first 128 numbers or in other words they are 7-bit numbers. So a character ‘0’ is internally 48 in decimal which is its integral or internally it is handled as a sequence of binary numbers representing 0x30 in hexadecimal. These integral values for characters are known as ASCII value. A full table of ASCII values is given in the appendix A. A simple program which takes input for few characters and then prints them on console along with their ascii values is given below: #include <stdio.h> int main() { char c = 0; char c1 = 0, c2 = 0; printf("Enter a character on your keyboard and then press ENTER:\n"); scanf("%c", &c); printf("The character entered is %c and its ASCII value is %d.\n", c, c); // Their remains '\n' in the stdin stream which needs to be cleared. getchar(); printf("Enter a pair of characters on your keyboard and then press \ ENTER:\n"); scanf("%c%c", &c1, &c2); printf("The characters entered are %c and %c and their ASCII \ values are %d and %d respectively.\n", c1, c2, c1, c2); short int si = 0; si = c1 + c2; printf("The sum of c1 and c2 as integers is %hd.\n", si); return 0; } A sample run may have following output: Enter a character on your keyboard and then press ENTER: 1 The character entered is 1 and its ASCII value is 49. Enter a pair of characters on your keyboard and then press ENTER: 12 The characters entered are 1 and 2 and their ASCII values are 49 and 50 respectively. The sum of c1 and c2 as integers is 99. As you can see from the program that characters are internally stored as integers and we can even perform integers which we normally perform on numbers like addition as shown. We can perform other operation as subtraction, multiplication and division, however, most of the time addition or subtraction only makes sense to advance the characters in their class. Multiplication and division of characters with other characters or integers does not make sense. One problem of concern is the extra \n in the input stream. It does not cause trouble with integers but when you want to read characters then the Enter or Return keys which may be left over from the last input will cause trouble. \n is recognized as a character and will be assigned to next variable if it is in stdin. One of the ways to remove it is to make a call to getchar which reads one character from the stdin stream. 3.5.3. Floating Types Floating point representation is a lot more complicated in computers than it is for us human beings. C specification takes floating points description and specification from IEC 60559:1989 which is a standard for floating point arithmetic which is same as IEEE 754. In C there are three types of floating point numbers float, double and long double. It is described in specification in \(\S(\text{iso.5.2.4.2.2})\). A floating-point number is used to represent real-world fractional value which is a trade-off between range and accuracy because as I said in fractional binary numbers, a decimal fraction cannot represented in binary unless the denominator of that number is an integral power of 2. A number is, in general, represented approximately to a fixed number of significant digits (the significand) and scaled using an exponent; numbers are usually binary, octal, decimal or hexadecimal. A number that can be represented exactly is of the following form: \(\text{significand} \times \text{base}^\text{exponent}\) For example, \(1.2345 = \underbrace{12345}_\text{significand} \times \,\underbrace{10}_\text{base}\!\!\!\!\!\!^{\overbrace{-4}^\text{exponent}}\) The term floating point refers to the fact that a number’s radix point (decimal point, or, more commonly in computers, binary point) can “float”; that is, it can be placed anywhere relative to the significant digits of the number. 3.5.3.1. Representation of Floating-Point Numbers Given below are pictorial representations of 32-bit and 64-bit floating point numbers: 32-bit floating-point numbers Similarly in 64-bit floating point numbers we have 1 bit for sign, 11 bits for exponent and 52 bits for fractional part. Clearly zero will be represented by all sign and exponent bits having value 0 for them. C also has concept of positive and negative infinities. Sign bit is 0 for positive infinity and 1 for negative infinity. Fractional bits are 1 while exponent bits are all 1. Certain operations cause floating point exceptions like division from zero or square rooting a negative number. Such exceptions are represented by NANs which stands for “not a number”. Sign for NaNs is similar i.e. 0 for positive and 1 for negative. Exponent bits are 1 and fractional part is anything but all 0s because that represents positive infinity. There is also four rounding modes which we will see later. Now let us see a program to see how we can take input and print the floating point numbers. #include <stdio.h> int main() { float f = 0.0; double d = 0.0; long double ld = 0.0; printf("Enter a float, double and long double separated by space:\n"); scanf("%f %lf %Lf", &f, &d, &ld); printf("You entered %f %lf %Lf\n", f, d, ld); return 0; } If you run this you might have following output: Enter a float, double and long double separated by space: 3.4 5.6 7.8 You entered 3.400000 5.600000 7.800000 By default these print upto six significant digits but doubles have double precision as we have studied. Now that we know basic types let us learn a bit about input/output. Here I am giving the contents of limits.h for you to see limits of data types and check for yourself. /* Copyright (C) 1991, 1992, 1996, 1997, 1998,. */ /* * ISO C99 Standard: 7.10/5.2.4.2.1 Sizes of integer types <limits.h> */ #ifndef _LIBC_LIMITS_H_ #define _LIBC_LIMITS_H_ 1 #include <features.h> /* Maximum length of any multibyte character in any locale. We define this value here since the gcc header does not define the correct value. */ #define MB_LEN_MAX 16 /* If we are not using GNU CC we have to define all the symbols ourself. Otherwise use gcc's definitions (see below). */ #if !defined __GNUC__ || __GNUC__ < 2 /* We only protect from multiple inclusion here, because all the other #include's protect themselves, and in GCC 2 we may #include_next through multiple copies of this file before we get to GCC's. */ # ifndef _LIMITS_H # define _LIMITS_H 1 #include <bits/wordsize.h> /* We don't have #include_next. Define ANSI <limits.h> for standard 32-bit words. */ /* These assume 8-bit `char's, 16-bit `short int's, and 32-bit `int's and `long int's. */ /*) /* Maximum value an `unsigned long long int' can hold. (Minimum is 0.) */ # define ULLONG_MAX 18446744073709551615ULL # endif /* ISO C99 */ # endif /* limits.h */ #endif /* GCC 2. */ #endif /* !_LIBC_LIMITS_H_ */ /* Get the compiler's limits.h, which defines almost all the ISO constants. We put this #include_next outside the double inclusion check because it should be possible to include this file more than once and still get the definitions from gcc's header. */ #if defined __GNUC__ && !defined _GCC_LIMITS_H_ /* `_GCC_LIMITS_H_' is what GCC's file defines. */ # include_next <limits.h> #endif /* The <limits.h> files in some gcc versions don't define LLONG_MIN, LLONG_MAX, and ULLONG_MAX. Instead only the values gcc defined for ages are available. */ #if defined __USE_ISOC99 && defined __GNUC__ # ifndef LLONG_MIN # define LLONG_MIN (-LLONG_MAX-1) # endif # ifndef LLONG_MAX # define LLONG_MAX __LONG_LONG_MAX__ # endif # ifndef ULLONG_MAX # define ULLONG_MAX (LLONG_MAX * 2ULL + 1) # endif #endif #ifdef __USE_POSIX /* POSIX adds things to <limits.h>. */ # include <bits/posix1_lim.h> #endif #ifdef __USE_POSIX2 # include <bits/posix2_lim.h> #endif #ifdef __USE_XOPEN # include <bits/xopen_lim.h> #endif Here, I have given gcc’s limits.h as gcc includes that. For knowing exact implementation for floating-point implementation on your platform I recommend you to read . It is not possible to present all the information in detail here and I do not want to give you partial information. :-) I recommend you to go through and in particular. The range of log double varies from compiler to compiler. 3.6. New Data Types of C99 There are some new data types introduced in C99. They are _Bool, _Complex and _Imaginary. 3.7. Boolean Types _Bool counts as an integral type and is used to represent boolean values. Here is stdbool.h for your quick reference. /*===---- stdbool.h - Standard header for booleans -------------------------=== * * Copyright (c) 2008 Eli Fried __STDBOOL_H #define __STDBOOL_H /* Don't define bool, true, and false in C++, except as a GNU extension. */ #ifndef __cplusplus #define bool _Bool #define true 1 #define false 0 #elif defined(__GNUC__) && !defined(__STRICT_ANSI__) /* Define _Bool, bool, false, true as a GNU extension. */ #define _Bool bool #define bool bool #define false false #define true true #endif #define __bool_true_false_are_defined 1 #endif /* __STDBOOL_H */ As you can see from the definition true is 1 and false is 0. Any non-zero value is considered to be true. Here is a program demonstrating that. // Boolean Program // Description: Demo of boolean data typec #include <stdio.h> #include <stdbool.h> int main() { bool bcpp = 4; _Bool bc = 5; bool True = true; _Bool False = false; bool bFalseCPP = -4; _Bool bFalseC = -7; printf("%d %d %d %d %d %d\n", bcpp, bc, True, False, bFalseCPP, bFalseC); getchar(); return 0; } and the output is: 1 1 1 0 1 1 Note that true and false are keywords while True and False are identifiers. Though I wanted to avoid dealing with this but since I am including header files verbatim I must give an explanation of #define pre-processor macro at least. I will touch it very little as it will be covered in more detail later. #define has two parameters though not as function arguments. Whenever the first part is encountered second will be replaced. Consider this example: // Boolean Program // Description: Demo of boolean data type #define MAX 7 int main() { MAX; return 0; } Just do $gcc -E define.c to see the magic. Note that #define parameters are not type safe. Compiler will just paste the contents. Notice how MAX is replaced by 7. 3.8. Complex Types For complex types, there is a system header complex.h which internally includes various other headers. However I am giving you the summary here. There are following #define macros: complex: Expands to _Complex _Complex_I: Expands to a constant expression of type const float _Complex with the value of the imaginary. imaginary: Expands to _Imaginary. _Imaginary_I: Expands to a constant expression of type const float _Imaginary with the value of the imaginary value. I: Expands to either _Imaginary_I or _Complex_I. If _Imaginary_I is not defined, I expands to _Complex_I. - Complex types are declared as given below: float complex fCompZ; double complex dCompZ; long double ldCompZ; Now I will present a summary of library functions provided by complex.h //cabs, cabsf, cabsl - these compute and return absolute value //of a complex number z double cabs(double complex z); float cabsf(float complex z); long double cabsl(long double complex z); //carg, cargf, cargl - these compute and return argument of a complex //number z. The range of return value's range from one +ve pi radian //to one -ve pi radian. double carg(double complex z); float cargf(float complex z); long double cargl(long double complex z); //cimag, cimagf, cimagl - these compute imaginary part of a complex //number z and return that as a real number. double cimag(double complex z); float cimagf(float complex z); long double cimagl(long double complex z); //creal, crealf, creall - these compute real part of a complex //number z and return the computed value. double creal(double complex z); float crealf(float complex z); long double creall(long double complex z); //conj, conjf, conjl - these functions compute the complex conjugate //of z, by reversing the sign of its imaginary part and return the //computed value. double complex conj(double complex z); float complex conjf(float complex z); long double complex conjl(long double complex z); //cproj, cprojf, cprojl - these functions compute a projection of z // onto the Riemann sphere: z projects to z, except that all complex //infinities (even those with one infinite part and one NaN (not a //number) part) project to positive infinity on the real axis. If z //has an infinite part, then cproj( z) shall be equivalent to: //INFINITY + I * copysign(0.0, cimag(z)) //These functions return the computed value. double complex cproj(double complex z); float complex cprojf(float complex z); long double complex cprojl(long double complex z); //cexp, cexpf, cexpl - these functions shall compute the complex //exponent of z, defined as e^z and return the computed value double complex cexp(double complex z); float complex cexpf(float complex z); long double complex cexpl(long double complex z); //clog, clogf, clogl - these functions compute the complex //natural (base e) logarithm of z, with a branch cut along //the negative real axis and return complex natural logarithm //value, in a range of a strip mathematically unbounded along //real axis and in the interval -ipi to +ipi along the //imaginary axis. double complex clog(double complex z); float complex clogf(float complex z); long double complex clogl(long double complex z); //csqrt, csqrtf, csqrtl - these functions compute the complex //square root of z, with a branch cut along the negative real //axis and return the computed value in the range of the right //half-plane (including the imaginary axis) double complex csqrt(double complex z); float complex csqrtf(float complex z); long double complex csqrtl(long double complex z); //cpow, cpowf, cpowl - these functions compute the complex //power function x^y, with a branch cut for the first //parameter along the negative real axis and return the //computed value. double complex cpow(double complex x, double complex y); float complex cpowf(float complex x, float complex y); long double complex cpowl(long double complex x, long double complex y); //csin, csinf, csinl - these functions compute the complex //sine of z and return the computed value. double complex csin(double complex z); float complex csinf(float complex z); long double complex csinl(long double complex z); //ccos, ccosf, ccosl - these functions compute the complex //cosine of z and return the computed value. double complex ccos(double complex z); float complex ccosf(float complex z); long double complex ccosl(long double complex z); //ctan, ctanf, ctanl - these functions compute the complex //tangent of z and return the computed value. double complex ctan(double complex z); float complex ctanf(float complex z); long double complex ctanl(long double complex z); //casin, casinf, casinl - these functions compute the complex //arc sine of z, with branch cuts outside the interval //[-1, +1] along the real axis and return the computed value //in the range of a strip mathematically unbounded along the //imaginary axis and in the interval -0.5pi to +0.5pi radian //inclusive along the real axis. double complex casin(double complex z); float complex casinf(float complex z); long double complex casinl(long double complex z); //cacos, cacosf, cacosl - these functions compute the complex //arc cosine of z, with branch cuts outside the interval //[-1, +1] along the real axis and return the computed value //in the range of a strip mathematically unbounded along the //imaginary axis and in the interval -0 to +pi radian //inclusive along the real axis. double complex cacos(double complex z); float complex cacosf(float complex z); long double complex cacosl(long double complex z); //catan, catanf, catanl - these functions compute the complex //arc tangent of z, with branch cuts outside the interval //[-i, +i] along the real axis and return the computed value //in the range of a strip mathematically unbounded along the //imaginary axis and in the interval -0.5pi to +0.5pi radian //inclusive along the real axis. double complex catan(double complex z); float complex catanf(float complex z); long double complex catanl(long double complex z); //csinh, csinhf, csinhl - these functions compute the complex //hyperbolic sine of z and return the comupted value. double complex csinh(double complex z); float complex csinhf(float complex z); long double complex csinhl(long double complex z); //ccosh, ccoshf, ccoshl - these functions shall compute the //complex hyperbolic cosine of z and return the computed //value double complex ccosh(double complex z); float complex ccoshf(float complex z); long double complex ccoshl(long double complex z); //ctanh, ctanhf, ctanhl - these functions compute the //complex hyperbolic tangent of z and return the computed //value. double complex ctanh(double complex z); float complex ctanhf(float complex z); long double complex ctanhl(long double complex z); //casinh, casinhf, casinhl - these functions compute the //complex arc hyperbolic sine of z, with branch cuts //outside the interval [-i, +i] along the imaginary axis and //return the complex arc hyperbolic sine value, in the range //of a strip mathematically unbounded along the real axis //and in the interval [-i0.5pi, +i0.5pi] along the imaginary //axis. double complex casinh(double complex z); float complex casinhf(float complex z); long double complex casinhl(long double complex z); cacosh, cacoshf, cacoshl - theese functions compute the //complex arc hyperbolic cosine of z, with a branch cut at //values less than 1 along the real axis and return the complex //arc hyperbolic cosine value, in the range of a half-strip //of non-negative values along the real axis and in the //interval [-ipi, +ipi] along the imaginary axis. double complex cacosh(double complex z); float complex cacoshf(float complex z); long double complex cacoshl(long double complex z); //catanh, catanhf, catanhl - these functions shall compute the //complex arc hyperbolic tangent of z, with branch cuts outside //the interval [-1, +1] along the real axis and return the //complex arc hyperbolic tangent value, in the range of a strip //mathematically unbounded along the real axis and in the //interval [-i0.5pi, +i0.5pi] along the imaginary axis. double complex catanh(double complex z); float complex catanhf(float complex z); long double complex catanhl(long double complex z); Hers is a small demo program which explains two functions: // Complex Number Program // Description: Demo of complex data type #include <stdio.h> #include <complex.h> int main() { double complex z = 4.0 + 3.0i; printf("Absolute value of z is %lf\n", cabs(z)); double complex zConj = conj(z); printf("Imaghinary part of conjugate is now %lf\n", cimag(zConj)); return 0; } and the output is: Absolute value of z is 5.000000 Imaghinary part of conjugate is now -3.000000 You must note that in Makefile you must compile it like $gcc complex.c -o complex -lm. Note the -lm part. It tells to look for definition of these functions in Math library of C. Without it the program won’t compile. At this point I encourage you to further explore different functions presented in the summary. There are even more data types for integral type. I am sorry but I am unwrapping the layers one by one. These types are defined in inttypes.h and stdint.h. The types are int8_t, int16_t, int32_t, uint8_t, uint16_t and uint32_t. The numbers tell you how many bits each data type will occupy. The types without leading u are of signed type and the ones with it are of unsigned type. You can use the good old %d or %i for decimal integers and others for octals and hexes. Have a look at headers and try to decipher them. 3.9. Void and Enum Types There are these four types remianing. void type comprises an empty set of values; it is an incomplete type that cannot be completed. You cannot declare an array of void. It is a generic type in the sense that any other pointer to any type can be converted to pointer type of void and vice-versa. It is a low level type and should be only used to convert data types from one type to another and sparingly. A type occupies one byte. Typically you never declare a variable of void type. It is used mostly for casting. enum comprises a set of named integer constant values. Each distinct enumeration constitutes a different enumerated type. In C enums are very much equivalent to integers. You can do all operations of an enum on an enumeration member. An enumeration is is a set of values. It starts from zero by default and increments by one unless specifically specified. Consider the following example: // Description: Demo of enum #include <stdio.h> int main() { typedef enum {zero, one, two} enum1; typedef enum {alpha=-5, beta, gamma, theta=4, delta, omega} enum2; printf("zero = %d, one = %d, two=%d\n", zero, one, two); printf("alpha = %d, beta = %d, gamma=%d, theta=%d, delta=%d, omega=%d\n", \ alpha, beta, gamma, theta, delta, omega); return 0; } and the output is: zero = 0, one = 1, two=2 alpha = -5, beta = -4, gamma=-3, tehta=4, delta=5, omega=6 3.10. Constants We have seen some variables now let us see some constants. There are five categories of constants: character, integer, floating-point, string, and enumeration constant. We will see enumeration constants later first we see remaining four types of constants. There are certain rules about constants. Commas and spaces are not allowed except for character and string constants. Their range cannot outgrow the range of there data type. For numeric type of stants they can have a leading (-)minus sign. Given below is an example: // Integer constants // Description: Demo of integer constants #include <stdio.h> int main() { int decimal = 7; int octal = 06; int hex = 0xb; printf("%d %o %x\n", decimal, octal, hex); return 0; } and the output is: 7 6 b As you can see there are three different categories for integer constants: decimal constants (base 10), octal constants (base 8) and hexadecimal constants (base 16). Also, you must have noticed how a zero is prefixed before octal type and a zero and x for hexadecimal type. The %d format specifier is already known to you for signed decimals. However, now you know two more %o and %x for unsigned octal and unsigned hexadecimal respectively. For unsigned integer it is %u. There is one more format specifier which you may encounter for signed decimal and that is %i. Note that there is nothing for binary constants. I leave this as an exercise to you to convert a number in any base shown above to binary and print it. Also vice-versa that is take a input in binary and convert to these three. Later I will show you this program. Now let us move to floating-point constants. Again, I will explain using an example: // Floating-point constants // Description: Demo of floating-point constants #include <stdio.h> int main() { float f = 7.5384589234; double d = 13.894578834538578234784; long double ld = 759.8263478234729402354028358208358230829304; printf("%f %lf, %Lf\n", f, d, ld); return 0; } and the output is: 7.538459 13.894579, 759.826348 We will learn to change precision later when we deal with format specifiers along with printf and all input/output family. Here also, you learn three format specifiers. Other are %e or %E for scientific notation of float family. Then there is %g or %G which uses shorter of %e and %f types. Now we move on to character and string type constants and as usual with a small program. // Character constants // Description: Demo of character constants #include <stdio.h> int main() { char c = 'S'; char* str ="Shiv S, Dayal"; printf("%c %s\n", c, str); return 0; } and the ouput is: S Shiv S, Dayal As I had said that commas and blanks are not allowed in numeric types but you can see both are allowed on character and string types. Also, the string is a character pointer that is it can point to memory location where a character is stored. In this case the string is stored in an area of memory called stack. When memory is allocated the compiler knows how much has been allocated. For string there is something called null character represented by ‘\0’ which is used to terminate string. By using this mechanism the program knows where the string is terminating. It is treated in next section as well.A very interesting thing to be noted is char is considered to be an integral type. It is allowed to perform addition etc on char type. Till now you have learnt many format specifiers and have seen they all start with %. Think how will you print % on stdout. It is printed like %%. It was simple,wasn’t it? C program have got something called ASCII table which is a 7-bit character table values ranging from0 to 127. There is also something called escape sequences and it is worth to have a look at them. 3.11. Escape Sequences All escape sequences start with a leading \ . Following table shows them: Note that there is no space between two backslashes. Sphinx does not allow me to write four continuous backslashes. Now we will talk about all these one by one. \0 which is also known as NULL is the string terminating character, as said previously, and must be present in string for it to terminate. For example, in our character constant program the str string is “Shiv S. Dayal”. So how many characters are there 13? Wrong 14! The NULL character is hidden. Even if we say str=””; then it will contain one character and that is this NULL. Many standard C functions rely on this presence of NULL and causes a lot of mess because of this. The bell escape sequence if for a bell from CPU. Let us write a program and see it in effect. // Bell Program // Description: Demo of bell escape sequence #include <stdio.h> int main() { printf("hello\a"); getchar(); return 0; } The output of this program will be hello on stdout and an audible or visible bell as per settings of your shell. Notice the getchar() function which waits for input and reads a character from stdin. Next is backspace escape sequence. Let us see a program for its demo as well: // Backspace Program // Description: Demo of backspace escape sequence #include <stdio.h> int main() { printf("h\b*e\b*l\b*l\b*o\b*\n"); printf("\b"); getchar(); return 0; } and the output is: ***** It is hello replaced by *. A minor modification in this program to replace the character as soon as key is pressed by some other character will turn it into a password program. Backspace escape sequence means when it is encountered the cursor moves to the previous position on the line in context. If active position of cursor is initial position then C99 standard does not specify the behavior of display device. However, the behavior on my system is that cursor remains at initial position. Check out on yours. The second printf function determines this behavior. Next we are going to deal with newline and horizontal tab escape sequences together as combined together they are used to format output in a beautiful fashion. The program is listed below: // Newline and Horizontal tab program Program // Description: Demo of newline and horizontal tab escape sequence #include <stdio.h> int main() { printf("Before tab\tAftertab\n"); printf("\nAfter newline\n"); getchar(); return 0; } and the output is: Before tab Aftertab After newline Here I leave you to experiment with other escape sequences. Feel free to explore them. Try various combinations. Let your creative juices flow.
https://www.ashtavakra.org/c-programming/basics/
CC-MAIN-2022-05
refinedweb
7,845
64.3
Library Interfaces and Headers - regular expression matching types #include <regex.h> The <regex.h> header defines the structures and symbolic constants used by the regcomp(), regexec(), regerror(), and regfree() functions. See regcomp(3C). The structure type regex_t contains the following member: size_t re_nsub number of parenthesized subexpressions The type size_t is defined as described in <sys/types.h>. See types.h(3HEAD). The type regoff_t is defined as a signed integer type that can hold the largest value that can be stored in either a type off_t or type ssize_t. The structure type regmatch_t contains: use extended regular expressions ignore case in match report only success or fail in regexec() change the handling of NEWLINE character Values for the eflags parameter to the regexec() function are as follows: The circumflex character (^), when taken as a special character, does not match the beginning of string. The dollar sign ($), when taken as a special character, does not match the end of string. The following constants are defined as error return values: regexec() failed to match. Invalid regular expression. Invalid collating element referenced. Invalid character class type referenced. Trailing '\' in pattern. Number in \\digit invalid or in error. “[]” imbalance. “\(\)” or “()” imbalance. “\\{\\}” imbalance. Content of “\\{\\}” invalid: not a number, number too large, more than two numbers, first larger than second. Invalid endpoint in range expression. Out of memory. '?', '*', or '+' not preceded by valid regular expression. Reserved. See attributes(5) for descriptions of the following attributes: regcomp(3C), types.h(3HEAD), attributes(5), standards(5)
http://docs.oracle.com/cd/E23823_01/html/816-5173/regex.h-3head.html
CC-MAIN-2015-40
refinedweb
250
50.33
Docs/Drafts/SELinux/SETroubleShoot/DeveloperFAQ From FedoraProject 3. SETroubleshoot Developer FAQ 1. RPC 1. Why does SETroubleShoot use RPC? 2. What RPC mechanism does SETroubleshoot use and why? 3. The internal RPC uses XML, why not just use XML-RPC? 4. DBUS 5. What is the data channel between the client and server? 6. What is the protocol between the client and server? 1. What are the RPC header fields? 7. What types of RPC transactions are there? 8. Are RPC calls synchronous or asynchronous? 9. How do I get a return values from a RPC call? 10. How are errors handled in RPC calls? 11. How are the signatures (parameter lists) of RPC methods defined? 12. RPC calls on the wire, and XML serialization 13. Calling a remote method vs. implementing a remote method 14. Can a single RPC interface provide both caller and callee methods? 15. How do I monitor the state of the connection? 2. XML 1. What is XML used for? 2. Why isn't Python introspection used for XML serialization? 3. Where is the XML structure defined and how does it work? 3. Plugins 1. What plugins are loaded? 3.1. RPC 3.1.1. Why does SETroubleShoot use RPC? SETroubleshoot is composed of two fundamental parts. A system daemon (setroubleshootd) running with root privlegesm, often referred to as the server and 1 or more clients which connect to the setroubleshootd server to receive notifications of new AVC denials and query the history of AVC denials on a particular node. The daemon (server) needs to exist for two fundamental reasons: It needs to run with root priveldges to interact with the audit system, perform system operations, and then to isolate the information it manages from user level processes. In addition by acting as a server on a particular node it is possible to build a distributed system whereby remote clients can connect to multiple nodes to listen for alerts or query their alert history. Initially only the client is sealert. sealert can operate either as a desktop GUI component or a command line tool. One can think of the server (setroubleshootd) as the process which manages data and the client (sealert) as the process which presents the data. Because they are two seperate processes, possibly running on different nodes, they communnicate via RPC. 3.1.2. What RPC mechanism does SETroubleshoot use and why? SETroubleshoot uses it's own RPC based on XML documents exchanged over a socket connection. But the world is full of RPC mechansisms, many of which are standardized, why invent a new private mechanism when instead you could use SOAP, D-Bus, XML_RPC, etc.? Because there were several requirements which prompted this decision: - setroubleshoot should not depend on packages which are not normally installed, in other words it should be mostly self contained and the installation should be minimal. For example the Twisted python library is an excellent RPC toolset, but it is large and not a standard package, therefore it fails this requirement. - The server and client work best together when the link between them is: - persistent (best for sending/receiving asynchronous alerts) - asynchronous (there should be no blocking, no order dependency) - bidirectional (either the client or server should be able to intiate communication and receive a response) - stateful (each communication link maintains information on each end of the link about the properties and state of the link). Such information includes: - session information (e.g. logged on user and type of session) - connection pool (set of connected clients and their sessions) - state of asyncronous transactions (e.g. what transactions have been initiated, what state are they in, how does one map an asynchronous transaction to an action at the receiving end). 3.1.3. The internal RPC uses XML, why not just use XML-RPC? - XML-RPC is not persistent - XML-RPC is not asynchronous - XML-RPC is not stateful - XML-RPC requires both the ends of the link to implement both a client and a server if one wants bidirectionality and somehow link them together (at that point ease of use is lost). - XML-RPC is targeted to simple data types, passing complex objects requires an additional layer bolted on top of XML-RPC (one quickly loses the XML-RPC simplicity advantage) 3.1.4. D-Bus D-Bus has nice python bindings and it is well supported. Why not use D-Bus as the RPC mechanism? Because D-Bus currently only supports local interprocess communication on one node, this is its design center. But setroubleshoot currently uses D-Bus, why is it used for some things and not others, more to the point, if you're using D-Bus already why introduce a private RPC mechanism? D-Bus is used for the desktop GUI component (sealert). It's use in this context makes perfect sense because D-Bus has at it's heart facilities for managing items in a user's desktop session. In particular DBUS provides easy ways to automatically launch programs, treat a program as a service provider for the login session, etc. The GUI desktop component of setroubleshoot (sealert) benefits from it's integration with the desktop session, but this is independent of the issue of where and how the AVC alert information is derived from. By analogy a web browser benefits from D-Bus integration on the desktop but its data communication remains HTTP to remote nodes. 3.1.5. What is the data channel between the client and server? The connection is a socket. By default the socket is a local UNIX domain socket for enhanced security. However, it is trivial to configure the client/server code to use INET sockets instead to accomodate remote connections. The vast bulk of the code is agnostic with regards to the socket type. 3.1.6. What is the protocol between the client and server? The protocol is a very simple text based protocol similar to HTTP. Each transaction consists of a header and a body. The header is a series of key/value pairs (e.g. fields). Keys start at the beginning of a line and may not contain whitespace or a colon (:). The key is separated from its value by a colon (:) and is terminated by a line ending. Line endings are carriage return, newline pairs. The header is separated from the body by a blank line. The header MUST contain a content-length field which is the octet count of the body (beginning after the blank line separating the header from the body). Fields in the header may be appear in any order. No information is provided which declares the size of the header. The header MUST declare the size of the body with a content-length field. The receiving end reads a header until it sees a blank line demarking the header from the body. At this point the receiving end knows the exact body octet count which must then be read to consume the entire body. After the body has been read the receiving end interprets subsequent octets as the header of the next transaction, thus it always knows the boundary between transactions. 3.1.6.1. What are the RPC header fields? - content-length: The mandatory octet count of the body - type: The RPC transaction type, may be one of: method, method_return, signal, or error_return - rpc_id: an identifier unique to the session which maps a specific instance of a method call to either the method return values or returned error information. 3.1.7. What types of RPC transactions are there? - method: An RPC call with one or more return values - method_return: An RPC call with the return values from a previous RPC method call. This is best thought of as a "callback". Callbacks have their own argument list (e.g. method signature) completely independent of the signature of its matching method. - signal: An RPC call which does not return any values (e.g. a one way event) - error_return: An RPC call whose signature is (method_name, err_code, err_msg). 3.1.8. Are RPC calls synchronous or asynchronous? RPC calls are always asynchronous. Eliminating blocking and handling RPC transactions as part of a larger event loop vastly simplifies large parts of the code and offers tremendous flexibility (e.g. event driven model). There is no support for synchronous RPC calls. 3.1.9. How do I get a return values from a RPC call? RPC methods return an async_rpc object which implements the add_callback() and add_errback() methods. Immediately after calling the RPC command one can use the returned object to attach any number of callback or error handlers to the command. At some point in the future the RPC command will return either its return values or in the case of a failure error information. When the return information arrives the RPC implementation looks up the object belonging to the call and calls each attached callback if the method succeeded, or each attached errback if the method failed. Here is a code example: #!python def get_flag(flag_name): def get_flag_callback(flag_value): print "flag %s = %s" % (flag_name, flag_value) def get_flag_error(method, errno, strerror): print "%s ERROR: error code = %d, message = %s" % (method, errno, strerror) async_rpc = foo.get_flag(item, flag_name) async_rpc.add_callback(get_flag_callback) async_rpc.add_errback(get_flag_error) This will call the get_flag method on object which implements the RPC interface which defines the get_flag() method. In this example 'foo' is an object exporting that interface. At some point in the future when control returns to the main event loop either the function get_flag_callback() or get_flag_error() will be called. Note: Because Python implements "function closure" one may nest functions (e.g. inner functions). When this is done values are "bound" in the inner function when the outer function is invoked. Thus any value which is in the scope of the outer function may be referenced in the inner function when the inner function is invoked. In our example flag_name is defined in the outer get_flag() function and referenced in the inner get_flag_callback() function. Whenever the inner callback is invoked in the future the value of flag_value will be whatever it was when the rpc method was invoked. This is very handy, it means your callback maintains variable state, if you need to reference something in your callback you can and be confident it will be unique to that callback instance. Even if we called get_flag() twice in a row passing "foo" and "bar" as the flag_name parameter before either of the callbacks were invoked the first instance of get_flag_callback would have flag_name bound to "foo" and the second instance would have flag_name bound to "bar". 3.1.10. How are errors handled in RPC calls? All RPC calls are assumed to succeed. Errors are never part of the normal return values. Instead, if a RPC call generates an error a seperate callback is invoked known as the errback. Thus when calling an RPC method you may attach a normal callback to it and/or a callback to handle an error, the two are distinct. When the RPC returns either the attached callbacks are going to be invoked if it is successful or the attached errbacks are going to be invoked if it failed. All errbacks have identical function signatures: #!python def errback(method, errno, strerror): The method parameter will be the name of the method which induced the error, the errno parameter will be a numeric error code, and strerror will be a string describing the error). The method name parameter in the errback is a convenience, it does not tell you which particular instance of an RPC method call failed, just the name of the method. If you need to know the particular instance recall there is an exact one-to-mapping when you bind an errback to a RPC call via the add_errback() method. This binding is identical to add_callback() and all the issues relative to binding scope described for callbacks apply to the errback as well. If you need to know the exact instance just make sure there is something in the binding scope of the errback which uniquely identifies it, for instance an object reference. 3.1.11. How are the signatures (parameter lists) of RPC methods defined? Each RPC call is a member of an RPC interface. Each method in an RPC interface must have a name unique within that interface. Different interfaces may have method names in common. The definitions of RPC methods, signals, and callbacks are done using Python decorators. A decorator is a python function preceded by an "at sign" (@). Python functions or methods which have been "decoratated" have one or more decorators immediately preceding their def statement. Our RPC implementation defines 3 decorators (in rpc.py ) - def rpc_method(interface): - def rpc_callback(interface, method): - def rpc_arg_type(interface, *arg_types): When a method is decorated with @rpc_method() it is saying "this method is a member of the interface". It's parameter list is defined by the python method that was decorated. Optionally we may define the type of each parameter via the @rpc_arg_type() decorator. After the interface definition comes a list of Python types, one for every parameter. If the @rpc_arg_type() decorator is absent the parameters default to being of type string. If the RPC call is a method (as opposed to a signal) it must have one or more return values. Return values are passed back via a callback so it is natural to define them as a parameter list to the callback function. The @rpc_callback() decorator says "this is the callback signature for a method in an interface" Just like the @rpc_method() decorator it may optionally be associated with @rpc_arg_type() decorator to define the parameter types. The RPC interfaces used in setroubleshoot are defined in rpc_interfaces.py Here is an example which illustrates the concepts: #!python @rpc_method('SETroubleshootServer') def database_bind(self, database_name): pass @rpc_callback('SETroubleshootServer', 'database_bind') @rpc_arg_type('SETroubleshootServer', SEDatabaseProperties) def database_bind_callback(self, properties): pass We are defining a method in the SETroubleshootServer interface called database_bind. The method takes one parameter, database_name. Because there is no @rpc_arg_type decorator associated with the method the parameters default to being strings. Because it is a method (as opposed to a signal) it must have an associated callback to return its values. The @rpc_callback() decorator is binding this callback defintion to the database_bind method in the SETroubleshootServer interface. The callback has one parameter which is defined to be an object of the class SEDatabaseProperties, this information is provided by the @rpc_arg_type() decorator. In summary, when database_bind() is called passing a database name it will return a SEDatabaseProperties object. 3.1.12. RPC calls on the wire, and XML serialization In signature.py we define the members of the SEDatabaseProperties object #!python SEDatabasePropertiesAttrs = { 'name' : {'XMLForm':'element' }, 'friendly_name' : {'XMLForm':'element' }, 'filepath' : {'XMLForm':'element' }, } Which simply states the SEDatabaseProperties object has 3 members (name, friendly_name, and filepath), and when the object is serialized into XML each member will be an element (defaulting to type string). On the wire the database_bind() method is encoded as a header+body. The header states the type of the RPC call is 'method' and its unique rpc identifier (rpc_id) is '1'. The rpc_id will be used at method return time to match the callbacks to this particular call. The header also states the body which follows the header is 181 octets long. A client calling database_bind('audit_listener') would have a wire representation which looks like this: data=content-length: 181 type: method rpc_id: 1 <?xml version="1.0"?> <cmd interface="SETroubleshootServer" method="database_bind" arg_count="1"> <arg name="database_name" position="0" type="string">audit_listener</arg> </cmd> The body is always an XML document which encodes the RPC call and its parameters. The top <cmd> element defines the interface and method which as a pair uniquely identifes what is being called. It also includes a count of how many arguments follow. Each child of the <cmd> element is an <arg> element which defines the parameter name, its position in the parameter list, and its type. The children of the <arg> element is the value for the parameter, which is interpreted via the type attribute of its <arg> element parent. Following our example of a client calling database_bind('audit_listener') the server might respond with content-length: 373 type: method_return rpc_id: 1 <?xml version="1.0"?> <cmd interface="SETroubleshootServer" method="database_bind_callback" arg_count="1"> <arg name="properties" position="0" type="xml"> <properties> <filepath>/var/lib/setroubleshoot/audit_listener_database.xml</filepath> <friendly_name>Audit Listener</friendly_name> <name>audit_listener</name> </properties> </arg> </cmd> At this point the header should be self explanatory. The body says this is a database_bind_callback method in the interface SETroubleshootServer. We know from the interface definition database_bind_callback() has one parameter called 'properties' and it will be a SEDatabaseProperties object. When the wire representation is decoded we look up the definition of the method and see we are expecting one parameter and it should be a SEDatabaseProperties object. The type attribute in the <arg> element says it is encoded as XML, which is how we encode complex objects. The SEDatabasePropertiesAttrs says we should expect 3 elements (name, friendly_name, and filepath) all encoded as elements. We parse the children of the <arg> node and construct a SEDatabaseProperties from the values we parse. At this point the we lookup the rpc_id to see what callbacks were associated with the original database_bind() call. For every callback bound to this call we call the callback passing the SEDatabaseProperties object we constructed from the XML body. 3.1.13. Calling a remote method vs. implementing a remote method There is a distinction between calling an RPC method (caller) and implementing an RPC method (callee). Objects which want to call a remote method must include somewhere in their ancestor classes the RPC interface class which contains the method they wish to call (currently all RPC interfaces are defined in rpc_interfaces.py ). In addtion the class must derive from RpcChannel so there is a communication pipe. Recall that methods defined in the RPC interface class are decorated with things like @rpc_method(). These decorators are the magic which transforms a method call on an RPC interface into RPC communication. From the caller's perspective one only needs to include the interface definition and then make the call remembering that all methods in a RPC interface return an async_rpc object which you will need to connect a callback and/or errback to. Lets use the following RPC interface example for both a caller and callee: #!python class MyInterface: @rpc_method('MyInterface') def get_user_data(user_name): pass @rpc_callback('MyInterface', 'get_user_data') @rpc_arg_type('MyInterface', UserData) def get_user_data_callback(user_data): pass As the caller your code might look something like this: #!python class DoSomethingRemote(RpcChannel, MyInterface): def __init__(self): self.open() # pseudo code for opening channel self.user_data = None def lookup_user(self, user_name): def store_user_data(user_data): self.user_data = user_data def user_data_error(method, errno, strerror): print "could not find data for user %s: %s" % (user_name, strerror) sys.exit(1) async_rpc = self.get_user_data(user_name) # make the call async_rpc.add_callback(store_user_data) # attach the callback async_rpc.add_errback(user_data_error) # handle errors To call the RPC get_user_data() the object derived the channel and the interface and simply just called the method providing a callback handler for the return value, which in our example will be a UserData object. To implement the RPC method on the remote side a class provides an implementation of the method which matches the signature (parameter list) in the RPC interface. That class DOES NOT derive from the RPC interface! The class just provides a method with the same parameter list as defined in the interface and provide an RpcChannel for communication. Then it connects the communication pipe (RpcChannel) to the object implementing the RPC interface. The connection is made by: channel.connect_rpc_interface(interface_name, handler_object) What this does is tell the channel when it sees an RPC on the specified interface it should call the method in the handler_object. A callee returns values as if it were the parameter list for the callback. Thus if the callback had two parameters and looked like this: iface_callback(foo, bar) the callee would return (foo, bar). If the callee does not have any return values it should return None. Thus a callee's return value is always either a list or None. Thus on the callee side your code might look like this: #!python class MyClass(RpcChannel): def __init__(self): self.open() # pseudo code for opening channel self.connect_rpc_interface('MyInterface', self) def get_user_data(self, user_name): user_data = find_user(user_name) if user_data is None: raise ProgramError(ERR_USER_NOT_FOUND, "user (%s) not found" % user_name) user_data = UserData(user_name) return [user_data] Error returns to the caller are handled gracefully by the Python exception mechanism. The RPC framework will catch ProgramError's. If a ProgramError exception is raised during the execution of a RPC callee's implementation of a method the RPC framework will catch the ProgramError and automatically return the error code and error message to the caller via the errback mechanism. On the caller side this translates to calling store_user_data(user_data) if the lookup succeeds or calling user_data_error('get_user_data', ERR_USER_NOT_FOUND, 'user (xxx) not found") if it fails. 3.1.14. Can a single RPC interface provide both caller and callee methods? No. RPC interfaces are one directional. A RPC interfaces defines what can be called on the interface. If you want both ends of the connection to be able to call each other you will need an interface for each end of the connection so there is a seperate calling interface on each end. One end calls, the other end implements. 3.1.15. How do I monitor the state of the connection? It is often necessary to know when a connection has been made, when it drops, etc. The RpcChannel class provides a callback, on_connection_state_change. Whenever the connection state changes it will call you with the new state. Currently the states are: - closed - open - retry - hup - error - invalid - timeout 3.2. XML 3.2.1. What is XML used for? XML is used primarilly for two purposes: - persistent storage of our data objects - transporting our data objects over a communication link (e.g. via RPC) This means any object which will be stored or passed in RPC will need to be able to be serialized into and out of XML representation. 3.2.2. Why isn't Python introspection used for XML serialization? Fundamentally there are two approaches one could take to provide XML serialization of objects: 1. The object is unaware of how it might be serialized, instead via introspection and recursion objects are broken down into fundamental types with simple rules on how to encode each fundamental type in XML. 2. The object is XML aware and is in control of exactly what its XML representation is. Option 1 is simple and elegant. Unfortunately it's not robust. There is no way to control what the final XML representation will be, anything in the object will get serialized, even if its not meant to be part of its portable representation. Python is very forgiving and you can attach any data you want at any time by simply assigning to the object. Such "extra data" might be legitimate internal private use, or it might get attached to the object by programmer error. Either way, it's not data which should get serialized into its portable representation. The portable representation should be very well defined. Lacking a well defined representation for the object also means it's difficult to provide defaults for member values, to validate its structure, guard against injecting superfluous data, especially if the extra data is malicous in intent, convert between versions of the representation, etc. Automatic serialization via introspection is like programming in Basic were everything is a global variable. Option 2 is much more robust. There is a well defined structure for objects. If a value is absent there is a defined default. Values which are not part of the definition can never be introduced via serilization. Malformed representations are easy to detect. Values can be assigned types. Versioning can be used to upgrade and downgrade representations. The representation can be controlled to take advantage of XML features and tailor the reprensentation to optimize for size or speed. One of the original goals of the project included communicating data across diverse systems possibly running at different revision levels making the well known structure of the XML representation critical. Automatic serialization via introspection fails the goal of well known structure. There needs to be a definition for the XML structure independent of the objects being serialized. 3.2.3. Where is the XML structure defined and how does it work? For historical reasons the XML structure is defined in signature.py . Each object which can be serialized inherits from the class XmlSerialize. When the XmlSerialize class is initialized it is passed a XXXAttrs dict which defines the structure, where XXX is the class name of the object. Each key in the Attr's dict is a member name in the object. When the object is created every key in the Attr's dict is instantiated as a member of the object and given a default value. Each member can specify whether it will be serialized as an attribute or an element (XMLForm) Each member can define it's type, at the moment it is either a class (which includes complex objects, and simple objects suchs as integers) or a list. Lists are unordered homogeneous collections. For both class and list members their values are a dict which defines their properties. For example the 'name' key in a class definition is the name of the class. The name key in a list defintion is the (element) name given to every member of the list. If the 'default' key is present in a defintion dict it is the default value to be assigned, otherwise the default is None. Actually, the default value is a function which is called that returns the default value, this is much more flexible. For instance it can return an instance of a class. Because the XML definition allows any object member to be either an object or a list of objects the serialization process is recursive yielding surprisingly complex XML representations from simple definitions. The basic process for when an object is serialized procedes like this: For every member in my Attr's dict get the value from the object. If the value is not None ask it to return it's representation as a xml node and add it to my xml node, then return my xml node. It's easy to see the recursion in this. Plus it guarantees only members in the defintion will be serialized according the definition. When XML is parsed to recreate an object the process begins with the definition. For each member in the definition find the XML node in the tree which matches it, ask that node to convert itself to a python object by it's defintion rules and then assign it to that member of the object. Once again the recursion should be self evident. Also note this process is significantly different than "walking" an XML tree. In that case the resulting python object would be whatever happened to be in the XML input. By letting our definition drive the parsing we end up with Python object which exacatly match our definitions. 3.3. Plugins 3.3.1. What plugins are loaded? Plugins are located in the directory /usr/share/setroubleshoot/plugins The load_plugins() function in util.py will attempt to load any file in the plugin directory with a python suffix as a python module. If the module load results in a python exception a diagnositic message is emitted and the plugin module is removed from the list of plugins. This allows for the entire system to be brought up even if one or more plugin's are bad.
http://fedoraproject.org/w/index.php?title=Docs/Drafts/SELinux/SETroubleShoot/DeveloperFAQ&oldid=83968
CC-MAIN-2014-42
refinedweb
4,635
54.63
Welcome to Replit! This platform aims to show you a new workflow that can change the way you write code. This guide should give you a quick overview of the many features of our platform. Don't worry if you are new to programming; we have tutorials to help you. To get you started, we have created these guides to get you coding in Python: From your "My Repls" dashboard, you can create a new repl by clicking on the "+ New Repl" button at the top of your sidebar, or the blue "+" button in the top right corner of the page. This will bring you to a dialog box where you can specify your preferred language from a drop-down menu, and name your repl. This will bring you to your workspace. The right repl name and discription will help with organizing your repls, and make it easier to find your desired repl later. Once you have created your repl, you can edit its name and description: There are three main parts to a repl: Now that you have your repl sorted, it's time to start coding. In the Console, type the following and hit enter: print("Hello World!") Here, you can evaluate code line by line and interact with its results. Now let's try entering the following: x = "hey" Then type: x * 3 Variables declared in the console persist, so you can continue to interact with variables there. Now let's move over to the Editor in the middle. Type in the following code: name = input("What's your name?") print("Hello", name) To run it, click on the big "Run" button at the top of the screen, or hit CTRL+Enter (Windows/Chromebook) or CMD+Enter (Mac). You'll see the code run on the right hand side of the screen. Since the program is asking for input, go ahead and type your name in the console and hit enter. It should then greet you! To demonstrate how to add packages, we are going to make a simple plot. Clear the code you have created up to now, and let's find a package. Packages are essentially directories which help us organize code without starting from scratch. We'll be using the matplotlib package: matplotlibto search for the package. +button to add it to your packages. This will create new files, pyproject.toml and poetry.lock, which contains all the package information for your repl, including the version number. It will also start installing on the right. Now select main.py to return to your program. Learn more about packages. Let's enter the following code: import matplotlib as mpl import matplotlib.pyplot as plt plt.plot([1, 2, 4, 8, 16]) plt.savefig('plot.png') Run the code. You'll see that the newly generated image, plot.png, shows up in the filetree. Clicking on it will show you the image in the editor! We hope you love this feature as much as we do. Learn more about plotting in Python. Let's create a new Python3 repl. (Save time and use this shortcut). Let's call this one "python flask server". Our first step is to add the flask package. Go through the steps above) except this time, choose the package called flask. Once finished, go back to main.py and enter the following code: from flask import Flask app = Flask(__name__) @app.route('/') def hello_repler(): return 'Hello, Repler!' if __name__ == '__main__': app.run(host='0.0.0.0', port=8080) Hit run, and you'll see that a new pane has appeared with the URL for your repl's hosted site, along with a preview of what it looks like. You can share this link with your friends to show them the simple app that you made. Learn more about web servers. So far, your repl is public to everyone (unless you have a paid plan) and they can see the code that you put here. If you need to add some private information, such as an API key or a database password, you can use the repl secrets manager. Create a new environment variable by clicking the "padlock" icon on the side panel Add a key-value pair for the environment variable setting the "key" as PASSWORD and "value" as pass1234. This secrets configuration will only be visible to you. Anyone who is visiting your repl won't be able to see the configured environment variables. Now let's edit main.py to include the following in the console: from flask import Flask, request, redirect import os app = Flask(__name__) def hello_world(): return redirect('/secret_route?secret=pass1234') def secret_route(): password = request.args.get('secret') if (password == os.environ['PASSWORD']): return 'You found the secret!' else: return 'Wrong password!' if __name__ == '__main__': app.run(host='0.0.0.0', port=8080) We're creating a new page where we look for a query parameter secret and we check to see if it matches with the secret stored in our environment variable. The gif below demonstrates the results. Note that this isn't a very secure way of handling secret tokens, since the URL including the query parameter can be cached. This is just a simple demonstration. Learn more about secrets & environment variables Now that you've created your first repl, feel free to share it with our community! Here's how: Feel free to join our Discord Community as well! Join with this invite link. If you're interested in exploring more and seeing what you can do with Replit, take a look at the following repls: You can find tutorials created by members of our community here. There are tutorials for creating single player and multiplayer games, web apps, Discord bots, and AI programs. Be sure to give the post an upvote if you enjoyed it! If you want to check out other cool repls that people have shared, you can find them on Share. If you have a question about programming or need help debugging something, be sure to post on Ask. Someone will help you if they can! Enjoy being a Repler! We would love to hear more from you about how you use Replit, how you found out about Replit, and if there's anything we can do to improve. Feel free to contact us through any of the following avenues:
https://docs.replit.com/repls/quick-start
CC-MAIN-2021-25
refinedweb
1,062
75.61
/* +++Date last modified: 05-Jul-1997 */ /* $Id: hash.h,v 1.9 2003/10/22 18:50:12 rjs3 Exp $ */ #ifndef HASH__H #define HASH__H #include <stddef.h> /* For size_t */ #include "strhash.h" #include "mpool; struct mpool *pool; } hash_table; /* ** This is used to construct the table. If it doesn't succeed, it sets ** the table's size to 0, and the pointer to the table to NULL. */ hash_table *construct_hash_table(hash_table *table, size_t size, int use_mpool); /* ** Inserts a pointer to 'data' in the table, with a copy of 'key' as its ** key. Note that this makes a copy of the key, but NOT of the ** associated data. */ void *hash_insert(const char *key,void *data,hash_table *table); /* ** Returns a pointer to the data associated with a key. If the key has ** not been inserted in the table, returns NULL. */ void *hash_lookup(const char *key,hash_table *table); /* ** Deletes an entry from the table. Returns a pointer to the data that ** was associated with the key so the calling code can dispose of it ** properly. */ /* Warning: use this function judiciously if you are using memory pools, * since it will leak memory until you get rid of the entire hash table */ void *hash_del(char *key,hash_table *table); /* ** Goes through a hash table and calls the function passed to it ** for each node that has been inserted. The function is passed ** a pointer to the key, a pointer to the data associated ** with it and 'rock'. */ void hash_enumerate(hash_table *table,void (*func)(char *,void *,void *), void *rock); /* **_hash_table(hash_table *table, void (*func)(void *)); #endif /* HASH__H */
http://opensource.apple.com/source/CyrusIMAP/CyrusIMAP-188/cyrus_imap/lib/hash.h
CC-MAIN-2015-40
refinedweb
258
71.55
Hi, I’m building a project which have 2 pushbutton, every click need to be counted. (like counting pulses). It’s using clickbutton lib and publishAsync to send theses data to particle. The most important thing is that every click on the buttons is counted, if particle connection is lost for few minutes it not problematic but still need to count the button internally and send the count value afterwards. During normal condition it’s working fine but discovered that during wifi reconnect it miss button counts. I investigated the reason of missing events count : - button clicks variable are not send to particle ?. No, i setup internal counters (count button press) and they have the same value as the particle published data. - Blocking code in the main loop : Button.update() is triggered in the main loop, nothing fancy could block the loop, publish only if particle connected. - Some kind of button bounce which cause wrong count? No, hardware debounce in place with Max6817, Minimum pulse lenght is 50ms. - read several post on the forum and could not found a solution (system thread enabled and mode semi_auto, seems to comes from wifi.connect() blocking code) It seems that during a Wifi reconnection the main loop hang few time for much more than 50 ms. (button press min length is 50ms, scope verified) To make sure it is not something in my code i tried with a extremely basic code to demonstrate my issue : A simple led blinking, changing state every 50ms using a millis. #include "Particle.h" SYSTEM_MODE(SEMI_AUTOMATIC); SYSTEM_THREAD(ENABLED); unsigned long lastTime = 0; void setup() { pinMode(D8, OUTPUT); Particle.connect(); } void loop() { unsigned long now = millis(); if ((now - lastTime) >= 50) { lastTime = now; digitalWrite(D8, !digitalRead(D8)); } } It works fine until I hold the antenna in a closed hand (which make loosing signal as the signal is not very strong ), Argon is loosing Wifi and try to reconnect “status led blinking Green” During this time (status led blinking green) my test led on D8 blink normally and stop to blink for some instant then it start again in a loop. Apparently this is due to the Wifi.connect which seems to block application code. Checked the timings (scope) and they are always the same : code running for 3.3sec and blocking for 2 sec, then run 3.3 sec and stop 2 sec again, this is repeating until it success connecting on Wifi again. Tried the same on a basic Thread but it didn’t change anything. So it looks like it makes impossible to use an Particle device under bad wifi condition if you application cannot miss any external event. I’ve read few thread about the semi auto and manual mode and the loop blocking but didn’t really found a solution, it’s not very clear in which mode what is blocking or not and it seems to depend also which firmware you are using. The only way i think to fix that is to use another uC (like attiny) to count the button and deliver that using I2C I’m quite amazed that it block code for 2 sec during a reconnect as wifi is handled by the ESP32 and application code by the Nordic. If you have any idea to minimize this blocking code or if I did/say something wrong please correct me, i’m quite a noob using particle devices. (Using Argon software 1.5). Thanks in advance Nico
https://community.particle.io/t/wifi-reconnect-repeating-hang-in-application-code/55886
CC-MAIN-2020-40
refinedweb
576
69.01
Notes on Building C Code in Windows 2014-10-08 16:14. A better basic answer in my humble opinion is that you can use the Microsoft Windows SDK to get a usable C/C++ compiler on your system. Ok, so, how do you go about to compile a C-program from command line on Windows once you got the SDK installed? First we have to locate the compiler. If installed by the SDK it can be found at C:\Program Files\Microsoft SDKs\Windows\< version >\bin\cl.exe but if you have Visual Studio installed it can be found at C:\Program Files (x86)\Microsoft Visual Studio < version >\VC\bin\cl.exe. Of course, being windows, as I run through these examples the installation of the SDK fails so I resort to the fallback of using Visual Studio thus failing to prove my point of not need to install Visual Studio entirely. So my initial assertion about there being a better basic answer to this is false. Anyways... Compile and link Using the this simple test program (saved as main.c): #include <stdio.h> int main(int argc, char* argv[]) { printf("hello world!\n"); return 0; } With Visual Studio installed just run a Developer Command Prompt (found under Tools section of Visual Studio program group), change dir to your project directory and run: cl main.c This should compile and link the code to give you a main.exe executable. Just out of curiosity I wrote a bat file to accomplish the same thing my system (still using Visual Studio) without using the developer command prompt: set compiler=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\cl.exe set include=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include set lib=C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\LIB;C:\Program Files (x86)\Windows Kits\8.1\lib\winv6.3\um\x86 "%compiler%" /I"%include%" main.c /link "%lib%"* The magic of the develop command prompt is it runs the vcvarsall.bat to setup paths correctly. Have a look at it if you want to understand how it works. On my system it can be found in C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat. Conclusion The easiest way to compile a C-program in Windows is without doubt to install Visual Studio. The second viable option, with a smaller footprint and very well suited for those coming from a UNIX world, is to use MinGW or Cygwin.
https://inb4.se/post/2014-10-08-Notes-on-Building-C-Code-in-Windows/
CC-MAIN-2018-39
refinedweb
421
64.71
Are there plans for theming support in Quasar? Like the IOS theme Quasar v0.x used to have. dobbel @dobbel Best posts made by dobbel - RE: Ask Razvan a Question! Q & A for Quasar.Conf - RE: How to achieve v-ripple effect on table rows? yes that fixes the ripple on the tr. Thanks! I updated the codepen with your css. - RE: Vuex getter undefined You’re mixing MapGetters with explicit store getter calls. You either use the explicit store getter call like: this.$store.getters.getColorScheme or you use ( with mapGetters) : this.myMappedGetterFunction() BUT because your getter getColorSchemeis in a vuex module colorsyou have to do it like this: explicit store call ( without mapgetters): let colorScheme = this.$store.getters["colors/getColorScheme"](this.dashboardColorScheme) With mapgetters: computed: { ...mapGetters({ getColorScheme: 'colors/getColorScheme', anotherGetter: 'colors/anotherGetter', }) // This is the syntax used: ...mapGetters('some/nested/module', [ 'someGetter', // -> this.someGetter 'someOtherGetter', // -> this.someOtherGetter ]) } // somewhere else in for example a method: let colorScheme = this.getColorScheme(this.dashboardColorScheme) found a nice vue vuex demo with namespacing(modules): - RE: Line break in Q-tooltip? this works with <br>in hovertext: <q-tooltip <div v-</div> </q-tooltip> - RE: QCalendar: hide times in day view if outside work hours You can use interval-startin combination with interval-count: - RE: Electron Auto-reload doesn't work well in Node v15.0.1 It’s recommended to use node version 12.x for Quasar. - RE: Quasar Admin CRM Template very nice. Would love to see a Vue alternative for react admin. - [V1] how to build with ios theme? -T ios [V1] How do I build/run (cordova)apps with ios theme? From the V1 doc: quasar dev -m cordova -T ios quasar build -m cordova -T ios these commands result in a app with Material Android look/theme instead of ios. This used to work in v0.17x - RE: vuex getters actions This is better: In your component: computed: { …mapGetters(‘MODULE_NAMESPACE’, [‘GETTER_NAME’]) } then you can use the store getter as a computed property in your component. - RE: My profile template made using Quasar Framework and Vue.js the cards wit the ribbon look very pro. Why not use the gallery/lightbox component so people can fullscreen see your nice drawings. Latest posts made by dobbel - RE: Style selected row in table Here’s a codepen with custom hover and selected: - RE: Axios / quasar.config.js proxy - In Chrome api requests are working, In Firefox/Opera CORS issue If you set a proxy for postsand apiin devServer, then in your Quasar app you must use your Quasar’s host:port as baseUrl for the actual axios requests. This works , assuming you run your Quasar app on port 8080: import axios from 'axios'; export function getDataNode() { return axios .get('') // can be replace by `/api/resources` .then( yy => yy.data) } export function getDataJsonPlaceholder() { return axios .get('') // can be replace by `/posts` .then( xx => xx.data) } proxy: { '/api': { target: '', changeOrigin: true, }, '/post': { target: '', changeOrigin: true, }, }, In your original code the proxies where not used at all, because you used the proxy target url for the axios request. btw I also had cors issues on chrome. - RE: Datepicker Formating issue l. We’ve been having a weird datepicker formatting issue where there is a white container that shows up under the datepicker on desktops - why do you call this a formatting issue? ( With your topic title I presumed you had a time/date formatting problem) - with desktop you mean electron? If yes does the problem also occur in spa mode? If no what do you mean with desktop? - Did this problem always exists or did it suddenly appear? - RE: Question related to a document topic on usage of Axios Why is Axios imported again in Vuex store I think this is because Vuex actions, mutations etc. canbe defined outside of the Vuex store in separate .js files ( quasar’s default ). And those files don’t have access to the this.$axios( because of the isolated scope of an imported js module). If you would define the the actions, mutations directly in the vuex store you can use the global axios ref. See here for an example of isolated scope when using import: - RE: quasar-dev localhost for capacitor apps @aitcheyejay said in quasar-dev localhost for capacitor apps: Unfortunately, this required a hack of the quasar-dev codebase on my part. could you share this ‘hack’? - RE: Building a Windows build on a MacOS - Error: spawn yarn ENOENT here are some people having successfully build a windows build in macos in docker: - RE: Custom bottom of QTable without removing pagination data You could use the bottom slot with your own pagination( copied from the pagination slot example), something like this:
https://forum.quasar-framework.org/user/dobbel
CC-MAIN-2021-04
refinedweb
785
66.84
help me plz.. i am an it student who needs an advice on what particular codes could help me in reading a text message in a cellular phone and queries directly to our database... i am taking my thesis ryt now as a requirement 4 graduation.. hop u can help me..the Hats off!! SImply told means,,I fell great about the developers of Roseindia.net...This website dedicates lots & lot of useful info to me and my colleagues... Am really enjoyed your service... Hats oFF..Hats offf... Yours Harikumar.N.T Where to i save this program dear programmer, Where to i save this program(HelloWorld), HI I rally appreciate the tutorial help given by the site.I thank the authers and ask god to bless you ppl The Java ME Architecture comprises of i love this web site so much. i have some comments related to j2me Architecture : j2me consists of three software layers as you said but there are some Overlaps. The first layer is JVM and we have two typesof it KVM and CVM. The second la J2ME EXCELLENT ME 3 Thanks you for providing knowlege. Does this work with JME SDK 3 NOT SUCCESSFULL I do not understand Step 11: Execution of the compiled Java class files on the emulator gives the following customized output. This output window have........... my error is.. Roseindia,roseindiaMID exception:java.lang.class not found exception: greate this is cool but try to use less complex words. Java Platform Micro Edition in 1999, Sun introduced the Java 2 Micro Edition. J2ME (now Java ME...Java Platform Micro Edition  ...; Plz Help Me Plz Help Me Write a program for traffic light tool to manage time...? Program must be written in Micro C. Here is a code that displays traffic light on the frame. We have used java swing. It may help you. import Java 2 micro editionJ Java 2 micro editionJ Hello, i am using JCreator, for writing my J2ME program, after building the program, it keeps on given me the following errors... symbol class TextField cannot find symbol variable TextField please help me Help me quickly plz?? Help me quickly plz?? Can you help me to write code quickly this code is a java code take input as double and should use command line arguments and enhanced for statement then find the combine of the numbers plz help quickly plz help me - Java Beginners plz help me Deepak I can write a sessioon code plz help me admin_home.jsp page is display but data is not disply plz help me what is wrong
http://www.roseindia.net/tutorialhelp/allcomments/8273
CC-MAIN-2014-35
refinedweb
433
74.29
INANCIENT UGARITBYMICHAEL HELTZER1976DR. LUDWIG REICHERT VERLAG WIESBADENCIP-Kurztitelaufnahme der Deutschen BibliothekHeltzer, llichaelThe rural community in ancient Ugarit.-I.Aufl.-Wiesbaden : Reichert, 1976.ISBN 3-920153-61-8 1976 Dr. Ludwig Reichert Verlag WiesbadenGessmtherstellung: Allgii.uer Zeitung KemptenPrinted in GermanyIFOREWORDThis work was written with the generous financial support of the IsraelCommission of Basic Research. The Faculty of Humanities of the Uni-versity of Haifa contributed to the typing of the manuscript. The sub-vention of the Haifa University made possible the appearance of themonograph in print.The author wishes to use this opportunity to express his deepestgratitude to all these institutions, whose generosity helped to bring themanuscript to the publisher.My cordial thanks are also given to the publisher, Dr. Ludwig Reichert,and to Professor Dr. Richard Haase, whose aid and cooperation contribut-ed so much during the editing of the manuscript.M. Heltzer. '.' '.'j "I ."TABLE OF CONTENTSList or Abbreviations .Introduction . . . . . . . . . . . . . . . .The Geographical and Environmental Setting .Chapter I. The Rural Community . . . . . . .Chapter n. Taxes and Duties of the Villages of UgaritThe Villages . . . . . . . .Military Duty (Conscription) . . .Non-military (1) Naval Service . .Labour Obligations of the VillagesPayment of Taxes. . .Taxes Paid in Silver .Tithe Paid in Grain .Payments of Wine. .Payments in Olive OilTaxes Paid in Cattle.Taxes Paid in ArtifactsVarious Unidentified Taxes and DutiesConclusions .Chapter III. Royal Grants of Tax and Labour Obligations to HighFunctionaries. . . . . . . . . . . . . . . . . . . .Chapter IV. Non-Performance of Obligations by the Villagersand Their Defection from Ugarit . . . . . . . . .The nayylilu . . . . . . . . . . . . . . . . . . .The Enslavement of Rural Debtors by Foreign TamkarsDefection of the Peasants of Ugarit . . . . . . . .Chapter V. Other Aspects of Community Life in UgaritCollective Responsibility in Legal Actions . . . . .Communal Landowning and Landholding by the Rural Com-munity .Local Religious Cults and Communal (Local) Sanctuaries inthe Kingdom of Ugarit . . . . . . . . . . . . . . . .Chapter VI. Communal Self-Government in the Villages andRelationship to the Royal Administration . . . . . . .Types of Local Self-government According to Various Non-administrative Sources .Communal Assemblies . . . . . . . . . . . . . . . . .IX-X1-32-34-67-477-1818-2323-2424-3030-4630-3435-4040-424243-4444-4646-474748-5152-6252-5757-5858-6263-7463-6565-7171-7475-8375-7777-79VIII Table of ContentsFuFANLRCAHDADISOABAfOAHWANETAnalecta Bibliea, Rome.Archiv fur Orientforschung.W. von Soden, Akkadisches Handworterbueh, 1959-J. B. Pritchard, Ancient Near Eastern Texts to the Old Testament,Princeton.Accademia Nazionale dei Lincei, Rendiconti della Classe di ScienzeMorali, Storiche e Filologiche, Roma,Acta Orientalia Hungarica, Budapest.Archiv Orientalny.Assyriological Studies, Chicago.Biblical Archaeologist.Bulletin of the American Schools of Oriental Research.Bibliotheca Orientalis, Leiden..Baghdader Mitteilungen.Bulletin of the Schools of Oriental and African Studies, University ofLondon.Beitrage zur sozialen Struktur des Alton Vorderasien, Berlin, 1971.Chicago Assyrian Dictionary.Codex :ijammurapi.L. R. Fisher (ed.), The Claremont Rae Shamra Tablets, Rome, 1971.A. Herdner, Corpus des Tablettes Cuneiformes Alphabetiques decou-vertes a. Ras Shamra-Ugarit de 1929 a. 1939, T. I et II, Paris, 1963.The Cambridge Ancient History (Revised Edition).Dialoghi di Archeologia.Oh. F. Jean, J. Hoftijzer, Dictionnaire des inscriptions semitiques del'Ouest, Leiden, 1962-65.Forschungen und Fortschritte (der deutschen Wissenschaft und Tech-nik). .Israel Law Review.Israel Oriental Studies.Journal of the Economic and Social History of the Orient, Leiden.Journal of the American Oriental Society.Jahrbuch fiir Kleinasiatische Forschungen.Journal of the Near Eastern Studies.Journal of the Northwest-Ssmitie Languages.Lietivos TSR Aukstuj1! Mokyklq Moksliniai Darbai, Istorija, Vilnius.J. Levy, Neuhebraiaehea und Chaldiiisches Wdrterbueh tiber die Tal-mudim undMidrasehim, I-IV, Leipzig, IS76-89.Or Orientalia, Rome.OA Oriens Antiquus.OAC Oriens Antiquus Collectio, Rome.OLZ Orientalistische Literaturzeitung.PEFQS Palestine Exploration Fund, Quarterly Statement.PEQ Palestine Exploration Quarterly.PRU, II - Oh. Virolleaud, Le palais royal d'Ugarit, II, Paris, 1957.PRU, III - J. Nougayrol, Le palais royal d'Ugarit, III, Paris, 1955.PRU, IV - J. Nougayrol, Le palais royal d'Ugarit, IV, Paris, 1956.PRU, V - Oh, Virolleaud, Le palais royal d'Ugarit, V, Paris, 1965.PRU, VI - J. Nougayrol, Le palais royal d'Ugarit, VI, Paris, 1970.PS Palestinskij Sbornik.List of AbbreviationsAOHArOrASBABASORBiOrBMBSOASBSSAWCADCHClaroCTCILRlOSJESHOJAOSJKFJNESJNSLLAMMDLevy7980-838 ~ 8 81-8282-8384-10184-8889-9090-9696-100100-101102103103-112112113The Council of Elders .Heads of the Local Administration and Their Relationship tothe Royal Authorities1. Hazannu .2. Rb .3. Skn (ame1aiikinu)Chapter VII. Property Relations within the Rural CommunityThe Evolution of Property Relations .Additional Lists of Families of the Villagers. . . . . . .The Relations of Individual Households to the CommunityDivision of Property and Disinheritance . . . . . .The Preference Given to the Family to Regain its LandGeneral Conclusions . . . . . . .Appendix I. Royal Landownership .Appendix II. Demographic Survey ofthe Population of the RuralCommunities of Ugarit. . . . . . . . . . . .Appendix III. Chronology of the Late-Ugaritic PeriodIndices .xRARAIRSIRSJBSVSYU,VUFUTVDIVTWOWUSZAZULList of AbbreviationsRevue d'Assyriologie.Rencontre Assyriologique Internationale.Rivista Storica Italiana.Recueil Societe Jean Bodin.Sovetskoye Vostokovedeniye.Semitskiye Yazyki, Moscow.Ugaritica, V, Paris, 1968.Ugarit-Forschungen, Neukirehen-Vluyn.a. H. Gordon, Ugaritic Textbook, Rome, 1965.Vestnik Drevney Istorii, Moscow.Vetus Testamentum, Leiden.Welt des Orients.J. AiBtleitne.r, Wtirterbuch der Ugaritischen Sprache, Berlin, 1963.Zeitschrift fiiI' Assyriologie.M. Dietrich, O. Loren, J. Sanmartin, Zur ugaritischen Lexikographie,VII, UF, V, 1973, pp. 79-104; VIII, UF, V, 1973, pp. 105--17; XI, UF,VI, 1974, pp. 19-38; XII, UF, VI, 1974, pp. 36-46.Table No.1 .....Notes to Table No.1.Table No.2 .....Notes to Table No.2.Table No.3 .....Notes to Table No.3.Table No.4 .....Notes to Table No.4.LIST OF TABLESPages8-1515-1836-38384141106106INTRODUCTIONThis book focuses on the village-community in the ancient kingdom ofUgarit during the fourteenth to thirteenth centuries B. C. What was thecharacter of the community? What role did it play, particularly in theconduct of agriculture, the economic mainstay of the kingdom? What wasthe village-community's social structure?The answers to these questions may shed light not only on the socialand economic character of Ugarit, but also on that of Syria-Palestine ingeneral in the Late Bronze Age. The study of this area as a whole has beenhindered by the limited number of documents, apart from the Alalab(Mukis) texts. Even these texts do not yield information comparable tothat found in the Ugaritic sources.The sources available for this study were mainly the clay tablets writtenin alphabetic Ugaritic, in Akkadian cuneiform scripts, and in languagesfrom the el-Amarna period and until the invasion of the "peoples of thesea" at the very beginning of the twelfth century B. C. and the destruc-tion of the kingdom. These clay tablets are mainly administrative, eco-nomic, and legal documents from the royal archives. Some monographsand articles have been written about the social structure of ancientUgarit in general," but a major detailed investigation of the questionsraised above does not exist. This author has contributed several papersconcerning these questions; most of which have appeared in Russian.Concerning political history, we must base our conclusions on thebrilliant works of M. Liverani8and H. K1enge1,4except in those caseswhere examination of the sources forces us to reinterpret some minorevents in the history of Ugarit. Weare indebted to the French scholars, thelate J. Nougayrol, and the late Oh, Virolleaud, for almost all text-editions.The sources edited by 01. Fisher, and A. Herdner have also been of greatimportance.1 A. F. Rainey, A Social Structure of Ugarit, A Study of West Semitic SocialStratificationduring the Late Bronze Age, Jerusalem, 1967 (Hebrew with Englishsummary); M. Liverani, Communautes de village et palais royal dans la Syrie duIIememiIIenaire, JESHO, X V ~ 1975, No.2, pp. 146-64; M. Liverani, La royautesyrienne de I'age du Bronze Recent, "Le palais et la royauM," XIX RencontreAssyriologique internationale, Paris, 1974, pp, 329-51.I M. Heltzer, Problems of the Social History of Syria in the Late Bronze Age,OAC, IX, Roma, 1969, pp. 31-46; idem., The Economy of a Syrian City in the,Second Millenium B. C., V International Congress of Eeonemic History, Leningrad,1970, separate paper, 13 pp. (with references to earlier papers).I M. Liverani, Storia di Ugarit, Roma, 1962. H. Klengel, Geschichte Syriens im II. Jahrtausend v.u. Zeitrechnung, I-III,Berlin, 1965-70.The Geographical and Environmental Setting 3The Geographical and Environmental SettingThe territory of the ancient kingdom of Ugarit extended inland as faras forty to sixty kilometers from the Mediterranean coast. The northernborder of the kingdom lay in the region of Jebel-el-cAqra (Ugar. MountQazi, $pn classical Mons OaaiUB). Southwa.rd, the territory of Ugaritreached at least to Tell-Siikas (ancient Suksi). Thus, we can assume thatthe whole territory of the kingdom covered approximately 3,000-3,600square kilometers.sThe capital city was situated close to the Syrian coast and about fifteenkilometers to the north of Latakije (ancient Laodikeia), where modernRas-esh-Shamra (Ras-Shamra) is today. Not far from the tell is the bayof Minet-el-Beidha (White Bay, classical Leukos Limen, possibly inUgaritian Ma'lJiizu), the ancient harbour of Ugarit.sThe terrain was generally flat with occasional small hills. The onlysignificant heights were those of Mt. Casius, in the northern part of thekingdom, which were covered with forests. 7Taking into account that except for some minor rivers in the areairrigation facilities were almost completely lacking, agriculture developednormally. The climate was relatively mild, as in most mediterraneancountries. The rainfall on the coastal plain in modern times averages800 mm., and sometimes even reaches 1500 mm.s Environmental condi-tions more favorable to agriculture were prevalent until the middle of thethirteenth century B. C., when climatic conditions reduced the amount ofrainfall to the more or less modern average. Also, in ancient times thearea was not completely deforested and this had a favorable influence onagriculture.' Still, Ugarit was much less densely populated than Meso-I K. Bernhardt, Die Umwelt des Alten Testaments, Berlin, 1967, pp. 107-11;G. Buccellati, Cities and Na.tions of Ancient Syria, Roma, 1967, p. 38; M. Astour,Place-Names from the Kingdom of Alalab in the North-Syrian List of ThutmoseIV, JNES, XXII, 1963, pp. 220-41; J. O. Oourtois, Deux villes du royaume d'Ugaritdans la vellee du Nahr el Kebir en Syrie du Nord, "Syria," XL, 1963, pp. 261-73;J. Nougayrol, Soukas-Shuksu, "Syria," XXXVIII, 1961, p. 215; J. Nougayrol,PRU, IV, p. 17; H. Klengel, Geschichte Syriens, III, Berlin, 1970, pp. 5-29.I M. Astour, Ma'fJadu, the Harbour ofUgarit, JESHO, XIII, 1970, No.' 2,pp.113-27. Cf. PRU, III, 11.700, where the concluding line of the lists states that thevillages mentioned there are: 31) dldni "the settlements of themountain (region)." Cf. J. Weullersse, Le pays des Alaouitee, I, 'Tours, 1940. M. Liverani, Variazioni clime.tiche e fiuttuaziani demografice nella storleSiriana, OA, VII, 1968, pp. 77-89; M. Rowton, The Woodlands of Ancient WesternAsia, JNES, 26, 1967, pp. 261-77; ibid., The Topological Factor in the Problem, AS, XVI, pp. 375-87.potamia and Egypt, where the economy was based on irrigation, resultingin a much greater agricultural yield.We have no information about any large mineral deposits in the areaof ancient Ugarit.The Rural Community 5CHAPTER ITHE RURAL COMMUNITY1 Cf. M. Heltzer, Review of "Ugaritica V," VDI, 1971, No. I, p. 106 (Russian). The great Hittite king.and entering the (territory) of the the Great King, I shall not accepthim.To the king of UgaritI shall return him.17) Barru rabl1 u-ul a-la-qi-Iu.18) a-na sar mallJ-ga-ri-it19) u-to-ar-s16) a-na libbibi ir-ru-ubFrom this text we can see that in Ugarit there were three principalsocial categories or olasses: "servants of the king," "servants of the ser-vants of the king," and the "sons of Ugarit." The "sons of Ugarit" whohad defaulted on their debts were, in certain oases, turned over to theircreditors in foreign countries (of. below pp. 57-58).The text confirms that the king of Ugarit had sovereignty over thewhole population of the kingdom. This was legally accepted by theHittite king, to whom Ugarit was subservient. We also see that the textis dealing with originally free people, not slaves. The "servants of theking" and the "servants ofthe servants of the king" were those immediate-ly dependent upon the royal authorities of Ugarit. The Ugaritic termdesignating them was bnBmlk "people of the king" (cf. below).3It is note-worthy that here, as in all the other texts concerned, the royal dependents(bnB mlk) are not identified with the main mass of the "sons of Ugarit."This is best seen in the text CTC, 71 (UT. 113) (cf. below pp. 19-21)where the number of bowmen conscripted to the army of Ugarit appearsapart from the professional groups of royal dependents and also apartfrom fifty-nine villages ofthe kingdom ofUgarit. The same thing appearsin PRU, V, 58 (UT. 2058): 1) [spr] argmn BpS "[The list] of the tribute ofthe Sun" (i. e. the Hittite king), where seventy to eighty villages werementioned together with the amount of their tribute. The reverse of thetablet gives the same tribute, which various groups of royal dependents(bnB mlk) had to pay.'The term "sons of Ugarit" (mareM al o-ga-ri-it) is often used in referenceto the inhabitants ofthe kingdom of Ugarit. In most cases similar wordingappears in the texts, where, in addition to the "sons (citizens) of Ugarit,""sons" of the neighbouring kingdoms (Siyannu, Amurru, Usnatu, eto.) M. Heltzer, "Royal Dependents" (bnA mlk) and Units of the Royal Estate(gt) in Ugarit, VDI, 1967, No.2 (Russian with English summary), pp. 32-47; M.Heltzer, Problems of the Social History, pp. 43-46; M. Liverani, Storia di Ugaritnell'eta degli archivi politici, Roma, 1962, pp. 86-87; G. Buccellati, Cities andNations, pp. 56-62; of. also "Introduction," note No.1. cr. also the fragmentary tablet PRU, VI, 131 (RS. I9.35A), where the re-presentatives of professional groups of the bnAmlk and residents of the villages arereceiving arms, but the bnAmlk and villagers receive as separate groups.If the sons (citizens) of Ugarit,(who) are delivered for theirsilver (debts) to another country,and from the (land) of Ugaritthey are fleeing,6) ma-am-ma i-te-eb-bi-ma7) libbib 1 eqli uSamsi i-ru-ub8) sarru rabl1 u-ul a-la-aq-qi-lu.11) sum-ma maruMmal tJ-ga-ri-it12) sa mdtitl sa-ni-ti13) i-na kaspi-Bu-nu i-pa-aB-sa-ru14) iB-tu libbib l maltJ-ga-ri-it15) in-na-ab-bi-it-ma9) a-na sar mallJ-ga-ri-it10) u-ta-ar-su. In Ugarit there were no rivers nor irrigation' systems based on them.Still, the principal wealth of the kingdom was derived from andcattle breeding. It is natural to suppose that the peasants of Ugarit andtheir household, organized in village-communities, played a large role inthe economic and social life of the country. Since most of our informationis taken from the royal (palace) archives, we have a somewhat one-sidedpicture of the situation. Although there were certain "private" archive.s,(such as those of Rasapabu and Rap'anu, edited by J. Nougayrol III"Ugaritica" V). They belonged to royal scribes and functionaries and inlarge part they consisted of official documents taken from the royalarohives.!Social stratifioation in Ugarit becomes clear from the text PRU, IV,17.238, written in the name of the Hittite king Hattusilis III to kingNiqmepa of Ugarit. The Hittite king declares that:3) Bvm-ma ararJ,Bar rnaltJ-ga-ri-it If a servant of the king of Ugarit,4) Ulu-u mdr maltJ-ga-ri-it or a son (citizen) of (the land) ofUgarit,5) lu-u arad ardi Bar maltJ-ga-ri-it or a servant of a servant of the Kingof Ugarit(if) somebody (of them) rebels andenters the territory of the (people) of the Sun,"(I) the great king shall not accepthim.To the king of UgaritI shall return him.6 The Rural Communityare mentioned.! Designating the citizens of a country or the inhabitantsof a local community as "sons" of that country or community is generallycommon to the whole ancient Near East. This forces us to conclude thatthe term "sons" refers to the main mass of the freeborn population,without special reference to social differences. In our case we have to payspecial attention to the references to "sons" as inhabitants or citizens ofcertain local or rural (village) communities of the kingdom ofUgarit. Forexample, tablet PRU, IV, 17.288 relates a legal case between the king ofUsnatu and the "sons" of (the village) Araniya (cf. below). Here, as inmany other places, we see that "sons" (mdre) were citizens of particularvillages. We also learn that they were treated as a collective body in thelegal and administrative senses. PRU, III, 16.270; IV, 17.43; 17.319; 17.234; 17.158; 17.341; 18.115; 17.239;17.130; 17.79+374; 17.335+379+381+235; 17.397. Cf. also, Buccellati, Cities andNations, pp. 36-38. Concerning other countries of the ancient Near East cf. I.Djakonov, Etnos i socialnoye deleniye v Assiri'i, BV, 1958, No.6, pp. 45-56 (Russianwith English summary).CHAPTER IITAXES AND DUTIES OF THE VILLAGES OF UGARITThe VillagesVillages were usually, although not always, designated in the Akkadiantexts of Ugarit by the term or determination sign URU-diu. This cor-responds to the Ugaritic word, qrt(pl. qritlqrht) which appears in thealphabetic texts. The number of these villages may have reached 200,but it is possible that during almost two centuries of the existence of thelate-Ugaritic kingdom several of the villages changed their name, severaldisappeared, and some new ones came into existence. It is also possiblethat the same villages sometimes appeared under different spellings. Theexact number of villages is still unknown to us.Table 1 lists the villages whose names were found in the documentarysources. Place-names are included only if a) the word dIu appears at leastonce before the name or the text deals in general with dIulqrit of thekingdom, b) information is available about a collective duty or obligationof this village, c) the place-name is mentioned in a list where other knownvillages are mentioned. The names of the villages are listed according tothe order of letters in the Ugaritic alphabet, as determined from the schooltablets from Ugarit.! Names of well-recognized non-Ugaritic villages areomitted.10k. Virolleaud, PRU, II, 184 (A. 12.63); 185 (B. 10.087); 186 (C. 15.71); 188(19.40); Gordon, UT, p. 299, No. 1184; O. EiBsfeldt, Ein Beleg fUr die Buchstaben-folge unseres Alphabets aus dem Vierzehnten Jahrhundert v . Chr., FuF, XXV,1950, p. 217.8 Taxes and Duties of the Villages of UgaritTable No.1Taxes and Duties of the Villages of UgaritTable Nr. 1 continued9"t:l "t:l .p '" rn rD." gs1 I=l0 CDCD'J:: "t:l CD .....,.C..... '" til <isJl .g 0 ..... .. .S... til ..... CD"<Obi:> til .S eo...,'" l .. 0"" til"" .... 8...t<l I=lCD eo bOO ;.a CD bOCI)'" .S be .S e .....S :5 '" ...,.S f::0 ....'" '" CD0'" CDtil'" '" I::s '" -S p.,til p.,CD1 00.g S p., S 0 p.,,,, :p0S g"g I- eo 00 s 0 I:: <Il'sI=l CD '" 1=l'Oe. CI) ...,CD;'sCI) :::::I 0-S B <Il ::s'f:: "t:l BI:: rn "t:l1=1"S <Il.s 8 til till tilr.tJ .9 'F:: 'F:: ..... ..... 0 0"<0 <IlGO:e ... .s 0 :e 1=1.s'S $ CD<is 1j ,.C ..., 1=1$ "'...,1 0 til 0"' ..... mOJ. <Il 0'" 1=1 ... t> CD 0-a bO_ bOo<il <is p., <is ...<is 0 "" s s s 1': 0 0 S P=l >$ >.><:0 > .... A1 2 3 4 5 6 7 8 9 101. Agm (&IA-gi-mup + - - - + - + -2. Agn (&IA-ga-nu) + - - - - -+ -3. Ayly (E-la-ya?)8 + - - - - + + -4. Al!Jh - - - -+ + + -5. &IAl-lu-ul-lu - + - - - - - -6. Amg,y (&IAm-me-sa, A-me-za) + - - - - - + -7. Anan - - - - - - + -8. Ap + - - - - - - -9. Aps(nt) (&IAp-8U-na) + - - - + - + +10. Ar8+ - - - - -I- + +II. Ary (&IA-ri)8+ - + - - + + -12. &IAr-ma-nu - - - - - - - +13. Arn(y) (&IA-ra-ni-ya) + - + - - - + +1 2 3 4 5 6 7 8 9 1014. Arsp(y) - - - _. - - +(?) -15. Arr(?) - --. - - 1 - 1 -16. Art (&IA-ru-tu)1o+ + + + + -+ -+ +17. &IAsri-Ba'alu-+ - 1 - - -- - +18. Agt (&IA-lJ,a-tu)l1+ - - - - - -+19. Atlg (&IA-tal-lig) -I- -+ - - + + -+ -+20. &1Be-ka-nil2+ - - - + + + -21. &1 Be-ka-I starl2+ - - -- - - - -22. Ely+ - - - - + + -23. y) &1 + - - - - + + -24. Bqet (&IBa-aq-at),Ba-qa-at)-+ -+ - - - - + -25. &1 Bi-ta-lJ,u-li-wi14 --+ - - - - - -26. Bir (&1ss,Be-e-ra]+ - - - + + + +27. Gbel/Gbl (&IGi-ba-la,&IGi-llBa'alal&)16+ + + - - + + -28. Gwl (&IGa-wa-lu) - - - + + + + -29. &IGal-ba - - - - - - - -30. Glbt(&IGul-ba-tu)18+ + - - - - - -31. Gll.Tky{Tky (&IGa-li-li-tu-ki-ya)1?+ - - - +1 - 1 -32. &IGa-mil-tu - - - - - - - -33. &IGan-na-na18+ - - - - - - -34. Gney18(&IGa-ni-ya)+ - - - + - + -35. QbtlQpty (&IQU_ba-ta, Qu-pa-ta-u,Quppatu)1'+ - + - - + + +36. Qlb (&IQal-bapo ? + - - - - + -37. Qlby (&IQal-ba-yapO+ - - - - - + -38. Qlb gngnt+ - - - - - - -39. Qlb krd (&IQal-biqar-ra-di)+ - - - - - - -40. Qlb sprm. (&IQal-bi&meIMSAG.GAZ(lJ,apiru))+ - - - - - - -10 Taxes and Duties of the Villages of UgaritTable No.1 continuedTaxes and Duties of the Villages of UgaritTable No. 1 continued111 2 3 4 5 6 7 8 9 1041. !Jlb {lpn (al!Jal-bihUrBan.[fa-zi)21+ - - - - - - -42. .[flb rp (al.[fal-birapi)+ - - - - - - -43. al.[fu-ul-da - - - - + + - -44. al!Ju-lu-ri - + - - - - - -45. al!Ji-rnu-lu - + -- - - - - -46. !Jrnrnzz+ - - - - - - -47. al!Je-en-zu-ri-uxi - + - - - - - -48. al.[fa-ap_pu - - - - - + - --49. .[frbtjlrn (al.[fu-ur-ba-lJ,u-li-rnip8 - + - - + - + -50. al.[far_ga-na - - - - - - + -51. al.[fu-ri-ka (.[fU)I (l{lur-beliu+ - + - - + - -52. al.[fa-ar-rna-nu - - - + - - - -53. al.[fu-ur-{lu-u+ - - - - - - -54. !Jr{lbc+ - - - - - + +55. Drnt/Drnt qd8(? )aIDu-rna-tu,Du-rnat-ya26+ - - - - - + +56. 0.1Du-mas-qu,Du-ma-te-qiw+ - - - - - - -57. Hzp,allz-pu,aIA8(?)_piZ8+ - - - - - + -58. Hry+ - - - - - - -59. 0.1Wa-na-a-lurn+ - - - - - - -60. aIZi-ib-lJ,a+ - - - - - - -61. Zbl - - - + + - - -62. 0.1Za-za-lJ,a-ru-wa - + - - - - - -63. Zly (Zi-il-a)27+ - - - - - + -64. aIZi-irn-rna-ri - + - - - - - -65. 0.1Za-rni-ir-ti -+ - - - - - -66. aIZa-qi[XX] /Zi-qa-n[i]-rnaZ8- - - - + - - -67. r n ~ r n (aIZa-ri-nu, Za-ri-ni-ya)Z9+ - - - - - - -1 2 3 4 5 6 7 8 9 1068. su(aIE[.X.]is)8+ - - - - - - -69. lJdtt + - - - + - - -70. lJl.yrn+ - - - - - - -71. 'l'bq/Tbq (aITe-ba-qu]+ - - - + + + -72. Ykncrn (0.1 Ya-ku-na-rnu, E-ku-nasamu]+ + - - + + + +73. aIYa-al-du+ + - - - - - -74. Yny (aIYa_na)81+ - - - + + + -75. ycly (aIYa-a-lu)+ - - - + - + -76. ycny (aIYa-a-ni-ya)81+ + - - + -+ -77. r-ur (aIYa-ar-tu)+ - - - - + + -78. Ypr (aIYa_pa-ru)+ - - - - - + -79. Yrgb - - - - - - - -80. Yrrnl - - - - - - - -81. 0.1Ya-ar-qa-nsi - + - - - + + +82. aIYa-at-ba - + - - - - - -83. alKu-urn-bu+ - - - - - - -84. Krnkty+ - - - - - - -85. aIKi-na-du - + - - - - - -86. aIKan-g/ka-ki - + - - - - - -87. Knpy (Ka-an-na-pi-yay - - - - + + + -88. 0.1Ka-on-za-ta - + - - - - - -89. Sbn/'lpn (aISu-ub-ba-ni)81+ - - - + + + -90. Sdrny - - - - - + + -91. aISu-wa-u+ - - - - - - -92. Slj,q (aISa-lJ,a-iq)+ - - - - - + -93. aISu-uk-8i83- + + + - - - -94. Slrny (aISal-rna)+ + - - - - + -95. Srng(y) (al8,arn-rne-ga)8&+ - - - - + + -96. Srnngy8& - - - - - - + -12 Taxes and Duties of the Villages of UgaritTable No.1 continuedTaxes and Duties of the Villages of UgaritTable No. 1 continued131 2 3 4 5 6 7 8 9 1097. Smny (aISam-na)+ - - -- - - + -98. aISa-ni-zu-la - + - - - - - -99. Sert (sla)36 + - - - + + + -100. Sql (aISu-qa-lu)+ - - - - + + -101. Srs (aISu-ra-su)+ - - - - - + -102. S,t88+ -- - - ? ? ? -103. Sct (aISe-ta)+ - - - + - + -104. Lbn(m) (aILa-ab-ni-ma aILa-ab-nu)+ - - - + + + -105. Liy - - - - - - - -106. MidlJ,S7+ - - - - + + -107. Ma{ilJ,d87+ - - - - + + -108. Mgdl(y) (aIMa-ag-da-la)88+ + - - - + + -109. aIMi-lji{u+ - - - - - - -110. Mljr{Mgrt88+ - - - + - - -111. Mld + - - - - - + -112. Mlk (aIMu-lu-uk-ku)'o+ - - - + + + +113. Mnt - - - - - - + -114. Mcbqu+ - - - - - - -115. M cbr4S(?)- - .- - + -+ -116. Mcqb (aIMa-qa-bu,Ma-a-qa-bu, M a-at-qab)'l+ - - - + + + -117. MC1' (aIMu-a-ri)+ - - - - - + -118. Mcrb(y) (aIMa-'a-ra-bu, M a-ta-bu,Ma-alj-ra-pa)+ - - -+ + + +119. M )) + - - - + -+ -120. aIMi-ra-ar -+ - - - - - -121. Mrat (aIMa-ri-a-tel + - - - - - - -122. u-u (aIMa-ra-ilu,Ma-ra-el)4s+ + - - + -- + -123. aIMa-ti-ilu - - - - - + - -1 2 3 4 5 6 7 8 9 10124. Mtn - - - - - - - -125. alNa-bal-tu - - - - - - + -126. Ndb(y) (aINi-da-bu{i)+ + + - - - - -127. Nljl(?) +(?) - - - + - - -128. Ng1Jt (aINa-ga-alj-tU)44+ + - - +(?) - - -129. Nnu{i (aINa-nu-uti)+ + _..- -+ + -130. Npkm{Nbkm(aINa-ba/pa-ki-ma) - - -- -+ + + -131. Na-ap-sa-ti46 _.+ - - - - - -132. aINa-qa-bi+ - - - - - - -133. Sknm (aISakna)48+ - - - + - - -134. Sald (aISu-la-du,'llt{'l1047+ + - - + - + -135. Sllj+ - - - - - - +136. Snr{$nr (aISi-na-ru)48+ - + - + + + -137. Sgy - - - -+ - - -138. cnmk(y) (allnu-ma-ka-ya,1nu-ma-ka]+ - - - - + + -139. Cnnky48- - - - - + + -140. cnqpat (allnu-qap-at)+ - - - + - + -141. r+ - -- - - - - -142. crgz+ - -- ---- - - - -.143. crm(-t)+ - - - - - + -144. aIPu-gul-u{i - + - - -- - - -145. Pd(y), (aIPi-di)+ - + - - - + _.146. alPa-niB-ta-i - + - - - - - -147. alPa-Ia-ra-te+ - - - - - + -148. $c (al$a-u, Sc(?))+ - - - --+ + +149. $cq (al$a-'a-qa)+ - - - - - - +150. Qd8 (aIQi-id-si)+ + - - - - - -14 Taxes and Duties of the Villages of UgaritTable No. 1 continuedTaxes and Duties of the Villages of UgaritTable No.1 continued151 2 3 4 5 6 7 8 9 1015I. Qmy60+ - - - - -+ -152. &IQi-arn-l[a] -- - - - - - ? -153. Qmnz (&IQa-ma-nu-zi)+ - - - -+ + -154. Q1n + - - -- - - + -155. Q(?)rn+ - - - - - - -156. Qrt (&IKAR, Qu-ur-tu) 61+ - - - - + + +157. Rkb(y) (&IRa-ak-bay+ - - - - - + +158. &IRi-mi-Bu+ - - - - - - -159. Rqd (&IRi-iq-di,Ra-aq-du)+ - - - + + + +160. su (&IRMu,SAG.DU)6S+ - - - - + + +161. Xbil68+ - - - - - - -162. Xl1}n (&ISi-il-lJa-nay+ - - - - + + +163. Xlrb(y) (&IBa-lirx-ba-a) + - - - - + + -164. ;Em (&IBum-me)66+ - - - - + - -165. Xmry (&IBa-am-ra-a]+ - - - -+ + -166. Xncy (&IBan-ne-a)+ - - - - - - -167. Xnq (&IBan-ni-qa)+ - - - - - + -168. Xrmn+ - - -+ - + -169. Obl26+ - - - - - - -170. Ol/ffly (&I.fJi-li,.fJu-li)66+ - - - + + + -171. On (&I.fJa-[n]i) - - - - - - + --172. Or6S+ -- - - - - - --173. &ITu-lJi-ya+ - - - - - - -174. Tkn - - - - - - + -175. Tmrm - - - - - - + -176. &1Tu-na-a-na - - - - - - + -177. - - - - - - + -178. &ITa-ri-bu+ - -- - - - - -1 2 3 4 5 6 7 8 9 10179. Trzy - - - - - -+ -180. &1Tu-tu - - - - - - - -181. &Ilb-na-li-ya+ - - - + - - -182. &11-zi-lJ,i-ya+ - - - - - - -183. &Il-li-ya-me+ - - - - - - -184. llstmc(&IIl-is-tam-'i)+ - - -+ + + +185. lpll - - - -+ + - -186. lrab+ - - - - - - -187. Jrbn - - - - - - + -188. &IU-qi - - - - - - + +189. Ubz/UM (&IU-bu-zu]+ - - - - - - -190. Ubrc(y) (&IU-bur-a)+ - - - + + + +191. Ugrt - - - - - + + -192. UlJnp (&IUlJ-nap-pu)67+ - + + -+ + +193. Ull+ - - - - - + -194. Ulm (&IU1-la-mi)+ + - - + + + +195. Uskn (&IUs-ka-ni)+ - - - -+ + +1 Based on information found in texts PRU, IV, 17.335 + 379 + 381 + 235;19.81; 17.339A; 17.62; 17,366; 17.340 defining the borders of the kingdom ofUgarit. Cf. below pp. 71-74. Cf. below pp. 65-67. Cf. below pp. 29-30 and M. Heltze, Royal Dependents .., VDI, 1967, No.2,pp. 34-47; and ibid., review article on "Ugaritica" V, VDI, 1971, No. I, pp. 113-17 (Russian). Cf. M. Heltzer, Povinnostinoye Zemlevladenye v drevnem Ugarite ("Conditio.nal Land-holding in Ugarit"), LAMMD, IX, 1967 (1968), pp. 183-208 (Russian). Cf. below pp. 29-30 and M. Heltee, Royal Dependents . On the identification of the Ugaritic spellings with the place-names written inAkkadian cf. PRU, II-VI, "Ugaritica" V and CTC; of, also A. M. Honeyman, TheTributaries of Ugarit, JKF, II, 1951, No. I, pp. 74-87 (partly out of date); con-cerning the general principles of the phonetic equivalents of the Ugaritic spellingsand their interchanges, as well as their equivalent Akkadian spellings cf. P. Eron-zaron, La fonetica Ugaritica, Roma, 1955; M. Mverani, Elementi innovativi nel-l'Ugaritico non Letterario, ANLR, se. VIII, vol. XIX, 1964, fasc. 5/6; M. Dietrich,16 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 17O. Loretz, Untersuchungen zur Schrift und Lautlehre des Ugaritischen, (I), DerUgaritische Konsonant g, WO, IV, 1968, No.2, pp. 300--315; cf. also M. Dietrich,O. Lorete, J. Sanmartin, ZUL, VII, VIII, XI, XII. PRU, VI, 29 (RS. 17.147),5) aa i-na eqldtM e.la-ya "which is among the fieldsof Elaya." Ar and Ary are different villages because both names appear several times onthe same list of place-names (PRU, V, 40, CTC. 71 etc.). It is more difficult todifferentiate between Ar and Ary in the texts written in Akkadian cuneiform: cf.ZUL, VII, pp. 82-84, No. 5-7.10 ZUL, VII, p. 85, No.9.n Identification of AfitlAlJ,atu cf. J. NO'IJ{Jayrol, PRU, VI, p. 146; about the lateUgaritic graphic interchange, cf. note 7.II Bekani, &IBe.ka-ilI8tar (nos. 20, 21) may be the same village, but this is im-possible to prove.13 ZUL, XI, p. 23, No. 21... May be Bi-ta-b-u-li-mi; cf. no. 49 fJrbglm and the corresponding note 23.II Various spellings of the same plaee-namej the Akkadian spelling &1Gi-IlBa'alaconfirms that it cannot be identified with Byblos, always spelled Gubla in Akkadiantexts from Ugarit, and sometimes appearing as Gbl in texts written in Ugaritic.10 ZUL, VIII, p. 106, No. 17.17 The text PRU, VI, 79 (RS 19.41) shows that at least at one time Galilitukiyabelonged to the "cities ofthe (land) Siyannu" (26) dlaniM mitSi-e-ani). Galilitukiyais also known as the name of an Ugaritic village and as such it had to perform cer-tain obligations (PRU, V, 42. Tr, 2. Gll.tky; V, 18, 8 and 9 Glltky).10 These two place-names may be spelling variants of the same village; anotherview cf. ZUL, XI, p. 23, No. 29.It Honeyman, The Tributaries, supposes that fJpt and fJpty are not identical.But it must be pointed out that the interchange b/p is normalfor Ugaritic spelling.Also, fJbt and fJpty do not appear in the same list of place-names. Cf. Gordon UT,pp. 400 and 404, nos. 929 and 993, where an attempt is made to relate the place.name fJbt to the Hurrian goddess fJeba(t), but the Akkadian spelling (&lfJu.ba-ta,&lfJu-pa-ta.u) contradicts this, of, also ZUL, VIII, p. 109, No. 27. 0 A comparison of the Akkadian spelling fJalba and fJalbaya confirms thesupposition that these are two different place-names, cf. ZUL, VIII, p. 108, No. 24.U On fJa-zill,pn, ZUL, VII, p. 97-98, No. 631-2.II It is uncertain whether this is a place-name or not. fJrbglm-cf. PRU, V, 48. In text PRU, IV, 17.62, 15, Professor J. Nougayrolreads fJu.ur-ba-b-u.li.bi--the Ugaritic reading helps to decipher as mi, cf. alsoC. Kuhne, Mit Glossenkeil markierte fremde Worter in akkadischen Ugarittexten,UF, VI, 1974, p. 166-167... Although Honeyman, The Tributaries, thinks that the ideogram does not correspond to fJu-ri-ka, it is clear from PRU, III, 11.841 that &lfJu-ri-kaperforms its obligations together with &ISu.ra-eu. According to PRU, III, 10.044,13, &lfJU performs its duties together with &ISu-ra-au also. This suggests the identi-fication of fJU and fJu-ri-ka as spelling variants of the same village. fJU is also (bird) in Akkadian, thus also seems to be identical with fJU andfJu.ri-ka; of, also ZUL, VII, s. 95, No. 63. The definitive clearing of the questiondemands new texts: may be gbll/fJU-be-li. &IDu-matqi is possibly identical with Dmtl&IDuma-tu. The autograph of thetext PRU, VI, 138 (RS. 19.46) shows the spelling as &IDu-mat-ki, which may be arare usage in the Akkadian texts from Ugarit of the place-name determinative Klfollowing the word. Thus, we may have to read the word &IDu.matK1 Cf. Hzp in PRU, V, 4, 28; 40, 43; 74, 31; 76, 16, etc. &llz.pi in PRU, 111,11.790,24; 11.800,5; U. V, 102 (RS. 20.207A, 13); PRU, VI, 70 (RS. 17.50), 11; 131(RS. 19.35A); &IAs(?)-pi in PRU, III, 15.20,4.'7 Cf. Zlyy in PRU, II, 176, 3. Instead of the reading Si-ll-a, of J. Nougayrol inPRU, III, 16.204, we would propose Zi-il-a; of, ZUL, VII, s, 87, No. 31, where theUgaritic and Akkadian spellings remain unidentified.II U. V, 95 (RS. 20.011), 11 and U. V, 96 (RS. 20.12).II This may be a respective change of as in the case of SnrIZi-na-ru. Interestingly, none of the texts containing lists of place-names mentions Zrnl in the same tablet. Thus, it may be that areidentical. ..0 Strictly phonetically the Ugaritic!t had to be represented by the Akkadian e.81 It may be that YnylY"ny are identical; on this place-name, ZUL, VIII, P- 10,No. 29-30 (Yny); No. 35 (Yeny). II Akkadian s = Ugaritic I occurs frequently in personal and place-narnea, bopmterchange.II Tell-Soukas, located south of Ugarit; cf. P. J. Riis, Siikas, I, Kobenhavn,1970. There may be various spellings of the same place-name Smg(y)fSmnrry. Here,as a result of phonetic dissimilation, we have n; cf. also ZUL, VIII, s, 114-115, No.3 (oben) und 3. Bmy. 4.Bmgy, und 3 (unten)... Sert in PRU, V, US, 25; 40,11; 58,12; 74, 11 etc; at the same time in PRU, III,11.790, 4 as well as in Clar., 3, the Sumerian ideogram SiG (urusiG) appears.Sert and SiGboth mean "wool" in Ugaritic and Sumerian respectively. So we have toidentify the Ugaritic name with the Sumerian ideogram, as well as to reject the formerreading of the village-name SiG as Bipatu ("wool" in Akkadian) .by J. Nougayrol inPRU, III, 11.790,4, and instead to propose the reading of SiG as Sa'anu. The identity with sert is not excluded..7 Different place-names. ZUL, XI, p. 31, No. 67. Only gt Mgrt; cf. notes 7 and 11.'0 ZUL, XI, p. 33, No. 76... Possibly scribal error instead of Mcqb( ?)... Possibly only a gt; cf. U. V, 96 (RS. 20.12), 7) bit dim-ti Ma-ba-ri 8) &ISu-ba-ni. ZUL, VIII, p. 112, No. 50.U ZUL, XI, p. 33, No. 78.u cr. ZUL, XI, r- 33, No. 80.U Identification based on the fact that the Ugaritic term 8kn and the AkkadiansumerogramMASK1M-8iikinu, aiikinu in Ugaritic are identical in meaning ("vizier,""governor"). cr. G. Buccellati, Due noti di testi di Ugarit, OA. II, 1963,MASKIM-8iikinu, pp. 224-28; A. F. Rainey, LUMASKIM at Ugarit, Or., 35,1966, pp. 426-28; cf., ZUL, XII, p. 43.. U The changes of 8. in Ugaritic, whose phonetic value is not definitively clear,With I and the syllable 8U (possibly read au) in Akkadian, makes the identificationpossible... Cf. note 29... Possibly a scribal variant or error of enmky; on all the scribal variants of"nmky, ZUL, VIII, P: 113-115, No. 57. .'0 ZUL, VIII, p. 115, No. 58.51 The general meaning of the word is "town," "dwelling," "village," but thelists of the collective obligations of the Ugaritic villages show that there was also avillage with this name.51 &IRUu, written by the ideogram SAG.DU in the Akkadian texts from Ugarit,formerly read by J. Nougayrol in PRU, III as The comparison between18 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 19ri8 "head" and SAG.DU "head" forced us to propose the present reading (M. HeU-zer, Povinnostnoye zemlevladeniye, p. 189, note 50) which is now also accepted byJ. Nougayrol, PRU, VI, p. 147... ZUL, VIII, p. 116, No. 66-67, akk. aI8a-bilpi-il."' The spelling 1mconfirms the reading of the sign in Akkadian as lum; cf., ZUL,VII, pp. 82-3... About the graphic interchange of gllJ, cf. notes 7 and 11. Therefore it is im-possible to agree with P. R. Berger, Zur Bedeutung des in den akkadischen Textenaus Ugarit bezeugten Ortsnamens ijilu (Ijl), UF, II, 1970, pp. of., O.J{uhne, UF, VI, 1974, pp. 166-167.II Cf., ZUL, XII, p. 40, No.7.57 Formerly read alAlJ,.nab-bu, without parallels in Ugaritic. Only the-publicationofPRU, V by Ch. Virolleaud in 1965 gave the alphabetic spelling UlJ,np. The Akka-dian syllable alJ, can also be ulJ,; nab and bu are also nap, pu, therefore there is noobjection to the reading UlJ,-nappu.Table No.1 offers a more or less complete picture of the number ofvillages found in ancient Ugarit. Indeed, this number may be somewhatinflated since some villages may be listed more than once under differentspellings. Few new place-names were revealed by the publication of newtexts, beginning with PRU, V by the late ot: Virolleaud, PRU, VI,"Ugaritioa" V, and "The Claremont Ras 8hamra Tablets."The table shows that about 130 villages had to perform collectiveobligations and pay collective taxes. It is most interesting that all obliga-tions were performed and paid collectively by the entire village. Thus, itis possible to clarify the communal character of such village-communities(dlulqrt) and, even without the concrete data given below, to elucidatethe collective responsibility of all members or families dwelling in suchvillage-communities.We will now consider the various duties, taxes, and other obligationsof the rural communities.l\lilitary Duty (conscription)From the text CTC, 71 (UT, 113) we learn that professional groups ofroyal servicemen (bnAmlk) as well as certain villages, which were listedseparately, had to supply a number of "bowmen'P to serve in some kindof guard unit. The text names sixty villages, of which fifty-five are legible. Edge of the text: !u[p}pu ,dMMia "tablet of bowmen.': On theorganization of the Ugaritic army, except for the bodyguard of the king, andwithout the data of PRU, VI, cf. M. Heltzel', Soziale Aspekte des Heereswesens inUgarit, BSSAV, 1971, pp. 125-31.The parallel text to CTC, 71, PRU, III, 11.841, is written in Akkadian."We learn from these texts that various dlulqrit had to send a number ofmen varying from one bowman on behalf of three villages- to ten bowmenon behalf of one village.s Most frequently we find 1-3 bowmen conscriptedfrom a single village. The varying number of conscriptions was perhapsrelated to the population of each village.In certain cases a "general conscription" of all or almost all male mem-bers of the rural community took place. It is even possible to compare thecharacter of limited conscriptions, such as described in both texts men-tioned above, with the character of "mass" or "general conscriptions"from the same villages.Text CTC, 119 (UT, 321) is most interesting in this regard. It deals withthe conscription of warriors from various villages of the kingdom and thenumber of bows (qstm, Akk. i'qa8(UuM) and slings (qle, Akk. masakgababu) orshieldss delivered to them. The tablet PRU, VI, 95 (R8. 19.74) also men-tions a certain number of "soldiers" conscripted from variousvillages. A comparison of these texts gives us the following figures:1. CTC, 71, 9 bowman; PRU, VI, 95, 2 alZa-ri-nu-13 soldiers.2. CTC, 71, 10 Art-l bowman; PRU, VI, 95, 3 aIA-ru-tu-13 soldiers.3. CTC, 71, 11 ,!,llJ,ny-l bowman; PRU, VI, 95, 7 [aISil-O}a-nu-4[+x]soldiers.4. CTC, 71, 12 ,!,lrby-l bowman; PRU, VI, 95, 4 aISal-lirx-ba-a-l0soldiers.5. CTC, 71, 13 Dmt (together with Agt and Qmnz)-1 bowman; PRU,VI, 95, 8 [alDu]-[m]a-[t]u-x + [x] soldiers," Although the beginning and the end of the tablet are broken, the correspond-ence of the names of the villages in both texts which deliver one bowman conjointlywith another village shows that the text deals with the same kind of conscription(CTC, 71,49) Agm w ijpty-l-PRU, III, I1.S41, 13-14) alA_gi_mu, iju.pa-ta-u-l;(CTC, 71,58) and 8M-I; PRU, III, 11.841, and 8a-Qa-iq-1. CTC, 71,13-15) Dmt AgtwQmnz-1; 17-19) Yknem, 8lmy w Ull-l; PRU, III,11.841,20-22) alUlJ,-nap.pu, aI8u-ra-lu, aliju-ri.ka-1.I PRU, III, 11.841, 15) aIMa-a-qa-bu-lO, 22) aIRa-aq.du-lO.I Cf. Hebr. qelae "sling" and the parallels from other semitic languages-WUS,p. 227, No. 2413; UT, p. 478, No. 2233. The translation is not fully convincing sincethe texts of Mari employ for the term "sling," aapu, which corresponds to the Ugar.utpt; cf. B. Landsberger, Nachtrag zu aapu "Schleuder," AfO, XIX, 1959-60, P: 66.According to Rainey ("The Military Personnel of Ugarit," JNES, XXIV, 1965, P-22), qle in Ugaritic could also mean "shield." E. Salonen, Die Waffen der altenMesopatamier, Helsinki, 1965, p. 134, translated klgababum "Schleuder"-"sling,"admitting that this word could also have the meaning "shield" (p. 135) and(w)aapu(m), conld have the meaning "sling." More than one without any doubt.20 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 216. CTC, 71, 14 Agt (together with Dmt and Qmnz)-1 bowman; PRU,VI, 95, 9 [+x] soldiers.7. CTC, 71, 17 Yknem (together with Slmy and Ull)-1 bowman; PRU,VI, 95, 10 [allY[aJ-ku-naeamu-4 [+x] soldiers.8. CTC, 71, 18 Slmy (together with Ykncm and Ull)-1 bowman; PRU,VI, 95, 6 [a]ISal-ma-a-5 soldiers.9. CTC, 71, 20 'fmry-l bowman; PRU, VI, 95, 5 aISam-ra-a8-6sol-diers.10. CTC, 71, 21 Qrt-2 bowmen; PRU, VI, 95, 1 [a]IQa-ra-tu-20 +[x]soldiers.ll. CTC, 71, 27 Amy (together with M er)- 1 bowman; CTC, 119-10 soldlers."12. CTC, 71, 57 M erby- l bowman; CTC, 119 M erby- 21 soldiera.P13. CTC, 71, 21 Ubrey-2 bowmen; CTC, 119 Ubrey-61 soldiers.P14. CTC, 71, 26 Mcr (together with Amy, cf. above)-1 bowman; CTC,119 Mer- 6 soldiers.PText CTC also lists 21 men from Ulm,18 7 persons from Bqet,143 from!JIb rpB,16 3 from Rkby,18 and 8 from SertY .The text PRU, V, 16 (UT, 2016) 1) MilJdym "people of (the village)MilJd" apparently deals with the same subject. Only fifty names arelegible, but the text originally listed no less than ninety people. The wordlJlq "perished" or "defected" appears after the names of the persons in I,2,4,8,9, 14 and II, 18.18This may indicate that we have here a conscrip-tion list or a text concerning a contingent designated for conscription.The villages were listed in a particular order. We learn this by a com-parison of texts CTC, 71 with PRU, VI, 95 and CTC, 119. In CTC, 71 the8 The reading of J. Nougayrol, PRU, VI, p. 88: al(l.ra-a, but this town wassituated in eastern Asia Minor and was known by its trade relations with Ugarit.Therefore, it seems correct to read the signs otherwise. The autograph of the textshows uand the reading can also be Bam. Thus, the reading aam-ra-a is preferable.'l'mry-Samra occurs in various texts from Ugarit. (PRU,II, 181,13; 81,4; PRU,V, 44,8; 58, II, 38; PRU, VI, 77,7; 105, 2, 6, eto.) II, 1-12 named each personally.10 I, 25--48.11 CTC, 119, III, 1-46; IV, 1-19.11 CTC, 119, II, 13-20.13 I, 1-24, among them 12 gmrm.u II, 21-29.u II, 34--37; of; also PRU, II, 68 (UT, 162), 1-4 where the same three personsare listed.18 II, 35--39.17 II, 40-49.18 Cf. below with PRU, VI, 77 (RS. 19.32),names of the villages listed in PRU, VI, 95 appear between lines 9-21.The names listed in CTC, 119 appear in CTC, 71 between lines 26-57.Possibly, these texts belonged to a very short chronological period.Nevertheless, theyreveal a certain order of military conscription. Natu-rally, the larger conscriptions took place in times of emergency or warfare,and the given figures might include the whole militarily fit adult malepopulation of the villages listed.As mentioned above, CTC, 119 tells us about arms received from theroyal stores by the conscripted villagers. Delivery of arms is listed in thetablet PRU, VI, 131 (RS. 19.35A) also. According to this text, bows(iSqaAtu) and shields or slings19(masakga-ba-bu and ma.akiS_pa_tu, Ug. ulpt"quiver"(? were distributed to the various professional groups of royaldependents ("servicemen"-bn8' mlk)IO and to the villages, which arelisted as single bodies. We find listed 7) aIIz-pi, 10) aIA-gi-mu, 11) alAsar-lIBa'ali, V, 1) alllu-M-tam-'i. Each of them received 1-2 bows and 1-4other pieces of armament.By comparing texts CTC, 119 and PRU, VI, 95 with CTC, 71 and PRU,III, 11.841 we can see the difference between a partial and general con-scription to the army ofUgarit. General conscription was a collective dutyin which all villagers were obliged to participate. The royal authoritiesconsidered the village as one single body with collective responsibility.The term lJ,lq "perished" or "defected" in PRU, V, 16 gives us good evi-dence of this. Nevertheless, it is clear that the people were personally freemen, even though there was strict control by the state (royal) authorities.The data about the defection of villagers from their obligations (cf. belowp. 58-62) lends strong support to this view.21The peasants of the villages of Ugarit were also obliged to serve in thefleet of the kingdom. It is probably that only the coastal villages wereobliged to perform such service. The available lists, however, may notcontain the names of all the coastal villages which existed. We learn aboutconscription to the fleet from CTC, 79 (UT, 83). The people of variousvillages are designated by the term bnsm "people."8810 or, above, Note no. 6.10 Cf. also texts about receipt of various arms by royal dependents, PRU, V,47 (UT, 2047), where nqdm "shepherds" are receiving bows (qBt), slings and shields qle) and spears (mrl.!); cf. Heltzer, Soziale Aspekte ... p. 130.81 At present we have no well-documented data about conscription activities,except partially AlalalJ, in Northern Syria, for the period of the second miIleniumb.c. Even the archives of Mari, with their enormous number of tablets have notyet produced adequate sources. Cf. J. Sa880n, The Military Establishments at Mari,Rome, 1969.U The manifold meaning of the term lm8 cf. M. Heltzer, "Royal Dependents,"22 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 23As we see, the text mentions three ships, or three squads of ships underthe direction of sdm, Bn Klan, and The crews of these ships wereconscripted from the villages Tbq, Gr, Mcqb, Snr, abcl, and Pd(y}. Mem-bers of the crews are always mentioned as bnSm and on this occasion itcorresponds to the Akkadian term mdreM &lX "sons of the village (or city)x", i.e., the citizens of this certain community. Thus, we can determinepp. 32-47; the previous full investigation of the text, T. H. Gaster, A PhoenicianNaval Gazette, PEFQS, 1938, No.2, pp. 105-21 is out of date. The restoration ofthe text is according to A. Herdner CTC... Our reconstruction; designate a certain number of people. May be a coastal town or village; cf. M. Ma'lJ,adu, p. 113... Possibly 1n-2; 1f-6; #f-3; Illm-30 etc. Astor, Ma'lJ,adu, p. 115, a harbour village of the kingdom.t, Possible reconstruction.II About the fleet of Ugarit in general cf. J. M. Sasson, Canaanite Maritime In-volvement in the Second Millenium B.C., JAOS, 86, 1966, No.2, p. 131; cf. alsoPRU, VI, 138 (RS. 19.46), where the lower fragmentary part of the text lists16) IIb[ri].mu.za &lDu-matKI 17) IId-ki-ya &lQar.ti.ya 18) IM[ic]nu-ru &lSal-mi-ya19) IKu-ru.e-[n]a &ISa.lirx-bi-y[a] (four persons from four various villages, andpossibly similar listings in those parts of the text which were illegible of the text).This is followed by the summary: 20)naplJ,ar 10 +:1: ,dbeM "in all, 10+xsoldiers of the ship." Possibly, this text dealt also with the conscription to the fleet;on this text cf. also A. F. Rainey, Gleanings from Ugarit, lOS, III, 1973, p. 48.Non-military (1) Naval Servicethat on certain occasions, or possibly even on a regular basis, people ofcertain villages were conscripted for service in the fleet of Ugarit.28PRU, Y, 855) bn. Dnn8) P88z. bn Buly10) Nsmm: bn, cyn11) cpln. bn. Ilrs12) IltlJ-m. bn. Szm13) Smlbu. bn. arb13) 12) P8827) bn. cyn2) bn it-s22) Bn. Szrn8) bn, arb82&II Our reconstruction contradicts A. Herdner (CTC) and O. H. Gordon (UT)MilJ,d[t].8. On the maritime position of MilJ,dand Ria cf. M. Astour, Ma'lJ,adu, pp. 115-16.11 About the types of vessels cf. J. Sasson, Canaanite Maritime Involvement,p. 131.II Dietrich, Loretz and Sanmartin in ZUL, XI, p. 36, No. 101 give the interpreta-tion of qnum as a personal name, but the real sense of the word may become clearfrom new text editions.8- The reading ofOh. Virolleaudin PRU, V and O. H. Gordonin UT-bn Grb[n]is without foundation.The texts indicate that villages were not only obliged to serve in thenavy but were obliged to participate in other maritime activities as well.To this end the authorities supervised the owners of all vessels of themaritime villages of Ugarit. Thus, the text CTC, 84 (UT, 319) is a list of"The vessels of the people of (the village) 1) anyt. Although the text is in a bad state of preservation, we see that at leastseventeen persons of possessed vessels of various types (br, Ikt,wry}.81More information on the same subject is revealed by the texts, PRU, Y,78 (UT, 2078) and PRU, Y, 85 (UT, 2085). The location of these tabletsupon their discovery in the tablet-baking oven gives the best evidencethat they belonged to the very last period of the existence of the kingdom.PRU, Y, 78 begins with the words 1) Risym qnum "people of (the village)Ris (the) qnum(?}."82 The text lists twenty-two persons by name, or thenames oftheir fathers (bnx-"son of x"), orby both (xbn y). ThetextPRU,Y, 85 lists at least fifteen persons (thirteen names are legible) by their ownnames and the names of their fathers. Every name is followed by the wordtkt, which is the type of vessel owned by each person. In comparing bothtexts we gain the following results:PRU, Y, 78Crew of the shi[p] (or "ships")(of) bn AbdMrJPeople of (the village) Pdyfive menPeople of (the village) Snrnine me[n]People of'(the village) abclfour m[en]People of (the village) Tbq [x men].""Cre[w of the ship] (or "ships")(of) cdn[ J (p.n.)[People of] 'J'bq, [x men][People of] jJfcq[b .. .J19 [men]Gr x [men]Crew (of the shi[p] (or "ships")(of) bn KlanGr 1[9 men]1) anytJ2) cdn[ J3) 'J'bq[ym x bnsmj284) Mcq[bymJ5) Mc, c[sr bnSJ6) Gr24I {. . . bnsJ267) {lbu any[tJ8) bn Klan9) Gr-- Mc[csr bJnS10) any[tJ11) bn AbdMrJ12) Pdym13) bnSm14) Snrym2815) tscbns[mJ16) abclym17) arbcb[nsmJ18) 'J'b'qy[mx bnSmj27)a. PRU, II, 181 (UT, 1181), a badly preserved tablet, lists the villages Gl[btJ,Dmt, Yrt, Ykncm, Cnmky, Qmnz, 'l'mry, and 9 others, whose names are illegible. every village name "6 pairs of oxen in all" (6 to-pal alpeMnaplJ,aru) ismentioned. !Jf. also PRU, III, 15.114. According to this text the people ofalSaknuare freed from .fipru ("royal eorvee") which they had to perform by: 14) ("[thei]r oxen, their [don]keys,[their] people"). M. Dietrich, O. Loretz, Der Vertrag zwischen Suppiluliuma und Niqrnad, WO,III, 1966, No.3, p. 206. Also see M. Dietrich, O. Loretz, J. Sanmartin, Eine brieflicheAntwort des Konigs von Ugarit an eineAnfrage: PRU, II, 10 (= RS. 16.264), UF,VI, 1974, pp. 453-55; E. Lipinski, Une lettre d'affaires du chancelier royal, "Syria,"L, 1973, pp. 42-49; J. Holtifzer, A Note on iky, UF, III, 1971, p. 360.81 rgm. Cf. akk. qibima... Seems to be a functionary responsible for carrying out the royal order; con .cerning the name cf. Lipinski, p. 44, and UF, VI, p. 454... lm. Cf. UT, p. 428, No. 1384... iky cf. Dietrich, Loretz; "Der Vertrag," p. 206, and UF, VI, p. 453 which is indisagreement with the other interpretations.253) to IJyil424) Why48 are you sending me (thequestion):5) How44shall I deliver1) Sayu the message2) (of the) kingTaxes and Duties of the Villages of Ugarit5) iky. alkn3) 1IJyil4) lm, tUk. cmyHowever, in only one instance can a direct comparison be made. This is inthe case of the village of 8IYa-pa-ru which is named in both texts. PRU,III, 11.830, 4 describes aIYa-pa-ru as carrying out its labour for elevendays, while according to CTC, 66 it did so for "a month and five days."Perhaps the shorter lengths oftime related to a shorter period, for example,a season only. At the same time, these obligatory days may have beencomputed and recorded on the basis of the time it would take one man toperform all the obligatory days. Another possibility is that the differenttexts belongto different short periods of the historyof Ugarit. Inany case, itis definitelyclear that the village as a whole had the collective responsibilityfor performing the obligatory labour.The texts mentioned above do not make clear what type of labour wasdue. Sometimes it was certainly ploughing or some other work performedwith pairs or oxen.89 There also existed a mixed eorvee consisting oflabour and products produced by that labour. The relevant text in thisregard is PRU, II, 10 (UT, 1010), which was elucidated by M. Dietrichand O. Loretz, who explained the difficult lines 5_6.40This text, which canbe dated only in general, belongs to the XIV-XIII centuries b. c. It has"the following wording:1) tltm. rgm2) m1kTaxes and Duties of the Villages of UgaritThus we see that the owners of vessels who are named in PRU, V, 85 werealso people of RiB who were obliged to perform some duty with theirlkt-vessels.We learn from the above sources that both the people of RiB and thepeople of MilJd had to perform maritime duties8Sindividually or collec-tively... The Ugaritic dlu{qrit were obliged to work on various objects for theroyal authorities (or the treasury) in different parts of the kingdom. Thetexts dealing with this obligation are PRU, III, 11.830 and 11.790,84 PRU,II, 101 (UT, 1101), CTC, 65 (UT, 108),66 (UT, 109), and 136 (UT, 84).8&From PRU, III, 11.830 and 11.790, as well as CTC, 65, we learn offorty-three villages which had to perform labour obligations. In general,they owed from 1-5 days of service. Eleven villages had to work morethan five days; five of these owed more than ten days, and aIBe-ka-ni wasobligated to serve thirty days.8sCTC, 66 mentions "villages, which had to pay (to perform) the obliga-tions in ';r1rby" (1) qrht. d. t8l1mn. 2) ';r1rbh).87 Eight villages are namedwhose people worked from fifteen days (Mrat) to two months (Art). Mostof the villages had to work "a month and five days."88 Clearly, this textis dealing with relatively long periods of labour obligations. Perhaps thelengths of time mentioned were the total yearly obligations of the villages.Labour obligations of the Villages.. Cf. PRU, V, 123 (UT, 2123) relating to vessels of various types in the hands ofcertain persons. However, the bad state of preservation of the tablet allows nofurther conclusions. Cf. also PRU, VI, 73 (RS. 19.107 A), a fragment listing peoplefrom at least three dlu and mentioning "ships" (illeleppu) at the end of the text... The efforts are counted in "days" (-4meM) , but this word is preserved only atthe beginning of the text PRU, III, 11.830. Although in 11.790 the word -amiM isnot preserved, after aIAmeza and 8IGan.nana the same figures are written as in11.830 (2 and 4, respectively). Following alLaabnima the corresponding figuresare 8 and 4, aIMi.!J,i--2 and 4, 8IIaartu-5 and 4, 7 and 4. It is thuspossible to conclude that: a) PRU, III, 11.790 concerns eorvee-labour, as does11.830 also; b) the text are not contemporaneous and certain changes, due tochronology and demography, account for differing figures in both texts.a. Possibly PRU, V, 23 (UT, 2023) also. I) bMm. dt. iI. alpm.lhm, ("People whopossess oxen"), possibly the following names are a list of the members of a ruralcommunity, together with their oxen, performing the lebour-eorvee. Cf. also PRU,. V, 117 (UT, 2117), I) bMm dt il[..J with personal names and figures following.a. PRU, III, 11.790,4. UT, p. 491, No .. .flmSafcel ("to render service (or tax.'''). Cf. also I Krt130 .f.flmt a. ymm (i.1l. no less than 33 days). out. ; \ . "'''' \liaS . l 0. \'" "1 'fP '__. \ 4"1'26 Taxes ami Duties of the Villages. of Ugarit Taxes and Duties of the Villages ofUgarit 27Clearly this text is an order of the king for the delivery of tree trunksfor the building or repair of the sanctuary of the deity DmZ. It also seemsthat an individual by the name of lJyil was responsible for the project.The villagers of Ar, Ubrcy; Mlk and Atlg had to cut and deliver the treetrunks, and this is generally understood by all the interpretors of thetext, but we must point out its special significance for the social history ofUgarit. Possibly, it was an irregular oorvee and therefore required aspecial order from the king. Thus, we see that maintenance of the sanc-tuaries was the responsibility of the royal authority. At the same time,villagers had to fulfill the corvee of cutting and transporting the treetrunks.We know nothing about woodcutting corvec's in Mesopotamia. Suchactivities were more characteristic of the Syro-Phoenician coast. But the6) cpn. lbt. DmZ7) penk: atn8) cpn. lk9) arbc. cpn10) cl. Ar11) w. tlt.12) cl. Ubrcy13) W. tn cl14) MZk15) w. al),d.16) cll] Atlg17) wl. cm18) tepr19) nfrl(?)n. al too20) ad. at. lhm.21) Um. ksp6) tree trunks46 for the sanctuaryof Dml?7) And I shall give468) you the tree trunks:9) four tree trunks10) due from (lit. "on") (the village)Ar,11) and three12) due from (the village) Ubrcy,13) and two due from14) (the village) Mlk,15) and one16) due from (the village) Atlg.17) And (concerning) the tree trunks18) you have to report46a19) Nfrl(?)n (and) do not .20) 4721) sixty (shekels) silver.sources give us some opportunity to draw some analogies. The papyrusof Wen-Amon from the beginning of the eleventh century b. c., which tellsof his voyage to Byblos, informs us that the ruler of Byblos "detailed300 people and 300 cattle and he put supervisors at their head, to havethem cut down the timber. So they cut them down."48 (The story alsotells about transporting tree trunks to the seashore, which is not charac-teristic of similar cases in Ugarit.) There is another text, from the Bible,dating from the middle of the tenth century b. c. which mentions apossible parallel. 49 This text deals with the stocking of timber by Hiram,king of Tyre and Sidon, for King Solomon. Unlike these two texts, theUgaritic text is an official document concerning woodcutting in themountainous coastal woodland of the Eastern Mediterranean. The wood-cutters were the inhabitants of the rural communities performing theirobligatory labour. It may well be that in Byblos at the time of the Wen-Amon, as well as in the time of Solomon, the labour force was recruited bythe same means.The cutting down and transporting of timber, according to the Wen-Amon text, required 300 people and 300 oxen, but the quantity of treetrunks was larger (II, 44-II, 58) than in the Ugaritic text, and the distancefrom the forest in the mountains to the seashore was longer. The text PRU,II, 10 mentions only ten tree trunks. The Wen-Amon text is valuable asan aid to understanding the duties of the villages of Ugarit since it is thefirst documentary account of a woodcutting corvee, not only in Ugarit,but as far as I know, in the whole ancient Near East.In certain instances villagers were given special exemptions from ser-vice obligations.GO These exemptions offer another demonstration of theexistence of such labour obligations.At the time of their obligatory labour the people of the village receivedfood rations. CTC, 136 (UT, 84) relates 1) 8Zmym. lqIJ. akZ "People of8lm(y) (a'8alma) took food." Eleven persons are listed who received from1-3 kd-"jars"-ofoil (8mn) each.61This lends support to the notion thateveryone had to work a period longer than one day. We also see that.. Cf. Gordon, UT, p. 356, No. 147, "how can I deliver logs 1" c,m is more prob-ably understood as "tree .trunks," ef, LipiMki, p.42, "arbres"; UF, VI, p. 453"die Holzer.".. Dml--one of the Ugaritic deities. It is not clear why Gordon, UT, p. 385, No.673, defines "bt Dml" as "a place name rather than a temple," at the same timegiving in his glossary the name of the deity; atn "I shall give," UF, VI, p. 453, "ichbestimme," which is also acceptable for our interpretation. According to UF, VI, pp. 454-55... The meaning is unclear; cf. UF, VI, P- 454, and LipiMki, pp. 42 and 6 ~ 8 J. A. WilBon, ANET, 1955, p. 28; cf. also the most recent edition of the papy-rus, M. A. KoroatovtBev, Puteshestviye Un-Amuna v Bibl, Moscow, 1960, P- 31, II,42-44 (Russian). II Reg. 5,20.o. PRU, III, 16.18B-King Ammi8tamru II frees a person (v, 6) it-ti ma[re]M&IMa-ra-ba-m[a?] 7) ame1ka_al_la la-o il-io-ail] ("with the sons of Maraba (MCrb)he must not go to the messenger (service)"). Cf. also PRU, 15.114, footnote 39.01 In Akkadian texts usually corresponded to DUG as a certain unit of liquidmeasure.28 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 2910) IMaB-da-bi-u 6 napBiiteMIi(?) MaBdabiu-6 souls, 5 oxen, in all( 'I)alpfL2 napljar( ?): 11 11689) IIli-i12 Ba'a.l [qa-du] 366Iliba'al [with] 3(?) s[oul]s, 24 [+2]n[iipBii]teM24 [+x] immeriitu sheep, 2 oxen2 alpfL11) Ya-ri-mu i-na aIZa-qi-[xxJ Ya-rimu in (the village) Zaqi[xxJlllu-ra-[m]u i-na al{fa-[n]i Iluramu in (the village) {fani6712) IAbdi-ili-mu i-na alQi-am-l[a-aJ Abdiilimu in (the village) Qiaml[aJ13) I Ili-ya-nu i-na dimti Gal-ni-um Iliyanu at the dimtu68GalniumAnother text, U. V, 95 (RS. 20.01), gives additional data aboutobligatory service performed by people from the rural Ugaritic communi-ties. This text must be a list of mixed character since it mentions not onlyvillagers but also royal dependents (bns mlk) of various royal gt, theprimary units of the royal estate. The list includes people from variousdifferent villages. The text also gives information about the livestockpossessed by the people whose names are listed in the tablet.63Niqimadu with 6 souls, 3 oxen,13 [+2( ?)] sh[eep]4 souls (people) of {fudaBifi 4Yarimu with 5 souls (people)Matenu with his wife, 6 oxenBa'almateni with 6 souls, 20[x]en,5 she[ep]and Ili[y]a10 souls (people) in (the village)Uskani, 2 oxenA pteya, 3 souls, 3 oxen 7) IApteya 3 napBiitiiM3 alpfL8) INi-qi-ma-du qa-du 6(?)napBiite-' 3 alpfLM13 [+2(?)]im[meriitu]M1) I Ya-ri-mu qa-du Ii napBiiteM2) IMa-te-nu qa-du aBSati-BU6 alpiLM3) it n-u-tv;4) 4 napsiUiLM[sJa l{fu-da-si5) 10 napBiUii, i-na alUs-ka-ni2 alpiL6) IIl2Ba'al-ma-te-ni qa-du 6napBiite2a[l]pn Ii(?)immer[atu]II Cf. the analysis of the text by M. Heltzer, VDI, 1971, No. I, pp. 114-16(Bussian]... Probably a scribal error-instead of alffu.da.ii (of; IJdtt, PRU, II, 84 (UT,1084), 11-12; 98 (UT, 1098), 22-23) we have the determinative of a masculine per-sonalname.IS Or 6, the lower part of the text is damaged... A very strange summing up of people and cattle!61 Cf. Ziqa.ni.ma in table No.1; IJa.ni Ug, Gn, Ug, gt, unit of the royal real estate; cf. Helteer, VDI, 1971, No. I, pp. 114-16.5) [Ily. w.]. J)mry. rb [Ilyand] Dmry entered6) b. Tbem with Tbem9) l]mry. lm, Yrm 12mry, son of Yrm10) srb, b. Adey entered with AdcyEight persons from Ris (citizens of RiB) appeared in four pairs. It seemslikely that every pair appeared, together with one additional person, forthe purpose of performing their obligatory labor together. The additionalperson may have been a dependent of the pair, or he may have been theirslave. But there are also different views about the meaning of this text.6SaII We know that only 5 soldiers were conscripted from Slmy/alSalma (cf. above,p.20)."a M. Dietrich, O. Lorets, J. Sanmartin, Keilalphabetische Biirgschaftstexte ausUgarit, UF, VI, 1974, s. 466 consider the text unhesitatingly to be a surety-grant.,3) I]mry. w. Plpl. erb l]mry and Plpl entered4) b. Yrm with Yrm7) Ydn. bn, llrpi Ydn, son of Ilrpi8) w. Tbem. srb. b. e[d]n and Tbem entered with e[d]neleven people from the village were obliged to serve.fi SText PRU, II, 59(UT, 1059) also lists 1) MalJdym "People of (the village) MalJd". In lines2-5 four persons are named and after each name is the word lt7;t, a unit ofdry measure. It is possible that here too the text is describing the distribu-tion of products to people who were performing their service obligationsaway from their own villages.Text U. V, 99 (RS. 20. 425) is a list of provision (wine and oil) deliv-eries for various professional groups of royal dependents of the kingdomof Ugarit. But among them also appear:3) 1 karpat kariinu a-na m,dreMalA-ri"1 jar of wine to the people of Ari"4) 1 karpat kariinu a-na mo,reMaIUl-la-me"1 jar of wine to the people of Ullame"Thus, we see that in some cases food was distributed to the people ofUgaritic villages on an individual basis. This indicates that food wasdistributed only to those individuals who were working at any giventime.Text PRU, V, 79 (UT, 2079) from the tablet-baking furnace (i.e.from the last years of the existence of the kingdom of Ugarit) lists sucha labor force.1) Risym. dt. erb People of (the village) RiB who2) b[.] bnBhm entered with their men30 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 31Lines 4-5, 11-12, 16-21 refer to people of various village-communitieswho had to perform labour obligations. This is confirmed by lines 13-14,where it is related that certain people had to perform their obligatorylabour at the dimtujgt, i. e. at the royal real estate in the kingdom ofUgarit. We also see that in the case which is dealt with by the given textvarious people had to work at the same time in different places. It ispossible that a certain number of these people (line 15) were seized asdefectors (cf. below p. 58-60). The villagers had to report for labor togetherwith their beasts of burden, oxen and donkeys, although sometimes sheepare mentioned.Despite the texts given here, the information about the distribution ofobligatory labour inside the village-communities is relatively poor. Per-haps analysis of the families of the peasants inside the community cangive us a more detailed picture of the distribution of the royal labour (cf.below Chapter VII, pp.90-96 ).According to CTC, 69, seven villages paid 8.5 sheqels. According to PRU,II, 176, eight villages paid 37 sheqels, The villages Dmt, Ary and Ykncmare mentioned in both texts and pay 1 and 3, 1 and 5, and 1 and 5 sheqels,respectively. It is not clear whether these were regular or exceptionalpayments. We cannot exclude the possibility that these lists may beexcerpts from a more detailed tax list, or a memorial note, made by thescribe. 87Much more can be learned from the large tablet PRU, V, 58 (UT,The sources mention "silver of the offerings" (or "offering people"-kasap &mC1Msar-ra-ku-tijvar. sirku),62 "silver of the honourables" (kasapsu-sa-pi-nu-ti),83 and "silver" or possibly "fine" for scolding( 1) (kasap&meIMZi-in-lJa-na-se).84 These specific taxes are only mentioned in regardto three villages (Ulj,nappu,. Bi-i-ru, and E[. . .jiS). The detailed lists oftaxes which were paid in silver do not indicate the nature of the taxes.It seems likely that there was no fixed sum due at regular intervals.The amount due varied from payment to payment. This can be seen fromthe comparison of two tax lists.14) 12(?) napSiiteM11 alpeM3imeruM i-na dimti I llu-milki15) 4 napsiiteMsa ifJ-fJa-batis-t[u?j .. .j16) 1 amelu i-na &IGiz_ilBa'alal u17) 3 napSiiteMi-na &Illu-is-[tjam-i18) [x+j 1 napsiiteMi-na &IPi-[dji19) 1 [amjelu i-na &Iffal-ba-ya20) [x+j 2 napsiitelMj 4 napSiiW1[. . .j i-na &ITu-na-a-na21) 1 amel[u i-nja &ISAG.DU(su)12 souls, 11 oxen, 3 donkeysat the dimtu llumilki&94 souls, who were seizedfr[om .....]801 person in (the village) Gibala3 souls in (the village) lluiS[tjami[x-l-] 1 soul in (the village) Pi[dji1 person in (the village) ffalbaya[x+] 2 souls, 4 souls[...] in (the village) Tunana1 pers[on i]n (the village) R8u81CTC, 69 (UT, 111)1) Qrt tqlrn w nfJp (2.5 sheqels)8&2) Blrny tql (1 sheqel)3) Ary tql . (1 sheqel)4) Xmry tql. w. ntJp (1.5 sheqels)5) Agt nfJp (0.5 sheqel)6) Dmt. tql (1 sheqel)7) Ykncm tql (1 sheqel)PRU, II, 176 (UT, 159)1) Dnt tlt (3 sheqels)2) Qmnz tql (1 sheqel)3) Zlyy tql (1 sheqel)4) Ary lj,rnSt (5 sheqels)5) Ykncm lj,rnSt (5 sheqels)6) cnmky tqlm (2 sheqels)7) [Kmjkt88csrt (10 sheqels)8) Q(?)m &bct (7 sheqels)Payment of TaxesBesides military conscription and the labour obligations mentionedabove, which were distributed among the villages, there were also taxobligations in Ugarit. These taxes were paid by the village-communitiesin silver or natural products. We will first consider those taxespaid in silver.50 Not of the person Ilumilki, but it was the name of the dimtu/gt. Possibly, thisdimtu was originally named after the former owner of the land. Possibly former defectors seized elsewhere for their royal corvee( 1).n Cf. table No. I, note No. 52... PRU, III, 16.276,9, from &IU1)nappu; PRU, III, 16.277-"IBi.i-ru; PRU, III,16.153, 13. PRU, III, 16.153, 13-"IE[.. .JU. PRU, III, 16.244, 16, &IBi-i-ri: cf. also I. Mendelsohn, Samuel's Denunciationof Kingship in. the Light of the Akkadian Documents from Ugarit, BASOR, 143,1956, pp. 17-22... I Ugaritic sheqe1 varied between 9-9.9 grams, cf. the detailed study of N. F.Parise, "Per unostudie del sistema ponderale Ugaritico, DA, I, 1970/71, pp. 3-36. Our reconstruction based on PRU, V, 119 (UT, 2119): 11) ...J Kmkty,12) .. .J b Kmkty, 16) .. ;Jb Kmkty.07 The fragment CTC, 70 (UT, 112) where at least 15 villages were listed (7 namesare legible) seems to be a document of the same type. Following the place-namesappears a number, varying from for each village. Hzp has to pay 1n-2; Ypr arb[C}-4; MCqb. cb-lO; Tn"Ylll-3; fflb cprm.ln-2,Am!!y.Ilt-3. These place-names do not appear in CTC, 69 and PRU, II, 176.32 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 3311 N. B. Yankov8ka, L'autonomie de Ia communaute a Ougarit (garanties etstructure), VDI, 1963, No.3, P- 33 (Bussian), The contrary view is presented byM. Heltur, Once More on Communal Belf-Govemment in Ugarit, VDI, 1965, No.2, pp. 11-12 [Russian).U Or "tribute-deliverers" (to the treasury). This is the only case where the wordargmn ("tribute") is used in the plural form (argmnm). Perhaps there is a secondarynoun from argmn, "the argmn collectors" or "the argmn deliverers." Possibly, thiswas also a tax for paying tribute to the Hittite king; Pardee, UF, VI, p. 277, doesnot explain the plural form (argmnm).15 kbd, in various lists and economic texts from Ugarit, in the sense of "totally,"but not necessarily summing up the results. Cf. M. Liverani, "kbd" nei testi am-ministrativi ugaritici, UF, II, pp. 89-108.ever, compared with other instances (for example, CTC, 69 and PRU, II,171, where the village Ykncm had to pay 1 and 5 sheqels, respectively,and PRU, V, 58 where Yknem had to pay 21 sheqels; and CTC, 69 andPRU, V, 58, where the village Blmy had to pay 1 and 43+x sheqels,respectively), the payments mentioned above were much heavier thanthe norm. Perhaps the figures mentioned were payments made over aperiod of time longer than in the other texts. Or perhaps the tribute tothe Hittite king was an extraordinary payment.In connection with the taxes mentioned above the question arises: howwere taxes collected In our opinion, there is no data to confirm the viewof N. B. Yankovska that merchants [tamkars] from abroad farmed thetaxes in Ugarit.78Contrary to this view, the text PRU, V, 107 (UT,2107), found in the tablet-baking furnace, provides convincing testimonythat, at least in some cases during the last period of the existence of thekingdom of Ugarit, the village taxes were collected by tamkars of theking of Ugarit. The text reads as follows:2058).88 The obverse side is divided into two columns having a commonheading: 1) {sprJargmn spS, "The list of tribute to the Sun" (i.e. theHittite king).88In the first column 36-40 names were originally listed, butonly 17 are fully legible or capable of reconstruction. 70 Every place-nameis followed by number-signs, also only partly legible. The payments beginfrom 5 sheqels (Qlb prm, QrM) to 152 sheqels (Il8tme) and in line 21,where the name of the village is damaged, the payment reaches 400(4 ME) sheqels, The second column consisted originally of 40 place-names, but only 27 are fully legible or capable of reconstruction." Thesepayments vary from 4 sheqels (tIlby) up to 107 sheqels (Meqb), but theaverage seems to be less than 100 sheqels per village. On the reverseside of the tablet professional groups of the royal dependents, who hadto pay the tax also, are listed. Text eTC, 71 concerning bowmen, men-tioned above on pp. 18-19, offers newevidence that every village and everyprofessional group was regarded as a single unit.The total sum is written in Akkadian and only partly preserved.Although it does not aid in the reconstruction of the text PRU, V, 58(UT, 2058) it is clear that the sum was paid in silver.7BIt is difficult todetermine whether this was a regular or extraordinary payment. How-II PRU, V, pp. 75-78, the editor, Oh, ViroUeawl, gives only the autograph,transliteration of the lines, written in Akkadian on the reverse side, and the list ofthe Ugaritie villages and professional groups of royal servicemen (bni mlk)-bothincomplete. Despite the bad condition of the text, it is possible to reconstruct con-vincingly at least a part of the damaged lines... argmn ("tribute"), cf. Oh, Rabin, Hittite Words in Hebrew, Studies in theBible, presented to M. H. Segal, Jerusalem, 1964, pp. 156-57 (Hebrew). Ugar. argmncorresponds to the hittite arkamma(u) ("tribute"); also D. Pardee, The UgariticText 147 (90), UF, VI, 1974, pp. 277-78.,. Our reconstruction, which differs from the reading of Oh: ViroUeawl, or ismissing in his reconstruction, is marked by an asterisk (*): *Gbel, Mcrby, Mer, Amy,enqpat, sert, UbrCy, I18tm", Sbn, Tbq, Rqd, *Srl (given also by O. H. Gordon), (ffl]bkrd, [lJl]b s-prm, QaB, Am!!y, *[Gn]ey.11 Meqb, Agm, lJpty, Ypr, UlJ,np, Art, Nnu, Smg, Smn, Lbnm, Trm, MidlJ" *IJlym [lJ]lby, cr, *en[mky] (also in UT), Glbty, Ykn"m, Slmy, *Tl[rby],Tm[ry], Arj[t, Dm[t], *Sl[lJ,ny] (cf. SllJ,ny.tabll\No. 1. Not Slmy for the secondtime, as it is reconstructed by O. H. Gordon).11 Rev, II, 6) [x l]iim 1 meat 22 +[to] 7) []na[pMar kaspiM 10 allZniM8)[x l]i.im 6 me-ott} 30 [+x] 9) na[plJ,Jar kaspiM al[lZniM] (Dividing line follows).10) [x l]iim 56 [+x] 11) [nap]lJ,ar ka8p[iMJ."6) [x th]ousand 122 [+x] 7) [) at [al]l silver [from] 10 villages 8) [x th]ousand630 [ +x] at [al]1 silver (from the) vii [lages] (Dividing line) 10) [x th]ousand 56 [ +x]11) [at] all (sheqels of) silve[r].Thus we see that after the listing of the professional groups there is the totalsum collected from the Alu, and then the grand total including the professionalgroups; cf. also Liverani, Communautes, ... p. 147, note 2.1) spr argmnm2) "srm. ksp. d. mkr3) Mlk4) ksp.d.Sbn5) mit. ksp.d. 'fbq6) lmnym arbe7) kbd kep.8) nqdym9) lJ,mAm. lmit10) ksp. d. mkr. ArList of the tribute-collectoraw20 (sheqels) silver from the tamkarof (the village) lIfllc 300 (sheqels) silver from (the tamkar)of (the village) Sbn100 (sheqels) silver from (the tamkarof the village) 'fbq84-totally76 (sheqels) of silver(from) the shepherds150 (sheqels)silver from the tamkar of (the village)Ar34 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 35. "On" is (cf. with cl in PRU, II, 10 above). It seems likely that this the sum total which t!te tamkor had not yet delivered to the treasury. ThereforeIines 15-19 could be scribal memory notes concerning tamkars (mkrm) who did notliquidate their obligations to the treasury.'11& About the role of the tamkar cf. M. Heltzer, Tamkar et son role dans l'AsieOccidentale de XIV-XIII siecles avo n.e., VDI, 1964, No.2, pp. 3-16, (Russian);A. F. Rainey, Business agents in Ugarit, IEJ, XIII, 1963, pp. 313-21; R. Yaron,Foreign Merchants in Ugarit, ILR, IV, 1969, pp. 71-79; M. Astour, The MerchantClass of Ugarit, RAI, XVIII, Miinchen, 1972, pp. 11-26.77 PRU, III 16.153, where theaIE{.. JiI is freed from various duties and taxesand among them: 12) u immriituM ma-aq-qa-du. ("and sheep, (pay for) pasture").Cf. Mendelsohn, Samuel's Denunciation, P: 20... PRU, VI, 116 (RS. 17.64). 00.. M. Heltzer, On the Ownership of the Pastures in Ugarit, in "Studies in theHistory of the Jewish People and of the Land of Israel," III, Haifa, 1974, pp. 9-17(Hebrew), p. III English summery.This text shows that the tax was paid by six villages and one profes-sional group of "royal men" (bnA mlk)-the shephers (nqdm).The silverhad to be collected by special tamkars (mkrm) , royal commercial agents78awho were undoubtedly dependents of the king of Ugarit. Every village,as well as every group of bns mlk, was considered a single unit, and as suchwas collectively obliged to pay the tax imposed on the village or group.The tax farmer was obliged to see that this payment reached the royaltreasury. At least at the very end of the existence of the kingdom, it ispossible that the taxes were farmed out to the tamkars of the king ofUgarit.Mixed taxes consisting of silver and natural productswere also collected in Ugarit, although data concerning this' matter isvery searse. We know of a certain pasture-tax (ma-aq-qa-du) which waspaid in sheep." We also know about a pasture-tax paid in silver, kasapsa maqadu "silver for pasture." This tax was paid by various professionalgroups of "royal men," as well as by the village of aINa-nu-u, which hadto pay five sheqels.78 Such forms of taxation suggest that the pasture-lands belonged not to the village-community but to the king.7911) arbcm ksp dmkr14) Ilstmc15) csrm. 1mit. ksp16) -t bn Alkbl 8b[nyJ17) csrm kep cl18) Wrt, Mtny. wei19) Prdmy. atth40 (sheqels) silver from the tamkarof (the village) Ilstmc120 (sheqels) silveron78 (or "to") bn Alkbl, man of (thevillage) 8b [n]20 (sheqels) silver on (or "to")Wrt, man of (the village) Mtn and onPrdmy, his wifeTithe paid in GrainTithes, paid to the king, made up a large part of the various taxesdelivered in silver and agricultural products.w This was brilliantly de-monstrated in the investigation of 1. Mendelsohn.s! The tithe is designatedin the Akkadian texts from Ugarit as ma-'a-sa-ru/e8retu.82There is nomention of a single individual paying the tithe. The tithe was imposedon the whole villiage as a collective body. We learn of one case in which thetithe consisted of grain and sikiiru (the beer( 1) made from barley).83The text PRU, III, 10.044 seems to record such tithes. According to thistext, various villages of the kingdom of Ugarit paid grain, vine and oxento the royal treasury.Sometimes the tithe appeared under the name miksu, usually translatedas "custom duty."84 However, this translation is not exact. In the textPRU, III, 16.276 miksu appears in addition to the tithe (esretu) and otherkinds of payments. This makes it possible to consider the term in abroader sense, sometimes covering various taxes, as well as custom-duties. From this we conclude, in agreement with F. R. Kraus, thatmiksu should be translated as "public payment from the field."85But if we turn to the lists of payments of grain made by various villagesof the kingdom of Ugarit, it is impossible to tell whether we are dealingwith the tithe or not. Only the mention of grain as the tithe in PRU, III,16.15388 makes it possible to identify this form of taxation. Althoughthe period of time for which the payment was due is not mentioned, wemay assume that the lists refer to yearly paymente.s?Table No.2 classifies various data about the grain deliveries to theroyal stores or treasury which Ugaritic villages (dlu/qrit) had to pay.80 A. F. Rainey, A Social Structure, pp. 96-108.81 Mendelsohn, Samuel's Denunciation, pp. 17-22.8> Mendelsohn, Samuel's Denunciation, p. 20. Cf. Hebr. maCa.ser ("tithe"); men-tioned in Ugarit in PRU, III, 16.153, aIE{ .. .Jis; 16.276, aIUb--nap-pu; 16.244.aIBi-i-ru had to pay; of, also M. A. Dandamajev, Der Tempelzehnte in Babylonienwahrenddes 6.-4.Jh. v.u.Z, "Festschrift fiir Franz AItheim," Berlin, 1969, pp. 82-90;E. Salonen, tIber den Zehnten im AIten Mesopotamien, Helsinki, 1972, pp. 60-61.83 PRU, III, 16.153, 10) s-su8ikarM-8u 11) sa ma'a-sa-ri-su ("his grain and hisSikaru of his tithe"), i. e. of the village E[JiI, when, in some cases, other productssuch as oil, cattle, etc., are mentioned without direct evidence, then we assume weare dealing with the tithe. Cf. also PRU, III, 16.269.8( Resp. amelma-ki_su ("customer"); cf. PRU, IV, 17.134,3-5, etc.85 F. R. Kraus, Ein Edikt des Konigs Ammi-l;laduqa von Babylon, Leiden, 1958,pp. 141-42, "Offentliche Feldabgabe."85 Cf. above, note 83.8. Cf. some texts which mention payments by some groups in Ugarit which hadto be paid yearly: ina sanatiM-PRU, III, 16.157,21; 16.254D, 10; 15.132, 14, etc.36 Taxes and Duties of the Villages of UgaritTable No.2Taxes and Duties of the Villages of UgaritTable No.2 continued37AmountSort Deliv- AverageNo. Village Text ofof grain ery fromgrain through- village1. aIA-ra-ni-ya PRU, III, 2 kUr Zl.KAL. - 2 kur10.044 MES"flour 1""barley"2. aIU-bur-a " 18 kur " - 18 kur3. alBru " [1]6 kU1 " - [1]6 kUr4. tnu-qap-at " 6 kUr " -}6 kurallnu-qa- PRU, VI,110 6 kur8" -par-at)1 (RS.19.88)5. aIBe-ka-ni PRU, III, 50 kur " - 50 kUr10.0446. tu-u- " 18 kur " - 18 kurtam-'i7. aISub-ba-ni " 5 kur " - 5 kur8. al'fe.-ba-qu " 5 kur " -}8.5 kuraITi-ba-qu PRU, VI,106 12 kUr - -(RS. 19.119)9. alRiq-di PRU, III, 18 kur Zl.KAL. - 18 kUr10.044 MES10. aISu-ra-su " 6 kur " - 6 kur11. a ~ ~ u r u " 6 kur " - 6 kur(flU)12. al]b-na-li PRU, VI,100 1 kUr - - -(RS. 19.51)13. alPa-sa-ra-te PRU, VI,102 40kur ZlZ.AN.NA lA-ri- 40kUr(RS. 19.12) (kunaSu"em- maorimer")14. alllIa-ri-a-te " 6 kur " lSil- 6 kurdi-[nJa15. alla-a-pa-ru " 40kur " lZu-ga- 40 kUru16. al]a-a-lu " 10 kUr " ISi-ga- 10 kUrnuAmountSort Deliv- AverageNo. Village Text of ery fromgrain of grainthrough1 village17. aIA-ru-tu PRU,VI,102 - " -(RS. 19.12)PRU, VI,105 7 kur se "grain" PA(RS.19.117) (=aklu"over-seer")6.25kurPRU, VI,106 3 kur - -(RS. 19.119)PRU, VI,110 5(?} kUr - -(RS.19.88)PRU, VI,l11 10 kur se "grain" -(RS. 19.129)18. alSa-lirx-ba-a PRU, VI,105 5 kUr u "grain" PA(=(RS.19.117) aklu)5 kurPRU, VI,111 5 kUr se "grain" -(RS. 19.129)19. alE-ku-na-mu PRU, VI, roe 5 kUr Be "grain" PA (= 5 kurug. Ykncm) (RS.19.117) aklu)20. aIDu-ma-tu PRU, VI,105 5kur u "grain"PA(=l(RS.19.117) aklu) .5 kurPRU, VI,I11 5 kur se "grain" -(RS.19.129)21. alA-lw-tu PRU, VI,105 5 kur se "grain" PA(RS.19.117)4kUrPRU, VI,111 3 kur " -J(RS. 19.129)22. aIQa-ma-nu- PRU, VI,105 5 kUr Be "grain" PA 5 kUrzu (RS. 19.117)23. aISa-am-ra PRU, VI,105 6 kUr se "grain" -(RS.19.117)6 kUrPRU, VI,l11 6kur " -(RS. 19.129)24. &IQu-ur-tu PRU, VI,105 1 se "grain" PA 1(RS. 19.117)38 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 39AmountSort Deliv- AverageNo. Village Text ofof grain ery fromgrain through- village25. aIAp-su-na PRU, VI,lll [x] s ~ " - 1(RS. 19.129)26. aIZa-ri-nu PRU, VI,lll 10 kur s ~ " - 10 kUr(RS. 19.129)27. aI8a[m]- PRU, VI,lll 6kur se. "grain" - 6 kU1'[na] (1) (RS. 19.129)28. al[8a]l-ma-a " 3 kur s ~ - 3kUr(1)29. aI8u-wa-a " xkur s ~ - xkur30. aIA-ga-nu OL.1957,3 164 kur se.ME8 -62kur ZIZ.AN NA. U-te-lu 226kurME8"emmer"31. 8a'artu " 52 kur se.ME8 - 105kur(81G,8ert) 53 kUr ZlZ.AN NA. -ME81 Tells to whom (eli x) the grain was given for preservation, storage or otherpurpose.s a1lnu-qa-pa-[atJ instead of the reading of J. Nougayrol alMa[UJ.ka.na[..J.The orthography shows that the first sign is by no means m l ~ and that the onlypossible reading instead of mal ist>-ina without the additional vertical stroke; cf.W. von Soden, W. RiJllig, Das Akkadische Syllabar, Roma, 1967, No.1. The thirdsign is the same (PA), which recurs on tablets PRU, VI, 109 (RS. 19.191), 105(19.117), etc. The figure seems more likely to be "6".Table No.2 records the grain payments made by thirty-one villages ofUgarit, but the specific amounts are known for only twenty-seven villages.Averages can be computed for seven villages from the data available. Thisdata does not demonstrate any striking difference in payments from yearto year, thus, it can be assumed that the amount recorded for the re-maining villages is fairly accurate as an indicator of their average pay-ments. The overall figures for the villages ranges from 2 kur to 226 kur.The total amount of grain for all twenty-seven villages is 635.75 kur. (Nodistinction is made between barley and emmer.) The average for onevillage is 23.6 kur of grain. From texts U. V. 143-5288we learn that theII R. S. 20.10; 20.196; 20.161; 20.160; 20.14; 21.05; 21.65; 21.07; 21.196 A;RS 6 X; Rs. Pt. 1844.kur in Ugarit consisted of 300 ka (1.2 ka = I liter). Thus, I kUr wasequivalent to approximately 250 liters.8t As was demonstrated earlier,there were about 200 villages in Ugarit.tOThe treasury thus received ap-proximately 4,700 kur of grain (200 X3.6 kur)-a little less than 1200metric tons.The data also shows that, in some cases, the royal stores did not receivethe grain tax directly from each village, but rather by delivery throughcertain individuals.s! The text PRU, VI, 102 mentions four such persons:Arimari, 8idina, Zuga'u and 8iganu. Text Ol. 1957,3 mentions one suchperson, Utelu. Instead of naming these individuals by name, PRU, VI,105 designates them all with the Sumerian ideogram FA (ugula, Akk.aklu) "overseer." The above-mentioned names are given even withoutthe fathers' names. Therefore there is no possibility to identify theseoverseers with Ugaritic officials known from other texts. But text PRU,VI, 105 seems to prove that all of them were FA "overseers." Perhapstheir function was to control and oversee the regular payment of thesetaxes by the village-communities of Ugarit. It is interesting to note thatin this case the taxes were not farmed by tamkars (mkrm) of the king ofUgarit, as was the case with the taxes paid in silver (cf. above pp. 33-34).We must remember that the amount of grain given here was received bythe royal treasury of Ugarit only by payments from the rural communitiesand that it does not include the income of grain from the royal real estatewhich has been discussed in a separate work by this author.taWe know that in this same period the Hittite king purchased about2,000 kur of grain in the land of Mukis. The task of transporting it bysea was imposed on the king ofUgarit who had to perform this task withhis ships.tS We can see that if 2,000 kur was a considerable amount ofgrain for the Hittite kingdom then Ugarit was quite wealthy in thisrespect... About the ka in the contemporary Kassite Babylonia, cf. B. Meissner, Waren-preise in Babylon, Berlin, 1936, pp. 4-5. Cf. table No. land accompanying comments.II Cl, 1957,3; PRU, VI, 102 and 105. M. Heltzer, "Royal Dependents"; the investigation does not include theeditions of texts from U, V, PRU, VI and Claremont Tablets. The amount of grain,received from the landholdings of royal servicemen (bnJ mlk) was a very little one... U, V, 33 (RS. 20,212), 19) i1Bam8uSU 2 lim BE BAR[J 20) motu maIMu-kiA-lJ,iuktallim8u-nu-ti ("The Sun (the Hittite king) assigned from the land of Muki1i2000 (kur) grain,") the order or transporting them by the ships of the king ofUgarit follows (lines 21-26), cf. the fragment U, V, 171 (RS. 26.158), cf. also H.Klengel, Geschichte Syriens, II, 395.40 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 41Some centuries later, in the middle of the tenth century b.o., kingSolomon of Israel had to pay 20,000 kitr of wheat (grain)94 yearly toHiram, king of Tyre, for various types of timber which Solomon used forhis building activities. If we compare this figure with the 5,000 kitr ofgrain received annually as tithes in Ugarit we see that, taking into accountthat the kingdom of Solomon was at least ten times larger than the king-dom of Ugarit, and that the income of Solomon must have been relativelythe same, the figures are by no means exaggerated.Payments of WineAt least from the third millenium b. c. vineyards and wine productionplayed a large economic role in Ugarit, as in most of the coastlands of theeastern Mediterranean. The mythological and epical literature of Ugaritis full of references to wine and its consumption. The ritual texts oftenexplain that wine was used for offerings to the gods. One of the Ugariticmonths was named yrlf,risyn95/Akk. ara!12res-karaniM, "(month) ofthe head-of-the wine."98 We also know about deliveris of large quantities of winefrom the royal stores to be used for various purposes. So it is natural thata wine tax should have existed in Ugarit.The wine tax was measured by jars (lcd/DUG/karpatu). Let us considerthe tablet PRU, V, 4 (UT, 2004): 1) yn. d. yk1. bd. [ .. .J 1. dblj, m1k 1) "Thewine from (or "of the kind of") yk1for [...] 2) at the royalsacrifice."97 Thedividing line in the text is followed by a list of the gods of Ugarit togetherwith the prescribed offerings for each of them.98The reverse of the tabletdiffers from all the other known texts of this type. It contains a list of thenames of thirteen villages of the kingdom of Ugarit (Lbnm, {f1b gngnt, Nnu, 8q1, 8mny, 8mgy, Hzp, Bir, Agm, 8rs, Rqd, UlJnp) as well as.. I Reg 5,25 liit!im("wheat") as well as ("grain") generally... A. Herdner, "Un nouvel exemplaire du rituel RS.1929, No.3," Syria, XXXIII,1956, pp. (UT, 173,1), PRU, II, 106, 32 (UT, 1106), PRU, V, 12,21 (UT,2012); cf. Gordon, UT, p. 481, No. 2296. U, V, 99 (RS. 20.425), 13, date formula i-na ara1!.rU.karaniM Cf. also footnoteof J. Nougayrol, P. 194, No.3, RS. 19.25,4, ITUSAG GESTIN. MES = arabrU-karani in PRU, VI, 107, 11. On the Ugaritic months see, J. P. J. Olivier, Notes onthe Ugaritic Month Names, JNSL, I, 1971, pp. 39-45; II, 1972, pp. 52-59; riByn =Sept./Oct... Cf. O. Eisa/eldt, Molk als Opferbegriffim Punischen und Hebriischen und daaEnde des Gottes Moloch, Beitrige zur Religionsgeschichte des Altertums,3, 1935.Cf. also O. Eisa/eldt, Neue Keilalphabetische Texte aus Ras Sehamra-Ugarit, Berlin,1965, p. 14... A. Herdmer, Un nouvelle, PRU, II, 4 and 5 (UT, etc.the number of "jars of wine" (kd yn) which they had to deliver. Everyvillage was required to deliver from 2-10 jars. Thus, we have here aspecial wine tax for sacrificial purposes. It may have been connected withthe temple economy.Another text, CTC, 67 (UT, 110), records the total sum of "148 jars ofwine totally" (13) 1 me-at 48 DUG GE8TIN napfpar). This text, as wellas PRU, III, 10.044, discussed above in connection with the grain taxand confirming the yearly character of the payments, helps us somewhatin reconstructing this tax. TableNo. 3 summarizes the informationfound in these two texts concerning wine payments.Table No.3 shows a total of 160 jars of wine from fourteen villages, i. e.an average of 11.5 jars pers village. The total for the estimated 200 villagesof Ugarit would thus be approximately 2,300 jars of wine. But sourcedocuments are so scarse at the present time that we cannot draw definitiveconclusions.Table No.3No. Village Quantity Measuring Text No.Unit1. {f1b sprm H (6) DUG CTC, 67 (UT, 110)2. J.f1b krd tn csr (12) " " " " "3. Qmy arbc csr (14) " " " " "4. $cq arbc csr (14) " " " " "5. $c tmn (8) " " " " "6. csrm arb (24) " " " " "7. .fJ1b rpA arb csr (14) " " " " "8. Bqct tt (6) " " " " "9. Irab tn csr (12) " " " " "10. lfbS tmn (8) " " " " "11. AmrJy arb csr (14) " " " " "12. [GJncy It (6) " " " " "13. aI8u-ra-su 11 DUG.GE8TIN PRU, III, 10.044, 12114. ({fU) 17" PRU, III, 10.044, 1321 81'S (aI8u.ra-au) appears also in PRU, V, 4, 32 where the village has to deliver7 jars of wine. Lines of the same text tell about 12 and 7 jars of wine respectively, butthe names of the villages are not preserved on the tablet.42 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 43It should be noted that, as in all the previously discussed cases, eachvillage is treated as a single unit.Payments in Olive OilFrom various Ugaritic texts, especially from tablets containing legaldocuments concerning land transactions, we know of the important roleplayed by olive trees in the economy of Ugarit.The royal gt(dimtu) served as centers where olive oil from the royal estates, taxes,and other income, was produced and stored.99Since olive oil was soimportant in the economy, it is only natural that a tax on this commoditywas exacted. Oil ([8am]nu) is mentioned as the tax from the dlu Be-qa-ll18tar. 100Tax lists which would indicate the number of dlu/grit havingto pay taxes in olive oil are currently unavailable. However, PRU, II, 82(UT, 1082) seems to be a completely preserved list of all, or almost all, thehouseholds of a whole village from whom the olive oil tax was collected.The first line reads: 1) kd. 8mn. cl Hbm Slm[y] ("(One) jar of oil on (i.e.for derlivery)lOl Hbm, man 0/ Slmy."). Lines 2-26 and Rev. 1-7 list thenames of thirty-two persons; only three lines are reconstructed. Everyline begins with x (the number) kd(m) cl y ("x jar(s) on (for delivery by)y"). At least eighteen persons (including Hbm) had to deliver 1 jar ofolive oil; 3 persons had to deliver 2 jars; 2 persons had to deliver 3 jars;2 persons had to deliver 4 jars. For the other persons the numbers in thetext are not legible. At the end of the text the total figure is given as Rev.8) tgrm. amn. d bn, Kwy 9) sl; 81mym. Jmn. kbd 10) 11m amn ("8) Totaily10 2oil from bn Kwy 9) on (for delivery by) the people of Slmy in all 10) 68 (jarsof) oil"). Thus we see that the village Slmy had to pay, perhaps annually,a tax of 68 jars ofolive oil. The tax, as in other cases in which taxes weredistributed among the households of the villagers, was not distributedequally. Bn Kwy could be an individual responsible for collecting the tax,similar to the tamkars mentioned in PRU, V, 107 or to the "overseers"responsible for collecting the grain tax.II Heltzer, "Royal Dependents," pp. 40--47; Heltzer, Problems, pp. 42-43...0 PRU, III, 16.269, 18.'" Cf. above, text PRU, y, 107, note No. 76.... Scribal error, tgrm instead of tgmr ("total(ly)").Taxes Paid in CattleApart from the mixed tax paid in silver and cattle there was a tax paidonly in cattle (of, above p. 34). PRU, III, 10.044, mentioned above inconnection with grain and wine taxes, also refers to oxen (GUD-alpu)paid to the royal treasury. This seems to be, as in other cases, an annualpayment. aISu-ra-8u, (.flU), and aIA-ra-ni-ya, together withanother dlu whose name was in the broken part of the tablet, had to deliv-er I ox from 2 villages. aIU-bur-a, alBeru, and four other villages whosenames are completely illegible (lines 14-17) had to deliver one each. Thesame obligation may have been demanded of alRiqdi(?) (line 11). al Be-qa-ni was obliged to deliver 13 oxen. Text PRU, V, 39 (UT, 2039),17 alsomentions Tbq alp, "the village Tbg-(one) ox," in addition to the taxespaid in sheep from the village TlJ (cf. below).PRU, V, 64 (UT, 2064) deserves special attention. This text comesfrom the tablet-baking furnace. It is a letter of a royal official,103 The firstpart, which is badly preserved, consists of greetings. The text goes on torelate that "the king gives pretty horses to cbdyr!J, (16) w. ml[k]. S.8.wmnCmm 17) ytn. lcbdyr!J,), and adds: "And according to the tablets, plough-ing oxen, on your demand from me, the people of Bly have chosen. Theoxen (are) for you and for me" (21) alpm. ftrtm 22) k. rgmt.ly Elym23) alpm. ar8t.lk. w. ly).lO. So we see that the people of Ely, which was anUgaritic village, had to deliver ploughing oxen for the royal estates. How-ever, in this case the king made a concession and handed some of the oxenover to the author of the message contained in PRU, V, 64, perhaps foruse by the latter in his household.PRU, V, 39 (UT, 2039) gives information about the sheep tax. Thetablet has the heading 1) b Tlt ("in (the village) TW').lo6 Then the textlists 2) [I]lmlk; c8r #n 3) Mlkncm c8r. 4) bn. Adty c8r 5) [$]dq8lm !J,m86) Krzn. !J,m8 7) Ubrcym lJ,m8 ("2) [I]lmlk-l0 small cattle 3) Mlkncm-l04) bn Adty-l0 5) [$]dq8lm-5 6) Krzn-5 7) people of Ubrcy-5"). The"3 A partial analysis of the text is found in M. Heltze, VDI, 1966, No.3, pp.201-202 (Russian).10. 'r8-cf. UT, p. 367, No. 379, "to request." On the interpretation "to chose"see,"M. Helsze, A Oharaekin, New Inscriptions from Pirgi in Etruscan and Phoeni-cian, VDI, 1965, No.3, pp. 111-12 (Russian). The term l[1, ("tabIet")-UT, p. 427,No. 1358.10. In disagreement with Oh, Virolleaud (PRU, V, p. 53), who translates "forthree (sheqels of silver)." We know the village Tl1/aISuladu/S.ld/TlJ well; cf, tableNo. "1, 134. This place-name appears in PRU, IV, 17.340, v.7; 17.62; PRU, V, 41(UT. 2041); PRU, VI, 118 (RS. 18.116), 2.44 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 45Taxes Paid in Artifacts,.&& On this text cf. A. F. Rainey, lOS, III, 1973, p. 47; O. KUhne, UF, V, 1973,p.189.Information about taxes paid in utensils is found in the tablet PRU,III, 15.20. According to this source at least 4 dlu (&IAs(?)-pu, &IGul-ba-ta,&IYa-al-du, &IU-bu-zu) had to deliver two bronze vessels each. It is notclear who produced these bronze vessels (TAL. MES. 8iparri).Text PRU, VI, 134 (R8. 19. 19A) records the delivery of lances(senniiM) from various villages of the kingdom to the royal stores. Thetext reads as follows :106&following lines (8-16) list 9 persons whose names are only partly legible.Each was obliged to deliver only one small animal. It is not clear to whichvillage these people belonged. As was pointed out above (p. 43) the villageTbq had to deliver one ox (alp). It seems that the persons namedin thetablet were head of families. A significant feature of this text is its revela-tion of the way in which the tax was divided amount the members of thecommunity. This was not done on the basis of full equality between thefamilies. The text, which mentions only certain villages, probably doesnot list all the families ofthe community. It is possible that some familiesin the community did not have to pay every tax. However, the scarsityof information at the present time prevents us from drawing definitiveconclusions.Only one tablet (CL. 1957.4) records a large number of sheep paid byone single village, 1) 68 UDU. NIN. MA 2) IJli-ya-na mar Ba-ri-ya 3)alIli-iS-tam-i ("1) 68 spring lambs 2) (through) lliyana, son of Bariya3) (from) IliStam'i."). Although the text is very brief, we see that the taxwas delivered through a certain person, perhaps an aklu, "overseer." Asnoted before, this was the case in regard to the grain tax. A particularlyinteresting aspect of the tax is the fact that the village had to pay "springlambs," probably a part of the yearly natural increase of the flocks. The lack of more detailed information prevents us from drawingfurther conclusions.Salirba delivered 15 lances6 lances 1 remainedYakunacamu delivered 15 lances10 lances 1 remained[x lances] 1rema[in]ed (for delivery)[AlJJatu (delivered) z-l-Llanees l[QaJratu [delivered] 35 l[anc]es 1fully![ZaJrinu (delivered) 29 la[nces] 1[x lance]s 1 remained[x lances] 1 remai[ne]d (for deliv-ery)Apeuna 40 lances 1 fully!Samra (delivered) 15 lances 1P08 ] ??? [7) &ISa-lirx-ba 16 sennuM i-biola8) 6 senniiMir-te-lJu5) 81Ya-ku-nacamu 15 sennii i-bi-la6) 10 senniiMir-te-lJaIt is difficult to say how and by whom these arms were produced. Untilnow the only information we have indicates that these were produced byroyal artisans.10BIt is possible that the villagers, or villages as a whole,had to buy the required artifacts from the royal artisans. But is seemsmore likely that the villagers produced the arms themselves and had todeliver themto the royal stores as taxpayments. Inthis framework this ninevillages hadto deliver lances. The number which every village had to delivervaries. Only Qaratu and Ap8una fulfilled the whole obligation. The rest ofthe dlu{qrit remained debtors and were obliged to fulfill the obligation inthe near future. Here again the village is treated as a single unit with noindication of how payment of the tax was distributed among the house-holds or individual families. About 20-40 spears (lances) were demandedfrom each village.'.8 Our reconstruction. In all other cases, unless otherwise specified, reconstruc-tion of the text is by J. Nougayrol., Sam.ra-a, read by J. Nougayrol Uwa-a; Ura is known as a city in Asia Minor.The sign can be read also as and this is preferable.108 It seems that the last broken line gave the total figure of lances ( ?) deliveredand still to be delivered; cf. Rainey and KUhne, "kettles" instead of "lances" sincethe ideogram SEN. MES usually means "kettles," and the translation of J. Nou-gayrol (PRU, VI, 155, No.5) is based on an unpublished text., M. Heltee, Organizatsiya remeslennovo proizvodstva v Ugarite, PS, XIII,1965, p. 47ff. (Hebrew translation, 'rgwn hml'kh b'wgryt in Ml'kh, wnwhg b'wgryt, tAL' (1970) pp. 1-25.)9)&I[QaJ-ra-tu 35 se[nnJiL [i-bi-lapoe10) [sJa-lim18) [11) [&IZaJ-ri-nu 29 s[enniLMJ12) I sennJiL ir-te-lJa17) [x senniL] ir-te-[!JJu13) [&I]Ap-8u-na 40 senniiMsa-[lim]14) [&]ISam-ra-a10715 senniiM15) [x sennii] ir-te-[!JJa16) [&IA-lJJa-tu [x+] 1 senniiMSalima delivered 12 lances8 lances 1 remained (for delivery)Arutu [brought (delivered)] 30lan[ces]5 lances 1 remained (for delivery)3) &ISa-li-ma-a 12 senniiMi-bi-l[a]4) 8 senniiMir-te-lJa2) 5 sennii ir-te-lJa1) [&]IA-ru-tu 30 sen[niiMi-biola]46 Taxes and Duties of the Villages of Ugarit Taxes and Duties of the Villages of Ugarit 47Various Unidentified Taxes and Duties110 Meaning unknown, but apparently not a precious type of timber; cf. AHW,p. 619 and Rainey, IDS, III, p. 46.111 The word cannot be convincingly interpreted. Oh, Virolleaud, PRU, V, p.104, translates it as '.'purple dyers"; O. H. Gordon, UT, p.479, No. 2246, translatesit as "to be zealous," but this is also unacceptable.One form of the labor tax,according to the available information in-volved the distribution to the villages of raw materials, from which cer-tain artifacts were to be produced. These artifacts were to be turned overto the royal treasury, as shown in the text given above. According to textPRU, VI, 113 (R8. 19.26) the villages received raw materials for theproduction of certain wooden objects.ConclusionsThe above discussion has outlined the duties, taxes and other obliga-tions of the villages of Ugarit insofar as these are determinable fromcurrently available sources. The most important conclusions emergingfrom our analyses are: 1) Villages, as collective units, were obligated tomeet all taxes and duties placed upon them by the royal government. Thisdemonstrates the communal character of the Ugaritic village, whichshould thus be considered a rural community. 2) Within the rural com-munity the taxes, labor obligations, and so on, with the possible excep-tion of military conscription, were not necessarity distributed equallyamong all the villagers. The tax burdens may have been distributed onthe basis of the amount of property owned, or on the basis of family size.It seems likely that PRU, V, 75 (UT, 2075), also from the tablet-bakingfurnace, belongs to the group of duty or oorvee texts. The heading 1) aprrpB d 1 y[dyj,m "List of rps(?) which are at ydy(?)."1l8 Lines 2-5 list4 villages; the personal name bn SlJrn follows in line 6. Lines 6-12 list6 names of villages followed by 7 personal names in lines 13-19. Thereverse (line 20) begins again with rpBd. ydy and following 8 village names(lines 21-28) bn lfgby (line 29) is named. The text is concluded by the nameof the village Mrat (line 30). Perhaps at the end of the existence of thekingdom of Ugarit some large families grew into small villages, whichwere designated by the name of the founding family. This developmentcould explain why family names are mixed together with village names inthis text. However, no conclusive evidence is presently available. Otherfragmentary texts which are available mayby be concerned with taxes andduties. However, at the present time no definitive interpretation ispossible.ll4111 The reconstruction of Oh, Virolleaud, PRU, V, p. 104, y[dym(?)] is withoutany real foundation.111 Cf. line 20 of the same text-rpi. d ydy.11& PRU, III, 11.800; 15.183; 15.189; 15.179; PRU, V, 17 (UT, 2017). 1)Mi1jdym, "People of (the village) Mi1jd," followed by eight personal names; 21(UT, 2021) I) [s}p[r} Uiknym. dt. b[d?}, "List of people of (the village) Uikn who[]," at least thirty personal names follow; 22 (UT, 2022); 24 (UT, 2024); 25 (UT,2025); 41 (UT, 2041) village names; 74 (UT, 2074) village names; 77 (UT, 2077)village names; 118 (UT, 2118); 144; 145; 146; 147; 165; U, V,102 (RS. 20.207A);103 (RS. 20.143B); 104 (RS. 20.144); PRU, VI, 94 (RS. 17.431); 96 (RS. 19.91); 97(RS. 19.118); 169 (RS. 18.279), etc.230( 1) tree trunksof maswatu-timberfor (the people) of (the village)Ibnaliya220 (trunks) ofof ma[swjatu-timberllOfor the peo[ple] of (the village)Arutu1) 2 ME 2 ~ M2) ma-ti]s-wja-tu3) a-na a[melejM 8IA-r[ujtu4) 2 ME 3[OJ(?) I ~ M5) ma-sa-wa-tu-[m.ja6) a-na 81 Ib-na-li-gWe see that the people of Arutu and Ibnaliya, each mentioned as a singlebody, received quantities of timber to be used in some type of sort. Itshould be noted that Arutu appears in the text PRU, VI, 134 (R8. 19.19A)among the villages delivering lances 1Thus it is very possible that the textunder discussion is describing the delivery of raw materials not to profes-sionals, i.e. royal dependents, but to villagers. The latter, in this view, hadto produce artifacts from the raw materials and to turn over these arti-facts to the royal treasury as taxes.PRU, V, 78 (UT, 2078), one ofthe tablets from the tablet-baking fur-nace, which was quoted above (p. 23), talks about 1) Risym qnum,"People of (the village) Ris qnum (pl.)."lll It appears that in this quotewe are dealing with a participle of the root *qn', and that the worddesignates a certain action which the people had to perform. The text lists,by their names and the names oftheir fathers, 21 persons who had to per-form this obligation.CHAPTER IIIROYAL GRANTS OF TAX AND IJABOR OBLIGATIONSTO HIGH FUNCTIONARIESWe possess a number of legal texts from Ugarit, written in Akkadian,concerning grants of the obligations of certain villages to certain individ-uals. Full texts and excerpts from these texts follow.1. PRU, III, 16.276.1) is-tu umi an-ni-im 2) INiq-ma-IlAdu mar Am-mi-[is-tam-]ri 3) saralU-ga-ri-it 4) it-ta-din alUlJ,-nap-p[i] 5) a-na IKAR-IlKuSulJ, mar A-na-a[n] u a-na fA_pa_pa_a 7) marat sarriri 8) qa-du eJreti[?]-sa qa-du 9)miksi-sa qa-du 10) si-ir-ki-sa ma-am-ma 11) a-na alUlJ-nap-piki 12) la-ai-ra-gu-um 13) a-na IKAR-IlKuSulJ, u 14) a-na fA_pa_pa_a u 15) a-namariM. fA_pa_pa_a 16) alUlJ,-nap-piki id[-din](?) 17) sa-ni-tam IKAR-IlKuSulJ, 18) za-ki ki-ma IlSamSisi 19) a-na da-ri-it-ti 20) ar-ka-na-suza-k[i] 21) bitumtum IlBacallJ,ursan [fJa-zi] 22) u amelMku-um-[ra-su](?)23) IKAR-IlKuSulJ, 24) la-a u-te-bu-u,"1) From the present day: 2) Niqmaddu, son of Ammi[stam]ru, 3) kingofUgarit 4) gave (the village) UlJ,nappu 5) to Kar-KuSulJ" son of Ana[n]u6) and (to) A papa, 7) daughter of the king, 8) together with the tithe,9) together with its taxes! together 10) with its offerings. Nobody 11) shallhave any claims 12) (concerning) UlJ,nappu. 13) To Kar-KuSulJ, and 14)to Apapa and 15) to the sons of Apapa 16) (the village) UlJ,nappu hega[ve]. 17) Further: Kar-KuSulJ, 18) is pure likeS the Sun, 19) forever.20) For the length (of his life) he is pure." 21) The house (sanctuary) ofBaal of Mount [fJazij 22) and its prie[sts] 1 23) (to) Kar-KuSulJ, 24) mayhave no claims."From this text it is clear that the royal princess, the daughter of theking, and her husband, received the right to demand and collect for them-selves the taxes and labor obligations of the village UlJ,nappu. We maythus assume that this was not a long-term grant. Perhaps it was only validfor the lifetime of the recipients. The text also seems to indicate that1 mikau, of, above, Ch, II, p. 35. Typical formula used in freeing one of various obligations in ~ g o r i t First comes the standard expression of freedom from obligabions forever,followed by the more exact definition that the freedom from obligations is only forthe lifetime of the individual. Mount Sa/on, classical Mons Casius, modern Djebel-el Aqra, cf. W. F. Al-bright, Baal-Zephon, "Festschrift fiir A. Bertholet;" Tiibingen, 1950, p. 4ft".Royal Grants of Tax and Labor Obligations to High Functionaries 49before this gift was made the sanctuary of Baal-Safon. had some specialprivileges in the village of UlJ,nappu.2. PRU, III, 16.269.This text relates that a certain Gabanu killed "Yatarmu, the scribe"(7) Ya-tar-ma ameltupSarrumrum), "for he was an enemy ... of the kinghis lord" (7) i-nu-ma na-kir ... 8) it-ti sarri beli-su). The text continuesto relate that Gabanu "gives (the village) Be-qa-vIha to the king accord-ing to the law" (9) ... i-na-din 10) alBe-qa-llI8tara-na sarri 11) as-sumdni-su-ma). It seems that Yatarmu formerly possessed this village, or itsobligations and taxes. The text continues: "11) ... his lord 12) gave as agift 13) to Gabbanu and his sons (it)." (11) ... beli-su 12) na-din ni-id-nu-uS 13) a-na IGab-ba-na a-na mariM-su). It is very probably that the text isreferring to the same village Beqa-Lstar, After that the tablet mentionswhich taxes and obligations Gabbanu is no longer obligated to pay to theking. Although the text is broken we can read: 18) "[his grain, oi]l (and)beer 19) his [oxen] (and) sheep." The rest ofthe text is broken. It may bethat these taxes also came from Beqa-Lstar, but because of the break inthe tablet this is not definitively clear.3. PRU, III,16.244.1) is-tuI zumi an-ni-i-im 2) IN[iq-m]e-pa mar Niq-rna-IlAddu 3) sarU-ga-ri-it 4) it-ta-si kasapM ameIMsar-ra-ku-ti 5) it kasap ameIMzi-in-lJa na-Ie6) it kasap ameIMti-pa_li na-se 7) it ma-Ia-ra sa alBeri 8) it it-ta-din-su 9)a-na IEn-ta-sa-li 10) amelSakini alBeri 11) a-na umeM zbalati gamriltiM12) IEn-ta-sa-li 13) ma-am-ma la-a i-la-qi-su 14) is-tu qa-ti-su."1) From this day 2) Ni[qm]epa, son of Niqmaddu, 3) king ofUgarit,4) withdrew the silver ofthe offerers 5) and the silver of the ...6 people, 6)and the silver of the ... peoples 7) and the tithe of (the village) Beru 8)and gave it 9) to EntaSalu, 10) the sakinu7of Btr 11) for the lifetime12) of EntaSalu. 13) Nobody shall take (it away) 14) from his hands."This text clearly relates that only the taxes and other payments, notthe village itself, was handed over to a certain high official4. PRU, III, 15.114.1) [i]8-tu umimi[annim] 2) IA-mis-tam-ru mar Niq-me-p[a] 3) saraIU-ga-ri-i[t] 4) it-ta-si eqlatMITa-ri-[] 5) it eqlatMKu-lJi-ia-na ali 6) itaIAt-ka-sak-na U it-t[a-din-su] 7) a-na Tak-lJ,u-li-na amelsakin7 ekallim Meaning unclear. J. Nougayrol, PRU, III, P- 93, "portes d'ordures," i.e. acertain fine for scolding?!; CAD, v. 16, P: 20, l'inlJ,u, "excrement." J. Nougayrol, PRU, III, p. 93, "contraventions," "deliquencies( ?)."7 MASKIM. On the reading of this ideogramm in the Akkadian texts fromUgarit, cf. table No.1, note No. 46. The sakinu of the village was certainly therepresentative of the royal authorities; E. Lipinski, UF, V, 1973, pp. 106-97.50 Royal Grants of Tax and Labor Obligations to High Functionaries Royal Grants of Tax and Labor Obligations to High Functionaries 518) it -Tak-lJ,u-li-nu 9) &ISa-ak-na 10) i-na kaspiM-su i-na eriM-su11) i-na gab-bi mim-mi-su 12) u sarru u-za-ki 13) &ISa-a[k]-na i-na pU-ki14) alpuM-s[u-nu im]er-;jM-su-nu 15) ameluM[-su-nu] 16) i-na s[i-ip-ri]sarrir 117) [ ... la(?) il-l [a-leu, (The rest of the tablet is broken.)"1 [F]rom [this] day 2) Ammistamru, son of Niqmep[a], 3) king ofUgari[t] 4) withdrew the fields of Ta.ri[x] 5) and the fields of KulJ,ianaof the village (town 1) 6) and (the village) Atka-Sakna and ga[ve it] 7) toTaklJ,ulinu, the siikinu (vizier) of the palace. 8) And TaklJulinu 9) shallreconstruct (the village) Sakna 10) for his silver and copper 11) (and) onhis (own) full expense. 12) And the king freed 13) (the village) Sakna fromthe obligation. 14) Its oxe[n], [its don]keys 15) [its] people 16) to theroyal w[ork] 17) r... must not] go."Here we see that the king handed over a complete village to a high official-TaklJ,ulinu-who was the majordomo (siikin ekallim).8 TaklJ,ulinu hadto rebuild the village at his own expense. The village was freed from taxesand duties to the king. These were handed over to Taklj/ulinu, at least fora certain period.5. PRU, III, 15.147.This text consists of some royal gifts given by the king Ammistamru II.We read there:VO 5') ... a-nu-um-ma 6') &IWa-na-a-lum res qa-du [eqli?-su] 7') it&ISa-pi-U qa-du e[qli(?)-su(?)J 8') it-ta-din-su-nu sarru 9') a-na IA-mu-ta-ru-na 10') ua-na mdreM-su a-di da-[ri-ti] 11') uIA-mu-ta-ru-nu 12') 13') uu-se-si-ib-su-nu 14') amelu ma-am-ma-an 15') la-ai-la-aq-qi-su-n 16') is-tu qd-ti IA-mu-ta-ru-ra 17') u is-tu qlUi mareM-sua-di da-ri-[ti]"5') ... So 6') (the village) Wanalum-the-High 7') and the low togetherwith [its] fi[elds] 8') the king (Ammistamru II) gave 9') to Amutarunu10') and his sons forev[er]. 11') And Amutarunu 12') shall rebuild them13') and populate them. 14') Nobody 15') shall take them 16') fromAmutarunu 17') and his sons foreve[r]."The purpose of the grant is to repopulate and to rebuild a villagedevastated by war, disease, etc. It seems that Amutarunu received inreturn the right to collect all taxes and duties for himself. The text thusdeals with the recreation of a village. But the principle on which thecommunity was established is not specifically mentioned.6. PRU, III, 16.153.1) i[s-t]u l1mim 1an-ni-i-im 2) IA[m-mi-]is-ta-a[m]-r[u rna]r Niq-me-pa3) sar &[lJU-ga-r[i-i]t 4) &IE[XX]is qa-duc 5) ga-ab-bi m[i]im-mi sum-si-sa Cf. 8kn. bt, mlk-PRU, II, 7 (UT, 1007), 5-6; cf. also M. Helteer, Royal Ad-6) id-din a-na 7) mdr 8) a-na da-ri-is 9) a-namareMmdreM-su 10) seM-susikarM-su 11) sa ma-'a-sa-ri-sa 12) it immeriituM ;ma-aq-qa-dsi 13) a-na 14) kaeap sa-ra-ku-ti 15) it kasap 16)a-na I "1) F[ro]m this day 2) A[mmi]sta[m]r[u, so]n of Niqmepa, 3) king ofUgar[i]t 4) gave (the village) E[xx]-is 5) together with all that it 6) has,to 7) son of 8) forever 9) (and) to his sons (and) grand-sons. 10) Its grain (and) its beer 11) of the bithe," 12) and the sheep:pasturing (tax)l 13) to (he gave). 14) The silver of the offerings(or offerers),ll 15) and the silver ofthe bestmen-s 16) (he gave) to ranu."Once again we have a more or less complete description of the taxes andduties handed over by the king to Y possibly for his merits orservices. But this text declares clearly that Y received the right tocollect the tithe and pasture-tax as well as two taxes (silver of theofferings (or offerers) and silver of the bestmen) which seemed to beirregular and occassional.7. PRU, III, 16.202.This tablet relates only that king Ammistamru II delivered the villageKumba (&IKu-um-ba) to a certain Tulaya and his sons. No other detailsare given.The documents presented above show us that: a) the village wastreated as a single unit-a community; b) the recipient of the village didnot receive any right ofownership over the lands and people of the village.He received only the right to collect for himself the regular and irregulartaxes and duties. It also seems likely that despite the fact that some textsstated that the granting of a village applied to the children and grand-children of the favoured individual, the endowment was really for ashorter period, possibly the lifetime of the recipient. None ofthe availabletexts mention military conscription and it may be assumed that this rightremained in the hands of the king, All in all there is not enough availableinformation to make any comparison with the European feudalism of themiddle ages as has been proposed by some aeholars.Pministration and Palace Personnel in Ugarit (Russian), LAMMD, X, 1969, pp.227-28; M. Dietrich, O. Loretz, J. Sanmartin, UF, VI, 1974, pp. 41-42, No. 15.o Cf. above, Ch.II, p. 35-40. 10 or, above, Ch. II, p. 34.11 Cf. above, p. 31; PRU, III, 16.244.11 Nougayrol, PRU, III, p. 147, "garcons d'honneur"; cf. AHW, p. 1063, "Braut-fiihrer"-"bestman," "bridgeroom's supporter."13 Rainey, Social Structure, pp. 31-36 (including the previous bibliography);A. F. Rainey, The Kingdom ofUgarit, BA, XXVIII, 1965, No.4, pp. 102-25. For the term cf. above, pp. 50-51. cr. M. Helteer, Some Questions of the Agrarian Relations in Ugarit, VDI, 1960,No.2, p. 89 (Russian).8) it i-din-su a-na INu-ri-ya-na 9) U. btt-.fueqilM-.fu 10) sa I Bin-Bu-uk-ru-na11) i-na aIMa-ra-pa 12) is-si-su sarru it id-din-su 13) a-na INu-ri-ya-naa-na mdreM-su 14) a-na da-ri du-ri 15) u-ra-am se-ra-am ma-am-ma-an16) la i-le-qi is-tu qatiM17) Nu-ri-ya-na (it) is-tu qatiM[mdreM]-su"1) From the present day: 2) Niqmaddu, son of Ammistamru, 3) with-drews the house, the fields, 4) (and) all that (as) Igmaraddu 5) the nayyiiluin (the village) Ari, 6) and the house and field 7) of Igmaraddu in (thevillage) 8) And he gave it to Nuriyanu. 9) And the house (and)field 10) of IBin-Bukruna 11) in (the village) Marapa 12) the king with-drew and gave it 13) to Nuriyanu and his sons 14) forever. 15) In thefuture nobody 16) (shall) take (away) from the hand 17) (of) Nuriyanu(and) from the hands of his [sons]."At least one of the persons from whom the land was confiscated was anayyalu. The profession of the persons who were deprived of land is notmentioned, but we know what villages their possessions were located in.We oan thus assume that they could have been members of the ruralcommunity. It must be noted that Nuriyanu was a member of the royalfamily-the king's brother.s2. PRU, III, 15.89.The tablet begins with the standard formula and relates that kingNiqmaddu (II), son of Ammistamru: 4) it-ta-si btt-su eqil-su 5) gab-ba mi-im-mi-su 6) sa IIli-sa-li-ma alJi IDa-li-li 7) ame1na-ya-li 'II, id-din-su 8) a-nafA-lJa-ti-milku 9) mdrat IDalili 10) u-ra-am se-ra-am 11) lJa-aa-lJa-at IA-lJa-tum-milku 12) it a-na INu-ri-is-ti 13) ta-na-din-su lJa-aa-lJa-at-ma 14)it a-na IYa-ri-milku 15) ta-na-din-h a-na sa-ak-nim bi-it-sa 16) ta-na-din-.fu u-ra-am se-ra-am 17) ma-am-ma-an la i-le-qi 18) is-tu qa,titlfA-lJa-ti-milku 19) a-na da-ri du-ri 20) it u-nu-u8-8a biti 21) up-pa-lu."4) withdrew the house (and) field 5) together with all (property) 6) ofIlisalima, the brother of Dalilu, 7) the nayyiilu, and gave it to the (woman)AlJatmilku, 9) daughter of Dalilu. 10) (If) in the future 11) AlJatmilkushall desire, 12) so she gives it to 13) Nuristu, and if she desires, 14) soshe gives it 15) to the sons of 16) Yarimilku (and if she desires) she givesit to the sakinu of 17) her household. In future 18) nobody shall take(away) from the hands of AlJatmilku 19) forever. 20) And the unu88u-service of her household 21) they have to perform."This text relates that llisalimu was the nayyiilu. It seems that hisbrother DaWu was no longer living. The land was not taken away fromCHAPTER IV.'\.\' \NONPERFORMANCE OF OBLIGATIONS BY THE VILLAGERSAND THEIR DEFECTION FROM UGARITThe nayyiiluEven though the whole community bore collective responsibility forfulfillment of tax "and other obligations, all taxes and duties were dis-tributed among the individual families inside the community. The sourcespresent us with an opportunity to learn the reaction of individuals whocould not fulfill their obligations as well as the treatment of these individ-uals by the authorities.The nayyiilu. Tbis term is known not only from Ugarit, but only intexts from Ugarit (and some rare Middle Assyrian legal texts) is it usedto mean "the man who did not perform his obligations."! The term itselfseems to be a derivate from the word niiilu (ni'lu)-nayyiilu-verbaladjective, nomen actionis from the D-stem of nil'll" meaning "idler,""lazy."There are instances in the sources of royal servicemen being mentionedamong the nayyalu. These individuals were deprived of their landhold-ings. The texts also deal with members of the rural communities whodefaulted on their obligations and had their land taken by the authorities.The confiscated land was handed over to other persons. The texts whichcan be interpreted as concerning the members of the rural communitiesare given below.1. PRU, III, 16.248.1) is-tu .umi an-ni-im 2) INiq-ma-IiAddumdr Am-m[i-is-tam-ri] 3) it-ta-si btt-sueqilM-su 4) gab-M mi-im-mi-su sa IIg-ma-ra-IiAddu 5) ame1na_ya-li i-na alA-ri 6) it btt-su eqilM-su 7) sa I Ig-mar-llAddu i-na 1 For a special investigation of the term in Ugarit, with references to the earlierliterature, cf. M. Heltzer, Penalties for Non-Performance of Obligations (the termnayyalu in Ugarit), VDI, 1971, No.2, pp. 78-84 (Russian with English Summary);cf. also J. N. P08tgare, Land Tenure in the Middle Assyrian Period; A reconstruction,BSOAS, 34, 1971, pp. 496-520, eep. pp. 508-12. Only three texts (KAU 160, 162,KAV 212) are known in which the term nayyalu appears. Although J. N. P08tgateinterprets this term as "a man with no living father and no male heirs," it is clearfrom the content of the texts that the nayyalu in Middle Assyria was, similar to thenayyalu found in the Uga.ritic texts, a man deprived of his Iandholdings.Non-performanoe of Obligations by the Villagers 5354 Non-performance of Obligations by the Villagers Non-performance of Obligations by the Villagers 55the family since the king handed it over to the niece of Ilisalimu, thedaughter of his brother. She had the land in her possession, but could notfreely dispose of it. There were only three persons to whom she could handover the land: a certain NuriStu; the sons of Yarimilku; or the siikinu(skn) of her household (majordomo). The mention of a majordomo indi-cates that the household under consideration was a large and wealthy one.It is possible that Nuristu and Yarimilku also had a close relationship tothe same family. It is very important to note that the unu8su-corvee orservice of the house had to be performed. This indicates that the land wasnot royal property, bound with some service, but that the lands had theirobligations inside of the eommunity.s3. PRU, III, 16.174.According to this text the same king, Niqmaddu II, withdrew thefields of 5) ... ITa-ki-ya-na mdr 6) ame1na-ya-li 7) U id-din-su 8) a-na ITup-pf,-ya-na ame1satammi 9) istenen_suITup-pl-ya-nu 10)i-na 1 me-at 35 kaspi 11) il-te-qi-su 12) i-na simti qamirti: 13) usa-na-am it-ta-si-su 14) sarru u id-din..su 15) a-na ITup-pf,-ya-na16) u-ra-am se-ra-am 17) ma-am-ma-[a]n u-ul i-laq-qi-su 18) is-t[u qdtiITup-pl-ya-na] (the rest is broken)."5) Takiyanu, son of Kamalibadu, 6) a nayyiilu, 7) and gave it 8) toTuppiyanu, the satammu.69) First: Tuppiyanu 10) bought it ll) for 135(sheqels) of silver 12) for the full price (it is granted). 13) And then theking 14) withdrew it and gave it 15) to Tuppiyanu. 16) In future 17)nobody shall not take it 18) fro[m the hands of Tuppiyanu] ..."The satammu-official did not receive the land from the king as a gift forhis service. Rather; he purchased it "for the full price." Thus, we see thatthe land confiscated from the nayyiilu was not royal land but privateproperty inside a certain unnamed village.4. PRU, III, 16.262.This text relates that King Niqmaddu II "withdrew the house, thefields, and all that he had from YaBlimanu, son of 7) ame1na-ya-li8) uit-ta-din-su 9) a-na IA-da-nu-um-mi 10) uIA-da-nu-um-mu 11) pi-il-kacsa bUi u-bal (Lines 12-15 contain the prohibition to deprive him and hischildren of the land). On the sakinuof the household, cf. Ch. III, p. 50, note No.8. On unu8su (Ug.unt), ef, with Akk. ilkulpilku from Ugarit; M. Liverani, Storia, pp. 140, 148-98; Dietrich, O. Lorete, Die soziale Struktur von Alalab und Ugarit, I, Die Berufs-bezeichnungen mit der hurritischen Endung -b-uli, WO, III, 1966, No.3, pp. 194-97.& On the functions and social position of the royal functionary satammu in Uga-rit, cf. M. Heltzer, Povinnostnoye Zemlevladeniye, pp. 191-92, esp. note No. 70;Rainey, Social Structure, pp. 34-35."7) the nayyiilu 8) and gave it 9) to Adanummu. 10) And Adanummull) has to perform the pilku-service ofhis housethold)."Adanummu received the lands and immovables confiscated fromYaalimanu, the nayyiilu. But Adanummu had to perform the service ofthe house(hold). The difference between this text and PRU, III, 15.89(cf. above) lies only in the designation of the service as pilku, whereas inPRU, III, 15.89 we have the term unu8su. But the fact that the servicehad to be performed for the household shows, that the nayyiilu, as wellas the recipient, were villagers, members of the rural oommunity.s5. PRU, III, 15.168.This text relates that king Ammistamru II 4) it-ta-si bua sa IQa-tu-na5) [ame]lna-ya-li sa i-na alRMi 6) u it-ta-di-in-su 7) a-na fQi-ri-bi-li 8) iti-na-an-na fQi-ri-bi-lu 9) ti-ir-ta-si-ip 10) btta an-na]-a] (Lines 11-17,standard formula of ownership; 18-21, the seal of the king and name ofthe scribe)."4) withdrew the house of Qatuna 5) the nayyiilu in (the village) RMu6) and gave it 7) to (the woman) Qiribilu. 8) And therefore Qiribilu shall9) rebuild 10) this house ..."7It is very interesting that the nayyiilu who was a villager from RMucould neither perform his obligations nor keep his house in order. Thewoman Qiribilu was obligated to rebuild the house. No mention of specialobligations appears in the text, hut it seem that Qiribilu had the economicmeans to rebuild the house and to perform her obligations in the com-munity.6. PRU, III, 15.141.This tablet declares that Ammistamru II withdrew the fields of Kurbanu"5) son of Niltanu, the nayyiilu, 6) which lay among the fields of (thevillage) $au 7) together with its dimtu (buildings), 8) with its olive trees,9) with its vineyards, 10) with all that he has." (The text goes on to decscribe additional land confiscations (lines 11-12), but the end of thetablet is broken.) It is clear from this text that a villager was deprived ofhis land.7. U, V, 9 (RS. 17.61).This tablet differs to a great extent from the texts given above andit aids in obtaining important additional data about the nayyiilu-formermembers of the village-community in the kingdom of Ugarit. Texts about withdrawal of lands from nayyalu, but it is unclear whether theseare villagers or royal servicemen. Cf. also PRU, III, 15.145, 15.122; and the frag-mentary text, PRU, III, 16.86 ... 7' {Jqa-niame1na-ya-li i-naalBiri. Cf. PRU, VI, 28 (RS. 17.39), where, in the badly damaged part of the text,4) [ .. ]s[a] i-naalReBi 5) [ i]a-na(?) ame1na_ya_lu, appears.56 Non-perfonnanoe of Obligations by the Villagers Non-performance of Obligations by the Villagers 571) is-tu.dmi ml an-ni-im 2) a-na pa-ni amelstbdtete 3) if-ri-bi-ilu amel8iikin(MASXIM) alRiq-di 4) it-ta-si btta eqlaMgab-M mi-i[m-m]i-si-na 5) samdrat Ya-ak-ni it sa mdra[t X]-ab-i 6) ame1na-ya-lu-ti 7) it it-ta-din-s[u]a-n[a] IAbdi-IlYara!J, mdr Xu-um-dU 8) i-na 3 me-at ka8[pi] 9) eqluM 10) ur-ra se-ra-am 11) ma-an-nu-um-ma 12) u-ul i-leq[-qi-s]u13) is-tu qdti IAbdi-uYara!J, 14) it qdti mdreM-su 15) stbu ITup-pi-ya-numdr Ar-8u-wa-na 16) stbu mdr Ku-za-na 17) stbu IAbdu mdrAbdi- lIRaSap 18) stbu ifli-IlRaSap mdr Tu-ba-na 19) stbu IAbdi-lIRaSapmdr Tub-bi-te-na 20) stbu mdr Ya-an-!J,a-am-mi 21) abankunuTeif-ri-bi-iii 22) Illu-milTcu ameltup.arru"1) From the present day, 2) before wit-nesses, 3) lribilu, the 8akinu of(the village) Riqdu, 4) withdrew the house (and) the fields (and) whatthey (women) possess, 5) of the daughter of YaTcnu and the daught[erof x]abi, 6) the nayyiilu (women) 7) and he gave i[t t]o Abdiyara&-, son ofX um-Us 8) for 300 (sheqelslof sil[ver]. 9) The fields are bound. 10) In thefuture 11) nobody 12) shaIIta[ke] them away 13) from the hands ofAbdiyara!J, 14) and from his sons. 15) Witness: Tuppiyanu, son of Arsu-wanu. 16) Witness: Imidanu, son of Kuzanu. 17) Witness: Abdu, son ofAbdiraSap. 18) Witness: lliraSap, son of Tubanu. 19) Witness: AbdiraSap,son of Tubbitenu. 20) Witness: AbdiaSarti, son of Yan!J,ammu. 21) Seal ofIribilu. 22) Ilumilku, the soribe."Contrary to the text oomposed in the' name of the king, this text iswritten in the presenoe of witnesses and in the name of 1ribilu, the 8iiT.:inuof the village Riqdi,10who was the representative of the royal administra-tion. The land was taken away from two women. Perhaps they werewidows and had no manpower in their households for performing. theregular obligations connected with their lands. (Of. note No.1, p. 52.)It is clear that the representative of the local royal authorities had theright to deprive the nayyiilu of their lands. The new landowner, Abdiyara&-,had to pay 300 sheqels of silver and, as in former cases, .the recipient paidthe full price of the land. Finally,this text shows clearly that the nayyiilu Theophorio name, but it is unclear which deity appears under the ideogrammso..' Cf. also, the fragmentary part of PRU, VI, 55 (RS. 18.22), 5') u eqlatuMsaffJa.me.en.na-ya- 6') ame1na-yali sa ina eqlatM II.Utar. ("5') and the field of (thewoman) fJamenaya, 6') the nayyalu, which is among the fields of (the goddess)Istar.")' Although this is not entirely clear, we see that among the nayyalu thereappears again a woman. .. . .10 About thesakinu of a village, cf. M. Heltzer, Carskaya administraciya 1dvorcovy personal v Ugarite, LAMMD, X, 1969, (Russian), p. 228; of. below, p.82.in various villages were members of the rural community. The royalauthorities, after oonfisoating the lands of the nayyiilu in the villages,1) delivered them, for a certain price, to people who had to take onthemselves the obligations of the disowned member of the rural com-munity, or b) handed the land over to royal servioemen as a holding fortheir service. But we must keep in mind that royal servioemen who didnot perform their obligations could also beoome nayyiilu. The textsdealing with royal servioemen nayyiilu are not given here.It is obvious that land confiscation from the nayyiilu who were mem-bers of the rural community was one ofthesouroes of enriching the crownand the treasury. The only way for a nayyoJu to survive, once deprived ofland, was to enter into royal service and to become a "royal dependent"(bnS mlk},The Enslavement of Rural Debtors by Foreign TamkarsSometimes, as we have seen above, the villagers lost their land fornon-performanoe of their obligations; But this was not the only means ofdealing with debtors. We have the following declaration of the Hittiteking Hattusilis III, oonoerning the aotivities of the city of Ura in AsiaMinor in Ugarit. (PRU, IV, 17.130.)25) it sum-ma kaepu sa mdreMalU-ra 26) it-ti mdre aIO-ga-ri-it 27) ita-na su-lu-mi-su la-a i-le-u 28) it sar matO-ga-ri-it ameluUmsa-a-su 29) qa-duaSsati-su qa.-du mdreM-su 30) i-na qdlitlmdre alU-ra 31) amelM tamkiirii-na-an-di-in..su-nu-ti."25) And if silver of the sons of Ura 26) is with the sons of Ugarit,27) and they are not able to repay it, 28) so the king of Ugarit thesepeople 29) together with his Wife, together with his sons, 30) into thehands of 31) the merchant shall deliver."It is clear from this text that, at least in some cases, the foreign tamkarshad the right to enslave the "sons ofUgarit," i. e. people of various villagesof this oountry. It is noteworthy that the foreigners had no right toaoquire the lands of these people, which remained in the hands of theking of Ugarit.l111 Liverani, Storia, pp. 80-86; M. Heltzer, Slaves, Slave-owning, and the Role ofSlavery in Ugarit, VDI, 1968, No.3, 12.91 (Russian with English summary);M. Heltzer, The tamkar and his role in Western Asia in the XIV-XIII centuries,B.C., VDI, 1964, No.2, pp. 7-8 (Russian); R. Yaron, Foreign Merchants in Ugarit,ILR, IV, 1969, pp, 71-74.58 Non-performance of Obligations by the Villagers Non-performance of Obligations by the Villagers 59"1) Sam[a]nu whom you search for2) (is in the) village Magdala,3) Suanuanu and [!!]ebatAapas,7) INa-zi-ya-a-nu 8ISa-am-ra-aKIMIN8) naplJar 6 9) la-li-ku sa il-ki5) IAs-ta-bi-sarru &I!!ar-ga-na-au-sab6) Ilbrirl-za-zu &1Bi-ta-lJ,u-li u-sab4) who are said (to be in the) vil-lage Apsuna (and) did not per-form their corvee.815) Astabisarru is in the village!!arganu.6) lbrizazu issS in the villageBitalJ,uli.7) Naziyanu (the same) in the vil-lage Samra8) Together 6 warriors (soldiers)S39) who went not to their (con-scription) duty,10) &'Ap-su-ni-ya-ma 10) Apsunites."This text lists six villagers of Apsuna, a well-known Ugaritic village,who did not perform their conscription duty.24 The author of the textII The scribal omission is reconstructed by J. Nougayrol.II iqabu--pluraI. la-lak from lit il-lak, cf. U, V, 96 (RS. 20.12) lii Ila-li-ma ("did not pay," "didnot perform (the duty)").11 Or "duty."II The verb waJtibu can be interpreted as being in a certain place at the moment,also a permanent dwelling. J. Nougayrol, PRU, VI, p. 75, translates, "travailleurs (ou: soldats)" but bycomparison with text PRU, VI, 95 (RS. 19.74), where the term ,dbU appears frag-mented, and which relates details about conscription-duty from the villages ofUgarit, we prefer "warriors," or "soldiers," cf. Ch, II, pp. 19-21; cf. Rainey, lOS, III,1973, pp. 40-41, where the author gives a slightly different interpretation of thetext, supposing that the six villagers tried to escape from their feudal services. About the conscription of villagers of Ugarit, cf. M. Heltzer, Soziale Aspektedes Heerwesens in Ugarit, BSSAV, Berlin, 1971, p. 130; of, also, Ch.II,pp. 19-22.Let us consider the more detailed texts from PRU, VI which deal withparticular cases. (The defection of representatives of the upper classesfor political reasons are not under consideration here.)A small tablet, PRU, VI, 76 (RS.17.361), relates: 1) [up-pu an-nu-usa 2) mu-un-na(-ab)-[u-ti.18"1) This tablet (concerns) the persons,2) who are defectors." The scribe evidently did not intend to give a listof the defectors since the tablet has no room for one. In contrast, PRU,VI, 77 (RS. 19.32) contains a letter concerning refugees, sent by oneroyal official to another.1) ISa-m[a]-nu sa ta-ba-'a2) [&]'Ma-ag-da-la3) ISu-a-nu-a-nu it [I!!]e-bat-llSapaa4) sa i[q]a-bu19&'Ap-su-na il-kala-laksoDefection of the Peasants of UgaritIt is natural that developments such as those described above createdtendencies to leave home and seek refuge in neighbouring countries orkingdoms, as well as in other places of the same country. The tendency todefection at this time were brilliantly clarified in a recent study by M.LiveranL18 The main bulk of M. Liverani's study is devoted to clarifyingthe social character of the lJapiru (SA.GAZ) people and investigating thetendency toward nomadisation. Our data from Ugarit, and especiallyfrom PRU, VI, shed light on this tendency inside Ugarit. There are eveninstances where the documents available deal with concret situations andindividuals.Text PRU, IV, 17.23814deals with the "sons ofUgarit" (line 4), amongother social categories of the people of Ugarit. The text relates that:"sons of Ugarit, (who) are delivered for their silver (debts) to anothercountry, and from (the land) of Ugarit they are fleeing ... and enteringthe (territory of the) lJapiru ..." Such defection could occur for politicalreasons, or, as we have seen above, for material reasons. We possess acertain number of texts in which the guarantors of certain persons areinstructed to pay large sums to the king in case the persons who receivedthe guaranty flees to another country.li We know from the same texts,that some of the refugees were seized and returned to their country oforigin.Even more interesting is the second part of the text, which confirmsthat sometimes citizens of Ugarit-people of the villages of Ugarit-weredelivered to their creditors from abroad as slaves.18It may be that suchpeople were the nayyalu, people who did not, or could not perform alltheir obligations,17II Cf. PRU, IV, 17.238, the text translation, cf. Ch. I pp. 4-5.II Liverani, II fuoroscitismo in Siria nella tardo eta del Bronzo, RSI, LXXVII,1965, No.2, pp. 315-36.U Chapter I, pp. 4-5.II Cf. PRU, III, 15.81, p. 37; 16.287, p. 37; PRU, IV, 17.315, p. 111; 17.341,p. 161; 18.04, p. 241; 17.369A, p. 51; PRU, VI, 68 (RS. 17.84), p. 63; 69 (RS. 17.329), p. 64.II Cf. PRU, IV, 17.130; ef, above, p. 57.17 Helezer, Penalties; cf. also, part 1 of this chapter.We know also, that "the sons ofUgarit were delivered to other countriesfor their silver,"12 and can assume that these rural citizens were debtorsunable to repay their debts.60 Non-performance of Obligationsby the Villagers Non.performance of Obligations by the Villagers 61instructs another official where to search for hiding men. Magdala (Ug.Mgdly),I' Bitay,uli,le Samra (Ug, ,!:mr(y),17 are well known villages ofthe kingdom of Ugarit. We also know that Magdala and BitalJuli wereborder-villages of the kingdom. Qargana occurs here for the first time inthe published documents. Concerning two individuals (lines 3-4), weknow only that they did not perform their duty; it was not known wherethey were hiding. We can assume from the text that the people, whowanted to escape conscription, successfully disappeared. The other per-sons mentioned in the text were located in villages of the kingdom ofUgarit, but these villages were near to the border of the kingdom andtheir intention may have been to defect abroad.A text similar to that given above is PRU, VI, 78 (RS. 19.41). The lastlines of this text (25-26) show that it is dealing with 25) ameluMBlQa-ra-ti-ya-ma i[-na ga]b-bu 26) dliiniD.D.M.. mBISi-e-a-ni. "25) People of thevillage Qaratu (who are) in 26) the villages of the land of Siannu."17BSiannu was a country bordering on Ugarit, and subservient to it untilthe time of the Hittite king, Mursili II. Mursili II freed Siannu fromsubservience to Ugarit. Thereafter, Siannu paid annual tribute to theking of Karkhemis, where princes of the Hittite royal dynasty ruled.IeThe text mentions by name twenty-three persons from the well-knownUgaritic village Qaratu. They dwelled (u-sab) in the villages of: 1) BlGi-ma-ni, 2) BlLa-s[a]-be, 3) BlSi-il-la-[x], 4) BIDu-ma-te-qi, (Du-ma-teK.I) 5)BlMu-ur-sa-a, 6) 7) BlSam-ra-a,18 8) 9)BlSa-ba-a-ili, 10) Bl$a-'u, 11) BlMar-du-se, 12) BlAm-me-sa-be, 13) BlAr-me-lu(seven persons), 14) BlMa-ra-ilu.Listed here are fourteen villages to which men of Qaratu defected. Butthe text raises a problem. Six villages, BlDu-ma-te-qi,80 BlGa-li-la-tu-ki-ya.. Cf. PRU, II, 81 (UT. 1081), 10; PRU, IV, 17.62, 6; 17.366, 16; PRU, V, 44(UT, 2044), II; 145(UT, 2145); U,V, 102(RS. 20.207A), 10... Var, Bi-ta-lyu-li-un; PRU, IV, 17.62, 1; 17.366,12.S7 CTC, 69, 4 (UT. Ill); 71, 20 (UT, Il3); PRU, II, 81 (UT,1081),4; 181 (UT,1971),13; PRU, V, 44(UT, 2044),8; 58, II (UT,2058), 37; PRU, VI, 105(RS. 19.117),8; 111 (RS. 19.129), 6.I7B Rainey, lOS, III, 1973, pp. 41-42 gives a similar explanation of these lineswithout entering into the meaning of the text in general... Liv61'ani, Storia, pp. 72-73, with referencesto the sources.II Nougayrol, PRU, VI, p. 75, gives the reading U-ra.a, but the town Ura was,as weknow, located in AsiaMinorand not in the vicinity of Ugarit. Inside the king.domof Ugarit we knowof BlSamra (Tmry). The usignalsohas the readinglam. SoSamra is preferable..0 PRU, VI, 138(RS. 19.46), 16; ef, also, table No.1.(Ug. Glltky),81 BlSam-ra-a(Ug. '!'..mry),81 (Ug; BI$a-'u(Ug. $0)," and BlMa-ra-ilu (Ug. Mril),81 are well-known as villages ofthe kingdom of Ugarit. (The other place-names could really be villagesof the kingdom of Siannu.) At the same time, we have no reason to doubtthat if the document designates these alu as villages of the kingdom ofSiannu, it is not really so. In connection with this problem arises anotherproblem, that of the datationof the text PRU, VI, 78. Knowing thatSiannu was freed from the sovereignteyof Ugarit in the last years ofMursili II, the first years of Niqmepa, King ofUgarit, we can assume thatthis tablet dates from no later than 1315 B.C.E.8eOn the other hand, the texts PRU, V, 74, 77, and 90, which mention $0 and Mril, came from the tablet-baking furnace and. thereforebelong to the very last years of the existence of Ugarit. During thisperiod these dlu/qrit belonged to the kingdom of Ugarit. The text PRU,III, 15.155, concerning $a-'u is dated by the reign of Ammistamru II, asare PRU, III, 15.140, 15.141, and 16.131. We see that $a'u, at least, waswithin the confines of the kingdom of Ugarit during the reign of Am-mi8tamruII. We must therefore assume that the six dlu mentioned in thetext as belonging to Siannu were subdued by Ugarit only during theperiod following the reign ofMursili II (died ca. 1315 b.o.), during thereign of Niqmeqa of Ugarit (reigned until ca. 1265 b.c.), and until thebeginning of the reign of AmmiBtamru II (reigned until ca. 1230 b.c.),son of Niqmepa. At least at the time of Ammisiamru. II, the kingdom ofSiannu did not cease to exist. But Ugarit probably enlarged its owndomains at the expense of Siannu. Thus, the text concerning refugeesfrom Ugarit gives us very important chronological evidence.t"The principal difference between the texts PRU, VI, 77 and 78 lies inthe fact that PRU, VI, 77 concerns people who defected from their ownvillage to other villages in the same country, while PRU, VI, 78 deals11 PRU, V, 42. Tr. 2 (UT, 2041); 118,8-9 (UT, 2Il8)... Cf. Note No. 29... PRU, V, 74,14 (UT, 2074) . 8 CTC, 67, 5 (UT, 116);71,4 (UT, 113); PRU, III, 15.141, 12; 15.182, 5; 16.150,11; 16.277,6; 15.155,5; 15.140,5; 15.142,6; 16.131,6; PRU, V, 40,14 (UT, 2040);77,4 (UT, 2077); 146,2 (UT, 2146); U,V, 6 (RS. 17.149); 159(RS. 17.86)... CTC, 71, 51 (UT, 113); PRU, III, 11.830, 10; PRU, IV, 17.62, 25; 17.340, v,7' PRU, V, 48,22 (UT, 2048); 90, 9 (UT, 2090); 144, 1 (UT, 2144) ., .8 Cf. Liverani, Storia, Tavola I; Klengel, Geschichte Syriens, 2, Berlin, 1969,p.455.17 Cf. PRU, VI, for full evidenceincludingall available cf. y,V, about reign of Niqmepa and Ammistamru II, also Klenqel, GeschIChte Syrlens, II, Berlin,1969, pp. 361'-388. .62 Non-performance of Obligations by the Villagerswith persons who defected to the neighbouring kingdom. Taking intoaccount the evidence given at the beginning of this paper about refugeeswho defected to the territories under the direct rule of the Hittite king,we have to conclude that the heavy burden of taxes, duties, conscriptionsand debt caused the defection of villagers from the kingdom of Ugarit toother places in the same country, to neighbouring countries, or to terri-tories under direct control of the Hittite king.11This is aside from defec-tions caused by political struggles and attempts to seek asylum.The texts referred to above illustrate cases in which villagers becamenayyiilu, were enslaved to foreign creditors for their debts, or defected.Defections may have been prompted by fear of enslavement, or fear ofconscription. Defection may also have been an alternative to the burdenof taxes, corvee-service, and other obligations. These texts seem toindicate that every villager was known to the authorities as a member ofa particular village-community.I. PRU, VI, 80 (RS. 19.111), containing a list of various persons; dwelling invarious alu, but does not make clear whether they were refugees or not.CHAPTER VOTHER ASPECTS OF COMMUNITY LIFE IN UGARITThe royal authorities in Ugarit had both the power and the skill toimpose their demands on the rural communities. However, there werecustoms and traditions which protected the village-community fromruination. Using all the available material, we will try to elucidate themanifold life of this social body-the rural community.Collective Responsibility in Legal ActionsThe rural communities were collectively responsible for eorvee, con-scription, taxes, etc. They were also collectively responsible in variouslegal actions.Text PRU, IV, 17.229 relates that, "in the village of Apsuna waskilled"! a royal tamkar of Talimmu, king of a small state not far fromUgarit. The murder took place because Talimmu "raised a legal casewith the sons of Apeuna:" The outcome was that the "sons of Apsuna"had to pay "1 talent of silver"l to Talimmu.In PRU, IV, 17.288 the king of the neighbouring kingdom, U8natu,demanded from the siikinu of Ugarit' an investigation of "the sons ofAraniya ... for the slaves filled the hands of the sons of Araniya withstolen (property)."5The state of preservation of PRU, IV, 17.299 is very poor, but we candiscern that a certain "Qadidu brought a legal case againtst the sons offJalbi rap8i,"8 because his brother was killed in that village."U, V, 52 (RS. 20.239) is a most outstanding text, which is in a goodstate of preservation.1 i-na alAp.su.na.a di.ku.-u.mi. it-ti mareMaIAp-BU.na ana di-ni iq-ri-bu, 1 bilat kaspu{]. 1 talent in Ugarit equalled about 28 kilograms', N. F. Parise,Per uno studio del sistema .., pp. 21-23; cf. also PRU, IV, 17.369B, where thepeople of Apauna are shown also to bear collective responsibility for a murder, butthe text is severely damaged and the details of the document are illegible. Heltzer, Carskaya administraciya (Royal Administration), pp. 224-27. 8) dinutiM-ti B{a] mareMaIA-ra-ni-ya 9) ip-ru-sum.mu ... 21) ki-i-me-e arduMBa.ra-qa i-na qa-ti mareMalA.ra-ni.ya 22) u-ma-lau. 2) IQa-di-du it-ti mareMal!fal-bi rapBi 3). [aj-na dini iB-ni-qu.7 5) ... ~ u y ("my brother") (i-na al!fal-bi rapsi (?)] di-ku-ni]], It seemsthat an answer of the people of !falbi rapBi followed.,64 Other Aspects of Community Life in Ugarit Other Aspects of Community Life in Ugarit65 The sdkinu, vizier, of the kingdom of Ugarit. All reconstructions of the texts are made by the editor, J. NOtlflayrol.... Berger, UF, II, 1970, p. 290 alpiME[S.iaj.10 A military rank in Ugarit; cf. also PRU, VI, 52 (RS. 19,78),4.11 In order to give the oath; Berger, UF, II, p. 290 reads the beginning of theline dinaan e[. . .1) um-ma IMa-da-'-e2) a-na ameI8a-ki-ni3) qi-bi-ma4) lu-u sul-mu a-na muo,-Qi-ka5) ildnuMa-na sul-ma-ni6) 7) a8sum alp'ltM-ya sa il-tar-qu8) ameluMdl Ra-ale-b[a-y]a9) k-i taq-ta-b];10) ma-a ki-i-me-e [sarru(?)JII) iB-tu m[atUgarit?]12) il-la-[ak ]13) su-up-ra-a[m-mi( ?) J14) di-na sa alpiM[-lea( ?)J15) lu ga-mi-ir-[mi]16) i-na-an-na di-na sa-a[-s{?}]i.17) gua-mi-ir alpeM-ya18) li-te-ru-ni-i?l--ni19)u.fum-ma alpeM-ya20) la-o i-na-di-nu-ni.21) amelM,sbiituMsa al Ra-ak-ba22) I Ba-bi-ya-nu23) mdr I Ya-du-da-na24) IAb-du qa-du Imdri-su25) u IAd-du-nu26) amellw,-at-ni-su27) U amelaleilli-im28) ameluMan-nu-tuc lil-l[i ]ku-ni29) [a]-(?)-na btl ilimllmli-ru-bu30) u lu-u za-ku-u"1) So Mada'e2) to the 8iikinu83) says4) Peace to You!5) The gods for health6) May guard You!7) Concerning my oxen, which themen of8) Rakba had stolen:9) According to what You sai[d10) "That alike [the king( 1)] ...II) from th[e land of Ugarit 1]12) he go[es ?J (he would go ?)913) Ask m[e (personally) (or "de-mand")14) (on) the legal ease concerning[Your 1] oxen9a15) So we will finish it.16) Further: Th[isJ legal case:17) All my oxen18) - (who) has to return them me ?19) And if my oxen20) shall not he returned21) (So) the elders of Raleba:22) Babiyanu,23) son of Yadudana,24) Abdu together with his son,25) and Addunu,26) his son-in-law27) and the head of the thousand!"28) - these people sha[IlJ go29) {and) enter the sanctuary.s!30) and they are free (from obliga-tions)"The above text shows that people of Raleba were collectively responsi-ble for the stolen oxen and that the only way to prove they were not guiltywas to give an oath in the sanctuary. The oath had to be given by theelders of the diu, in the name of the whole population of this village.The data available from the various texts shows us that every theft,murder,. or other committed by people of a certain village, or insidethe territory of a VIllage, was the collective responsibility of the citizensof that village. Perhaps this occurred only in cases where no criminal wasnamed or apprehended by the authorities. The village had to free herself responsib!lity through oathgiving, or some other act, performed byIts representatdvea, the elders of the village. The data thus shows, oncemore, the communal organization of the dlu/qrt in Ugarit.Communal Landowning and Landholding by the Rural OommunltyIt would he difficult to assume that the rural community in Ugarit wasso primitive that it possessed land which was collectively worked by itspeople. But it seems very likely that the community had certain rights' andjurisdiction over the lands of its members, At the same time, the king hadcertain rights over the community. But the mere fact that the king ad-dresses the village (dlu) as a single body, brings the whole issue into theconfines of communal organization.This is treated in text PRU, III, 16.170. Only the reverse of thetablet is partly preserved. Lines 1'-3' of the text deal with Abdianatiking of the neighbouring Siyannu. This is followed hy: '4') [u eqliit]M aIQa-ar-ma-na 5') [sa u]l-tu da-ri-ti 6') [sa i-ina qatiameleMaIMu-lu-ule-lei 7') [ionia qdtiM-ma ameleM aIMu-lu-ule-[lci] 8') ueqldtMaIQa-ar-ma-na 9') sa ul-tu da-ri-ti 10') sa i-na qati ameleM alGal-ba11') i-na qatill-ma ameleMalGal-ba 12') abankunule INiq-me-pa mar Niq-ma-llAddu 13') [Bar] aIU-ga-ri-it."4') [and the fieldJs (lands) of (the village) Qarmanu 5') [which frJomever 6') [were iJn the hands of the people of (the village) Mulukleu7') (shall be) [ijn the hands of the people of (the village) llfulule[leu]. And the fields of (the village) Qarmanu 9') which from ever 10') werein the hands of the people of (the village) Galba 11') (shall be) in the hands Cf. I. M. DiakonoQ, Problems of Property. The Structure of Near EasternSocietyto the Middle ofthe MilleniumB. C. (Russian with English summary),VDI, 1967, No.4, pp. 13-35; ibid., The Rural Community in the Ancient Near EastJESHO, XVIII, 1975, pp. 121-33. '66 Other Aspects of Community Life in Ugarit Other Aspects of Community Life in Ugarit 67of the people of (the village) Galba. 12') Seal of Niqmepa, son of Niqmaddu,13') [king] of Ugarit."The remnants of this text correspond to a great extent with PRU, IV,17.123.1) is-tu l1mi an-ni-im 2) di-nu-tua eqli'itM &18u-uk-si 3) it di-na-tuaeqli'itM &lfJa-ar-ma-na 4) i-da-i-nu a-na pa-ni 118amSisi5) it i-na-an-nais-lcu-nu 6) ki-it-ta i-na be-ri-su-nu 7) ki-i-ma da-ri-i-ti 8) eqli'itMsar&ll1-ga-ri-it 9) sa i-na 10) sa ul-tuada-ri-ti 11) a-na qdtitl-ma sa" &ll1-ga-ri-it12) it eqli'itMsar &ll1-ga-ri-it 13) sa i-na eqli'itM&lfJa-ar-ma-na 14) sa ul-tuada-ri-ti 15) a-na qdtitl.ma sa,r &ll1-ga-ri-it 16) it eqliitM IAbdi-IINinurta17) sa ul-tua da-ri-ti 18) sa i-na &18u-uk-si 19) a-na qdtitl-ma IAbdi-IINinurta 20) it eqli'itM &lfJa-ar-ma-na 21) sa ul-tua da-ri-ti 22) sa a-naqdtitl IAbdi-IINinurta 23) a-na qdtitl-ma IAbdi-IINinurta 24) &bankunukIAbdi- IINinurta 25) sar &ISi-ya-ni 26) ur5-ra se-ra ameluma-na amelim27) la i-ta-ur."1) From the present day 2) the legal case (about) the fields of (thevillage) 8uksi 3) and the legal case (about) the fields of (the village)fJarmanu 4) was settled in the presence of the Sun (the great Hittiteking). 5) And so he ruled: 6) Justice between them 7) as forever (letthere be). 8) The fields of the king of Ugarit, 9) which are in 8uksi,10) (and) which were fromever 11) in the hands of the king of Ugarit;12) and the fields of the king of Ugarit, 13) which are among the fields of(the village) fJarmanu, 14) which were (his) fromever 15) shall remain inthe hands of the king of Ugarit, 16) and the fields of Abdininurta, 17)which were fromever, 18) and are (located) in (the village) 8uksi, 19) inthe hands of Abdininurta, 20) and the fields of (the village) fJarmanu21) which were fromever 22) in the hands of Abdininurta 23) shall remainin the hands of Abdininurta. 24) Seal of Abdininurta, 25) king of Siyannu.26) In future nobody shall 27) return (to this issue)."We see from PRU, III, 16.170 that certain lands in the village fJarmanuwere at the disposal of the people of two villages-Mulukku and Galba.This fact is significant because it means that a) people of a certain villagecould have lands in another village, b) these lands were under some kindof collective administration or management by the "people" (mdreM) ofthe villages of Mulukku and Galba.Text PRU, IV, 17.123 has more relation to political affairs. It dealswith the arbitration of the Hittite king between the kings of Ugarit andSiyannu. We see that there were royal lands of both kings in the villagesof 8uksi and fJarmanu. Both kings remained owners of these lands despitecertain political changes in these villages. (It is not definitively clearwhether these villages were under the sovereignty of Ugarit or Siyannuat that period.) It is important to note, that fJarmanu, mentioned inboth texts, included royal lands, as well as communal lands of the villagersof Muluklcu and Calba. The division between royal and communal landsis definitively clear in this text.The analysis ofPRU, III, 16.170and IV, 17.123 helps us to understand anumber of texts, written in alphabetic Ugaritic and dealing with landowned or held in one village by people of another village. Thus, PRU, V,26 (UT, 2026) relates: 1) sd. Snrym. dt. eqb. 2) b. Ayly. "1) The fields ofthe people (of the village) Snr, which are (located)18 2) in the villageAyly." This is followed by six lines (3-8) mentioning six fields, togetherwith the names of their owners or holders, who are men of Snr. Line9) sd. bn. ,mr[n. M]idlJ,y ("field of bn ,mr[n] man of (the village[ M]idl/') is of special interest. Perhaps he also had a field in Ayly. Thus,six fields of "men of Snr," and one field of a "man of MidlJ,,"u werelocated in the village Ayly. This is strikingly similar to the data fromPRU, III, 16.170.The question now arises: how could people of one village have theirlands in another village 1 It seems unlikely that they purchased the land,for they did not get their rights as "sons" (mareM) of the second village.They remained "sons" of their original village. Perhaps they receivedcertain holdings in villages ,where depopulation had taken place as a re-sult of war, epidemic, or defection of the villagers (cf. above, Ch. IV).PRU, V, 29 (UT, 2029) may shed light on this problem.This text deals with landholdings (ubdy),1& given to a number ofpersons by the king.1&&13 Cf. UT, p. 460, No. 1907; the translation of Oh. Virolleaud, PRU, V, p. 40, bycomparison with Hbr. eaqob "hill-country," is unconvincing. Here we have a verbal,not a noun form; cf. Hebr. pied of eqb, "to delay," "to retard," and in connectinonwith it, possibly the Ugaritic "to be located." Cf. also M. Dietrich, O. Lorete, Zurugaritischen Lexicographie, I, BiOr, 23, 1966, p. 131.U The last line of the text, 10, gives 8d Tb"m [ .. .]y, "The field of Tb"m manof ( ?) ."; the last letter y could be the ending of a nisb, and therefore it is possiblethat an additional place-name was mentioned here.15 ubdy, of, a) Rainey, Social Structure, p. 32, 120-21, a fief connected withservice and natural payments. A. F. Rainey agrees also that the word is of Hittiteorigin; b) H. G. Guterbock, "Oriene," X, 1957, p. 36, explains the term by the Hittiteupatiya; c) G. Rinaldi, Osservaeioni sugli elenchi ugaritici 8d ubdy, ubdy, MelangesE. Tisserant, I, Vaticano, 1964, pp. 345-49, ubdy, "occupied," or "delivered intodisposal," (field-ad); d) UT, p. 349, No. 17, "perpetual land grant," but the ex-planation of O. H. Gordon is unconvincing. The explanations ofGuterbockand Rinaldiare not in contradiction, but one aids the other in understanding the true meaningof the term.15& Cf. also ZUL, VII UF, V, 1975, p. 94, No.6, where the text is partially discussed.68 Other Aspects of Community Life in UgaritOther Aspects of Community Life in Ugarit 6918) ad. Pln. bn, Tiyn. bd[.] Ilmhr 18) The field of PIn, son of Tiyn, tonlJ,lh Ilmhr (and) his descendents.12) ad. Puyn [bid. []r[]n.l. Ty<n) 12) The field of Pgyn [t]o [..]1' [..]n[n]lJ,lh. to Tyn (and) his [des]cendents.13) .d. Krz. bn. Ann. c[] . . . 13) The field of Krz. son of Ann . . .14) ad. T[r]yn. bn, Tkn. bd. qrt. 14) The field of T[r]yn. son of Tknto the village-?22) 8d [x]dy. bn[.] Brzn 22) The field of []dy, son of Brzn,23) l. qrt. 23) to the village."There are twenty-one fields listed in the text. In most cases "the fieldof "x" (personal name)" is handed over to another person, "s: Sometimes"his descendents" (nlJ,lh) are also mentioned. This text is typical of thosetablets found in the archives ofUgarit, which dealt with the redistributionof the royallandfund to people in the royal service. The lands were con-fiscated from certain persons, perhaps nayyiilu. (Cf. above, Ch. IV, p. 57.)But lines 6, 9, 14, 16, 21, and 22-23, indicate that six fields were notdistributed to individuals, but were given to one village-Art. It is notclear if the rural community received the fields as their property, or onlyfor temporary holding. Were these lands considered part of the landfund,where the villagers had to work collectively for the treasury, delivering toit the products of their labor 1 Or were the fields distributed to certainindividuals or families inside the community 1It is most likely that theselands remained royal property and served the purposes of distributionand redistribution. It is obvious that the royal administration had deal-ings with these people. Even when they continued to be members of therural community, the land remained royal. Still, the rural community,through its local administration, or individual who were in charge of thevillage (qrt), managed the fields. If the land were distributed to individ-uals inside the community it is more likely that "l qrt" would not havebeen written in the text. Thus, it is more realistic to suppose that thecommunal authorities dealt with the fields and their management. It isalso possible that the crops harvested from these fields had to be paid tothe treasury. This was, therefore, an additional tax imposed on the villageArt.In referring to the eqliitM~ i i i r u ("the #bbiru fields"), we maysuppose that this type of land was similar to "public lands" (agel' publi-1) spr, ubdy. Art2) ad. Pm. bd. Agptn nlj,lh3) ad. S.wn bd. Ttyn. nMlh]4) ad Ttyn. [bin. Ark8[x].5) l[]q[.. .]6) ad. []l. bd. qrt7) ad. Ann[g,jr. bd. Bdn.[.]nlj,[lh]8) [ad.] Gyn. bd. Kmrm. n[lJ,l]h9) [ald. Nbzn. []l.qrt10) [ald. Agptr. bd. SlJrn. nlJ,lh11) .d. Annmn. bd. Tyn.nlJ,lh15) ad[]. dyn bd. Pln. nltlh16) ad. Irdyn. bn, lJrua[]. l. qrt17) ad. Irjlyn. bn, Krzbn. l. qrt"1) List of holdings (from the kingin the village) Art.2) The field of Prn to (lit. "into thehands") Agptn (and) his de-scendents.3) The field of S.wn to 'l'tyn (and)his descendents.4) The field of Ttyn. [s]onofArk8[]5) to ...186) The field of [x]. to the village-?7) The field of Ann[g,]r, to Bdn(and) [his] descenden[ts].8) [The field] ofGyn to Kmrm (and)his descenden[ts].9) the [fie]ld of Nbzn [] to the vil-lage.l710) The [fi]eld of Agptr to SlJrn(and) his descendents.11) The field of Annmn to Tyn (and)his descendents.15) The field of ... dyn to Pln (and)his heirs.16) The field of Irdyn, son of lJrua[ ] to the village. .17) The field of Irjlyn, son of Krzbnto the village.l"19) 8d Knn I.I bd. Ann. cdb20) ad Il[xx]. bn Ir[x]tr. l. SlJrnnlj,lh21) ad [a;]ptn. b[np' Brrn. l. qrt19) The field of Knn to Anncdb1820) The field of Il[xx], son ofIr[x]tr, to SlJrn (and) his heirs21) The field of []ptn, son18of Brm,to the village-?11 Reconstruction based on the autography uncertain.17 Or the alu-village Qrt. known from PRU, II. 24 (UT, 1024); PRU. V, 44 (UT,2044); 118 (UT, 2118, etc.). The fact that the fields are located in the village Artseems to prove that the word qrt has to be translated here as "village." But even ifitis the village Qrt our conclusions are unchanged.18 The word-dividing sign may be a result of scribal error, but cf. also ZUL, VII,UF. V; p. 94, No. 60.11 Gordon. UT, bId], but such a reconstruction is impossible, for we have 1qrt,"to the village." Thus, bIn] is a more logical reconstruction and also in accordancewith other similar lines of the same text.70 Other Aspects of Community Life in UgaritOther Aspects of Community Life in Ugarit71cus), but in this case the lands were only under royal disposition. How-ever, additional data concerning this situation is highly questionable.According to PRU, 111,16.137, King Niqmaddu II took land in variousplaces, among them 7) eqliit 8) i-na narRa-alJ,-ba-ni, "the fields in (the region) of (the river) RalJ,banu." He handed them over to hISmaryannuSOand miiduSlserviceman, Abd,,!,' son of to PRU, III, 16.233, this same person received one eqil ( field"). This term also appears in the large but fragmentary text, PRU,VI, 55 (RS. 18.22). We do not know all of the conditions by which theking handed over, or withdrew, the fields. The text at least 1( ?),1( ?), 4(?), 2, 7, 20, and 25 fields which were at the disposal of certainpersons of certain persons of the village Riqdu (amel Riq-di) .11 They wereall defined as sa i-na eqliitM ("which lay among (or "are of") thesibbiru fields." How these fields were dealt with further is unclear.. We lack a clear understanding of the term The translation ofJ. Nougayrol "territoire collectif" or "territoire du travail collectif"("collective territory" or "territory for collective given withoutany further explanation. Perhaps J. Nougayrol had In mind the Hebre,:-Mishnaitic ("community") or the Ugaritic which appears Inthe same sense in some passages in Ugaritic mythologic texts.14In ourown opinion, the occurring in the non-legendary texts men-tioned above, is closely related to PRU, V, 73 (UT. 2073).1) In. "1) Two (fields) 2) b. ou 2) in (the village) on3) lJ,d 3) One 4) b. Ar 4) in (the VIllage) Ar5) sbr. ahd. 5) One (field)6) b. 6) In (the village) Mlk7) al),d 7) One (field)8) b. Mcrby 8) In (the village) Mcrby"' On the role and position of the maryannu.servicemen.chariotwarriors inUgarit, cf. Heltzer, Soziale Aspekte, pp. 125-29, and OAC, IX, .1?69. ,11 On the mUdu servicemen in Ugarit, cf. M. Heltzer, Ugaritdc-Akkadian Ety.mologies (mUdulmd(m)), SY, II}, 1965, pp. 355-58.II Only one man, IIruna, was a "man of Ugarit" (amel al U.gariit)."' PRU, VI, p. 146... UT, p. 472, No. 2142; cf. below, Ch. VI, pp. 76-77, cf. also, C:AD: 16, p. where 8ippiri is explained as "a type offield," and the word, In Akkadianfrom Ugarit, is defined as a at the ,same tim? p. 202 8ipirtu, is given also as occurrmg In Middle-Babylcnian, ultu "from the lIipirtu to the irrigation ditch." .The word only once, andin our opinion it has to be read i/ibirtu in Babylonian and Ugaritic texts.9) a1),d 9) One (field)10) b. Ulm 10) in (the village) Ulm11) al),d 11) One (field)12) b. Ubrcy 12) in (the village) Ubrcy."It seems that this text is also referring to the fields quoted fromthe tablets in Akkadian,s& although in the village of Riqdi there were atleast sixty units, and here we have two only in Uskm, and one in eachof the other villages (Ar, Mlk, Mcrby, Ulm, and Ubrcy). It seems that the fields were bound to some administrative procedure by theauthorities of Ugarit. Perhaps they were collectively worked by thevillagers. IS The term by itself seems to allude to this. But the question isnot definitively answered. It is clear, as we have seen, that there werecertain categories of lands which were managed by the village. This offersan additional proof of the communal character of the village.Local Religious Cults and Communal (Local) Sanctuaries in the Kingdomof UgaritNaturally, the villages of the kingdom had to participate in the religiouscults of the whole country and, as we have seen from text PRU, V, 4 (UT.2004), the villages had to deliver certain quantities of wine for royalsacrifices.l? Still, a certain number of villages had their own cults, or wereattached to some special religious cults. It is clear, that some of the villageshad theoforic names. We know, for instance, of the villages of alBeqa-lIntar, "Valley of (the goddess) ntar or A.start;" .Ilstan; Mril;18 Mati-ilu;8lmy;18 aIAsri-lIBa'ala;80 .fJb/pty (Akk. !Ju-up-pa-tU);81 QdB(Akk. QidBu);81.. Cf. UT, p. 472, No. 2142. lIbr." a team (of workers)" in this context; cf. alsoM. Dietrich, O. Loretz, Zur ugaritischen Lexikographie, I, BiOr, 23, 1966, p. 132,where lIbr in PRU, V, 73 is compared with OldAssyrian lIUpru, "seized debtor";both explanations are unacceptable; a more detailed discussion ofthis issue, cf.M. Heltzer, Die lIibbiru.Felder in Ugarit, to be published in "Orientalia LovainensisPeriodiea."I. Thus I must abandon my former explanation of the term lIbr as meaning"assembly (of the people) of the village," M. Heltzer, Aspects of Social History,p.37.17 Cf. above, Ch. II, pp. 40-41... In Akkadian texts it = ilu ("god"), in these place-narnes.I. The Ugaritic pantheon knows the god Slm, cf. UT, p. 490, No. 2424.I. The "place", "site", abu, of the god Bel.11 The place-name composed by the name of the Hurrian goddess, fjeblpa(t).II The deity QadeJ, "The Holy one," broadly known as a Canaanite god orgoddess.\72 Other Aspects of Community Life in Ugarit Other Aspects of Community Life in Ugarit73fJlb (Akk. fJalbu !!uriaufJa-zi).88 The names of other deities did notcoincide with the names of the villages where they were worshipped, forexample; fJebat of (the village) Ari." The cult of Resel is known fromPRU, II, 154 (UT, 1154), and was worshipped in the village of IUtme.This problem brings. us to text CTC, 31 (UT, 14).1) bt. Il 2) bel. u. Ag,mny 3) bel. bt. Pdy 4) bolo u. Nqly 5) bel. bt, elr 6)bel. bt. 8817) bel. bt. 'l'rn 8) bel. u. Ktmn 9) [bell. bt. Ndbd 10) [bel. bt.] 11) [bel]. be. B8n.86"1)Sanctuary88 of Il," 2) lord of the temple (sanctuary) of Ag,mn,883)lord of the temple of the village Pd(y),88 4) lord of the temple Nqly, 5)lord of the temple of elr, 6) lord of the temple of 881, 7) lord of the templeof :Ern, 8) lord of the temple of Ktmn, 9) [lo]rd of the sanctuary of Adduin (the village) Ndb,"o 10) [lord of the temple] of (the village) 11)[lord] of the temple of Ben:"This text came from the temple-archives, where religious and mytho-logical, but almost no administrative texts were held. Therefore, it isimpossible to agree with those scholars who find in this tablet a patro-nymic list, as Yankovskaya and other scholars propose.ss In our opinion itcontains a list of sanctuaries (probably incomplete) subdued to the god II,head of the Ugaritic pantheon. Among the ten names given, Eshmoun andAddu (Adad) are the names of highly venerated gods in Ugarit, Fivenames, elr, S81, Trn, Ktmn, and Ben, are completely lacking in other texts.Only Pdy, and Ndb(y) are the names ofUgaritic villages. It seems tobe clear that all these local sanctuaries, named according to the place-aa Connected with the Ugaritic and Canaanite deity $aphon; cf. W. F. Albright,Baal-Zephon, "Festschrift lur A. Bertholet," Tiibingen, 1950, pp. 4-14. Theworship of this deity in Ugarit was connected with the holy mountain, $ajon (Akk.fjazi, Classical Mons Oaaiua).... PRU, IV, 17.369B, I, v'5'8',"-'-l1fje.bat aIA-ri.a' Cf. the discussion on this text: N. B. Yankov8kaya, L'autonomie de 10. com-munaute a. Ugarit, VDI, 1963, No.3, p. 39 (Russian); M. Heltzer, Once More onCommunal Self-Oovernment in Ugarit, VDI, 1965, No.2, p. 7 (Russian); of; ZUL,XI, UF, VI, 1974, p. 22, No. 20... bt, lit. "house," has often had the meaning "sanctuary" in all. Semiticlanguages, but this is especially the case in Ugaritic... Principal deity of the Ugaritic pantheon... The god E8hmoun, Phoen, 'imn... aIPidiIPd(y),.U, V, 12 (RS. 17.150); PRU, V, 27, 8 (UT, 2027); 42,3 (UT,2042.3); ll2, 2 (UT, 242,2), and many other texts. From Ndb + lid, ef. WUS, p. 202, No. 1752; Ndby as a place-name, cf. PRU,IV, 17.62, p; 17.339A--....aINi.da.bi, PRU, V, 119, 13-15... aISIZi.na-ruISnr-cf. CTC, 71, 33 (UT, ll3); PRU, II, 84, 14 (UT, 1084);PRU, iII, 11.800; PRU, V, 41, 8 (UT, 2041), etc.name ordeity, or both (Ndbd, cf. above), were located in various places ofthe kingdom of Ugarit.It is nat.uralthat the local cults also had their priests, or at least people were 111 charge. One such person was "Milkiyatanu, son of Mi[. . .],priest of Ba'al (of the village)[ ]," (IMil-ki-yatanu, mdrlci]; ..] amOlsangusa lIBa-'-Ii "I...]).48In another case, a certain is mentioned in PRU, II, 154 (UT, 1144),in relation to the sacrifices in the local community. This passage, which isof interest to us, follows.4) gdy lq1], g(?)tUbn ndr 5) umr []tn II !Jsn lytn 6) lr1], []t(?) lq1], 7) bt ur[]t Ilstmc db1], 18) Rsp."4) $tqn takes a Iamb which ) is (of the man) who gave his vow( 1)4& He looks( 1)46 .. six lJ,sn47for to give. 6) To his hand"8 $tqn takes, 7)(111) the assemblyw house, ... of (the village) IUtme sacrifices to9) (the god) Rsp."We see that the village Ilstme, well-known from various sources alsohad its cult of the god Reshef, one of the gods of the Ugaritic pantheon.It is interesting that Il8tme had its own bt ("assembly house"). Thefact that the sacrifice ceremony was communal gives additional evidenceof the communal character of the village. Although we have no paralleltexts which mention the bt it may be comparable to the bt hbr in theepic .of King Keret.6o ".. Yankov8kaya, L'autonomie, pp. 39-40; all references given in ZUL XI UFVII, 1974, p. 22. ' , ,'a Oh. Virolleaud, Cinq tablettes accadiennes de Ras Shamra RA XXXVII1940, No. I, text II. " ,." The autograph of this word is unclear, and the transcription is according to PRU, II, p. 184, and O. Gordon, UT. The text itself was written runningaround the tablet, so that each line is formed by reading the obverse and reversethe y (')t stands on the edge. Possibly, dt was the original word in which case wemust translate it as "which." ' Literally, "son of the vow.".. umr, cf. UT, p..361, No. 229 'mr, "to look," "to see," WUS, p. 25, No. 283. Le8laU, <?bs?rvatrons on Semitic Cognates in Ugaritic, Or., 32, 1968, p. 349,gives the ethiopio 'a'mara "know," "recognize."n Perhaps the plural st. cstr, but the meaning of the word is unclear. It does notseem to be a personal name, or a certain professional, as the dictionaries explain;WUS, p. ll4, No. 1056-59; UT, p. 403, No. 985... r[it, "hand," cf. Arab. rlt!;tat(un), Akk. rittu... qb,-Hebrew, "gathering, assembly," the bt qb8is not known fromothertexts. . I 14 = UT, Krt): 80)edb akllqryt 81){I!t lbt b-br ("He prepared breadfter the CIty 81) wheat for the b-br-house"). b-br may be "gathering, fellow, company,"e .74 Other Aspects of Community Life in UgaritAll of the above indicates beyond doubt that communal local religiouscults really existed in Ugarit.After studying various communal features in the kingdom ofUgarit, wecome to the question of local communal self-government. This will bediscussed in Chapter VI.CHAPTER VICOMMUNAL SELF GOVERNMENT IN THE VILLAGES ANDITS RELATION TO THE ROYAL ADMINISTRATIONTypes of Local Self-government According to Various Non-administrativeSourcesIn the mythological and epical texts from Ugarit, which were composedsome centuries before they were written down (XIV-XIII centuries b.o.),the word plJ,r (var. plJ,yr) meant "assembly," designating the "assemblyof the gods" (plJ,r ilm), or "assembly of the sons of II (mplJ,rt bn 1l).1Although this word does not occur in the administrative texts of thefourteenth to thirteenth centuries, it helps us understand the generaldirection of the political ideology of Ugarit. Royal rule did not excludethe possibilities of assemblies and other representative bodies.tAs was mentioned above,S text PRU, II, 154 mentions the "assemblyhouse" or "house of the gathering" (bt of the village of llstme Alsodiscussed was the bt lJ,br in the Keret epic. The same epic offers a parallelconcerning tribal or communal or some other type cf assemblies. CTC, 15,III (UT, 128): 13) mid rm Krt 14) btk rpi 15) bplJ,r dtn ("13) Arisemuch, 0 Keret! 14) among the heroes(1)' of the country 1/ 15) in thegathered assembly of dtn".'The Ugaritic epic of Danel contains a reference to some kind of localassembly also. The text, II Dnil V (= UT. 2 Aqht), relates that 6) (Dnil)ytb. bap. tyro tQ,t 7) adrm. dbgrn. ydn 8) dn. almnt. ytpt. tpt. ytm. ("6) (Danel)sits in front of the gate II under (among) 7) the nobles,' who are on the1 WUS, pp. 255, No. 2215; UT. p. 468, No. 2037; cf. W. Leelau, Observations onSemitic Cognates in Ugaritio, Or., 37, 1968, p. 361. Cf. Th. Jacobsen, Early Political Development in Mesopotamia, ZA, 18 (52),1957, pp. 91-140; I. M. Diakonog, Society and State in Ancient Mesopotamia,Moscow, 1959, (Russian with English summary). Chapter V, p. 73. Cf. WUS, p. 295, No. 2527; UT, p. 485, No. 2346. Cf. also, a controversialopinion, J. O. de Moor, UF, 1969, I, p. 176, "The Healer" (without translation);S. B. Parker, UF, II, 1970, p. 243. WUS, p. 83, No. 801, "lord"; UT, No. 712, tribal name. It is more likely thatthis name is the name of a deity or a hero, cf. U, V, No. 6 (Ugsr, RS. 24.272),1) k ymgy. adn. 2) ilm. rmb. em dtn 3) W. yial. mtpp yld ("I) When the lord 2) of thegreat gods arrives to Dtn 3) and asks the judgement about the child"). adrm--"nobles," cf. a# adrt wife"), and PRU, II, 92 (UT, 1092),6) arbeyn[. . .J 7) b. adrm [] 8) iqym. ("6) 4 (jare) of wine [] 7) for the nobles (elders 1)[] 8) who give to drink"), perhaps the literally translation has to be "mighty" (cf.Bebr. 'addir); cf. WUS, p. 8, No. 95; UT, p. 352, No. 92., grn--"threshing floor" as place for assemblies and trials in front of the gate,cf. S. Smith, On the Meaning of Goren, PEQ, 85, 1953, pp. 42-45; J. Gray, TheGoren of the City Gate, PEQ, 85, 1953, pp. 118-23; WUS, p. 69, No. 699; UT, p.381, No. 622; Leslau, Observations, p. 352.8 Cf. the translation, J. AiBtleitner, Die Mythologischen und Kultischen Texteaus Rae Schamra, Budapest, 1959, pp. 18-19.o Or simply, "the goddess."10 The same wording cf. (AJrt W bnh Ilt W ,brt aryh), CTC, 4, IV, 49-50 (UT, 51);CTC, 3 (UT, enf), V, 45.11 CTC, 17 (UT, 2 Aqht), I, 19; 19) din. bn.lh 20) km. alJh. w. MI. km. aryh 21) bl.iJ. bn. lh, km. alJh. wMI 22) km. aryh ("19) for he has no son 20) like his brothers,and (no) offspring like his ary(s) 21) he has no son, like his brothers, and offspring22) like hisary(s)").II,14) ... kyld. bn.ly. km 15) alJy. wMI. km aryy("14) . whena son shall be born to me like 15) to my brothers, and 8Jl offspring like to myary's").11 WUS, p. 35, No. 3021; UT, p. 366, No. 349. The only linguistic parallel givenhere is Eg. iry, "companion,"threshing-floor,1he decides 8) in the case of the widow, judges the judg-ment of the orphan").This text illustrates various traditions of primitive democraoy as shownalso in the other literary texts ofUgarit. Besides tho epical texts, as in thecase of the "assembly of the gods" (cf. above), various terms of the "prim-itive democracy" appear also in the purely mythological poems. Theexpression which is of interest to us appears four times in the knowntexts in almost the same wording. CTC, 6 (UT, 49 and 62) deals with thedeath of the god Aliyan Ba'al and the joy of his enemies on this event.II) ... tamlJ, ht 12) Alrt. wbnh. Ilt 13) rt. aryh, kmt Align 14) Bel. klJ,lq.zbl. bel 15) ..."II) ... there will rejoice i2) AAirat and her sons,llat' and the 13) of her ary's.Because dead is Aliyan 14) BaalBecause the noble, lord of the earth perished."loThe same expression occurs in a slightly different form in CTC, 4 (UT, 51),II, where the text is partly destroyed. 25) ... 26) aryy [ .. .J. Weseem to have here the plural form with the possessive pronominal suffixof the first person singular. Thus, the meaning is: "the of my ary's."Following the rules of the poetic structure of the text, which employs theparallelismus membrorum, we see that aryh has its parallel meaning inbnh, "here sons." The Danel epic employs aryh in parallelism with alJ,h"his brothers.t'-! This contributes to the understanding of the real mean-ing of the word ary, "kinsman."11 Taking into aocount all the above, it isCommunal Assemblies77 Communal Self-government in the Villages11 WUS, p. 263, No. 2301.18 UT, p. 472, No. 2142.11 Cf. Levy, IV,p. 164, Aram. with the same meaning; cf. also, Ch. V,pp. 70-74 about the ,br in various villages.18 M. Liverani, Due documenti con garantia di presenza, U, VI, P. 1969, pp.375-78; M. Dietrich, O. Lorete, J. Sanmartln, Keilalphabetische Burgsehaftadoku-mente sus Ugarit, UF, VI, pp. 466-67.18& According to UF, VI.17 The autograph enables us to read the remnants of the two letters, which werenot taken into account by Oh. Virolleaud.18 Oh. Virolleaud reconstructed this as Apa.[ny], but the space demands threesigns.18& The reconstructions of Liverani and UF, VI [Jth] and [Jthm] are unaccept-able.II Our reconstruction; space for 1-2 signs.10 Our reconstruction; the remains of the sign p are legible on an autograph.Although we have no direct mention of communal assemblies in Ugarit,the mere fact that the communities had to bear collective responsibility(cf. above, Ch. V, pp. 63-65), and possessed a bt "house of assembly"(cf. above, Ch. V, pp. 73-74), enables us to draw the conclusion that suchinstitutions existed. Some of the available documents shed additionallight on this issue, e.g., PRU, V, 116 (UT; 2116).181) TUn 2) Trkn 3) su 4) Plgn 5) Aps.ny 6) crb[. . .]n [xxxj18a 7) w.b.p[nj11 8) Ap8.[nyyj18 9) b. 10) l],wt[. .pea II) alp k[sp] 12)tslen[hm](?)1' 13) w. hm. al[pj2 14) I. ts.en 15) 16) tmkrn 17) yplj,.impossible to agree with the translation of as "mob"18 or "band,groUp."lC In our opinion, we are dealing with a more precisely definedsocial term. We must, therefore, base ourselves on the meaning of the root in Hebrew, "to gather, to bring together," as well as the Mishnaiticmeaning of "assembly, community."l& Although in Ugaritic theword appears in the feminine form, it must have had nearly the samemeaning, i.e., "entity," "assembly," "community." Thus, the mytholog-ical passage has to be translated, "AAirat and her sons II llat and thecommunity of her kinsmen."We have analyzed above the terms concerning the origins of communalself-government, as found in archaic mythological and epical texts. Wemay now use these terms as an aid to understanding similar terms foundin texts of greater historical reliability.Communal Self-government in the Villages 7678 Communal Self-government in the Villages Communal Self-government in the Villages 79cbdilt 18) bn. M. 19) yplj, tuu 20) bn. PrqrM 21) yplj, Mnlj,m 22) bn, IJnn23) Brqn spr,"1) Tldn, 2) '!.rkn, 3) Kli (and) 4) Plgn-5) people of (the village) Apsn(Ap8una) 6) took [on themselves mutual] guaranties." 7) And in the[presence] 8) [of the people] of Ap8una 9) at their departure'" 10) (by)their lives [they have sworn]28 11) about (1) thousand (sheqels of) sil[ver]12) for [their] travel. 13) And they have thou[sand] 14) for (their) travel15) to Egypt 16) for their tamkar operations. 17) Witness24cbdilt, 18) sonof M;28 19) witness Ilslm, 20) son of PrqrM; 21) witness Mnlj,m, 22) son ofIJnn. 23) Brqn, the scribe."In our opinion this text is unique among the alphabetic documentsavailable from Ugarit at present. It is a contraot of "comradeship," or"companionship"-tappiitu, known also from various Mesopotamiansources. 26 Four people combined their resources for a oommercial ex-pedition to Egypt. In our case, the most important thing is that the texthas witnesses. Despite this, the transaction was also made in the presenceof the people of Ap8una, the native village of the four. Thus, there was agathering or assembly of the people of the village, who also make legalconfirmation of the document. Otherwise, the people of Ap8una wouldnot have been mentioned. Unfortunately, there is no additional informa-tion available concerning an assembly of the people of a village.We also know of one case in which people of a certain village had treatyrelations with the royal authorities. The small text, PRU, II 173 (UT, 1173),relates: 1) mt}mt cb8 2) arr. d. gr 3) ht.26a "1) Treaty27 (of) cb8 "with" or"of"27a 2) Arr26 (of) (or "about") the mountain( 1) 3) Ht."28a But un-11 crb, "to enter," also, "to guarantee"; of, Akk. erebu and Hebr. crb... 1. e., at the departure of the four participants of the agreement, who gave themutual guaranties. . UT, p. 395, No. 850, "house, dynasty, realm," is comple.tely o?scurein thiscase; the word is connected with !tyy/!twy, cf. No. 856; M. Liveram,.pp. 375-78,givesa different interpretation of this .text. He comparesthe With 161 (UT. 116l); crb b he interprets as "to grant," 10)hwt (lth/ ("10, vita (delgarantd)e 10, sua (del debitore sostituta").It .UT, p. 412, No. 1129. ... This is the way it appears in the text; our article "Ein ugaritischer Genossen-schaftsvertrag" will be publishedelsewhere. CH 99; A. Finet, Le codede Hammurapi, Paris, 1973, pp. 71-72, etc.2_ According to the revised reading in ZUL, VII, p. 100, No. 72. 7 Dietrich, Loretz, Der Vertrag, p. 218, proves the identity of the Akk. rikiltuwith Ug. "treaty, contract."17a Personal name( ?).IB ZUL, VII, p. 100-"cbs (from) Arr," but such an abridged form on a smalletiquet can also denote that the treaty was concludedwith the village Arr.'oa Cf. ZUL, VII.fortunately, there is no additional information and, except for the factthat there existed some cases of treaty relations between the villages andthe authorities or individuals, it is impossible to draw any conclusions.The Council of EldersWe possess very little data concerning councils of elders. A certaininstitution of "fathers (amelabbeM) existed in Ugarit. In text PRU, IV, 17.4240, Addudayyiinu, king of Amqi, complies with an illegal demand, madeby the 8iikinu (vizier) of Ugarit, for customs duties imposed on his tradeagent or tamkar. . . . 24) ... sa-'a-al 25) [ame]labbeMal(J-ga-ri-it 26) [ki-i]il-qa-a mik-[sa] 27) [is]-tu qdtillame1tam[kiiri sa sepi-su(?)PO '.'24) ...Ask 25) the "fathers" of Ugarit 26) [did] (somebody) take custom[duties] 27) from the tam[kar] [of his feet] (personal tamkar)."80 Theterm "fathers" seems to refer to a collective body, perhaps composed ofelders, which preserved some kind of oral legal tradition. But, there is noproof that this body existed in the villages of the kingdom of Ugarit.More precise data is gained from U, V, 52 (R8. 20.239). From this text,we learn that in a certain legal case the elders of the dIu Rakba had toenter the sanctuary and to give an oath. The council of elders consistedof Babiyanu, son of Yadudana; Abdu and his son (or sons); Addunu, hisson-in-law; and the "head of thousand (men)" (ame1akil li-im).81 Thecouncil thus consisted of at least five persons. But these elders (amelMst_biituM) by no means comprised a democratic institution. First of all, wesee that at least three persons (Abdu, his sor-, and son-in-law) were closerelatives. One of the elders (akilli-im) was a man of high rank in the royaladministration. Perhaps he was also a landowner inside the rural com-munity. But the characteristic feature is that the eldership was distrib-uted among members of one family, and high-ranking officials. It ispossible that the councils of elders of the other villages were of a similarnature, although we have almost no additional information on thissubject.82II Reconstructed by J. Nougayrol, based on similar passages in the sametext.ao Translation of Aa "personal," of. M. Helteer, The tamkar andHis Role,pp. 9-10; cf. also, PRU, IV, 205, 10,ame1abu, in a fragmentary text.81 For the full text and translation see Ch. V, pp. 64-65. Cf.alsothe brokentext U, V, 66(RS. 21.54B) whichrelates: 1)[amelM.lib/utuM2) [Aa aIA/r-ru-ti 3) [i-na eka/lli-ka an-na-kum ("[The el]ders 2) [of the (village)A]rutu, 3) [who in] this your [pal]ace"), 4) [lu-u (?) i]t-ta-mu ("[must give] theoath"). Onthe councilofeldersin related ancient oriental societies, cf. J. L. McKen-80 Communal Self-government in the Villages Communal Self-government in the Villages 81Heads of the Local Administration and Their Relationshipto the Royal AutboritiesThe terms used to designate people in high positions in the villageadministration are not clearly defined. As we will show below, the wordslJ,azann'u, siiJcinu/skn, rb, and others, could be used for designating royalofficials of high rank, appointed to carry out certain functions in thewhole kingdom, as well as local officials, and even representatives of thelocal self-government. Therefore, we have to investigate every individualcase and deal with this question very carefully.1. Hazannu. In various villages of the kingdom, people who receivedlandholdings from the king, and who possessed certain privileges becausethey were also in the royal service, were freed from administrative powerof the "lJ,azannu of the village." PRU, III, 15.137, from the period ofAmistamru II, referring to a certain AbdilJagab, a "royal friend" (mfLduBarn), tells us: 13) UamellJ,a-za-nu dliKIUame1akil e[qJliitiM 14) la-a i-ma-li-ikeli-BU. "13) And the lJ,azannu of the village, and the overseer of thef[iel]ds 14) shall not have power over him." We must draw the conclusionthat there was a lJ,azannuin every village, and unlike those having specialprivileges, he had some power over the main mass of the local population,the peasants of the rural oommunity.wThe situation is more complicated in U, V, 26 (RS. 20.03) where aHittite prince or royal official, Sukurte8ub, wrote to king Ammistamru IIofUgarit:14) [iJ-na-an-na a-nu-um-ma 15) 16) mdre aIPa-ni-iB-ta-'a 17) a-na mulJ,-lJ,i-ka al-ta-pdr 18) mdB-da-a-ri a-na e-pe-Bi 19) i-nazie, The Elders in the Old Testament, AB, 10, Rome, 1959, pp. 388-406; D. A.McKenzie, Judicial Procedure at the Town Gate, VT, XIV, 1964, No. I, pp. 100-104; P. Artzi, "Vox populi" in the Amarna Tablets, RA, 1964, No.4, pp. 159-66;J. A. WilBon, The Assembly of a Phoenician City, JNES, IV, 1945, No.4, p. 245;H. Klenqel, Die Rolleder AItesten[LUMEA SU. GI] in Kleinasiender Hethiterzeit,ZA, 23(57),1965, pp. 223-36; H. Klengel, Zu den in Altbabylonischer Zeit,Or., 29, 1969, No.4, pp. 357-75; H. Reviv, On Urban Representative Institutionsand Self-Government in Syria-Palestine, JESHO, XII, 1969, pp. 283-97; M. Live-rani, Communantes ..., JESHO, XVIII, 1975, No.2, p. 154. ... Cf. also PRU, III, 16.157, where a privilegedperson in royal service, a moouAziru, is also: 22) u-tu qatiMame1akil I'narkabti U 23) zaki ... ("22)fromthe hands of the overseerofthe chariots and of the Oazannu 23)he is free ...");in PRU, III, 16.250, a certain Ilumilku, also a royal moou: 18)u-tu qatitl ame1akili'narkabti 19) uame1liaza-ni zaki ("19)fromthe hands of the overseerof the chariots20) and from the ltazannu he is free"); PRU, III, 16.348, gives details about theprivileges of a moou of the queen, Yanliamu, and also the: 10)ame1liaa[zz]a.nua-na ul[irrub] ("10) the liazannu shall not enter his house"). In all thesecases the word dlu, "village," is completelylacking.aIBelet-re-mi li-pu-su 20) it a-na amellJ,a-za-ni 21) sa aISa-al-mi-ya 22) a-naqdtitl-su su-ku-un-su-nu-ti 23) u ma-am-ma lu-u la-a 24) u-lJ,a-ab-ba-at-Bu-nu-ti 25) a-di i-na lJ,ursiini i-la-ku-ma 26) a-na pa-ni-su-nu ma-am-ma27) lu-u la-a e-el-li 28) u-nu-te lil-la-pi mi-nu-um-me-e 29) e-re-su an- [asJa-am-mi 30) ame11la-za-nu sa Sal-mi-ya 31) li-di-in-na-su-nu-ti."14) And now: 15) concerning (metal) casters, 16) sons (people) of (thevillage) Panistau, 17) I write to you. 18) They have to make their offerings19) into (the village) Beletremi.8 20) And to the charge of the lJ,azannu21) of (the village) Salmiya 22) you must deliver them. 23) And nobodyshall 24) plunder them8625) when they will enter the mountains. 26) Intheir presence nobody 27) shall 28) strive himself after8 (something). 29)The demand of food87(for them) 30): the lJ,azannu of Salmiya 31) has togive it them."Although some passages of the text are not definitively clear, we learnthat people from the village Panistau, from the kingdom of Ugarit, had. to make their sacrifices at Beletremi, outside the kingdom. On their way,the lJ,azannu of the Ugaritic village Salmiya had to protect them and givethem assistance.It is clear that every lJ,azannu was a lULzannu dli, "lJ,azannu of thevillage." He was a royal official, but it is unclear to what degree he wasconnected with the local communal authorities or self-government. It isonly clear that privileged royal servicemen were, at least sometimes, freedfrom his jurisdiction. The lJ,azannu was an official. But, even the com-parative data from the Hittite Empire and Canaan of the EI-Amarnaperiod does not give us a definitive answer about all the functions andprerogatives of the lJ,azannu.87a2. Rb. We do not know the exact Ugaritic counterpart of the Akkadianterm lJ,azannu, but rb is one of the possible alternatives. The literal mean-ing of the is "big," "great." In the list found in PRU, II, 24 (UT,1024) Bev. 3) "one great of the village" (rb. qrt. alyl) is mentioned. PRU,V, 8, 3 (UT, 2008) is a letter written to the king in the name of the rb of a Unknown as a village of the kingdomof Ugarit. Perhaps it was outside theconfines of the kingdombut inside the Hittite zone of political influence.81 AHW, pp. 303---4, contrary to the translation of J. Nougayrol, U. V, p. 93,footnote 4, "shall not imposea tax." "To strive (stretch) himself." Cf. AHW, p. 199, elepu(m) , "sprieJ3en."Although the word concerns mainly the growing of plants, it is the only possibletranslation. J. Nougayrol, U, V, p. 94, note 1, "inconnu"; cf. also Berger, UF, II,1970"p. 286lilepu = "Teil des Pferdegeschirrs anzusetzen." Berger, UT, II, 1970, p. 286, No. 263, line 29. ..'a H. Otten, Aufgabeneines Biirgermeisters in BM, 3, 1964, pp. 91-95.82 Communal Self-government in the Villages Communal Self-government in the Villages 83village.s8The text itself talks about naval affairs. The term rb was usedfor designating "elders" or "chiefs" of various groups of royal servicemen,e.g., rb khnm ("elder of the priests"), rb nqdm ("elder of the shepherds"),rb lj,rsm ("elder of the construction workers"), rab malaljljeM ("elder of theseamen"), etc. Except for the naval affairs discussed in PRU, V, 8, weknow nothing about the activities of the rb of the villages. It is unclearwhat sort of relations existed between the rb and the other branches ofthe local self-government.3. Skn-(Akk. ame1siikinu). This is sometimes written as MA8KIM.stAlthough this term sometimes means the "vizier" (of the whole kingdom)(siikin mati), we may consider only the skn qrt-siikin ali, the villageofficial. According to text PRU, II, 33 (UT, 1033), which is a "list ofblblm" (spr blblm),40 the skn of (the villages) Uskn,8bn, Ubr, and f r ~ b creceived a certain number of clothes from the royal stores. A skn ofUl[m] is also known from the sourees.s!The tablet PRU, V, 11 (UT, 2011) lists, among other people, bnS mlk("royal dependents" (servicemen)) who received food rations (lj,pr) in themonth of Ilt[bnm] (line 1). Listed also are: 10) cplrm. 8mcrgm. ekm. qrt11) lfgbn. 8mc skn. qrt. "10) cplrm (people)4B-8mcrgm-skn of village11) lfgbn (and) 8mc skn's ofvillages."4s To what villages they belonged isunknown. The text shows clearly that the skn qrt were "royal depen-dents."a. 3) t!'-m. rb Mi[lJd (or.[d!JJ) e]bdh ("the message of the great of Mi[!Jd] (orMi[dlJ)) , your servant"). The names of both villages are known in Ugarit. Thereading of O. H. Gordon, UT, p. *4 rb milt] ("head of hundr[ed] (men)") has noprecedence in the texts and is unconvincing.a. This sumerogramm is usually read as r d b ~ but in Syria in the Amarna age,and in Ugarit, it is to be read as 8iikinu. Cf. Hebr. 8oken, Phoen. slcn; W. F. Albright,Two Little Unterstood Amarna Letters from the Middle of the Jordan Valley,BASOR, 89, 1943, pp. 7-17; G. Buccellati, Due noti ai testi Aecadicidi Ugarit, OA,II, 1963, No.2, pp. 224-28; MASKIM-8iikinu, A. F. Rainey, LUMASKIM atUgarit, Or 35, 1961, pp. 426-28; Heltzer, Carskaya Administraciya, p. 222, -apre-liminary study on the 8kn/8iikinu of the dlu/qrit; E. Lipinski, Skn et Sgn dans lesemitique occidental du Nord, UF, III, 1973, pp. 191-207. Meaning unclear. WUS, p. 49, No. 518; UT, p. 372, No. 420; Dietrich, Loretz,BiOr, 23, 1966, p. 129, suppose that it could be the designation of people deliveringtheir grain-text ?), but in our opinion, the text is talking about delivery from theroyal stores of kee, "clothes," for royal dependents.U PRU, II, 93 (UT, 1093) 6) 8kn Ul[m] 9) 8k[n .[, The poor state of preserva-tion of this text precludes the possibility of further conclusions... The meaning of this designation of the professional group is unclear. (Cf. UT,p. 460, No. 1902.).. Plur. st. cstr.We also know that Iribilu, the siikinu of Riqdi,44 dealt with the with-drawal of lands from the nayyiilu in his village and had the right to handthe land over to another person. The siikinu (MA8KIM) Ukulliilanu, ofthe village Milji,46 appears as a witness in one document. EntaSalu, thesiikinu (MA8K1M) of the alu Beru, received the rights to collect thetaxes of the village in his own favour.48 Thus, we have additional con-firmation that the siikinu of certain villages were not elected by the self-government, but were royal dependenbs.s? The very fact that, in Ilstm,royal fields distributed to servicemen were in the hands of the skn is anadditional proof that the siikinu were royal officials.48In conclusion, the analysis of the above terms, ljazannu, rb, and skm,indicates that the difference of synonymy of these terms is as yet unclear,This is because these terms do not appear together in the same text. Whatis clear is that these officials were not elected members of the local popula-tion. They were dependents of the king. Thus, even the councils of theelders were far from democratic institutions being composed, most likely,of representatives of some of the more prominent families... U, V, 9 (RS. 17.61). For more about this text and its full translation of. Ch.IV, pp. 55-56... PRU, IV, 17.28, 26. PRU, III, 16.244. Cf. Ch. III, p. 49 for more details about the tablet... Taking into account the fact that we have no data to indicate that 8kn qrtgoverned more than one village, and that at least eight 8iikinu of villages are namedtogether with the village under their governance, we must drop the notion thatthese 8iikinu governed districts which were independent before merging with Ugarit(J. Aistleitner, Lexikalisches zu den ugaritischen Texten, AOH, XI, 1960, 1-3,p.34)... PRU, II, 104, 1-2) 8d. ubdy. I18tmc. dt. bd. ekn. ("The service-fields in Il8tmC,which are in the hands of the 8kn"); a list of the fields follows.PROPERTY RELATIONS WITHIN THE RURAL COMMUNITYThe Evolution of Property RelationsCHAPTER VII1 Cf. also, the fragment PRU, V, 142, which lists families. A partial analysis ofthese texts is made by M. Heltzer, VDI, 1966, No.3, pp. 203-204.I Unlessotherwise specified the readingis according to O. H. Gordon in UT.857) Agltn. [ypr]y. w. [alth]3) [YJ8dln. qmnzy. w. allth]4) 10 .In . bnh8) w. bnh w. alp. w.[l}inh(?)J1) [AjlJmu. apsty. b[J2) 10 . bnh . w. alth . w. alp10 .lmn .I}in5) Tmgdl. y1cnemy . w. alth6) 10 bnh. . 10 alp. alJd11) [Pr]d meqby[walthj812) Sum, qrty. 10[. alth] 8) Sum, qrty[althwbnh]813) [10]. bnh: w. tn alpm 9) ulj,h. w. esr[l}inh]814) [w]lllm. I}in9) Pln. [lmry]10) w. In. bn[h w. . . .]15) Annf!r . ykncmy16) 10 alth . w. bnh17) 10 . alp. w. ts[e] ~ i nProperty Relations Within the Rural Community4) ~ m t n In[bnh walth]85) w. Ill. alph. [6) Sum, qrty. w.[b]nh[ ]7) w. alph. w. a[rfb.l, arbe[m l}in]88) Pln. lmry. w. In.bnh.w[1) lJ8dd. arty ]2) Belsipa[ry wbnh]3) !cUll,. [ Ja Our reconstruction, based on analogy in the parallel texts.9) Ymrn. apsny f.] w.alth ... bn[h ]11) Prt. mgd[ly. w.tt(?).] at[th10) Prd. meqby [. 10.]a]lth[ ]12) edyn[Walth8]13) w. In[bnh ]14) Iwrm[w]8 bn[h8 ]rev.) Annt[n] w[alth8 ]16) w. tn. bnh, [ ]17) Agltn. ypr[y walthwbnh]-18) w. Bbe. I}inh[ ]CTC, 81 PRU, II, 80 PRU, V, 44l)yd(?).[ ]2) a[]m[In. a[ ]3) w. ant]lb. [ )8We have three tablets on which to base our analysis: PRU, V, 44 (UT,2044), PRU, II, 80 (UT, 1080), and CTC, 81 (UT, 329). All three textsmention the same families, but their property ownership changes fromone text to another. The references to the same persons in all three textsproves that although these texts were composed at different times, therecorded data spans the lifetime of one generation." Unfortunately, it isimpossible to establish the correct chronological order of these texts. Wewill use PRU, V, 44 as the basic text because it is in the best state of pre-aervation.tAs shown above, the rural community of the kingdom of Ugarit wasnot based on equal division of property among its members. We also seethat certain families became nayyalu and were deprived of their land.Several properties were divided among several persons (cf. below). Landtransactions between private persons took place also, and, at least inseveral cases, we are dealing with relatively rich people who possessedmuch land, cattle, slaves, and other property. The council of elders of thevillage was in the hands of some of the prominent families.For people who lost their land, the only way to survive was to enter theroyal service and become royal dependents (bna mlk}, People who boughtland became members of the community in which the land was situated.But, as we have seen above, foreigners did not have the right to purchaseland. Our task in this chapter is to try to discover how property relationsdeveloped within the community among certain families, provided thatthey were not nayyalu, and did not sell or lose their property.86 Property Relations Within the Rural Community Property Relations Within the Rural Community 8711) Prt, [man] of (the village) JJfgdl [and two( ~ 9 his] wives8) Pln man of (the village) ';!'mr and his two sons, and? [...]12) cdyn [and his wife ...] 13) and [his] two [sons ...]6) Sum, man of (the village) Qrt and his [s]on [and his wife]7) and his ox and [fou]rty fo[ur small cattle]8CTC, 81 (without parallel passages)1) lfdd. [man] of (the village) Ar [and ...]4) 'tty, man of (the village) Ar [ ]5) Nrn, man of (the village) Arn [...] 6) and his two sons and [...]7) .. [ ]2) BClsip [man of] (the village) A[r ... and his son] 3) (and) hisdaughter-in-law [...]PRU, II, 80 (without paralleling passages)1) [A]1,mu, man of (the village) Apsn in [ ] 2) and his son, and hiswife, and an ox, and eight small cattle.3) [Y]dln, man of (the village) Qmnz, and [his wi]fe, 4) and his twosons.5) ';!'mgdl, man of (the village) Ykncm, and his wife, 6) and his son, andone ox.17) The man of (the village) 'l'lfl,n, together with [...] (and) x his sons18) together with three [his] daughter-in-[law ...J 19) and sixty smallcat[tie ...]20) ... [ ]11) Plzn, man of (the village) Qrt [... and his son] 12) and his daughter-in-law in T[ ]15) Man of (the village) Ar together with ... [... his daughter]16) son-in-law. Sbcl [ ]13) Bcly [man] (of the village) Mlk [... and his wife] 14) together withhis daughter, together [ ]14) Iwrm [and his] son [ ]15) Ann{!r, man of (the village) Ykncm 16) and his wife, and his son17) and an ox, and nin[e] small cattle.10) Klyn, man of (the village) Apsn [and ...]17) Agltn [man] of (the village) Yp[r and his wife and his son] 18) andhis seven small cattle [ ]1015) Annt[n] and [his wife ...] 16) and his two sons [ ]]]]bthj4]17) '!'Jlj,ny. yd [x bnh]18) yd. tlt. kl[thi19) w. ttm. Iji[n20) t n[ J21) Agyn. [ J22) [ ]. tn. [ J15) Ary. yd. t[16) lJ,tnh. Sbcl [4) Tty. ary. m[ ]5) Nrn amy [ ]6) w. tn. bnh. w. [ ]7) b tn [ ]10) Klyn. apsn[y ]11) Plzn.qrty[ wbnh8]12) w. klth. b. t[ ]CTC.81rev.) Bcly. mlk[wbnh(?)]14) yd. bth. yd[PRU, V, 44PRU, II, 80 PRU, V, 44(Lines 1-3 illegible)4) Q ~ m t n two [his sons and his wife] 5) and his three oxen [ ]9) Ymrn, man of (the village) Apsn and his wife [and his] son[...]10) Prd, man of (the village) Mcqb [and] his wif[e ]8 "His daughter" (bth) must precede the word bJ.n, "son-in-law." klt--Hebr. kalUir-cf. line 12 of the same text. Three "daughters-in-law"indicates from one to three husbands, sons of the 'j'lf:,ny. The reading #1 kl[bm},"three dogs," is unacceptable. PRU, II, 80, "12) Sum man of (the village) Qrt and [his wife] 13) [and] his sonand two oxen 14) [and] thirty small cattle." CTC, 81, "8) Swn, man of (the village)Qrt [his wife and his son], 9) his brother and ten [small cattle 1]."7 PRU, II, 80, "9) [man of (the village) 'j'mr] and [his] two sons [and ..]." PRU, II, 80, "11) [Pr}d, man of (the village) MCqb [and his wife]." The reconstruction of a. H. Gordon, without explanation.21) Agyn. [ 22) [ ] two [Listed here are at least twenty-five heads of families. Unfortunately,the text is broken and we cannot draw conclusions about the sizes of thefamilies, and number of cattle possessed by these families. It is also clearthat these texts contained nothing about land-property ... Perhaps the10 PRU, II, 80, "7) Agltn, man of (the village) Ypr and [his wife], 8) and his sonand ox and [small cattle 1]."88 Property Relations Within the Rural Community Property Relations Within the Rural Community 89amount of land possessed by these families remained constant, and there-fore was not recorded in the lists. On the other hand, the number of cattle,as well as the size of the family, underwent certain changes. Therefore,such lists were rewritten, as we see from the documents presented here.Possibly, they were composed for tax-purposes, or to define the amount ofeorvee-serviee they had to perform.The twenty-five (twenty-four) families are designated as people of atleast twelve different villages: Ar(y), Am, Qrt, 'trnr, Apsn(t), Meqb,Mgdl, Ypr, uu; 'f'llJ,n, Qmnz, Yknem.llIt is characteristic that, beside the head of the household, there is men-tioned only his wife and his son(s), sometimes his daughter and son-in-law,as well as his daughter-in-law. We have to conclude that children whocould not be considered as serious labourers were not mentioned in thetext, which listed only adults. The mention of a son-in-law shows that, incertain cases, he entered the house of the father-in-law. Perhaps this wasconnected with the fact that the head of the family did not have sons.Completely lacking is any mention about slaves in the possession of thesefamilies. Perhaps these families did not possess them.On the other hand, we see that the number of adult sons, who did notyet begin independent households, was small, from 1-3, and the same canbe said of daughters. Only once is a brother of the head of the family men-tioned. Generally speaking, we are not dealing with large patronymics,but with small individual families, although married children were notnecessarily excluded.Cattle is not designated in every family, perhaps partly because of thepoor state of the text making recognition impossible. But we see thatthe number of oxen in one household varied from 1-3, and small cattlefrom 6-60.Concerning the evolution of property, we can state that Swn, man ofQrt, had in one case one ox and forty-four small cattle, and in the secondcase two oxen and thirty small cattle. In the third case he had only tensmall cattle. Agltn, man of Ypr had in one case seven small cattle, and inthe second case one ox and x small cattle.Such a difference in the number of cattle in the possession of variouspersons, as well as in the possession of the same persons, at different times,is also confirmed by the text PRU, V, 39 (UT, 2039) (cf. Ch. II, pp. 43-44)where five people of the village ,!,Itpaid from five to ten small cattle eachas their tax.11 After 5 personal names the place-name of their origin is broken.Additional Lists of Families of the VillagersWe must exclude from this study the texts listing the families of royaldependents. The number of lists mentioning the villagers of Ugarit withtheir families is limited.PRU, V, 80 (UT, 2080)1) bn, Beln. Biry 2) tlt belrn 3) w. adnkm. tr. w. arb. bnth.4) YrlJ,rn. yd. tn. bnh 5) bclrn. w. tlt. nsrm, w. bt. alJ,t.6) bn. Lwn. tlttm. belm7) bn. Bely. tlttrn. bslm. 8) w. ahd, lJ,bt 9) w. arb, att10) bn, Lg. tn. bnh. 11) belm. w. al:J,th 12) b Srt.13) Sty. w. bnh."1) Bn. Bsln, man of (the village) Bir, 2) three workmen.P 3) andtheir lord (may be' overseer) ']'r,12& and his four daughters4) YrlJ,m, together with his two sons, 5) two workmen.P and threeyouths14and one doughter.6) Bn. Lwn, SiX16workmen.7) Bn. Bely, SiX16workmen, 8) and one YUpSu-man189) and fourwives (or "women").10) Bn. Lg. two sons, 11) two workmen, and his sister, in (the village)Bri.11) Sty and his son."This text consists of a list of six families. One family was from thevillage of Bir, another was from Brt. The wife (or wives) of the head of thefamily are not always mentioned. But other members of the family, sons,daughters, and various categories of dependents, are listed. They arenerrn "youth," bslm. "workmen," lJ,upSu. No maidens are mentioned,including daughters who were not yet married. The number of sons perfamily was 1-2, daughters, up to four. In one case, the head of the family11 Cf. Oh, ViroUeaud, PRU, V, p. 106, on the interchange of b/p in Ugaritic;bel/pel, P. Fronzaroli, La fonetica Ugaritica, Rome, 1953; O. H. Gordon, UT, pp.35-5.28; p. 375, No. 494; Leslau, Observations, p. 351; M. Weippert, UF, VI, 1974,p.417.11& Ir-here a personal name--cf. ZUL, XI, p. 38, No. 117.13 Dual form.U May be children, but "dependents" also possible. Cf. Biblical-Hebrew nasar;M. Heltzer, Slaves, p. 86.11 Illtm, "three" in the dual form.U f.iblpt--Akk. &me1ltupsu-the exact sense of this term in Ugarit is not clear;a kind of dependent people; a analysis of this term is found in ZUL, XI, pp. 26-27.No. 44.90 Property Relations Within the Rural Community Property Relations Within the Rural Community 91has an unmarried sister in his house. It also seems that minor childrenwere not mentioned. It is also important that the text comes from theroyal archives. This underlines the fact that these people had to paytaxes and perform their oorvee, Neither the land nor the cattle of thesepeople is mentioned here.It is significant that the twenty-five families listed in the three textsgiven above, had no slaves or dependents. At the same time, of the sixfamilies mentioned in PRU, V, 80 (UT. 2080), five of them had suchdependents. Five families out of the total of thirty-one represents 17percent of the families which had dependents. The total number ofdependents was twenty-three, thus, there were 4,5 persons per family-household. Unfortunately, it is impossible to say whether such an averagegives us a true picture of the size and structure of the household in thevillages of the kingdom of Ugarit.We have also seen above (Ch, IV, pp. 52-58) that such people lost theirland to the royal authorities if they became debtors or did not performtheir obligations. They could also be taken abroad as slaves in cases wherethey could not repay their debts to foreign creditors. But even in suchcases, their lands, as seen from text PRU, IV, 17.130, remained in thehands of the king of Ugarit; it was not turned over to foreigners. The factthat royal servicemen received land-holdings in Ugarit is not in contradic-tion with this.!" Such royal servicemen could become Ugaritians throughland purchase, but only if they were royal dependents (bn.s mlk) of theking of Ugarit.The Relation of Individual Households to the CommunityAs we have seen above, in the nayyalu-texts (Ch. IV, pp. 52-56), peoplewho, in some cases, received land-holdings which were community landswithdrawn from the nayyalu, had to perform the "corvee of his house"(pil-ku btti-su, or unuBsa-bUi).18Naturally, such family possessions could be sold,19 bought, and in-17 Cf. A. F. Rainey, A Social Structure, pp. 87-91. Rainey makes no differencebetween holdings and property and, therefore, he states that foreigners were land-owners in the kingdom of Ugarit.lS PRU, III, 15.89, 20-21; 16.262, 10-11.lS R. Haase, Anmerkungen zum ugaritischen Immobilienkauf, ZA, 14 (58),1967,pp. 9 6 2 ~ a l l documents including PRU, IV; M. Heltzer, Some Questions of theAgrarian Relations in Ugarit, VDI, 1960, No.2, 86-90 (Russian); additional tabletsU, V, 4 (RS. 17.20); 6 (RS. 17.149); 159 (RS. 17.86); 160 (RS. 17.102); 161 (RS.heritedw within the community. Unfortunately, we do not always know,when such transactions were made, in which dlu{qrt they occured. Butthe formulae referring to the obligations of the house clearly point outthat it was within a certain village-a rural community.1. PRU, III, 15.156 relates that a woman Batrabi, and 8ubammu,both "children of (a women) Layawa" (m[dre]M fLa-ya-a-wa) sold 20iku of land in &l,!,ibaqu to a "(women) Talaya, daughter of [x] tTa-la-yamarat [x]) for 420 sheqels of silver. Further, it is said that 11) i[l-kau] pil[-ka 18u-ub-am-mu u] 12) rBat-ra]-ab-i [ubbalu(?)J 13) P8]u-ub-am-mu 14) [u] IBat-ra-ab-i 15) u-nu-uB-sa u-ba-lu,"11) the il[ku-servioe (oorvee) and] pil]-ku servioe (eorvee) 8ubammuand] 12) [Batr]abi [shall perform]. 13) [8]ubammu 14) [and] Batrabi15) shall perform the unussu-servioe (oorvee)."81Most interesting in this text is that the obligations remain on the re-sponsibility of the former owners of the land. They have to perform theobligations, and they formally remain the oommunity members. Thequestion is, who reoeived the rights 12. PRU, III, 16.14. Aooording to this text, Nuriyanu (the brother ofthe king) made an exohange of land with a certain Layo,. Layo, gaveNuriyanu, not his own field, but one of his holdings, the field of Abdinikal,son of Ananiya. As a result of the exchange, "11) Nuriyanu was free12) from the pilku of the house of Abdinikal." (11) u-za-ki 'Nu-ri-ya-nu12) is-tu pil-ki bit 'Abdi-ni-kal.) This. may indioate that one of the formerowners (Laya or Abdinikal) had to perform this servioe.113. PRU, III, 16.167. This text relates that king NiqmadduII handedover the lands of two persons to Anate8ub. The latter had to pay to theking 200 sheqels of silver, as also "he performs the unuBsu of the houses(households)." (17) u u-nu-so, bUa-tiM ub-bal.) So Anate8ub took uponhimself the former owners' obligations within the community. We do notknow in which dlu these households were located.4. PRU, III, 15.123. We learn from this text that two persons,Anatenu and Yayanu, son of Ayalu, made a land exchange. Anatenu17.325)-the latter are three cases are land purchases by the queen-mother ofUgarit; PRU, VI, 40 (RS. 17.360).I. Fr. Thurean.Dangin, Trois contrats de Ras Shamra, "Syria," XVIII, 1937,p. 249, RS. 8. 145, The Testament of Yarimanu.11 ilkulpilkulunu88u, of, Ch. IV note 4; the difference between these terms is notyet recognized. The latest study is by M. Dietrich, O. Loretz, Pilku = Ilku "Lehns-pflicht," UF, IV, 1972, pp. 165-66, but it does not explain the etymology of theterm.,II Cf. PRU, III, 16.133, a fragment where, according to the remnants of thetext, the problem could be the same.92 Property Relations Within the Rural Community Property Relations Within the Rural Community 93added [x] sheqels of silver for the more valuable field he received fromYayanu. But Yayanu remained obligated in that "he had to perform thepilku-service of his house(hold)." (18) it, IYa-ya-nu pU-ka 19) bUi-8aub-bal.)5. PRU, III, 16.246. A land-exchange between ljuttenu, son of AlJa-maranu, and YapaAarru, son of Sinaru, is the subject of this text. Thetext states that, "his pilku-service of these fields Yapasasr shall notperform." (15) it, pilka-81t8a eqliitiM8u-wa-ti 11) IYapa-8arru u-ul u-bal.)286. We also know of purely private land transactions inside the com-munity. PRU, III, 15.136 mentions a certain Kalbiya, son of Kabityanu,who sold six iku for 520 sheqels to a certain Kurwanu, son of Baalazki.The lands were totally freed from pilku-service.u7. PRU, I I I, 16.1 54. This text demands more serious consideration.1) i8-tu 'mimi an-ni-im 2) a-na pa-ni IAm-mis-tam-ru mdr Niq-me-pa3) 8ar al1J-ga-ri-itKl 4) IAbdi-milku mdr Din-ni-ya 5) ip-Bu-ur eqilM-8ui'kariiniM-su 6) i'serdiM-su bitdimta-su 7) sa i-na nBrNa-a"b--ra-ya 8) a-nafUm-mi-a,i-bi 9) i-na 7 me-at 40 kaspi 10) eqluM~ m i i d i-na u8amSiumi mill ) a-na fUm-mi-a,i-bi 12) it, a-na mdreM-sa 13) a-di da-ri-ti 14) ameluma-am-ma-an ul i-la-qi-Bu 15) is-tu qatiUfUm-mi-a,i-bi 16) it, is-tu qatiUmdreM-sa17) it, pU-ka ya-nu i-na eqliMan-ni-i sa narNa-a"b--ra 18) sa-ni-tamIPU-8U it, IAbdi-milku 19) 2 mar IA"b-i-milku 20) ip-Bu-ru-nim 2 ikt %eqlaH21) qa-du i'serdiM-8u 22) i-na eqliM narNa-a"b--ra-ya 23) a-na [flUm-mi-lJ,i-bi 24) i-na 1 me-at 30 kaspiM 25) 2 ikU %eqluMan-nu-u ~ m i i d i-nau8amSi 'mimi 26) a-na fUm-mi-a,i-bi Ua-na m d r ~ s a-di da-ri-ti 27) ameluma-am-ma-an la i-la-qi-su 28) is-tu qatiU'Um-mi-lJ,i-bi 29) uis-tu qatiUmareM-8a 30) it, pU-ka ya-nu i-na 2 ikt % eqliM an-ni-i 31) abBnkunukIA-mis-tam-ri mdr Niq-me-pa 32) 8ar &11J-ga-ri-it."1) From the present day, 2) before Ammistamru, son of Niqmepa,3) King of Ugarit: 4) Abdimilku, son of Dinniya 5) sold his field, hisvineyard, 6) his olivetrees, his dimtu (farmhouse), 7) which are located (inthe district) of the river Na"b-raya, 8) to Ummi"b-ibi 9) for 740 (sheqels) ofsilver. 10) The field is in the possession- as the daylight- 11) of Ummi"b-ibi12) and her sons 13) forever. 14) Nobody shall take (it away) 15) fromUmmi"b-ibi 16) and from her sons. 17) And these fields in the district ofNa"b-ra have no pilku (service). 18) Further: Pilsu and Abdimilku, 19) twosons of A"b-imilku 20) sold 2.5 iku of field 21) together with their olivetrees 22) located (in the district) of Na"b-raya 23) to Ummi"b-ibi 24) for 130.. Cf. also, the damaged tablet PRU, III, 15.143. Cf. also, PRU, III, 15.145--a land transaction with total exemption frompilku.service. See also PRU, III, 15.140; 16.134; 16.256.(sheqels) of silver. 25) These 2.5 iku of field are 26) -like daylight- in thepossession of UmmilJ,ibi and her sons forever. 27) Nobody shall take it28) from UmmilJibi 29) and from her sons. 3) And these 2.5 iku of fieldhave no pilku-service. 31) The seal of Ammistamru, son of Niqmepa,32) king of Ugarit."In this text we have seen that Ummi"b-ibi purchased two plots of land inthe same district. But, the land was free from labour or service. Whetherthe land was totally free, or the former owners sold only a part of theirland and continued to perform their obligations as previously, is notdefinitively clear. It seems that the latter possibility is more reasonable.It is partially oonflrmed by the text PRU, III, 16.343.1) i8-tU 'mimi an-ni-im 2) a-na pa-ni IA-mis-tam-ri mdr Niq-me-pa3) sar &11J-ga-ri-itKI 4) fUm-mi-lJ,i-bi ti-it-ta-aA-si 5) eqla qa-du b1tdimti-sui'kariiniM-su i'serdiM-su 6) sa i-na 18-si-qi 7) it, ti-it-ta-din-su-na 8) a-naI A -na-te-na mdr A8-mu-wa-na 9): ta-ap-de,-ti eqliM-8u 10) it, I A -na-te-nitmdr A8-mu-wa-na 11) it-ta-aA-8i eqlaM-su i'karaniM-su 12) qa-du bltdimti-sui'serdiM-8u 13) 8a i-na Na-[a}"b--ra-ya 14) uit-ta-din-8[u-n}u 15) a-na t Ummi-a,i-bi 16) eqluH~ m i i d a-na fUm-mi-a,i-bi 17) it, a-na mareM-8ait,pil-ka-8U ya-nu 18) it, IA-na-te-nu pil-ka bUi-8U 19) it,-ba-al 20) &bankunukIA-mis-tam-ri mdr Niq-me-pa 21) 8ar &l1J-ga-ri-it."1) From the present day: 2) before Ammistamru, son of Niqmepa,3) King of Ugarit: 4) Ummi"b-ibi withdrew 5) the field, together with herdimtu (farmhouse), her vineyard, her olive trees,25 6) which are located in(the village) 188iqi287) and gave them 8) to Anatena, son of A8muwana9) -as an exchange of his field. 10) And Anatenu, son of A8muwanu11) withdrew his field, his vineyard, 12) together with his dimtu, his olivetrees, 13) which are located in (the district) of NalJraya 14) and gavethem 15) to UmmilJibi. 16) The field is in possession of UmmilJ,ibi 17) andof her sons. And there is no pilku (servioe-corvee) ofit.2718) And Anatenuhas to perform the pilku 19) of his house. 20) Seal of Ammistamru, sonof Niqmepa, 21) King ofUgarit."Again, it is clear that Ummi"b-ibi received land free from oorvee-service,At the same time, Anatenu had to perform the pilku (service or oorvee) ofhis house. It also seems clear, that UmmilJ,ibi had the privilege of pur-chasing land, and, at the same time, was freed from obligations and taxes, The suffix, -au, suff. pers. pron, 3 sg. maso. by mistake instead of -8a, suff.pers. pron. 3 sg. fern . Ii8iqi or Iiqi, a known Ugaritic village, appears here without the determina-tive.If Of these fields.94 Property Relations Within the Rural CommunityProperty Relations Within the Rural Community95while commoners, members of the rural community, had to perform or todeliver the service for their house, in the framework of the communityobligations.9. PRU, III, 16.261, dated by the same reign as the former text,relates that, 4) t La-e-ya-a u [II1l2Addu-mi -is-la-am 5) u f mdruM-sa 6) il-te-qu-u eqla 7) sa I Ya-ap-lu-na 8) usa '.fJi-is-mi-ya-na9) u sa IUz-zi-na 10) usa 'Su-ub-am-m[i] 11) mdreM'S[d]-s[i]-y[a]-n[a12) qa-du b1tdirntiKI [ ...] 13) qa-du l'serdiIM) 14) qa-du l'kariiniM [ ]15) qa-du gab-bi [m]i-i[m-mu-su] 16) i-na 2li-im 2 me-at [. .. kaspi]."4) Laeya and AddumiSlam, 5) and (the woman) her children6) purchased the field 7) of Yaplunu 8) and of QiSmiyanu 9) and ofUzzinu 10) and of Subammu- 11) the sons of S[a]s[i]y[a]nu 12) to-gether with the dimtu (farmhouse), 13) together with the olive trees [...]14) together with the vineyards [ ] 15) together with all they possess16) for 2200 [(sheqels) of silver]."According to the standard formulae of ownership, the text points out,15) u pil-ku [y]a-a-nu 26) i-na eqliMan-ni-i ("and these fields have nopilku (service or oorvee). The seal and name of the scribe are following.")Perhaps formerly, the owners had to perform certain obligations for thesefields.As we have seen, the households in the rural communities of Ugarithad to perform certain obligations. Naturally, they were those same ob-ligations as were listed when we dealt with the community obligations asa whole.The texts given above offer us a certain amount of information aboutlandowning by small collectives of relatives. This brings us once more tothe problem of patronymies in the rural communities of thekingdom of Ugarit. In order to better understanding of this problemwe must analyze some additional texts.10. PRU, III, 15.182. This tablet, badly damaged, relates, that atleast two persons, who are designated as mdreM01 [x] ("sons of [x)"),sold to Uzzina, the siikin mdti ("the vizier of the land (of Ugarit)"),fields for ninety-five sheqels of silver. It is clear that the sellers werebrothers.11. U, V, 159 (RS. 17.86).1) is-tu 2'l1mi an-ni-i-im 2) a-na pa-ni amelM2stbiitili 3) '2Ili' L ya mdr'Si-ni-ya 4) u 'Pa-di-ya abn--su 5) u mdreM-su-nu 6) ip-sur-nim 4 eqilM-su-nu 7) sa i-na eqliM 8) i-na 1 me-at 80 kaspiM 9) a-na fSar-el-li10) sarrati 4 eqluM i-na IISamSi"u 12) 2'l1mi a-na fSar-el-li sarrati13) a-di da-ri-ti (Lines 14-19 names the witness and the scribes)."1) From the present day, 2) before the witnesses, 3) Iliya, son ofSiniya 4) and Padiya, his brother 5) and their sons 6) sold 4 (iku) oftheir field 7) which are located among the fields of (the village) 8) for 180 (sheqels) of silver 9) to Sarelli, 10) the queen.s" 4 (iku) of field11) are in the possession- like daylight- 12) of Sarelli, the queen 13)forever."The text, U, V, 160 (RS. 17.102) is incorrectly written. The queenbought land from 3) mdruruIPu-lu-lu-na ("the son of Pululuna"), but thenext line relates that, "he sold their fields" (4) ip-sur eqilM-su-nu). Thus,it is possible that here we have a case, similar to those above, in whichland was sold by a collective of owners-relatives.The scarcity of the sources obscures the real number of larger families,patronymies, in the villages of the kingdom. When we take the lists offamilies given above (pp. 85-90) we see only that the number of brothersbelonging to the family was not a large one. It is also impossible to deducethe real percentage of these patronymies. But, we see from the landsaletransactions: a) (PRU, III, 15.156) a brother and sister sold their land,belonging to them collectively; b) (PRU, III, 16.154, 18ff.) two brotherssold their common land to the woman UmmilJibi; c) (PRU, III, 16.261)One woman, together with her sons and daughter, purchased the land offour brothers, sons of Sasiyanu; d) (PRU, III, 15.182) Two brothers soldtheir collective land to Uzzinu; 3) (U, V, 159) Two brothers, togetherwith their sons, sold their land to the queen (cf. U, V, 160 also).Thus, we can see that, at least in some cases, there were traces of col-lective landownership by patronymies-the so-called "undivided broth-ers." It is also interesting to note, that women were among the purchasersof the land, as well as among the former owners. This feature is alsoknown from other Ugaritic texts. It may be added, that in Ugarit therights of women were almost the broadest in the ancient Near East.30The presence of "undivided brothers," or to be more exact, "undividedfamilies," among the basic population of the villages of Ugarit, also ap-"' The determinative is lacking. 1!gar. 'l'ryl, of, Nougayrol, U, V, pp. 261-62; Liverani, Storie, p. 237ff.Sarelh-'l'ryl seems to be the queen-mother during the reign of AmmiBtamru II. Onthe role of the queen-mother in Ugarit, ef, H. Donner, Art und Herkunft des Amtesder Konigin-Mutter im Alten Testament, Festschrift J. Friedrich zum 65. Geburts-tag am 27. VIII. 1958, Heidelberg, 1959, pp. 105-45. J. Klima, Untersuchungen zum ugaritischen Erbrecht, ArOr, XXIV, 1956,pp. 356-74; J .. Klima, Die Stellung der ugaritischen Frau, ArOr, XXV, 1957, pp.313-33; J. Klima, Le statut de la femme a Ugarit d'apres les textes accadiens deRas-Shamra, RSJB, XI, 1959, pp. 95-105nAmlk).1. PRU, III, 16.129.1) iB-tu umiml an-ni-i-im 2) IYa-an-lJa-nu mar Tdk-ka.-na 3) u-za-kiINu-ri-ya-na mar-.m 4) is-tu bUill-su iB-tu 5) eqliitiM-su is-tu gab-bi mim-mu6) sa la-bi-suSI za-ka. INu-ri-ya-nu 7) it, 25 kaspu eli sa (?) 8) INu-ri-ya-nasa 9) [8i(?)]-ir-ku kasap (?) la-bi-suSI 10) (sum-m]a ur-ra-am se-ra11) amelMalJ,!J.eM sa INu-ri-ya-na 12) i-tu-ur a-na INu-ri-ya 13) 50 kaepeli-su-nu 14) it, 8um-ma INu-ri-ya-nu 15) i-tu-ur a-na bUla-bi-8uSI 16) 10kaspu eli-su (Lines 17-19 state the names of the witnesses and thesoribe.)."1) From the present day, 2) YanlJan comprehendable.2. PRU, III, 15.90. This text was composed in the presence of kingNiqmaddu II.5) II-lJi-ya-nu mar Si-na-ra-na 6) zitteMzi-te 7) 8a 8) it-ta-din-ma-mi 9) it, za-ku-nim. 10) is-tu mu!J.lfi 11) it, iB-tu mu!J,b-i81 Determinative of masculine personal name--scribal error.mareM-su 12) za-ki amelum1u miB-tu mulJ,ifi amelum1um13) ma-am-ma mi-im-ma 14) amelum1u m a-na muMJ,i amelum1u m15) la-a i-ra-gu-um 16) sadi-na 17) 1 bilat kaspeM18) it, lli-im 19) a-na i-din 20) it, bU-.meqliitM-su 21) a-na alJi-su 22) abankunukkusa sarri."5) IlJiyanu, son of Sinaranu 6-8) divided plots of land (allotments) tohis brothers. 9) And they are freed (lit. "pure") from IlJiyanu and 11) fromhis sons. 12) Everybody is free from everybody. 13) Nobody shall raisedemands 14) to anybody 15) about somebody. 16) (If someone) raises alegal case, 17) 1 talent of silver 18) and 1000 (sheqels) gold 19) he sha.llJiyanu,possibly the elder brother, divided the plots. his broth.ez:". (Therewere at least three brothers in all.) Thus, this IS a case of the diVISIOn of apatronymy after the death of the father.3. U, V, 7 (RS. 17.36).1) is-tu. umi ml an-ni-i 2) a-na pa-ni amelMsbiitiMlI 3) IA-ba-zu-ya si-im-tibUill-su i-si-im 4) a-nu-ma i-na eqliM: ra-ba-ti 5) iBtenenikU eqli a-na rabUIAbdi-i-li ad-din-su 6) it, bUu-ya eqluM-ya 7) gab-ba mim-mu-ya 8) a-nabi-ri 9) bi-ri IUz-zi-na 10) sa-ni-tam sum-ma I Abdi-i-li 11) tup-pasa-na-a it-ta-si 12) 1 li-im kaspu eli-su (Lines 13-17 names the four wit-nesses and the scribe)."1) From the present day, 2) before witnesses 3) Abazuya fixed thefate of his house.88 4) "So from my large field 5) one iku of field I give myelder (son}' Abdiili. 6) And my house, my fields, 7) all that I possess,8) between Abdiili 9) (and) between Uzzinu (I divide). 10) Further:.IfAbdiili 11) produces another tablet,aa 12) 1000 (sheqels) of silver to him(to his father he shall pay)."We learn from this text that the elder son received a personal gift before (RS. 17.30). This damaged text also seems to be a documentconcerning the division of an inheritance between the sons of a certainAbimilku, son of {x] (IA -bi-milku mar (?]). At least one of the sonsreceived a slave (ardu) and the expression, V'5) i-na be-ri 3 mare!>L{SU'3 iimtu here is not "price," but "the fate," contrary to J. Nougayrol, U, V,p.ll . Changes the conditions of the contract.98 Property Relations Within the Rural Community Property Relations Within the Rural Community 99(?)] 6') rabubl ki-ma rabflti-su [ ...] ("between [his] three sons 6')the elder one, according to his seniority [ ]") seems to confirm that thisdocument is similar to the previous one.5. U, V, 83 (R8. 20.146). This text is also only partly legible:1) is-tu 2u[m]i an-ni-i-im 2) a-na pa-ni ameIMsi-bu-ti 3) IKur-wa-naa-kanona iq-ta-bi 4) ma-a INu-me-nu INu-ri-nu IAbdi-ili 5) mareM-ya it[. .. ]"1) From the present d[a]y 2) before witnesses: 3) Kurwana declaredthe following: 4) "Concerning Numenu, Nurinu and Abdiili, 5) my sons[...]" From line 6, which is damaged, it is possible to understand thatNumenu and Nurinu had, in one case, 7) 1 me[-a]t kas[p]aMu-ma-al-[li]8) i-[n]a qati alJ,lJeM-su 9) it 10) [ionia iaa[s]at IN[u-rina(?) ("the silver of the wife of Nurinu?"), and alsomentions a "house" (bit) and "field" (eqlu). Therefore, it seems that thistext also is a document about the division of property, and it also dealswith patronymic traditions.6. PRU, VI, 40 (R8. 17.360). This tablet, composed in the presenceof the scribe, Munay,imu, seems to date from the time of Ammistamru 11.84Unfortunately, the text is damaged.85 We learn only that it was composedin the "presence of witnesses," and that a certain 4) IUk-te-[xx] didsomething with 100 sheqels of silver and "the house of [his n father"(5) btl a-bi[-su?]). Probably, it was a division of property with his broth-ers, for he had, in a certain case, 22) 3 me-at k[aspa] a-na qati ay,y,[eM- ...] ("22) (to pay) 300 sheqels of silver to [his] brother[s]").7. PRU, VI, 50. (R8. 17.388).1) is-tu umiM a[-na-]ti(?) 2) a-na pa-ni amelsi-bu-ti 3) IA-kut-te-nu4) it IA-mi-ya-nu 5) it t Bu-ro-ka-na ay,i-su 6) u-za-ki ITu-tu ay,i-su-nu 7) 20kaspa e-na-da-ni 8) ITu-[t]u 9) i-na IA-ku-te-nu 10) it i[-na] IA-mi-ya-n[a] 11) it i-na [1]Bu-r[a]-k[a-na] 12) U u-za-ki IT[u]-t[u] 13) is-tuay,i-su a-da-[ri-ti] 14) summa u-ra si-r[a] 15) e-te-e-nu a-na libbibLsu-nu16) it te-sa-bi-tum. ITu-tu 17) 50 kaspa u-ma-la-e 18) i-na qati ITu-tu19) 50 kaspa u-ma-la-e i-rna qati-su(??)J 20) it Tu-tu u-[x(?)-]z[aJ(?)-[kif?)].O' J. Nougayrol, PEU, VI, p. 41... Cf. also, the badly damaged PRU. VI, 49 (ES. 17.378A)."1) From the [pre]sent day 2) before witnesses: 3) Akuttenu 4) andAmiyanu 5) and Burakanu his brother 6) freed (lit. "purified") Tutu,their brother.8s 7) 20 (sheqels) of silver they gave {them) (1).37 8) Tutu9) from Akutenu 10) and [fro]m Amiyan[u] 11) and from Buraq[anuj3s12) and they freed Tu[u]t[u] 13) from their brothers (1)39 forever.w14) If in future41(if) 15) they shall retu.rn48to their decision (= changetheir mind) 16) and theyshall seize43Tutu, 17) they shall pay 50 (sheqels)of silver 18) to Tutu. 19) 50 (sheqels) of silver they shall pay to him20) and Tutu is fr[ee]d."The scribe responsible for this tablet, (stbu IAbi-malku ame1tup-pu-sa-ru) "27) witness, Abimalku the scribe,"" participate Iandsale, in which the purchaser wouldneed a more exact definition of the confines of his possession. Here we aredealing with family property and a legal act inside the family, well withinO' We have to understand this as meaning that all the three persons werebrothers of Tutu... Instead of inadinu-Bu, "they gave him."a. It is impossible to agree with the translation of J. Nougayrol, "a(! ) Akkutenu,et a( l) Ammiyanu, et a(!) Burak[anu]," "to(!) Akkutenu and to(!) Ammiyanu andto(l) Burak[anu].' , Tutu was not the person who had to pay, it seems that ina("to, into") is here by error instead of iBtu ("from").O. ahi.8u, lit. "his brother," instead of ahheM-8u. a:da-[ri-ti], spoiled spelling of a-di U ur-ram Be-ram,lit. "tomorrow (and) the day after tomorrow," in the sense of"in future." This was a generally accepted formula in hundreds of legal texts fromUgarib, in this case u-ra Bi-ra is a spoiled spelling... ete-e-ru, instead of u-taar-ru... Here "you shall seize" in bad orthography.II Instead of tupBarru, tupuAarru; cf. the same opinion on the half-illiteratescribe, Rainey, lOS, III, 1973, p. 39nA mlk},1. PRU, III, 16.129.1) is-tu dmiml an-ni-i-im 2) IYa-an-lJ,a-nu mar Tdk-ka4-na 3) u-za-ki1Nu-ri-ya-na mar-su 4) is-tu bili t1-su is-tu 5) eqlatiM-su is-tu gab-bi mim-mu6) sa la-bi-su8lza-ka4 INu-ri-ya-nu 7) it, 25 kaBpu eli sa (?) 8) INu-ri-ya-nasa 9) [8i(?)]-ir-ku kaBap (?) la-bi-su8l10) [8um-m]a ur-ra-am se-ra11) sa INu-ri-ya-na 12) i-tu-ur a-na INu-ri-ya 13) 50 kaepeli-Bu-nu 14) it, sum-ma INu-ri-ya-nu 15) i-tu-ur a-na bit la-bi-Bu8116) 10kaBpu eli-su (Lines 17-19 state the names of the witnesses and thesoribe.)."1) From the present day, 2) YanlJ,an eomprehendable.2. PRU, III, 15.90. This text was composed in the presence of kingNiqmaddu II.5) II mar Si-no-ro-na 6) zitteMsi-te 7) sa 8) it-ta-din-ma-mi 9) it, za-ku-nim 10) is-tu mulJM II-lJi-ya-na 11) it, is-tu mulJlJi11 Determinative of masculine personal name-scribal error. 12) za-ki amelum1umis-tu amelum1um 13) ma-am-ma mi-im-ma 14) amelum1um a-na amelum1um 15) la-a i-ra-gu-um 16) sadi-na 17) 1 bilat ka8peM18) it, lli-im 19) a-na sarrir li-din 20) it, bit-Bu eqlatM-su 21) a-na al]i-su 22) abankunu1c1cu sa sarri."5) IMyanu, son of Sinaranu 6-8) divided plots of land (allotments) tohis brothers. 9) And they are freed (lit. "pure") from IMyanu and 11) fromhis sons. 12) Everybody is free from everybody. 13) Nobody shall raisedemands 14) to anybody 15) about somebody. 16) (If someone) raises alegal case, 17) 1 talent of silver 18) and 1000 (sheqels) gold 19) he sha!lJ,iyanu,possibly the elder brother, divided the plots. his ..(Therewere at least three brothers in all.) Thus, this IS a case of the division of apatronymy after the death of the father.3. U, V, 7 (R8. 17.36).1) is-tu4 dmi ml an-ni-i 2) a-na pa-ni amelMstbiZtiMti 3) IA-ba-zu-ya si-im-tibUiti-su i-si-im 4) a-nu-ma i-na eqliM: ra-ba-ti 5) isteneni1cd eqli a-na rabdIAbdi-i-li ad-din-su 6) it, bUu-ya eqluM-ya 7) gab-ba mim-mu-ya 8) a-nabi-ri IAbdi-i-li 9) bi-ri IUz-zi-na 10) sa-ni-tam sum-ma I Abdi-i-li 11) tup-pasa-na-a it-ta-si 12) 1li-im kaep eli-su (Lines 13-17 names the four wit-nesses and the scribe)."1) From the present day, 2) before witnesses 3) Abazuya fixed thefate of his house.81 4) "80 from my large field 5) one i1cu of field I give myelder (son}' Abdiili. 6) And my house, my fields, 7) all that I possess,8) between Abdiili 9) (and) between Uzzinu (I divide). 10) Further:.IfAbdiili 11) produces another tablet,88 12) 1000 (sheqels) of silver to him(to his father he shall pay)." .We learn from this text that the elder son received a personal gifbbefore (R8. 17.30). This damaged text also seems to be a documentconcerning the division of an inheritance between the sons of a certainAbimilku, son of [x] (IA-bi-milku mar I?]). At least one of the sonsreceived a slave (ardu) and the expression, V'5) i-na be-ri 3 mareM-[su Aimtu here is not "price," but "the fate," contrary to J. Nougayrol. U. V. p. II..3 Changes the conditions of the contract.98 Property Relations Within the Rural Community Property Relations Within the Rural Community 99(?)] 6') rab'l2bl ki-ma rabiiti-su [. ..] ("between [his] three sons 6')the elder one, according to his seniority [ J")seems to confirm that thisdocument is similar to the previous one.5. U, V, 83 (R8. 20.146). This text is also only partly legible:1) is-tu 2-a[m]i an-ni-i-im 2) a-na pa-ni ameIMsi-bu-ti 3) IKur-wa-naa-kanona iq-ta-bi 4) ma-a INu-me-nu INu-ri-nu IAbdi-ili 5) mdreM-ya it[ ...]"1) From the present d[a]y 2) before witnesses: 3) Kurwana declaredthe following: 4) "Concerning Numenu, Nurinu and Abdiili, 5) my sons[...J" From line 6, which is damaged, it is possible to understand thatNumenu and Nurinu had, in one case, 7) 1 me[-a]t kas[p]aMu-ma-al-[li]8) i-[n]a qdti 9) it 10) [i-n]a I$su-qi-riia8[s]at IN[u-rina(?) ("the silver of the wife of Nurinu?"), and alsomentions a "house" (bU) and "field" (eqlu). Therefore, it seems that thistext also is a document about the division of property, and it also dealswith patronymic traditions.6. PRU, VI, 40 (R8. 17.360). This tablet, composed in the presenceof the scribe, MunalJ,imu, seems to date from the time of Ammistamru 11.84Unfortunately, the text is damaged.85Welearn only that it was composedin the "presence of witnesses," and that a certain 4) IUk-te-[xx] didsomething with 100 sheqels of silver and "the house of [his I] father"(5) btl a-bi[-su?f). Probably, it was a division of property with his broth-ers, for he had, in a certain case, 22) 3 me-at k[aspa] a-na qdti su ...] ("22) (to pay) 300 sheqels of silver to [his] brother[sJ").7. PRU, VI, 50. (R8. 17.388).1) is-tu -amiM a[-na-]ti(?) 2) a-na pa-ni ame1si-bu-ti 3) lA-kut-te-nu4) it IA-mi-ya-nu 5) it IBu-ra-ka-nu 6) u-za-ki ITu-tu aM-su-nu 7) 20kaspa e-na-da-ni 8) ITu-[t]u9) i-na IA-ku-te-nu 10) it ilona] IA-mi-ya-n[a] 11) it i-na [i]Bu-r[a]-k[a-na] 12) it u-za-ki IT[u]-t[u] 13) is-tu a-da-[ri-ti] 14) summa u-ra si-r[a] 15) e-te-e-ru a-na libbibl-su-nu16) it te-sa-bi-tum. ITu-tu 17) 50 kaspa u-ma-la-e 18) i-na qd,ti ITu-tu19) 50 kaspa u-ma-la-e i-rna qati-su(??)] 20) it Tu-tu u-[x(?)-]z[aJ(?)-[kif?)].. J. Nougayrol, PRU, VI, p. 41.3' Cf. also, the badly damaged PRU. VI, 49 (RS. 17.378A)."1) From the [pre]sent day 2) before witnesses: 3) Akuttenu 4) andAmiyanu 5) and Burakanu his brother 6) freed (lit. "purified") Tutu,their brother." 7) 20 (sheqels) of silver they gave (them) (?).37 8) Tutu9) from Akutenu 10) and [fro]m Amiyan[u] 11) and from Buraq[anuJ3812) and they freed Tu[u]t[u] 13) from their brothers (?)89 forever.w14) If in futures- (if) 15) they shall return49 to their decision (= changetheir mind) 16) and they shall seizew Tutu, 17) they shall pay 50 (sheqels)of silver 18) to Tutu. 19) 50 (sheqels) of silver they shall pay to him20) and Tutu is fr[ee]d."The scribe responsible for this tablet, (sbu IAbi-malku ame1eup-pu-sa-ru] "27) witness, Abimalku the scribe,"44 partieipate landsale, in which the purchaser wouldneed a more exact definition of the confines of his possession. Here we aredealing with family property and a legal act inside the family, well withinas We have to understand this as meaning that all the three persons werebrothers of Tutu.., Instead of inadinu.iu, "they gave him." It is impossible to agree with the translation of J. Nougayrol, "a(!) Akkutenu,et a(!) Ammiyanu, et a(!) Burak[anuj," "to(!) Akkutenu and to(!) Ammiyanu andto(l) Burak[anuj.' , Tutu was not the person who had to pay, it seems that ina("to, into") is here by error instead of iitu ("from"). ab-i.8u, lit. "his brother," instead of ahheM-8u. a-da-[ri-tij, spoiled spelling of adi n ur.ram ie-ram, lit. "tomorrow (and) the day after tomorrow," in the sense of"in future." This was a generally accepted formula in hundreds of legal texts fromUgarit, in this case u-ra ei-ra is a spoiled spelling. ete-e-ru, instead of u-ta-ar-ru. Here "you shall seize" in bad orthography. Instead of tupiarru, tupuiarru; cf. the same opinion on the half-illiteratescribe, Rainey, lOS, III, 1973, p. 39.100 Property Relations Within the Rural Community Property Relations Within the Rural Community 101known and legally recognized limits. The documents were not composedin the presence of the king, or in the name of the king, or sealed by theking's, or any other official's, seal. On the contrary, they are composedonly "before witnesses." This proves that they are not documents con-cerning royal servicemen, but they involve people who had their land inthe villages, the rural communities of the kingdom. Naturally, only newconditions were mentioned, i.e., those connected with the results of thedivision of the inheritance, or the disinheritance of certain persons. There-fore, the well-known and traditional obligatory taxes, oorvee, etc., werenot mentioned at all.Four brothers seems to have been the maximum in one large patronym-ic family. In the specific conditions of Ugarit large patronymies could notsurvive for a very long time. This conclusion is by no means in contradic-tion to the comparison of -Iandsale documents given above. Thus, thegeneral conclusion derived from the texts presented in this chapter isthat the family in Ugarit was not a large one, and had relatively fewmembers.The Preference Given to the Family to Regain its LandThis problem is of importance in understanding various trends inlandholding, concerning certain families and their privileges in regard totheir former land.U, V, 6 (RS. 17.149).0) IMu-na-l!i-mu ame1tupAarru 1) M-tu umiml KAMan-ni-i-im 2) a-na pa-niMamelMstbiitiM 3) III Raaap-a-bu u f Pi-id-da aasat-su4) il-te-qu-ni 4 ilea eqlaM 5) qa-du l!8erdi-su 6) qa-du ardiitiM-su qa-du (= aklisu)44a 7) i-na eqliM$a-a-i 8) is-tu IYa-ri-ma-namdr fJu-za-mi 9) i-na 4 me-at kaepi 10) eqluM 11) i-nauBamSu umiml 12) a-na Raaap-a-bi u 13) a-na fPi-id-da aasati-su 14) ua-na mdreM-au-nua-di 15) da-ri du-ri aum-ma ur-raI6)-am se-ra-amI Ya-ri-ma-nu 17) u mdreM-su i-tu-ur-ni 18) a-n]a] libbibLsu-nu 1 li-imkaspu 19) eli-su-nu u eqluMa-nd IIlRaaap-a-bi 20) u a-na 'Pi-id-da 21) usum-ma IIlRaaap-a-bu u aasat-su 22) i-tu-ur-ni a-na libbi-su-nu 23) uk[i]-su-ma su-nu-ma sa-ni-tam 24) [pa-na-]na-ma eqlu an-nu-u sa IJ-za-al-da 25) a-bi fPi-id-du u i-na-an-na 26) eqluMi-tu-ur 27) fPi-id-dau [Ill RaaapJ( ?) -a-bu.Ua qa-du seen on the autograph (Pl. II) given by P. R. Berger,UF, I, 1969, p. 121. '"b Nougayrolr-a.[n]a?, Berger, UF, I, 1969, p. 121, A. [SA]MES."0) MunalJimu, the scribe.... 1) From the present day 2) beforewitnesses: 3) Raaapabu and Pidda, his wife 4) bought 4 iku of field5) together with its olive trees, 6) together with its slaves, together withtheir overseers, 7) located among the fields of (the village) $au, 8) fromYarimanu, son of .fJuzamu 9) for 400 (sheqels) of silver. 10) The field, theolive trees 11) are in possession like daylight 12) of Raaapabu and 13) ofPidda, his wife 14) and of their sons 15) forever. Ifin 16) future Yarimanu17) and his sons shall return 18) to their decision (change their minds),1000 (sheqels) of silver 19) shall be on them46and the field (belongs) toRaaapabu 20) and to Pidda. 21) And if Raaapabu and his wife 22) returnon their decision (change their minds) 23) so it is according to their(decision).48 Further: 24) [Form]erly this field belonged to Izalda, 25) thefather of Pidda and now 26) the field returns. The fi[eld]s are of 27) Piddaand [Raaap]abu."This document is of extraordinary interest. The land transaction is anormalone, but there is an indication that the motivation of Raaapabuand his wife, Pidda, in purchasing the land was to regain the propertyformerly belonging to Yzalda, Pidda's father. This shows that Pidda wasgiven preference in the purchase of this land. The situation could havebeen the following: Yzalda had to sell his land, the property of his family.His heirs had the privilege to buy it back before other purchasers."Perhaps, Yzalda had no male heirs and thus this right passed to Pidda.This act of purchase returned the land to the legal heir. The documentwas not composed in the presence of the king or other royal authorities.Thus, also here we have an internal issue of the rural community of $aeu.The text is also very important in seeing a tendency to maintain thestability of land-property within the community... I.e., Yarimanu and his sons had to pay 1,000 shekels of silver to RaJapabuand Piddo,.. That means that RaJapabu and Pidda had the right to decide freely and tochange their decision, without paying any fine..7 The Eshnunna Laws 38. Ifone of the brothers sells his share and his brotherwants to buy it, the latter must pay in full the average (price) of another. 39 iseven more important, where, if a man became impoverished and sold his house, theday the buyer will sell the former owner of the house may redeem (R. Yaron, TheLaws of Eshnunna, Jerusalem, 1969, pp. 40-41).GENERAL CONCLUSIONSIn summing up all the evidence we may say that large families, i. e.patronymies, sometimes existed in Ugarit. But the general trend wastowards its disintegration, and the large majority of families were smallones. We know of no patronymy which remained undivided into the thirdgeneration. Most of the families divided property according to the testa-ment of the father, or it came into effect between the brothers.It is difficult to discover all the reasons why this process took place inUgarit, But, it may be that the maritime position of the kingdom, itscommercial role in the ancient Near East during the XIV-XIII centuriesb. c., and the fact that Ugarit was in the focus of the political, cultural andeconomic influences of Hittite Asia Minor, Mesopotamia, Egypt and theAegeanworld, could have spurredthe more rapiddevelopment of its society.If we take, for purposes of comparison, the more or less contemporarysocieties of Alala\} (Mukish) and Arrapha, (Nuzu), situated inland, andvery far from the commercial routes and activities (as was Arrap\}.aparticularly) we see that in their societies patronymies, and more patri-archal societies in general, flourished.wOur investigation also makes it clear that the primary unit inside therural community was the individualfamily, the "house(hold)," bttu/bt (E).Naturally, full understanding of the society of Ugarit needs additionalinvestigation concerning the social status of the royal dependents (service-men), bns mlk, royal real estate, the economy, organization of craftsman-ship, and other issues. But the principal socio-economic unit in Ugaritwas the rural community, and the wealth of the kingdom was based on itsproductivity.There is no parallel, among any other ancient Oriental societies, situatedin the unirrigated zone, to the abundance of documentation from ancientUgarit. Thus, conclusions concerning Ugarit also have a certain value inreconstructing the socio-economic history of other countries for which thedocumentary evidence is scarce... N. B. Yankovakaya, Zemlevladeniye bolsbesemeynych dom?vych v klinopisnych istochnikach (Landownership of Large J;atronymles, According toCuneiform Sources), VDI, 1959, No.1, pp. 35-51 (RUSSIan); N. B. Yankovakaya,Zur Geschichte der hurritischen Gesellschaft (Auf Grund von Rechtsurkunden ausArraplJ,a und AlalalJ,), "Abstracts of the XXV International Congress of Oriental-ists," Moscow, 1960 (1062), I, pp. 226-32; N. B. Yankovakaya, Communal Self-government and the King of the State of ArraplJ,a, JESHO, 1969, :pp. M. Dietrich, O. Loretz, Die Soziale Struktur von AlalalJ, und Ugant (IV) DIe 19.= bttu-Listen aus Alalah IV als Quelle fiir Erforschung der gesellschaftlichen Sehichtungvon AlalalJ, im 15. Jh. v. Chr., ZA, 60, 1970, pp. 88-123.Appendix IItoyal LaadownershtpTexts U, V, 159 (RS. 17.86), 160 (RS. 17.102), and U, V, 161 (R8.17.325), given above, concern land purchases made by the queen, in thiscase, the queen-mother of Ugarit. The fact of the purchase is very signi-ficant since it denies the theory, until now unproven, that in the ancientNear East the king was the owner of all lands in his kingdom. If suchwere the case, then land purchase by the king (or queen) would be in-explicable. We see from the texts, that the queen had to perform all theformalities required of any other citizen who purchased land. Thus, evenif only formally, the king was not the only real landowner of the kingdom.He was only the sovereign in the political sense, and had the right toreceive the lands of the nayyalu, or debtors taken into slavery abroad(PRU, IV, 17.130 above). Only the lands of the royal real estate and ofthe land fund, distributed to royal servicemen, were at the king's fulldisposal. Such a view conflicts with the point of view of A. F. Rainey,who regards the kings as the feudal lords of all lands in the kingdom.!I Rainey, A Social Structure, pp. 32-36.Appendix IIDemographic Survey 01 the Population 01 theRural Communities 01 UgaritIt would be very interesting to know how large the population of therural communities was in the kingdom of Ugarit in the XIV-XIII cen-turies b.o, Naturally, such an attempt can only be a rough approxima-tion. First, we have to take into account that the various countries of theancient Near East differed in density of population. Of course, populationdensity was greater in the irrigated areas.The works available in this field are based on specific calculations re-lated to the character of the sources used in each case.I Thus, they cannot1 I. M. DiakonoU, Obshtshestvenny i gosudarstvenny stroi drevnevo Dvurechya,Shumer, Moscow, 1959, pp. 9-39 (Russian), pp. 291-92 (English summary); V. V.Struve, Gosadarstvo Lagash, Moscow, 1961, pp. 3-57 (Russian); I. M. Diakonof],104 Demographic Survey of the Populationof the Rural Communities of Ugarit Demographic Survey of the Population of the Rural Communities of Ugarit 10513 people13 people10 people Cf. Liverani, Oammunantes ... pp. 151-52, where the first steps towards theuse of the data fromAlalabfor demographic statistios are used.We arrive at an average figure, for one village, of 18.5 persons. This isthe average number to be conscripted from a single village. Thus, thetotal number of men conscripted on the occassion of a mobilization wouldhave been: 180 X 18.5 = 3,330-200 X 18.5 = 3,600.We have only one indirect way to prove the accuracy of these figures.This is by means of the texts concerning taxes and other duties, whichindicate, like the conscription texts, a certain proportion between thevillages responsible for providing a small number of men, and thoseresponsible for providing a large number of men, i.e. between smaller andbigger villages. Table No.4 compares the tax lists with the conscriptiontexts.sThus, it seems that the nine texts, and the data from Table No.2,where information about the grain tithe was calculated, prove that we cangenerally accept the division of the villages into three groups according tothe numbers of conscripted men from each.It must be noted, that CTC, 67 and PRU, III, 11.800 give only figuresdealing with the villages of the third group-the small villages. CTC, 68shows figures for the second group (middle-size villages), larger than forthe first group, and the amount of grain from Sert (group II) exceeds thatof group I also.On the other hand, texts PRU, III, 10.044, 11.790, and PRU, V, 58mention several villages whose figures exceed those of the large villages ofgroup I. This fact must not be ignored.be used as examples in our study. We must base our calculations on theinterpretation of the Ugaritic sources available. These include conscrip-tion lists, tax lists, lists of villages, arms delivery lists, as well as textswhich indicate the average size of the Ugaritic family (cf. below).The length of the coast of Ugarit reached approximately sixty kilo-meters. That was the maximum depth of the inland territory as well.sThus, the maximum territory occupied by Ugarit was 3,000-4,000 squarekilometers. There were also mountainous areas as well as forested areas.8Some of the villages can be localized- more or less exactly. As shown inTable No.1, there were approximately 190 villages. This figure appearsto be convincing. Thus, we may assume that there were approximately180-200 villages existing at anyone time.We have no proof that even those texts concerning the distribution ofvarious taxes, payments, and duties between the members of the villagecommunities (cf. Ch. II), list all the households of the community-s-evenwhen the texts are complete. It is possible that some households had toperform one obligation and others different obligations. However, itseems realistic to assume that the texts relating to military conscriptioncovered the whole community, mobilizing the heads of families, or adultsfrom every household.Text CTC, 71, discussed in Chapter II, as well as PRU, III, 11.841,concern only a small scale conscription of the villagers at the same timethat texts CTC, 119 (UT, 321), PRU, V, 16 (UT, 2016), and PRU, VI 95(RS. 19.74) give us the figures for a general conscription. (Villages forwhom the figures are broken have been omitted.)1. PRU, VI, 95, 12 Zrnj&IZa-ri-nu2. PRU, VI, 95, 13 Artj&IA-ru-tu3. PRU, VI, 95, 4 'l'lrbyj&ISal-lirx-ba-aRazvitiye ze.melnyoh otnosheniyi v Assiri'i, Leningrad, 1949, pp. 79-90 (Russian);W. F'.11bright, The Amama Letters from Palestine, Syria the Philistines andPhoenicia, CAR, Ch. II, XXIII, 1961, p. 19-200,000 inhabitants of Palestine inthe late Bronze Age.I J. Nougayrol. PRU, IV, p. 17: G. Buoeellati, Cities and Nations of AnoientSyria, Rome, 1967, p. 38.I Cf. PRU, III, 11.700, where the total of the text is designated as 3) dlaniDIDLI lJ,ur1ani ("the villages of the mountain distriot"). M. Astour, Place-Names fromthe Kingdomof Alalabin the North SyrianListofThutmoseIV; AStudyin Historioal Topography, JNES, XXII, 1963, pp. 22()"'41:M. Astour, Ma'badu, the Harbour ofUgarit, JESHO, XIII, 1970, No.2, p. 112ff.;J.-O. Oourtois, Deuxvillesdu royaumed'Ugarit dans Ia valeedu Nahr-el-Kebir en~ y r i ~ ~ Nord, "Syria," XL, 1963, pp. 261-73: J. Nougayrol, Soukas-Shuksu,Syria, XXXVIII, 1961, p. 215, eto.4. PRU, VI, 95, 65. PRU, VI, 95, 56. CTC, 119, II, 1-127. CTC, 119, I, 25-488. CTC, 119, III, 1-46; IV, 1-199. CTC, 119, II, 13-2010. CTC, 119, I, 12-2411. CTC, 119, II, 21-2912. CTC, 119, II, 34-3713. CTC, 119, II, 35-3914. CTC, 119, II, 40-4915. PRU, V, 16Total for 15 villagesSlmy/&ISal-ma-a'l'mry/&18am-ra-aArnyMerbyUbreyMerUlmBqetHlb RpBRkbySertMilJd5 people6 people10 people21 people61 people6 people21 people7 people3 people3 people8 peopleat least 90 people277 people106 Demographic Survey of the Population of the Rural Communities of UgaritTable No.4J::Q)S ... <IIj... ..."0'" 00- ~ Q)lQ t-'" .s eo~Q)0 0eo p..<Z ... ... .. '" .. co <:<I <:<I<Z '1:: :::::l 00- 0- ... ~...~...S o ~iQ"" 0gE-I0 ..... ....."" 0) 0 Q)I> "' .... ..... ..... <0 ..... 0t-: ~e- - 0 ..0]gggg 0 ..... ..... <Zo p.. ..... ..... ..... 00"" E-i+> .... ::lH"' H"' H"' lQ t- .... ~.... o 0o ~ 0~ hlQ t- oo ..... H H H> >"' '" <ZH H H'" <0 <0 <0 t- .... +>Q)~ ]c5 c5 c5 c5 ~g ~ ~ ~ ] .S S Q)+>~~ ~ ~Q) <Z <ZI> J:: tj tj tj E-iZ -< .... 0 Pol Pol Pol Pol ~ h1 2 3 4 5 6 7 8 9 10 11 12 131 MilyZ - - I-- - - - - - - I-- -2 Ubrey 75.515- 3 2 18 kur 14 114130 I-- 18grain +Lox -l-X3 Zrn - - '-- 1 - - - 1-- 104 Art - - I-- 1 - - - I- 6.255 Arny 13.72I-I-- %8 2 kurU - - 20 2 2grain,6.5 oxen6 'l'lrby - - - 1 - - - I-- 57 Merby '-- - 5 1 1 - 1172 -8 Ulm 21-- 6 - - - - 2 -9 Sert - f-- - - - - 24 2 10510 Blmy - - - %9 - - - 112- -11 'l'mry - - - 1 - - 117I- 612 Mer 5.5 11-- - :W 2 9 8171 -13 Bqet 1 6- - 2 - - - -14 ijlb-rpA 1 14 - - 2 - - 1 -15 Rkby I- - - - - 2 - - -Villages paying 50kur 30 4001650more, grain BekanillBekanithan group I 13(1) oxenBekani1 Large villages. Middle-size villages. Small villages.Demographic Survey of the Population of the Rural Communities of Ugarit 107At least one village from every group has statistics available for eightof the ten possible categories (= 80 percent of the texts available). At thesame time, the special group in which the figure is higher is mentionedonly three (four 1) times. We may conclude that the largest villagesappeared only in one-third of the given texts, i. e., less than forty percentof the texts. If one of the fifteen villages is 1/15 of the total, then the in-frequent mention of the large villages shows that their number could nothave exceeded 1/30-1/45 = 1140' If we assume that the population in suchvillages was twice that of the large group, then we could estimate anaverage of 150 families per village.Text CTC, 65 mentions nine villages. The figures show that:Group I 2 villages 23%Group II 2 villages 23%Group III 5 villages 54%100%CTC, 67 mentions twelve villages. Only one of these villages (Sl,tq) paidtwenty-four jars of wine, i. e., twice the amount paid by the villages ofGroup III. Thus, we have the following figures:Group II 1 village 8%Group III - 11 villages = 92%100% List of villages which performed a certain number of days of labour-corvee (cf.cs. II, pp. 24-25). List of vine tax (cf. Ch. II pp. 40-42). The object listed is not clear.7 Partial conscription list of bowmen (cf. Ch. II, pp. 18-19).8 Arny and Mer together contributed one person. Yknem, Slmy and Ull together contributed one bowman.,. Taxes paid in wine, oxen and grain.11 One or two villages; the name of the second village was not preserved.18 Duties of the "mountain district."18 The real object of the tax or duty is not precisely known, but it was probablycorvee counted in days( 1).14 Figure-sign broken.10 The largest number, 50, from &IMa.qa.bu; but we have no basis for comparisonwith the large villages.18 Cf. Ch. II, pp. 31-33; tax-list of the Hittite king.17 Illegible figures.18 Figure-signs preserved partly; purpose of the list is unknown.18 Average payments in kur's.108 Demographic Survey of the Population of the Rural Communities ofUgarit Demographic Survey of the Population of the Rural Communities of Ugarit 109= 100%54925 villages4 villages3 villages15 villages46204545574455958:10 =46%2082612II142315156:10=15%Group IGroup IIGroup IIIWe may take, in addition, the data derived from various small texts:Payments from large villages-(more than 25 kur)(15-25 kUr)(7-14 kur)(1-6 kur)1 Including 10.044.These figures are only approximations, but they may not be very farfrom reality. If, in basing further calculation on them, and assuming thefigure of 180-200 villages, we remove the following groups:I) Large villages 1,8-2 X 3 5-6 villages2) Group I 1,8-2 X 15 27-30 villages3) Group II 1,8-2 X 36 65-72 villages4) Group III 1,8-2 X 46 83-92 villages100% =180-200 villagesTaking into account the tentative average of mobilized men in everygroup of villages we receive the following number of people.I) Large villages 5-6 X 150 750-9002) Group I 17-30 X 75.5 2038-22653) Group II 65-72 X 13.7 890-9864) Group III 83-92 X 5 415-4604093-461119%15%11%55%100%These figures help us calculate the role of various groups of villages inthe general demographic picture of the villages of the kingdom.Text Large Group I Group II Group IIIVillages (Percentages according to the singletexts and Table No.2)23 2388046474044273311359:10 =36%33%44%100%9 villages12 villagesGroup IIGroup IIICTC, 68 mentions ten villages. Of these:Group I 2 villages 20%Group II - 8 villages = 80%100%In CTC, 71, the figures are preserved for forty-one villages.Group I (2 persons for 1 village) 3 villagesGroup II (1 persons for 1 village) 19 villagesGroup III (1 persons for 2-3 villages) 19 villages8%46%46%100%In text PRU, III, 10.044 figures are preserved for fifteen villages.Large villages - I village 7%Group I 4 villages 26%Group II 7 villages 47%Group III 3. villages 20%100%In text PRU, III, 11.790 figures for thirty-three villages are preserved.Large villages - I village 3%Group I 4 villages 12%Group II 13 villages 40%Group III 15 villages 45%100%In text PRU, III, 11.800 figures are preserved for twenty-five villages.Group I 3 villages II %Group II 12 villages 41%Group III 14 villages 48%.100%In text PRU, V, 58 figures for fourty-four villages are preserved.Large villages - I village 2%Group I - 6 villages 14%Group II - 12 villages 27%Group III - 25 villages 57%100%In text PRU, V, 74 figures for twenty-seven villages are preserved.Group I - (more than the figure 6 villages 23%2 concerned)- (2 concerned.)- (I concerned.)no Demographic Survey of the Population of the Rural Communities of Ugarit Demographic Survey of the Population of the Rural Communities of Ugarit IIIIf we assume that there was at least one additional person in 8 of thefamilies, and we take half of this number as certain, we have 4 additionalpersons, for a total of 81 persons in 19 families. As it was pointed out inChapter VII, no children were mentioned in these texts. The number ofchildren might have reached %of the number calculated above. Thus,there may have been up to 27 minor children in these families. (This smallnumber of children has been reached by taking into account the highmortality rate j it is a minimum number.) Thus, there were approximately108 persons among the 19 families = 5.7 persons per family.Text PRU, V, 80 (cf. Chapt. VII) mentions workmen who were notfreeborn, or who were semi-free. The sizes of the families mentioned inthis text are as follows:Total 45 personsHere, too, minor children may be added to the total. The percentage ofworking personnel is high. Therefore the number of children probably didnot exceed 74 of the persons listed here. Thus, the number of childrenmay have reached 11. The total number of people in these families couldhave been 56 persons = 56: 6 "" 9 persons per family. Not all families hadworkmen in their possession j those that did were the more wealthy fami-lies. They were not numerous among the villages of Ugarit, and do not,therefore, have any great bearing on the total village population. Amongthe people named in PRU, V, 80, we have 22 workmen. If we divide thisnumber among all the families listed above, we get 1 workingman perfamily. Thus, it is possible to combine the total of the results receivedfrom the 19 families and PRU, V, 80: 108 + 56 = 164. Dividing this totalamong 25 families (19 + 6), we arrive at an average of 6.5 persons (approx-imately) per family, including children and unfree or semi-free workingpersonnel.In order to calculate the general population we must multiply thenumber of people conscripted by 6.5, the average number of persons in anUgaritic family. The results are: approximately 3900 X 6.5 "" 24,350. Wemust also add the approximate number of elderly persons reckoned at700. We thus arrive at an average of 25,000 people making up the popula-Thus, an average figure would be:4093 + 4611 = 8704 : 2 = 4352 men mobilized at the general mobili-zations from the villages of Ugarit. This differs from the previouslycalculated figure of 3330-3600 = 3465 persons. Thus, the number couldhave been between 3465-4352 "" 3906 men.The largest conscription text, PRU, V, 16, where all the individuals arereferred to only as bn X, "son of x (the father's name)," allows us toconclude that only the heads of the families were named, or only one manfrom every family. This forces us to conclude that the conscription textslisted only people subdued to military conscription, not elderly personsor invalids. The number of men listed could not exceed 15-20% of alladult men, taking into account a relatively short lifespan. Thus, theirnumber could be not more than 600-800. Taking 700 as an .average, thenumber of adult free-born villagers may have been approximately 4100-4700 (an average of 4400). But, in order to be more exact, we must takeinto account the size of the average family.Texts PRU, V, 44, PRU, II, 80, and CTC, 81 were analyzed and recon-structed in Chapter VII. Using these texts, we can get an approximate ideaof average family size. The figures arrived at are only approximationsbecause of the bad state of preservation of these texts.1) l ~ m t n 2 sons, 1 wife 4 persons2) Swn, 1 son, 1 wife, 1 brother 4 persons3) PIn, 2 sons, 1 x ( ?) 4 persons (at least)4) Ymrn, 1 wife, 1 son 3 persons5) Prd, 1 wife, I son 3 persons6) Prt, 2 x, 1 wife 4 persons7) cdyn, 1 wife, 2 sons 4 persons (at least)8) Anntn, 1 wife, 2 sons, 1 x ( ?) 5 persons (at least)9) Agltn, 1 wife, 1 son 3 persons10) [xNmu, 1(?) x, 1 son, 1 wife 4 persons (at least)11) ru, 1 wife, 2 sons 4 persons12) 'f!..rngdl, 1 wife, 1 son 3 persons13) Annfl,r, 1 wife, 1 son 3 persons14) Nrn, 1 wife( ?), 2 sons + x 5 persons (at least)15) ru, 1 wife( 1), 1 son, 1 daughter-in-law 4 persons16) BcIy, 1 wife, 1 son( 1), 1 daughter + x 4 persons17) Bsleip, 1 wife( ?), 1 son, 1 daughter-in-law 4 persons18) Nrn, 1 wife( 1), + x, 2 sons 4 persons (at least)19) 'f!..1lJ,ny, 1 wife( 1),3 sons, 3 daughter-in-law 8 persons (at least)Total 77 persons (+ x)1) Bn. BcIn, 3 workmen, their head, his 4 daughters2) YrfJ,m, 2 sons, 2 workmen, 3 youth, 4 daughters3) bn Lwn, 6 workmen4) Bn BcIy, 6 workmen, 1 fJ,upSu, 4 wives (or women) =5) Bn Lg, 2 sons, 2 workmen, 1 sister6) Sty, 1 son9 persons9 persons7 persons12 persons6 persons2 persons112 Demographic Survey of the Population of the Rural Communities of UgaritChronology of the Late-Ugaritie Period!Appendix HI1 This table is given according toH. Klengel, Geschichte Syriens im 2. J ahrtausend,v, U.Z., Teil 2, Mittel und Siidsyrien, Berlin, 1969, p. 455.tion of the villages of Ugarit. We must take into account that this is notthe total population of the kingdom. To arrive at this figure we wouldhave to include the population of the town of Ugarit, the royal servicemen(bns mlk), and other smaller segments of the population.This data is very preliminary and far from exact. However, it is im-possible at present to use any other method to calculate populationfigures for Ugarit. Future publications will have to demonstrate thecorrectness or incorrectness of this method, or attempt to improve it.PRU. II, 98 29PRU. II, 101 24PRU. II, 104 83PRU. II, 106 40PRU. II, 154 72-73, 75PRU. II, 161 78PRU. II, 171 33PRU. II, 173 78PRU. II, 176 17,31,31PRU. II, 181 20, 25, 60PRU. II, 184 7PRU. II, 185 7PRU. II, 186 7PRU. II, 188 7PRU. III, 10.044 16, 35-36, 41, 43,105-106, 108-109PRU. III, 11.700 2PRU. III, 11.790 16-17, 24, 24, 103-107, 109PRU. III, 11.800 47,72,105-107,109PRU. III, 11.830 24-25,61PRU. III, 11.841 16, 19,19, 21, 104PRU. III, 15.20 17, 44PRU. III, 15.81 58PRU. III, 15.89 53, 55, 91PRU. III, 15.90 96PRU. III, 15.114 27, 49PRU. III, 15.115 25PRU. III, 15.122 55PRU. III, 15.123 91PRU. III, 15.132 35PRU. III, 15.136 92PRU. III, 15.137 80PRU. III, 15.140 61,61,92PRU. III, 15.141 55, 61, 61PRU. III, 15.142 61PRU. III, 15.143 92PRU. Ill, 15.145 55, 92PRU. III, 15.147 51PRU. III, 15.155 61, 61PRU. III, 15.156 9l, 95PRU. III, 15.168 55PRU. III, 15.179 47PRU. III, 15.182 61,94-95PRU. III, 15.183 47PRU. III, 15.189 47INDICES1 About other systems of citation ofthese texts and their identificationaccording to other citation systems cf.M. DIETRICH, O. LORETZ, Konkordanzder ugaritischen Textzahlung, Neu-kirchen-Vluyn, 1972.PRU. II, 4 40PRU. II, 5 40PRU. II, 7 50PRU. II, 10 25,27,34PRU. II, 24 68, 81PRU. II, 33 82PRU. II, 59 28PRU. II, 68 20PRU. II, 80 84-87, 110PRU. II, 81 20, 60PRU. II, 82 92PRU. II, 84 29, 72PRU. II, 92 75PRU. II, 93 821. Ugaritic and Akkadian texts fromUgaritlCL. 1957, 3 38-39CL. 1957,4 44CTC. 3, V 76CTC.4 76,76CTC.6 76CTC.14 73CTC.15 75CTC.17 76CTC. 65 24, 106, 108-109CTC. 66 24-25CTC. 67 41, 61, 105-106, 108-109CTC. 68 105-106, 108-109CTC. 69 31, 31, 33, 60CTC.70 31CTC.71 5,16,18; 21,19, 32, 60, 61, 72,104, 106, 108-109CTC.79 21.CTC.81 84-87, 110CTC.84 23CTC. 119 19-21, 104-105CTC. 136 24,27SuppiluliumaArnuwanda IIMursilis IITud{}aliya I VUrQ,iteaubfJattusilis IIIMuwatalluij:attiArnuwanda I I ISuppiluliuma IIAr{}albaNiqmepaAmmistamru INiqmaddu IIUgaritIbiranuNiqmaddu I I IfJammurapiAmmistamru IIBentesinaAmurru14001375 Aziru1350DU-Tdub1325 Duppitesub1300 Benteaina(Sapili)12751250 Sauagamuwa12251200114 Indices Indices 115PRU. III, 16.14 91PRU. III, 16.86 55PRU. III, 16.129 96,99PRU. III, 16.131 61PRU. III, 16.133 91PRU. III, 16.134 92PRU. III, 16.137 70PRU. III, 16.150 61PHU. III, 16.153 31,34-35,50PRU. III, 16.154 92,95PRU. III, 16.157 35,80PRU. III, 16.167 91PRU. III, 16.170 65, 66, 67PRU. III, 16.174 54PRU. III, 16.188 27PRU. III, 16.202 51PRU. III, 16.204 17PRU. III, 16.233 70PRU. III, 16.244 31, 49, 51, 83PRU. III, 16.246 92PRU. III, 16.248 52PRU. III, 16.250 80PRU. III, 16.254 D 35PRU. III, 16.256 92PRU. III, 16.261 94-95PRU. III, 16.262 54,90PRU. III, 16.269 35,42,49PRU. III, 16.270 6PRU. III, 16.276 31, 48PRU. III, 16.277 31, 61PRU. III, 16.287 58PRU. III, 16.343 93PRU. III, 16.348 80PRU. IV, 17.28 83PRU. IV, 17.43 6PRU. IV, 17.62 15-16, 43,60,61,72PRU.IV,17.79+374 6PRU. IV, 17.123 66-67PRU. IV, 17.130 6,57,58,90,103PRU. IV, 17.134 35PRU. IV, 17.158 6PRU. IV, 17.229 63PRU. IV, 17.234 6PRU. IV, 17.238 4,58PRU. IV, 17.239 6PRU. IV, 17.288 63PRU. IV, 17.299 63PRU. IV, 17.315 58PRU. IV, 17.319 6PRU. IV, 17.355+ 379+ 381 + 235 6,15PRU. IV, 17.339 A 15,72PRU. IV, 17.340 15,43,61PRU. IV, 17.341 6,58PRU. IV, 17.366 15,60PItU. IV, 17.369 A 58PItU. IV, 17.369 B 63,72PHU. IV, 17.397 6PHU. IV, 17.424 C 79PRU. IV, 18.04 58PRU. IV, 18.111) 6PRU. IV, 19.81 15PRU. V, 4 16,40-41,71PRU. V, 8 81-82PRU. V, 11 82PRU. V, 12 40PRU. V, 15 17PRU. V, 16 20-21,104-105,.110PRU. V, 17 47PRU. V, 18 16PRU. V, 21 47PRU. V, 22 47PRU. V, 23 24PRU. V, 24 47PRU. V, 25 47PRU. V, 26 67PRU. V, 27 72PRU. V, 29 67PRU. V, 39 43,88PRU. V, 40 16-17, 61PRU. V, 41 43, 47, 72PRU. V, 42 16,61, 72PRU. V, 44 20,60,68,84-87, 110PRU. V, 47 21PRU. V, 48 16, 61PRU. V, 58 5, 7, 20, 31-33, 60, 105-107, 109PRU. V, 64 43PRU. V, 73 70PRU. V, 74 16-17,47,61,61, 106-107,109PRU. V, 75 47PRU. V, 76 16PRU. V, 77 47, 61, 61PRU. V, 78 23, 46PRU. V, 79 28PRU. V, 80 89-90, IIIPRU. V, 85 23-24PRU. V, 90 61, 61PRU. V, 107 33, 42, 42PRU. V, 112 72PRU. V, 116 77PRU. V, 117 24PRU. V, 118 47,61,68PRU. V, 119 31, 72PRU. V, 123 24PHU. V, 142 84PRU. V, 144 47, 61PRU. V, 145 47, 60PRU. V, 146 47, 61PRU. V, 147 47PRU. V, 165 47PRU. VI, 28 (RS 17.39) 55PRU. VI, 29 (RS 17.147) 16PRU. VI, 40 (RS 17.360) 91,98PRU. VI, 49 (ItS 17.378 A) 98PRU. VI, 50 (RS 17.388) 98PRU. VI, 52 (RS 19.78) 64PRU. VI, 55 (RS 18.22) 56, 70PRU. VI, 68 (RS 17.84) 58PRU. VI, 69 (RS 17.329) 58PRU. VI, 70 (RS 17.50) 17PRU. VI, 73 (RS 19.107 A) 24PRU. VI, 76 (RS 17.361) 59PRU. VI, 77 (RS 19.32) 20, 59PRU. VI, 78 (RS 19.41) 60-61PRU. VI, 79 (RS 19.41) 16PRU. VI, 80 (RS 19.111) 62PRU. VI, 94 (RS 17.43) 47PRU. VI, 95 (RS 19.74) 19-21,59,104-105PRU. VI, 96 (RS 19.91) 47PRU. VI, 97 (RS 19.118) 47PRU. VI, 100 (RS 19.51) 36PRU. VI, 102 (RS 19.12) 36-37,39,39PRU. VI, 105 (RS 19.117) 20,37,39,39,60PRU. VI, 106 (RS 19.119) 36-37PRU. VI, 107 (RS 19.25) 40PRU. VI, 110 (RS 19.88) 36-37PRU. VI, III (RS 19.129) 37-38,60PRU. VI, 113 (RS 19.26) 46PRU. VI, 116 (RS 17.64) 34PRU. VI, 118 (RS 18.116) 43PRU. VI, 131 (RS 19.35 A) 5, 17, 21PRU. VI, 134 (RS 19.19 A) 44, 46PRU. VI, 138 (RS 19.46) 16,22,60PRU. VI, 169 (RS 18.279) 47RS.8.145 91RS. 19.25 40HS. 1929, No.3 40U. V, 4 (RS 17.20) 90U. V, 6 (RS 17.149) 61,90,100-101U. V, 7 (RS 17.36) 97U. V, 8 (RS 17.30) 97U. V, 9 (RS 17.61) 55,83U. V, 12 (RS 17.150) 72U. V, 26 (RS 20.03) 80U. V, 33 (RS 20.212) 39U. V, 52 (RS 20.239) 63, 79U. V, 66 (RS 21.54 B) 79U. V, 83 (RS 20.146) 98U. V, 95 (RS 20.011) 17, 29U. V, 96 (RS 20.12) 17, 59U. V, 99 (RS 20.425) 28,40U. V, 102 (RS 20.207 A, 13) 17, 47, 60U. V, 103(RS 20.143 B) 47U. V, 104 (RS 20.144) 47U. V, 143-152 (RS 20.10; 20.196; 20.161; 20.160; 20.14; 21.05; 21.196 A;RS 6 X; Rs Pt 1844) 38U. V, 159 (RS 17.86) 61,90,94-95,103U. V, 160 (RS 17.102) 90,95,103U. V, 161 (RS 17.325) 90, 103U. V, 171 (RS 26.158) 39U. V, 6 (Ugar) (ItS 24.272) 752. Selected Oriental Termsa) Ugariticadr(m) 75, 75akl 27alp 44anyt 23argmn 5,33ary 76,76 adrt 75cbs 78, 78 82116 Indices Indices 117eqb 67,67erb 78, 78bel(m) 89blbI(m) 82bns mlk 5, 5, 8, 18, 21, 29, 32, 34, 39,57,82,84,90, 96, 100, Il2bnEi(m) 22, 24bt (bhtm) 72, 102bt bbr 73, 73, 75bt qbs 73, 73, 75, 77grn 76gt 5, 8, 17, 29-30, 421}.pr 821}.rEi(m) 82 89,89bsn 73btn 86-87kd 27kbd 33kd 40,42kd yn 41khn(m) 82kIt 85-87l1}. 43,43It1}. 28md(m) 70mkrm 34, 34, 39mphrt 75ner(m) 89n1}.l(h) 68,69nqd(m) 34, 82pbr (pbyr) 75qle 19, 19qnu(m) 23, 46qrt (qrit, qrht) 7-8, 18-19, 24, 35, 42,45, 69, 81-83, 91qst(m) 19rb 80, 81, 82, 82, 83riB 18rps 47,47skn 17, 54, 80, 82-83spr 47,47sbr 70-71, 71, 77sbrt 76-77sd 67-69,83smn 27tgmr 42,42ubdy 67, 68, 83 19,21wrt 34yki 40yp1}. 77,78b. Akkadianabbe 79aklu 37, 39, 44, 80, 80alpu 25,43alu 2, 7-8, 16, 18-19, 24, 24, 32, 35,42, 45, 60-62, 65, 68, 79-83, 91ardu 97aspu 19bitu 80, 90, 93, 96, 97-98, 102, 102dimtu 30, 30, 42, 55, 92-94e1eppu 22, 24eqil sarri 8eqlat sibbiru 69-71eqlu 16, 65, 92, 94-95, 97-98, 100erebu 78esretu 48gababu 19, 19, 21bapiru 4, 5, 58bazannu 80-81, 83iku 91-94, 97, 100-101ilku 91, 91ispatu 21ka 39,39kasap so. maqadu 34karpatu 40kunasu 36kur 36-40, 106, 108ma'allsrufesretu 35, 35, 51makisu 35ma1abbu 82maqadu 34, 34maryannu 70, 70maswatu 46matu 82,94miksu 35, 48, 48mudu 70, 70, 80, 80munnabtu 59nayyiUu 52-58, 62, 69, 83-84, 90, 103pilku 55, 90-94qallatu 19, 21rabil\lu 82rikiltu 78resu 55sakinu, sakinu 17, 49, 53-54, 56, 56,63-64,79-80, 82, 83, 94serdu 42l\lsbu 18-19, 22, 59sibbiru 70-71sakin ekallim 49-50sangu 42samnu 42sa sepe.su 79sarrskuti (var, sirku) 31satsmmu 54, 54se 35,37-38sennu 44-45ffibutu 56, 64, 79-80, 94, 97-99simtu 97sipru sarri 25sikaru 35, 35sirku 48tamkaru 33,34,39,42,57,57,63,78,79tappfitu 78ugula 39unussu 53, 55, 90-91zittu 96c. SumerianDUG 40,41DUG GESTIN 41E 102,102GUD 43:ijU 16MASKIM 17,49,56,82-83PA 37,39SA.GAZ 58SAG. DU 18SfG 17SEN.MES 45TAL.MES. siparri 44UDU.NIN.MA 44URU 7Z:t.KAL.MES 36ZIZ.AN.NA 363. Personal Namesa. Written in Ugaritic Cuneiform Alpha.betAbdhr 22Adey 28Agmn(d) 72[A]dmu 85, 87Adty 43 68 68Agyn 86-87Agltn 85, 87-88, IlOAliyn BCI(d) 76Alkbl 34Ann 68-69Ann[d]r 68, 85, llOAnnmn 68Annt[n] 85,87, IlOArkS [] 68 (d) 76, 76ebdilt 78ebdyrb 43edn 22,28edyn 85-86, IlOebr(d) 72 23eyn 23Bel 71Beln 89, IIIBely 86-87,89, IlO-IllBelsip IlOBdn 68Brqn 79Brrn 69Brzn 69Buly 23Drnl(d) 26, 26Dnil 75Dnn 23tlmry 28Grb 23Gyn 68Hbm 42!:Idd 85, 87!:Igbn 82!:Igby 47!:Inn 78118 Indices Indices 119I.Iyi1 25, 26 85-86, 110:ijrgs 68Ig1yn 68Il(d) 72IlS1m 78Ilmhr 68Ilm1k 43Ilrpi 28Ilt(d) 76Ily 28III'S 23Ilthm 23Irdyn 68Iwrm 85,87Kmrm 68Kli 77-78K1yn 86-87Knn 69Krt 75Krz 68Krzbn 68Krzn 43Ktmn(d) 72Ktan 22Kwy 42Lg 89,111Lwn 89,111Mlkncm 43Mnhm 78NCmn 23Nbzn 68Nq1y (d) 72Nrn 86-87, 110Pgyn 68P1gn 77-78PIn 68, 85-86, 110P1zn 86-87, 110Prd 85-86, 110Prdmy (f.) 34Prn 68Prqds 78Prt 85-86, 110Pss 23Ptpt 28Qds(d) 71Rsp(d) 73Sbrn 47,68Ssl(d) 72Swn 85-86, 88, 110Szrn 23S.wn 68l?brt 76, 76l?dqs1m 43 73Slm 71Smc 82Smcrgm 82Sm1bu 23Sty 89, IIITiyn 68Tkn 68Tldn 77,78Ttyn 68Ttyn 68Tyn 681'bcm 28,671'mgd1 85,87, 1101'mrn 671'rkn 77,781'rn (d) 721'[r]yn 681'ty 86-87[Y]d1n 85, 87, 110Ydn 28Ymrn 85-86, 110Yrbm 89, 111Yrm 28b) Written in Akkadian Cuneiform andOther ScriptsAbazuya 97Abdiesarti 56Abdiilimu 29Abdianati 65Abdihagab 80Abdiili 97-98Abdimi1ku 92Abdinikal 91Abdininurta 66Abdinerga1 70Abdiraiiap 56Abdiyarah 56Abdu 56, 64, 70, 79Abima1ku 99Abimilku 97Adad(d) 72Addu(d) 72Addudayyanu 79Addumislam 94Adanummu 54Addunu 64, 79Abamaranu 92Abatmilku (f.) 53Akuttenu 98-09Amiyanu 98-99Ammistamru 48-55,_ 61, 80, 92-93, 95,98, 112Amutarunu 50Ananu 48Ananiya 91Anatenu 91, 93Anatesub 91Apapa (f.) 48Apteya 29Arhalbu 112Arimari 36, 39Arnuwanda 112Arsuwanu 56Asirat (d) 76, 77ASmuwanu 93Astabisarru 59Astart(d) 71Aya1u 91Aziru 80, 112Baalazki 92Baa1mateni 29Baal-Safontd) 49Babiyanu 64, 79Bariya 44Batrabi (f.) 91Batsidqitf) 94Benteaina 112Bin-Bukruna 53Burakanu 98-99Dalilu 53Dane1 76Dinniya 92Duppitesub 112DU-Tesub 112Entaaali 49, 83Eshmoun(d) 72Gabanu 49:ijamenaya 56:ijammurapi 112:ijattusi1is 4, 57, 112:ijeb/pat(d) 16, 71-72:ijebatsapaa 59:ijiram 40:ijismiyanu 94:ijuttenu 92:ijul;lanu 51:ijuzamu 100-101, 100Ib[ri]muza 22Ibiranu 112Ibrizazu 59Idkiya 22Igmaraddu 52Ibiyanu 96-97Ilat 76, 77Iliba'a1 29Ilirasap 56Ilisa1imu 53, 54Ili[y]a 29, 94-95Iliyanu 29, 44Ilumi1ki 30, 56, 80Iluramu 29Iribilu 56, 83Iruna 70Istar(d) 71Iste1u 39Iza1da 100-101Kabityanu 92Kalbiya 92Kamalibadu 54Kar-Kusub 48Keret 73Kum-U 56Kurbanu 55, 98Kurue[n]a 22Kurwanu 92Laeya (f) 94Laya 91Layawa (f) 91Mada'e 64Maadabiu 29Matenu 29M[i]nuru 22Milkiyatanu 73Munahimu 98, 100-101Mursili 60-61120 IndicesNaziyanu 59Niltanu 55Niqmaddu 29, 48-49, 52-54, 66, 70,91, 112Niqmepa 4, 49-50, 61, 66, 92-93Numenu 98Nuriyanu 53, 91, 96Nurinu 98Nuristu 53-54Padiya 94-95Pidda (f) 100-101Pilsu 92Pululuna 95Qadidu 63Qatuna 55Qiribilu (f) 55Rap'anu 4Rdapabu 4, 100-101Reilef(d) 72Samanu 59Sasiyanu 94-95Sinaranu 96-97Sinaru 92Siniya 94-95Solomon 40Suanuanu 59Sarelli (f) 94-95Sapili 112Sausgamuwa 112Sidina 36, 39Siganu 36, 39Subammu 91, 94Sukurtesub 80Suppiluliuma 112Takhulinu 50Takiyanu 54Takkana 96Talaya (f) 91Talimmu 63Tari[...] 49Tubanu 56Tubbitenu 56Tudhaliya 112Tulaya 51Tuppiyanu 54, 56Tutu 98-99, 99Ukte [] 98Ukulliilanu 83Ummihibi (f) 92-93, 95Urbitesub 112Uzzinu 94-95, 97Yadudana 64,79Yakmu 56Yanhammu 56, 80Yanhanu 96Yapasarru 92Yaplunu 94Yarimanu 91, 100-101Yarimilku 53,54Yarimu 29Yasiranu 51Yatarmu 49Ydlimanu 54Yayanu 91-92Zuga'u 36, 39
https://www.scribd.com/document/195055158/Heltzer-The-Rural-Community-in-Anceint-Ugarit
CC-MAIN-2019-43
refinedweb
49,801
67.45
CodePlexProject Hosting for Open Source Software Hi! I just finished (and contributed to the Gallery ofc) a module adding a must-have blog functionality - content sharing!:) It delivers a reusable and themeable with predefined themes (for now) ShareBar part which you can put onto your routable content types. It is based on AddThis service. Source is available (as always;) on Codeplex. I also wrote a detailed step-by-step article on how to use the sharing feature and change the share bar appearance - you can find it here. Hope you enjoy it! Cheers, Piotr Hello Pszmyd, Thank you for a great module - I have just started using it and I can see it will be beneficial. I have downloaded Version 0.5 from the modules library. With this version (and perhaps you have already updated it) I had the problem that the Content Parts was not automatically added so it was confusing to know how to get this part to work. I had to manually go to Content Parts and add "ShareBarPart" as a Content Part. After this it worked fine. However, I was wondering if you could update your migration with the following code to make this automatically happen: public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition( typeof(ShareBarPart).Name, cfg => cfg.Attachable()); return 2; } You will also need this at the top: using AddThisSharing.Models; This will make it easier on the next user and get more users hooked on your module. Also, if you could categorieze your module, perhaps as Content like this: Description: Cool Module for Sharing Category: Content It will show up better in the modules section. I hope these are helpful comments (and perhaps you have already done them in your source code) - either way, thank you for the great module. Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
https://orchard.codeplex.com/discussions/245050
CC-MAIN-2017-30
refinedweb
330
65.73
15 April 2011 07:00 [Source: ICIS news] By Ong Sheau Ling ?xml:namespace> Regional converters are hurting from the strong prices, but PP producers had to either rollover values or adjust them higher to keep a decent spread from feedstock propylene, even when demand is not strong, they said. (Please see graph below) PP raffia grade, which is used in packaging of grains, was discussed at $1,700-1,740/tonne (€1,173-1,201/tonne) CFR (cost and freight) GCC (Gulf Cooperation Council) and $1,720-1,740/tonne CFR East Mediterranean (East Med) on Friday, market sources said. Propylene was at $1,550-1,580/tonne CFR NE Asia at midday, while US crude futures were hovering at $108/bbl. “We have to monitor the crude and propylene prices, before we announce our May offers later in end-April. At the moment, we are certain prices will not drop,” said a key GCC PP maker. According to ICIS data, spot PP prices surged 21% since the start of the year on the back of rising raw material costs. “The struggle is there. On one hand, we have to cover our costs. On the other hand, we have to take care of our customers. It is really tough,” said another GCC producer. Meanwhile, PP prices will likely be supported by tight supply through June as two major Saudi Arabian PP producers are scheduled to take their facilities off line for turnaround. (Please see table below) Rabigh Refining and Petrochemical (PetroRabigh) is expected to shut down its whole petrochemical complex, including a 700,000 tonne/year PP facility, for scheduled maintenance in late April. In May, National Petrochemical Industrial Co (NATPET) will take its whole Yanbu complex off line for a 60-day turnaround. The complex includes a 400,000 tonne/year PP plant. “Two large players in the region are out of the market in May, this will definitely has an impact in the region and even to export regions,” said a UAE-based trader. PP supply in the Middle East market is currently tight with the 150,000 tonne/year plant of PIC plans to restart its plant in Shuaiba, which was shut on 10 March, on 8 May. Oriental Petrochemical Co (OPC) of For Oman Polypropylene (PP), technical problems prevent its 340,000 tonne/year PP unit from running at full tilt. PP demand was moderate in the GCC region, but slightly sluggish in a couple of the countries in the East Mediterranean region such as But converters are getting increasingly worried over the strong PP prices that are constraining their operations, market sources said. “Converters had to restock their inventories in May, as they have been operating on hand-to-mouth basis for the past few months,” said a regional PP maker. “Producers like us will ensure quantities to our key customers, but we can’t cater to the small to mid-sized end-users,” he said. (
http://www.icis.com/Articles/2011/04/15/9452790/middle-east-pp-likely-to-stay-firm-in-may-on-tight-supply.html
CC-MAIN-2014-41
refinedweb
492
66.27
keep your points and request that this question be deleted. .NET does not have any native classes or namespaces that allows you to access SNMP directly (the system.Management class only uses WMI). Go to microsoft.com and query SNMP there. They have some tutorials and such, but it's all for C++. The problem with SNMP is that it requires DCOM objects, which are basically distributed DLLs. You can try to use DLLImport("snmp32.dll") and then create your own wrappers, but SNMP DLLS have their own memory management and what not, so even those most basic queries (get IP Address) requires a lot of effort. In short, if you really want to do SNMP, use C++ or hope that MS includes SNMP in .net 2.0
https://www.experts-exchange.com/questions/21191193/c-WMI-SNMP-retrieve-network-printers-switches-unix.html
CC-MAIN-2016-40
refinedweb
128
76.01
Never Give Up, Retry: How Software Should Deal with Failures Viach Kakovskyi Sep 15 '17 Originally published on my blog: All You Need Is Backend. It's doubtful that your backend has everything within one process: you need to read configuration, store customers' data, write logs and metrics about the status of your software. If you're working on a network application - it's even more complicated: your database can be far far away from the running code. Some things can go wrong: a network blip might happen, the remote database can be overloaded by incoming requests, a query can reveal some bug in the DBMS and crash it, your data can be out of order on that side because of some reason, and so on. Microservice architecture encourages cross-process communications over the network. Now your service asks another one for its configuration, which is stored somewhere in the database. You should prepare the software to non-deterministic failures which might occur during the data transfer. And not only then. In the blog post, we will look into some common failures which can be solved with proper retrying. The basic ideas are described using Python, but experience with the language is not required for understanding. Failures When Retry Might Help Retry helps in the places when our code acts as a client of some other backend. It can be a wrapper for a database client, a client for an HTTP server, etc. As a consumer, we expect (sometimes without any reason) that the problem which prevents successful processing can be fixed by someone else shortly. I can name two categories of problems when I look for that: - errors during data transfer - failures of processing because of load issues In the first one, our request even does not reach the eventual endpoint - application code which handles your query on the other side. Possible reasons from my experience can be various: DNSError- domain name cannot be resolved into IP. It does not always mean that the system is not available. It might happen when your destination is being redeployed. ConnectionError- we failed to perform a connection handshake successfully. The connection might be not stable on the network level at the moment of making the request. Timeout- a server fails to send a byte after the specified timeout, but the connection was previously established. Some previous requests can be even processed successfully using the instance of your HTTPClient. The error may occur when the infrastructure of your destination scaled down, and the particular server which you used does not exist now. But service is available. You need to recreate HTTPClientand try to establish a new connection. Some common database issue from the same group: OperationalError- the errors occur when connection to storage is lost or cannot be established at the moment. I think that it worth to recreate an instance of the client and try to connect again in such cases. You can see the examples of error codes returned by PostgreSQL: Class 08 — Connection Exception 08000 connection_exception 08003 connection_does_not_exist 08006 connection_failure 08001 sqlclient_unable_to_establish_sqlconnection 08004 sqlserver_rejected_establishment_of_sqlconnection ProtocolErroris an example from Redis. The exception is raised when Redis server received a sequence of bytes which is translated to a meaningless operation. Since you test your software before deploying that, it's unlikely that the error occurs because of poorly written code. Let's blame our transport layer :). Thinking about the 2nd category of failures aka load issues I'd like to review the following responses from HTTP server: 408 Request Timeoutis returned when a server spent more time processing your request than it was prepared to wait. Possible reason: a resource is overwhelmed by a lot of incoming requests. Waiting and retrying after some delay can be a good strategy to finish data processing on your side eventually. 429 Too Many Requestsmeans that you sent more requests than the server allows you during some time frame. This technique which is used by the server is also known as rate-limiting. A good thing, that a server SHOULD return Retry-Afterheader which provides a recommendation how long you need to wait before making the next request. 500 Internal Server Error. which you use you should learn what's the reason behind the response. For the developers of web servers which are reading the lines, I suggest preventing sending of the type of response if possible. Think about using more specific response when you know the reason of failure. 503 Service Unavailable- service currently cannot handle the request because of temporary overload. You can expect that it will be alleviated after some delay. The server CAN send Retry-Afterheader like it was mentioned for 429 Too Many Requestsstatus code. 504 Gateway Timeoutis similar to 408 Request Timeoutbut means that connection with your HTTP client was closed by the reverse-proxy which stands in front of the server. But, hopefully, we do not live in the world where everything is transmitted over HTTP protocol. I want to share my experience of retrying on database errors: OperationalError. Yes, we already met this guy in the blog post. Both for PostgreSQL and MySQL it additionally covers the failures which are not under control of a software engineer. Examples: a memory allocation error occurred during processing, or a transaction could not be processed. I recommend retrying on them. IntegrityError- this is a tricky one. It can be raised when a foreign key constraint is violated, like when you try to insert a Record Awhich depends on Record B. And Record Bmight: from pymysql.ert import ER # from pymysql.err _map_error(IntegrityError, ER.DUP_ENTRY, ER.NO_REFERENCED_ROW, ER.NO_REFERENCED_ROW_2, ER.ROW_IS_REFERENCED, ER.ROW_IS_REFERENCED_2, ER.CANNOT_ADD_FOREIGN, ER.BAD_NULL_ERROR) # from pymysql.constants.ER BAD_NULL_ERROR = 1048 DUP_ENTRY = 1062 NO_REFERENCED_ROW = 1216 ROW_IS_REFERENCED = 1217 ROW_IS_REFERENCED_2 = 1451 NO_REFERENCED_ROW_2 = 1452 CANNOT_ADD_FOREIGN = 1215 Knowing that information you can make your software to do not retry on IntegrityError only when it's DUP_ENTRY and retry for other reasonable cases. References: Naive Implementation of Retry Decorator I can think about retrying only for I/O operations. Starting 2014 we tend to make production software that performs such operations in the asynchronous fashion. Twisted and asyncio have been our friends all the time. Python has the expressive concept of decorators: syntax for adding new functionality to existing functions using capabilities of High-order programming. For example, we have the fetch function to make an asynchronous HTTP-request and download a page for python.org: # Example is taken from import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() # Client code, provided for reference async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, '') print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main()) The fetch function works fine, but it might be not enough reliable. It's not protected from all the HTTP errors listed above. But we can make it better: import aiohttp @retry(aiohttp.DisconnectedError, aiohttp.ClientError, aiohttp.HttpProcessingError) async def fetch(session, url): async with session.get(url) as response: return await response.text() Now the function does not give up when the specified exceptions occur. It tries to perform a request several. This easy trick can make your software more reliable and remove various sliding bugs. Let's look how the naive implementation works under the hood: import logging from functools import wraps log = logging.getLogger(__name__) def retry(*exceptions, retries=3, cooldown=1, verbose=True): "". """ def wrap(func): @wraps(func) async def inner(*args, **kwargs): retries_count = 0 while True: try: result = await func(*args, **kwargs) except exceptions as err: retries_count += 1 message = "Exception during {} execution. " \ "{} of {} retries attempted". format(func, retries_count, retries) if retries_count > retries: verbose and log.exception(message) raise RetryExhaustedError( func.__qualname__, args, kwargs) from err else: verbose and log.warning(message) if cooldown: await asyncio.sleep(cooldown) else: return result return inner return wrap As you can see, the basic idea is to catch expected exceptions until we reach the limit for the number of retries. Between each execution, we wait cooldown seconds. Also, we write logs about each failed attempt if we want to be verbose. Implementing something like that with your favorite programming language can be a good exercise. Especially, when the language does not have the concept support of higher-order functions. Or decorators. Production-grade Solutions In the example above we have a minimum number of settings to configure: - types of exceptions to retry - number of attempts - the time between attempts - verbosity for logging unsuccessful attempts Sometimes it's enough. But I know cases when you need more features. Pick the ones which look sexy for you from the list of possible capabilities: - retry on synchronous functions - stopping after some timeout, regardless of the number of attempts - wait random time within some boundaries between retries - exponential backoff sleeping between attempts - specifying additional attributes for exceptions to retry, like integer error codes (you remember the example about IntegrityError, right?) - providing hooks before and after attempts - retrying not on exceptions, but on some values which satisfy a predicate - usage of some synchronization primitive to limit the number of ongoing requests against some backend - reading configuration for retry logic from some other source dynamically like from Feature Flags as a Service - retrying forever (sounds crazy for me, but who knows about your case) If you're looking for a retry library for adding into your Python-based product you might be interested in this third-party projects: Not using Python on your backend? At least JavaScript, Go and Java have open-sourced implementations of retry helpers. Summary The product which you build does not depend only on the software which you write. You need to rely on external resources like databases or other services which perform some good things for your customers. Backend programming is about making a wrapper of calls to the software built by somebody else. From my experience, I/O operations are the most vulnerable places for all kinds of random failures. In the blog post, I shared with you my recommendations when and why we should retry. But I would like to know: How do you decide when to retry? What do you use to provide such functionality? Suggestions for using `...arguments` while working with functions in javascript. In many situations, using arguments to pass the function args would lead to bug...
https://dev.to/backendandbbq/never-give-up-retry-how-software-should-deal-with-failures
CC-MAIN-2018-26
refinedweb
1,724
55.03
From: Schalk_Cronje_at_[hidden] Date: 2004-10-20 04:49:09 Would anyone be interested in having a perl-like regex shortcut notation? The original idea was born during a local C++ focus group discussion. Looking further into the feasibility I thought that this might be a useful addition to Boost. Possibly something like the following (from some proof-of-concept code) using namespace boost::short_regex; std::string str("And he said: 'BLAH BLAH'"); // [1] Substitutes first occurrence and copy (calls boost::regex_replace) // perl: ($s2=$str) =~ s/(BLAH)/Hooray/; std::string s2= _s / "(BLAH)" / "Hooray" / str; // [2] Substitute globally and copy // perl: ($s2=$str) =~ s/(BLAH)/Hooray/g; s2= _s / "(BLAH)" / "Hooray" / _g / str; // [3] Substitute first occurrence in-place // perl: $str=~ s/(BLAH)/Hooray/; ~_s/ "(BLAH)" / "Hooray" / str; In the above _s and _g are special placeholder/tag objects sort of like _1,_2. Other could include _i (case-insensitive), _m (string as multiple lines) and _s (string as single line). Multiple modifiers can be added using (,) // [4] Substitute globally and copy // perl: ($s2=$str) =~ s/(BLAH)/Hooray/gi; s2= _s / "(BLAH)" / "Hooray" / (_g,_i) / str; The purpose will not be to shortcut all of the boost.regex functionality, just the common cases, as in perl or sed. Cases [1] and [3] is very close to the perl and would be easy to understand, however [2] and [4] is moving away from perl-syntax. This might be considered illegible by some. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2004/10/74442.php
CC-MAIN-2022-40
refinedweb
263
62.48
Data binding is one of the most popular features in development today, and the Knockout JavaScript library brings those features to HTML and JavaScript development. The simplicity of the declarative binding syntax and seamless integration with separation patterns such as Model-View-ViewModel (MVVM) make common push-and-pull plumbing tasks much simpler while making code easier to maintain and enhance. In this inaugural Client Insight column I’ll discuss the scenarios for which Knockout is ideal, explain how to get started with it and demonstrate how to use its fundamental features. The code examples, which you can download from msdn.com/magazine/msdnmag0212, demonstrate how to use declarative binding, create different types of binding objects and write data-centric JavaScript code that follows good separation patterns such as MVVM. Getting Started Knockout, developed by Steve Sanderson, is a small, open source JavaScript library with an MIT license. Knockoutjs.com maintains an updated list of the browsers that Knockout supports (currently it supports all major browsers including Internet Explorer 6+, Firefox 2+, Chrome, Opera and Safari). You need a few important resources to get started developing with Knockout. Start by getting the most recent version of Knockout (currently 2.0.0) from bit.ly/scmtAi and reference it in your project. If you’re using Visual Studio 2010, however, I highly recommend that you install and use the NuGet Package Manager Visual Studio extension to download Knockout (and any other libraries you might use) because it will manage versions and alert you when a new one is available. NuGet will download Knockout and put two JavaScript files in the scripts folder of your project. The minified file is recommended for production and follows the naming convention knockout-x.y.z.js where x.y.z is the major, minor and revision number. There’s also a knockout-x.y.x-debug.js file, which contains the Knockout source code in human-readable form. I recommend referencing this file when learning Knockout and when debugging. Once you have the files, open your HTML page (or Razor file if you’re using ASP.NET MVC), create a script and reference the knockout library: No Bindings Knockout is best explained by first examining how you would write code to push data from a source object to HTML elements without using Knockout (the relevant source code can be found in sample page 01-without-knockout.html in the downloadable code sample). I’ll then show how to accomplish the same thing using Knockout. I’ll start with some HTML target elements and push some values from a source object into these HTML elements: If you have an object from which you want to push data into standard HTML elements, you could use jQuery: This code sample uses jQuery to locate the HTML elements with the corresponding IDs and sets their values to each appropriate object property. There are three main points to notice in this code. First, the values are pushed from the source object into the HTML elements, thus requiring a line of code for each mapping from source value to target element. If there were many more properties (or if there were arrays and object graphs), the code could easily get unwieldy. Second, if the values in the source object change, the HTML elements won’t reflect that change unless the code to push the values was called again. Third, if the values change in the HTML elements (the target), the changes won’t be reflected in the underlying source object. Of course, all of this could be resolved with a lot of code, but I’ll try to resolve it using data binding. The same HTML could be rewritten using Knockout: Notice the id attributes have been replaced with data-bind attributes. Once you call the applyBindings function, Knockout binds the given object (“product” in this example) to the page. This sets the data context for the page to the product object, which means that the target elements can then identify the property of that data context to which they want to bind: The values in the source object will be pushed to the target elements in this page. (All of Knockout’s functions exist within its own namespace: ko.) The linkage between the target elements and the source object is defined by the data-bind attribute. In the preceding example, Knockout sees the data-bind attribute for the first span tag is identifying that its text value should be bound to the itemNumber property. Knockout then pushes the value for the product.itemNumber property to the element. You can see how using Knockout could easily reduce code. As the number of properties and elements increase, the only JavaScript code required is the applyBindings function. However, this doesn’t yet solve all of the problems. This example doesn’t yet update the HTML targets when the source changes, nor does the source object update when the HTML targets change. For this, we need observables. Observables Knockout adds dependency tracking through observables, which are objects that can notify listeners when underlying values have changed (this is similar to the concept of the INotifyPropertyChanged interface in XAML technology). Knockout implements observable properties by wrapping object properties with a custom function named observable. For example, instead of setting a property in an object like so: you can define the property to be an observable property using Knockout: Once the properties are defined as observables, the data binding really takes shape. The JavaScript code shown in Figure 1 demonstrates two objects that Knockout binds to HTML elements. The first object (data.product1) defines its properties using a simple object literal while the second object (data.product2) defines the properties as Knockout observables. $(document).ready(function () { var data = { product1: { id: 1002, itemNumber: "T110", model: "Taylor 110", salePrice: 699.75 }, product2: { id: ko.observable(1001), itemNumber: ko.observable("T314CE"), model: ko.observable("Taylor 314ce"), salePrice: ko.observable(1199.95) } }; ko.applyBindings(data); }); The HTML for this sample, shown in Figure 2, shows four sets of element bindings. The first and second div tags contain HTML elements bound to non-observable properties. When the values in the first div are changed, notice that nothing else changes. The third and fourth div tags contain the HTML elements bound to observable properties. Notice that when the values are changed in the third div, the elements in the fourth div are updated. You can try this demo out using example 02-observable.html. <div> <h2>Object Literal</h2> <span>Item number</span><span data-</span> <br/> <span>Guitar model:</span><input data- <span>Sales price:</span><input data- </div> <div> <h2>Underlying Source Object for Object Literal</h2> <span>Item number</span><span data-</span> <br/> <span>Guitar model:</span><span data-</span> <span>Sales price:</span><span data-</span> </div> <div> <h2>Observables</h2> <span>Item number</span><span data-</span> <br/> <span>Guitar model:</span><input data- <span>Sales price:</span><input data- </div> <div> <h2>Underlying Source Object for Observable Object</h2> <span>Item number</span><span data-</span> <br/> <span>Guitar model:</span><span data-</span> <span>Sales price:</span><span data-</span> </div> (Note: Knockout doesn’t require you to use observable properties. If you want DOM elements to receive values once but then not be updated when the values in the source object change, simple objects will suffice. However, if you want your source object and target DOM elements to stay in sync—two-way binding—then you’ll want to consider using observable properties.) Built-in Bindings The examples thus far have demonstrated how to bind to the Knockout’s text and value bindings. Knockout has many built-in bindings that make it easier to bind object properties to target DOM elements. For example, when Knockout sees a text binding, it will set the innerText property (using Internet Explorer) or the equivalent property in other browsers. When the text binding is used, any previous text will be overwritten. While there are many built-in bindings, some of the most common for displaying can be found in Figure 3. The Knockout documentation online contains a complete list in the left navigation pane (bit.ly/ajRyPj). Figure 3 Common Knockout Bindings ObservableArrays Now that the previous examples got your feet wet with Knockout, it’s time to move on to a more practical yet still fundamental example with hierarchical data. Knockout supports many types of bindings, including binding to simple properties (as seen in the previous examples), binding to JavaScript arrays, computed bindings and custom bindings (which I’ll look at in a future article on Knockout). The next example demonstrates how to bind an array of product objects using Knockout to a list (shown in Figure 4). Figure 4 Binding to an Observable Array When dealing with object graphs and data binding, it’s helpful to encapsulate all of the data and functions the page requires into a single object. This is often referred to as a ViewModel from the MVVM pattern. In this example the View is the HTML page and its DOM elements. The Model is the array of products. The ViewModel glues the Model to the View; the glue it uses is Knockout. The array of products is set up using the observableArray function. This is similar to the ObservableCollection in XAML technologies. Because the products property is an observableArray, every time an item is added to or removed from the array, the target elements will be notified and the item will be added or removed from the DOM, as shown here: The showroomViewModel is the root object that will be data bound to the target elements. It contains a list of products, which come in from a data service as JSON. The function that loads the product list is the showroomViewModel.load function, which appears in Figure 5 along with the rest of the JavaScript that sets up the showroomViewModel object (you’ll find the complete source and sample data for this example in 03-observableArrays.html). The load function loops through the sample product data and uses the Product function to create the new product objects before pushing them into the observableArray. var photoPath = "/images/"; function Product () { this.id = ko.observable(); this.salePrice = ko.observable(); this.listPrice = ko.observable(); this.rating = ko.observable(); this.photo = ko.observable(); this.itemNumber = ko.observable(); this.description = ko.observable(); this.photoUrl = ko.computed(function () { return photoPath + this.photo(); }, this); }; var showroomViewModel = { products: ko.observableArray() }; showroomViewModel.load = function () { this.products([]); // reset $.each(data.Products, function (i, p) { showroomViewModel.products.push(new Product() .id(p.Id) .salePrice(p.SalePrice) .listPrice(p.ListPrice) .rating(p.Rating) .photo(p.Photo) .itemNumber(p.ItemNumber) .description(p.Description) ); }); }; ko.applyBindings(showroomViewModel); Although a product’s properties are all defined using observables, they don’t necessarily need to be observable. For example, these could be plain properties if they’re read-only, and if—when the source changes—either the target isn’t expected to be updated or the entire container is expected to be refreshed. However, if the properties need to be refreshed when the source changes or is edited in the DOM, then observable is the right choice. The Product function defines all of its properties as Knockout observables (except photoUrl). When Knockout binds the data, the products array property can be accessed, making it easy to use standard functions such as length to show how many items are currently data bound: Control-of-Flow Bindings The array of products can then be data bound to a DOM element, where it can be used as an anonymous template for displaying the list. The following HTML shows that the ul tag uses the foreach control-of-flow binding to bind to the products: The elements inside the ul tag will be used to template each product. Inside the foreach, the data context also changes from the root object showroomViewModel to each individual product. This is why the inner DOM elements can bind to the photoUrl and salePrice properties of a product directly. There are four main control-of-flow bindings: foreach, if, ifnot and with. These control bindings allow you to declaratively define the control of flow logic without creating a named template. When the if control-of-flow binding is followed by a condition that is truthy or the ifnot binding is followed by a condition that evaluates to false, the contents inside of its block are bound and displayed, as shown here: The with binding changes the data context to whatever object you specify. This is especially useful when diving into object graphs with multiple parent/child relationships or distinct ViewModels within a page. For example, if there’s a sale ViewModel object that’s bound to the page and it has child objects customer and salesPerson, the with binding could be used to make the bindings more readable and easier to maintain, as shown here: Computed Observables You might have noticed that the Product function defined the photoUrl as a special type of computed property. ko.computed defines a binding function that evaluates the value for the data-binding operation. The computed property automatically updates when any of the observables it depends on for its evaluation change. This is especially useful when the value isn’t clearly represented in a concrete value in the source object. Another common example besides creating a URL is creating a fullName property out of firstName and lastName properties. (Note: Previous versions of Knockout referred to computed properties as dependentObservable. Both still work in Knockout 2.0.0, but I recommend using the newer computed function.) A computed property accepts a function for evaluating the value and the object that will represent the object to which you’re attaching the binding. The second parameter is important because JavaScript object literals don’t have a way of referring to themselves. In Figure 5 the this keyword (which represents the showroomViewModel) is passed in so the dependent observable’s function can use it to get the photo property. Without this being passed in, the photo function would be undefined and the evaluation would fail to produce the expected URL: Understanding Fundamental Binding Properties This column got you started with data binding using the Knockout JavaScript library. The most important aspect of Knockout is to understand the fundamental binding properties: observable, observableArray and computed. With these observables you can create robust HTML apps using solid separation patterns. I also covered the more common built-in bindings types and demonstrated the control-of-flow bindings. However, Knockout supports much more functionality. Next time, I’ll explore built-in bindings in more detail. John Papa is a former evangelist for Microsoft on the Silverlight and Windows 8 teams, where he hosted the popular Silverlight TV show. He has presented globally at keynotes and sessions for the BUILD, MIX, PDC, Tech•Ed, Visual Studio Live! and DevConnections events. Papa is also a columnist for Visual Studio Magazine (Papa’s Perspective) and author of training videos with Pluralsight. Follow him on Twitter at twitter.com/john_papa. Thanks to the following technical expert for reviewing this article: Steve Sanderson Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/hh781029.aspx
CC-MAIN-2016-30
refinedweb
2,551
52.49
Copyright © 2010 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply. submitted for consideration to the W3C's Semantic Web Interest Group (SWIG) to publish it as a W3C Interest Group Note. The SWIG does not expect this document to become a W3C Recommendation. Publication as an Editor's Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress. Feedback on this document is welcome - please send comments to semantic-web@w3.org (with public archive). Additionally, we encourage to use the voiD issue tracker to record and track comments. The IPR status of information provided in this document is in accordance with Section 6 of the W3C Patent Policy. Disclosure obligations of the Participants of this group are described in the SWIG charter. A first version of this document was developed and published by the authors, starting in 2008. This is an extended and improved version, based on community feedback received since the original publication.. VoiD covers four areas of metadata: Deployment and discovery of voiD descriptions is discussed as well. This document is one of the two core documents of voiD; the other is the voiD vocabulary definition [VOID-VOC]. This document is aimed at both dataset publishers (those involved in maintaining, administering and hosting datasets), and data users (those involved in finding, querying, crawling and indexing datasets). Readers of this document should be familiar with the core concepts of RDF [RDF-PRIMER] and RDF Schema [RDFS]. Knowledge of the Turtle syntax [TURTLE] for RDF is required to read the examples. Some knowledge of widely-used vocabularies (Dublin Core [DC], Friend of a Friend [FOAF]) is also assumed. All examples in this document are written in the Turtle RDF syntax [TURTLE]. Throughout the document, the following namespaces are used: @prefix void: <> . @prefix rdf: <> . @prefix rdfs: <> . @prefix owl: <> . @prefix xsd: <> . @prefix dcterms: <> . @prefix foaf: <> . @prefix wv: <> . @prefix sd: <> . Furthermore, we assume that the empty prefix is bound to the base URL of the current file like this: @prefix : <#> . This allows us to quickly mint new identifiers in the local namespace: :MyDataset, :DBpedia and so on. Later sections of this specification provide more guidance on deploying voiD descriptions. The fundamental concept of voiD is the dataset. A dataset is a set of RDF triples that are published, maintained or aggregated by a single provider. Unlike RDF graphs, which are purely mathematical constructs [RDF-CONCEPTS],. Since most datasets describe a well-defined set of entities, datasets can also be seen as a set of descriptions of certain entities, which often share a common URI prefix (such as). In voiD, a dataset is modelled as an instance of the void:Dataset class. Such a void:Dataset instance is a single RDF resource that represents the entire dataset, and thus allows us to easily make statements about the entire dataset and all its triples. The relationship between a void:Dataset instance and the concrete triples contained in the dataset is established through access information, such as the address of a SPARQL endpoint where the triples can be accessed. The following example declares the resource :DBpedia as a void:Dataset: :DBpedia a void:Dataset . The resource is intended as a proxy for the well-known DBpedia dataset [DBPEDIA]. A good next step would be to make this unambiguously clear by adding general metadata and access metadata to the resource. voiD also allows the description of RDF links between datasets. An RDF link is an RDF triple whose subject and object are described in different datasets. A linkset is a collection of such RDF links between two datasets. It is a set of RDF triples where all subjects are in one dataset and all objects are in another dataset. RDF links often have the owl:sameAs predicate, but any other property could occur as the predicate of RDF links as well. In voiD, a linkset is modelled as an instance of the void:Linkset class. void:Linkset is a subclass of void:Dataset. The following example declares the resource :DBpedia_Geonames as a void:Linkset: :DBpedia_Geonames a void:Linkset . The resource is intended as a proxy for a set of triples that link resources in the DBpedia [DBPEDIA] and Geonames [GEONAMES] datasets. A good next step would be to make this clear by stating that these two datasets are the targets of the linkset. Links are sometimes published as part of a larger dataset. For example, many of the resources described in the DBpedia dataset are linked via owl:sameAs to other datasets. In other cases, linksets are handled as stand-alone sets of triples, independently from either of the two linked datasets. For example, link generation tools such as Silk [SILK] can discover new links between two existing datasets. Both cases—linksets published as part of a larger dataset, and linksets that are independent from the linked datasets—can be described in voiD. Note that rdf:type statements are not considered links for the purposes of voiD, even though subject and object typically reside on different domains. VoiD has a dedicated mechanism for listing the classes used in a dataset. This section describes how to provide general metadata about a dataset or linkset. General metadata helps potential users of a dataset to decide whether the dataset is appropriate for their purposes. It includes information such as a title and description, the license of the dataset, and information about its subject. Due to the inherently extensible design of RDF, any other property not listed here can of course also be used to describe a dataset. Almost every dataset will have a homepage of some sort on the web, where further information about the dataset can be found. A link to the dataset's homepage can be provided with the foaf:homepage property: :DBpedia a void:Dataset; foaf:homepage <>; . It is expected that the homepage linked to in fact talks about the dataset described. As foaf:homepage is an Inverse Functional Property ([OWL], Section 6.1), different descriptions of a dataset provided in different places on the Web can be automatically connected or “smushed” if they use the same homepage URI. To avoid inappropriate “smushing”, one should not use related pages that are not specifically about the dataset, such as the funding project's homepage or publishing organisation's homepage, as the value of foaf:homepage. Additional web pages with relevant information that can not be considered the homepage of the dataset can be linked with foaf:page: :DBpedia a void:Dataset; foaf:homepage <>; foaf:page <>; foaf:page <>; . The Dublin Core Metadata Terms [DC] contain a number of useful and recommended properties for providing basic metadata about a dataset. The following example shows a description of DBpedia that uses many of the properties above. It also provides additional details about some of the resources mentioned in the Dublin Core metadata, in particular the contributing organizations: :DBpedia a void:Dataset; dcterms:title "DBPedia"; dcterms:description "RDF data extracted from Wikipedia"; Using data that does not have an explicit license is a potential legal liability. Therefore, it is very important that publishers make explicit the terms under which the dataset can be used. The dcterms:license property should be used to to point to the license under which a dataset has been published. The URIs of Some licenses designed specifically for data are: The use of other licenses that are not designed specifically for data is discouraged because they may not have the intended legal effect when applied to data. Nevertheless, some other licenses are currently in common usage, including: While a publisher may want to facilitate reuse of their data with a very liberal rights statement, they may still wish to point to some community norms. Norms are non-binding conditions of use that publishers would like to encourage the users of their data to adopt. This can be done with the waiver:norms property defined in the Waiver vocabulary [WAIVER]. A common community norm is ODC Attribution Sharealike. In brief, it asks that changes and updates to the dataset are made public too, that credit is given, that the source of the data is linked, that open formats are used, and that no DRM is applied: The following example states that the Example dataset is published under the terms of the Open Data Commons Public Domain Dedication and License, and that users are encouraged (but not legally bound) to follow the community norms mentioned above. :Example a void:Dataset ; dcterms:license <>; wv:norms <>; wv:waiver """To the extent possible under law, The Example Organisation has waived all copyright and related or neighboring rights to The Example Dataset."""; . tag a dataset with a topic. <>; . DBpedia might not contain the concepts for describing some domain specific datasets. For example, there are no exact DBpedia resource URIs for “in situ hybridisation images” or “UniProt Genes”. In such cases, datasets should be tagged with concept URIs that are widely adopted in the respective community. Concept URIs from a SKOS concept scheme [SKOS] are particularly appropriate. Using widely adopted domain-specific concepts ensures that not only the categorisation is precisely captured, but also that these datasets could be connected with other relevant data from their domains. For example, we could define that: :Bio2RDF a void:Dataset; dcterms:subject <>; . The property of void:feature can be used for expressing certain technical features of a dataset, such as its supported RDF serialization formats. The domain of the property is void:Dataset and its range is void:TechnicalFeature. W3C provides a list of unique URIs [UUFFF] to describe file formats. Those that are relevant to RDF serialization format are listed in the following table. For example, using the W3C URIs together with void:feature we can express that “a dataset is available as RDF/XML”: :DBpedia a void:Dataset; void:feature <>; . These W3C URIs are instances of class, which is a sub-class of void:TechnicalFeature. If users need to describe, for example, other media types besides those provided by W3C or HTTP features such as content negotiation or etag headers, they should create the URIs under their own namespace or reuse existing URIs and define them as an instance of void:TechnicalFeature. For example, the following code shows how one could define a feature :HTTPCachingETags as an instance of void:TechnicalFeature. :HTTPCachingETags a void:TechnicalFeature; rdfs:label "HTTP ETag support"; rdfs:comment "the dataset supports HTTP caching using ETags"; rdfs:seeAlso <>; . Datasets in voiD are defined as sets of RDF triples. But the actual RDF triples are not part of the voiD description. Instead, access metadata is used to describe methods of accessing the actual RDF triples. If the entities described in a dataset are identified by HTTP URIs, then it is a reasonable assumption that resolving such a URI will return an RDF description of the entity. A SPARQL endpoint that provides access to a dataset via the SPARQL protocol can be announced using void:sparqlEndpoint: :DBpedia a void:Dataset; void:sparqlEndpoint <>; . This states that the default graph of the SPARQL endpoint contains the triples in the DBpedia dataset. voiD descriptions can be deployed as part of a SPARQL Service Description. This also allows the expression of further information about the features and capabilites of the SPARQL endpoint, as described in the SPARQL 1.1 Service Description [SPARQL-SD] specification. Note: In some SPARQL endpoints, named graphs are used to partition the data. Currently voiD doesn't provide a dedicated way of stating that a dataset is contained in a specific named graph. This kind of information can be provided in a SPARQL Service Description, as described below. If an RDF dump of the dataset is available, then its location can be announced using void:dataDump. If the dataset is split into multiple dumps, then several values of this property can be provided. The format of such dumps is not prescribed, but clients should expect dumps to be in one of the usual RDF serializations (RDF/XML, N-Triples, Turtle), and possibly compressed using GZip or other compression algorithms. The following example states that the complete :NYTimes dataset is available as a set of four RDF files. :NYTimes a void:Dataset; void:dataDump <>; void:dataDump <>; void:dataDump <>; void:dataDump <>; . Note: The void:dataDump property should not be used for linking to a download web page. It should only be used for linking directly to dump files. This is to ensure that the link can be used by automated spiders that cannot find their way through an HTML page. If a publisher desires to provide a link to a download page as well, then they should use the foaf:page property instead. Many datasets are structured in a tree-like fashion, with one or a few natural “top concepts” or “entry points”, and all other entities reachable from these root resources in a small number of steps. One or more such root resources can be named using the void:rootResource property. Naming a resource as a root resource implies: Root resources make good entry points for crawling an RDF dataset. This property is similar to void:exampleResource. While void:exampleResource names particularly representative or typical resources in the dataset, void:rootResource names particularly important or central resources that make good entry points for navigating the dataset. Besides the SPARQL protocol, a simple URI lookup protocol for accessing a dataset can also be described using voiD. Such a protocol could take the following steps: Note: The HTTP request should be performed with an HTTP Accept header that indicates the formats supported by the requesting client, e.g. “ Accept: application/rdf+xml” for a client that only supports RDF/XML. The following example shows how the Sindice API [SINDICE-API] could be described as a voiD dataset with a URI lookup endpoint: :Sindice a void:Dataset ; void:uriLookupEndpoint <> . Some datasets offer a free text search capability. Dataset publishers may create an OpenSearch Description Document [OPENSEARCH] that describes their text search service. This can be linked to a Dataset resource using the void:openSearchDescription property: :Sindice a void:Dataset; void:openSearchDescription <>. The RDF data model is highly flexible and places almost no constraints on the structure of datasets. This flexibility has many advantages, but also makes interacting with an unfamiliar dataset harder. Structural metdata provides high-level information about the schema and internal structure of a dataset and can be helpful when exploring or querying datasets. This includes information such as the vocabularies used in the dataset, statistics about the size of the dataset, and examples of typical resources in the dataset. For documentation purposes, it can be helpful to name some representative example entites for a dataset. Looking up these entities allows users to quickly get an impression of the kind of data that is present in a dataset. The void:exampleResource property names one or more such examples: :DBpedia a void:Dataset; void:exampleResource <> ; void:exampleResource <> ; void:exampleResource <> ; . Note: Datasets that are published as linked data with resolvable URIs often have two distinct URIs for an entity and for the RDF document describing the entity [COOL]. True entity URIs should be preferred as void:exampleResources. Example resources can also be given for linksets. The resource should be either the subject or the object of a representative link from the set. If the linkset is a void:subset of another dataset D, that is, the linkset is contained in D, then a resource described in D should be preferred as the example for the linkset. For example, if the linkset :DBpedia_Geonames is a subset of DBpedia, and we choose <> owl:sameAs <>. as a representative link, then we should use the resource from the DBpedia side as the void:exampleResource for the linkset, because users can look up the example in DBpedia, but not necessarily in Geonames. Often, the entities described in a dataset share URIs of a common form. For example, all DBpedia entity URIs start with. The void:uriSpace property can be used to state that all entity URIs in a dataset start with a given string. In other words, they share a common “URI namespace”. Issue: The range of void:uriSpace (literal or resource) is still under discussion. This is Issue 91. In cases where a simple string prefix match is insufficient, the void:uriRegexPattern property can be used. It expresses a regular expression pattern that matches the URIs of the dataset's entities. The pattern should use the same regular expression syntax as SPARQL, which uses the syntax definition of XML Schema 2: Regular Expressions ([XSD], Appendix F). The regular expression must match somewhere in the URI. It is a good practice to anchor the regular expression with a ^ in the beginning, and to escape dots with a backslash. A simple example of using void:uriRegexPattern, equivalent to the void:uriSpace example above: :DBpedia a void:Dataset; void:uriRegexPattern "^\\.org/resource/"; . Note: In the Turtle syntax, any backslashes in literals have to be escaped with another backslash. This is why the example above contains double backslashes. In RDF/XML, the same literal would be written as: <void:uriRegexPattern>^\.org/resource/</void:uriRegexPattern> A more complex example follows: :DBpediaTurtleFiles a void:Dataset; void:uriRegexPattern "^\.org/(.+)\.ttl$"; void:feature <> . This defines a dataset (presumably a subset of :DBpedia) that contains only URIs ending in .ttl, and states that they have Turtle representations, using void:feature. Note: One can use the REGEX filter function of SPARQL to check whether a URI matches a void:uriRegexPattern. The SPARQL standard does not contain a function for comparing string prefixes, so the same cannot be safely done with void:uriSpace (although some SPARQL implementations support such string comparisons via extension functions). This is one advantage of void:uriRegexPattern. To obtain an equivalent regular expression from a void:uriSpace URI, prepend it with the “ ^” character and escape any of the characters “ .()[]+*?$” with a backslash. Every RDF dataset uses one or more RDFS vocabularies or OWL ontologies. The vocabulary provides the terms (classes and properties) for expressing the data. The void:vocabulary property can be used to list vocabularies used in a dataset. Every value of void:vocabulary must be a URI that identifies a vocabulary or ontology that is used in the dataset. These URIs can be found as follows: The following table illustrates this: It is not necessary to list all vocabularies. Typically, only the most important vocabularies will be listed, especially those that can be useful in querying the dataset. The following example states that the :LiveJournal dataset uses the FOAF vocabulary [FOAF]. :LiveJournal a void:Dataset; void:vocabulary <>; . The void:vocabulary property can only be used for entire vocabularies. It can not be used to express that individual classes and properties occur in a dataset. For this purpose, class partitions and property partitions can be used. The void:subset property can be used to provide descriptions of parts of a dataset. A part of a dataset is itself a void:Dataset, and any of the annotations for datasets listed in this Guide can be applied to the subset. Reasons for subdividing a dataset might include: dcterms:source) dcterms:date) void:sparqlEndpoint) dcterms:subject) void:dataDump) The last example is expressed in the following snippet, which expresses the fact that parts of the DBpedia dataset can be downloaded as separate RDF dumps: :DBpedia a void:Dataset; void:subset :DBpedia_shortabstracts; void:subset :DBpedia_infoboxes; . :DBpedia_shortabstracts a void:Dataset; dcterms:title "DBpedia Short Abstracts"; dcterms:description "Short Abstracts (max. 500 chars long) of Wikipedia Articles"; void:dataDump <>; . :DBpedia_infoboxes a void:Dataset; dcterms:title "DBpedia Infoboxes"; dcterms:description "Information that has been extracted from Wikipedia infoboxes."; void:dataDump <>; . Making statements about a subset emphasizes that the statements apply only to a part of the dataset, and not the whole dataset. Note that the void:subset mechanism can also be used to describe aggregated datasets, in addition to partitioned datasets. The aggregation of two datasets :DS_A and :DS_B can be described like this: :Aggregate_DS a void:Dataset; dcterms:title "Aggregate Dataset"; dcterms:description "An aggregate of the A and B datasets."; void:sparqlEndpoint <>; void:subset :DS_A; void:subset :DS_B; . Class- and property-based partitioning offers a way of talking about particular classes and properties in a dataset. Note that void:classPartition and void:propertyPartition are subproperties of void:subset. This means that the partition is itself a dataset. A dataset that is the void:classPartition of another dataset must have exactly one void:class property. The partition contains all triples that describe entities that have this class as their rdf:type. A class-based partition with rdfs:Resource as its void:class is defined to also contain all resources that have no explicit rdf:type statement. A dataset that is the void:propertyPartition of another dataset must have exactly one void:property property. The partition contains all triples that have this property as their predicate. A partition without any statistical properties is thought to contain at least one triple. Hence, the following example asserts that the classes foaf:Person and foaf:Organization and the properties foaf:name, foaf:member, foaf:homepage and rdf:type are used in the dataset :MyDataset, without any assertion about the number of instances: :MyDataset a void:Dataset; void:classPartition [ void:class foaf:Person; ]; void:classPartition [ void:class foaf:Organization; ]; void:propertyPartition [ void:property foaf:name; ]; void:propertyPartition [ void:property foaf:member; ]; void:propertyPartition [ void:property foaf:homepage; ]; void:propertyPartition [ void:property rdf:type; ]; . voiD provides a number of properties for expressing numeric statistics about a dataset, such as the number of RDF triples it contains, or the number of entities it describes. Note: A previous version of voiD defined a different approach to statistics, based on the Statistical Core Vocabulary [SCOVO]. It was found to have several disadvantages. Statistics would be verbose, and querying them with SPARQL was difficult. A description of the SCOVO-based approach can be found in archived older versions of the voiD Guide ([VOID-GUIDE-1], Section 3). We discourage its further use. As a general rule, statistics in voiD can always be provided as approximate numbers. voiD defines the following properties for expressing different statistical characteristics of datasets: The following example states the approximate number of triples and entities in the DBpedia dataset: :DBpedia a void:Dataset; void:triples 1000000000; void:entities 3400000; . Since void:Linkset is a subclass of void:Dataset, statistics about the triples in a linkset can be provided in the same way as for datasets. Most importantly, the number of links in a linkset can be recorded with void:triples. The following example states that the DBpedia-to-DBLP linkset contains approximately 10,000 owl:sameAs links: :DBpedia2DBLP a void:Linkset; void:target :DBpedia; void:target :DBLP; void:linkPredicate owl:sameAs; void:triples 10000; . Class- and property-based partitions can be used to provide statistics such as the number of instances of a given class and the number of triples that have a certain predicate. Partitions can be described with voiD's usual statistical features, such as void:entities and void:triples. The following example shows how this approach is used to state that the DBpedia dataset contains 312,000 entities of class foaf:Person, and 312,000 triples that have the foaf:name predicate: :DBpedia a void:Dataset; void:classPartition [ void:class foaf:Person; void:entities 312000; ]; void:propertyPartition [ void:property foaf:name; void:triples 312000; ]; . A class-based partition for the foaf:Person class is defined, and it is stated to contain 312,000 entities. Because a class-based partition contains only the subset that describes entities of a single class ( foaf:Person in this case), we can conclude that the DBpedia dataset describes 312,000 people. Statistics about further classes could be given in the same way. Note: Many dataset statistics can be calculated automatically by running SPARQL queries over the dataset. Some informative examples for SPARQL queries that compute statistics are given in the voiD wiki. The void:Linkset class is a subclass of void:Dataset. All patterns for describing datasets can equally be used for linksets. There are however a number of specific properties for describing linksets. The structure of a typical linkset description is illustrated below: It expresses that the DBpedia dataset contains a subset of owl:sameAs links that connect resources in DBpedia to resources in Geonames. Linksets are defined as collections of RDF triples where subjects and objects of the triples are described in different datasets. The void:target property is used to name the two datasets. Every linkset must have exactly two distinct void:targets. The following example states that the :DBpedia_Geonames linkset connects the :DBpedia and :Geonames datasets. Presumably, the voiD file would contain additional information about those two resources: :DBpedia_Geonames a void:Linkset; void:target :DBpedia; void:target :Geonames; . void:target has subproperties void:subjectsTarget and void:objectsTarget. These can be used to state the directions of the links explicitly: The subjects of all link triples are in the dataset named by void:subjectsTarget, and the objects in void:objectsTarget. Note that this does not say anything about which dataset physically contains the link triples; they could be in either one. A linkset may not have more than one void:subjectsTarget. A linkset may not have more than one void:objectsTarget. To state that a linkset is a part of a larger dataset, the void:subset property should be used: :DBpedia_Geonames a void:Linkset; void:target :DBpedia; void:target :Geonames; void:subset :DBpedia; void:triples 252000; . The example expresses that the DBpedia dataset contains a linkset of 252,000 links to Geonames. The property void:linkPredicate can be used to specify the type of links that connect two datasets. In other words, it names the RDF property in the predicate position of the link triples. The following example uses void:linkPredicate to state that the DBpedia and Geonames datasets are linked by triples that have the owl:sameAs predicate: :DBpedia_Geonames a void:Linkset; void:target :DBpedia; void:target :Geonames; void:linkPredicate owl:sameAs; . A single void:Linkset should never have more than one value for void:linkPredicate. If two datasets are connected by links of multiple RDF predicates, a separate void:Linkset should be created for each type of link. For example, if datasets D1 and D2 are connected by two different types of links, through predicates p1 and p2: :D1 a void:Dataset . :D2 a void:Dataset . :L1 a void:Linkset; void:linkPredicate :p1; void:target :D1; void:target :D2; . :L2 a void:Linkset; void:linkPredicate :p2; void:target :D1; void:target :D2; . The voiD classes and properties are designed to be flexible and can be used in many different contexts. Some typical deployment scenarios for voiD and deployment-related considerations will be discussed in this section. An instance of void:Dataset stands as a proxy for an entire set of RDF triples. As always with RDF, an important question is what URI to choose for this dataset resource. The use of blank nodes for void:Dataset and void:Linkset instances is generally discouraged, because blank nodes do not provide identifiers for linking to a resource. However, if the dataset resource is not of particular importance, and if the creation of stable URIs would be difficult, then a blank node can be acceptable, for example when subsets and partitions are defined solely for the purpose of expressing statistics. When referring to a dataset published by another party (for example as a linkset target, or in a store that aggregates multiple other datasets), it is good practice to check whether the original publisher of the dataset has provided a voiD description (see the Discovery section on methods for discovering voiD descriptions), and use the URI assigned to the dataset there. If no URI has been provided by the original publisher, then one should mint a new URI in one's own namespace. When one doesn't use a URI provided by the original data provider, then one should include a link to the homepage of the dataset to allow “smushing” based on the foaf:homepage Inverse Functional Property. Publishers are encouraged to provide descriptions of their datasets by publishing a voiD file on the web along with the dataset. Popular options for publishing a voiD description alongside a dataset include: void.ttlin the root directory of the site, with a local “hash URI” for the dataset, yielding a dataset URI such as., as the dataset URI, and serving both HTML and an RDF format via content negotiation from that URI (see Cool URIs for the Semantic Web [COOL] for a more detailed description of this publishing approach). voiD authors are encouraged to provide metadata for their voiD files. This can be done by adding a document metadata block to the voiD file. A typical document metadata block will contain: void:DatasetDescription. foaf:topicor foaf:primaryTopicstatements that relate the voiD file to the dataset(s) described therein. If the voiD file describes a single dataset, then foaf:primaryTopicshould be used. If the file describes several datasets of equal importance, then foaf:topicshould be used. An example metadata block is shown below. Note the use of an empty-string relative URI (<>) as a syntactic shortcut. In Turtle and RDF/XML, the empty string URI stands for the URI of the document that contains the statements. <> a void:DatasetDescription; dcterms:title "A voiD Description of the DBpedia Dataset"; dcterms:creator <>; foaf:primaryTopic :DBpedia; . RDF datasets are often published on the web as many individual RDF documents. A common deployment pattern is to provide one description document for each resource in the dataset. On RDFa-enabled websites, each web page becomes an RDF document. Providing metadata about the entire dataset in such a scenario should not be done by including voiD details in every document. Rather, a single voiD description of the entire dataset should be published, and individual documents should point to this description via backlinks. A voiD backlink is a triple that points from an RDF document URI to a void:Dataset URI using the void:inDataset property: <> void:inDataset :DBpedia . Such a triple asserts that the triples serialised in the document are part of the dataset. Consequently, metadata of the dataset such as provenance and licensing information should be understood as applying to the data in the document. One should not specify multiple void:inDataset for the same document. Rather, we encourage to create a new void:Dataset that contains both as a subset, and link to that. Then, you can explicitly add metadata, like licenses, to the joint dataset. Note: Older versions of voiD suggested to use dcterms:isPartOf instead of void:inDataset. As dcterms:isPartOf is used for other purposes as well, we introduced a dedicated property in the voiD namespace. VoiD can be used to provide self-describing metadata in RDF dumps. To describe an RDF dump, one should not use the dump's download URL as a void:Dataset and attach metadata to it. Instead, one should use a different URI for the void:Dataset, following the good practices for choosing dataset URIs. Metadata statements should then be made about that URI. The void:dataDump property should be used to relate the dataset URI to the download URI of the RDF dump. The W3C SPARQL 1.1 Service Description [SPARQL-SD] specification provides a rich vocabulary for describing a SPARQL endpoint's capabilities and features, as well as a discovery mechanism for such SPARQL service descriptions. VoiD can be used in SPARQL service descriptions to provide additional information about the data available in a store. The SPARQL Service Description vocabulary defines two classes that can be aligned with voiD: sd:Datasetrepresents a SPARQL dataset ([SPARQL], Section 8), that is, a set of zero or more named graphs plus an optional default graph. Note that sd:Datasethas a narrower definition than void:Dataset: Any collection of triples can be a void:Dataset, while sd:Datasetalso requires that the triples are associated with the default graph or named graphs. sd:Graphrepresents an RDF graph within an sd:Dataset, either the default graph or one of the named graphs. void:Dataset is a superclass of sd:Dataset and of sd:Graph. Therefore, any instance of these classes can be described just like any other voiD dataset. The following fictional example describes a SPARQL endpoint that provides access to a mirror of DBpedia and Geonames in distinct named graphs, as well as to the service description itself in the default graph: <#service> a sd:Service; sd:url <>; sd:defaultDatasetDescription [ a sd:Dataset; dcterms:title "GeoPedia"; dcterms:description "A mirror of DBpedia and Geonames"; void:triples 1100000100; sd:defaultGraph [ a sd:Graph, void:Dataset; dcterms:title "GeoPedia SPARQL Endpoint Description"; dcterms:description "Contains a copy of this SD+voiD file!"; void:triples 100; ]; sd:namedGraph [ sd:name <>; sd:graph [ a sd:Graph, void:Dataset; dcterms:title "DBpedia"; foaf:homepage <>; void:triples 1000000000; ]; ]; sd:namedGraph [ sd:name <>; sd:graph [ a sd:Graph, void:Dataset; dcterms:title "Geonames"; foaf:homepage <>; void:triples 100000000; ]; ]; ]; . This section describes approaches for discovering the voiD description of a dataset given the URI of an entity described in a dataset. Note: a previous version of voiD had a discovery mechanism based on robots.txt and Semantic Sitemaps, which was deprecated because it was not widely adopted. For datasets that are published as a collection of RDF documents in the linked data style, the preferred mechanism of discovering an associated voiD description is the void:inDataset back-link mechanism. Clients should look for a void:inDataset triple that links the RDF document to the dataset: <document.rdf> void:inDataset <void.ttl#MyDataset>. A new discovery mechanism for voiD, based on the .well-known mechanism defined in RFC 5758 [RFC5758], is currently under preparation. This mechanism is defined in a separate document, Autodiscovery of voiD descritpions [DISCOVERY]. Progress on the IETF registration is tracked as Issue 74. The following tables give a quick overview of the terms defined in the voiD vocabulary. These tables are not normative; the normative definition of these terms is the voiD vocabulary document [VOID-VOC]. Our thanks go out to some chaps who influenced the design of voiD, provided use cases and ensured that we would never get bored too quickly. These people were (alphabetically): Dan Brickley, Li Ding, Orri Erling, Hugh Glaser, Olaf Hartig, Tom Heath, Toby Inkster, Ian Millard, Marc-Alexandre Nolin, Yves Raimond, Yrjänä Rankka, Francois Scharffe, Giovanni Tummarello, William Waites, Stuart Williams. The work has partly been supported by the following projects: $Log: index.html,v $ Revision 1.1 2011/01/17 11:31:13 mhausenb added dated version of voiD guide for 2010-12-16 (submission to SWIG and review start)
http://www.w3.org/2001/sw/interest/ED-void-20101216/
CC-MAIN-2015-35
refinedweb
5,798
53.41
Le decadi 10 thermidor, an CCXIX, Stefano Sabatini a écrit : > What's exactly the meaning of "back", and/or where I can find a > description of it? From audioconvert.h, with namespace prefix removed for readability: #define 5POINT0 (SURROUND | SIDE_LEFT | SIDE_RIGHT) #define 5POINT0_BACK (SURROUND | BACK_LEFT | BACK_RIGHT) Therefore, I assume that you have 5.1 when the extra speakers are supposed to be directly to the left and right of the listener whereas you have 5.1-back when the extra speakers are supposed to be significantly behind the listener. The following diagram gives an idea about the standard disposition of speakers in 7.1; I suppose that 5.1 and 5.1-back are subsets: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 198 bytes Desc: Digital signature URL: <>
http://ffmpeg.org/pipermail/ffmpeg-devel/2011-July/113612.html
CC-MAIN-2014-42
refinedweb
137
57.47
Template::Direct::Data - Creates a dataset handeler use Template::Direct::Data; my $data = Template::Direct::Data->new( [ Data ] ); $datum = $data->getDatum( 'datum_name' ); $data = $data->getData( 'datum_name' ); If you want to add more data you can push another namespace level This will force the data checking to check this data first then the one before until it reaches the last one. $data->pushData( [ More Data ] ) $data->pushDatum( 'datum_name' ) $data = $data->popData() Control a set of data namespaces which are defined by the top level set of names in a hash ref. All Data should be in the form { name => value } where value can be any hash ref, scalar, or array ref (should work with overridden objects too) Based on L<Template::Direct::Compile> (version 2.0) which this replaces Create a new Data instance. Add a new data to this data set stack Returns a new Data object with $object data plus The new data. Find an existing data structure within myself And add it as a new namespace; thus bringing it into scope. Returns 1 if found and 0 if failed to find substruct Find an existing data structure within myself and create A new object to contain my own data and this new sub scope. ( believe it or not this is useful) Remove the last pushed data from the stack Returns the structure or scalar found in the name. The name can be made up of multiple parts: name4_45_value is the same as $data{'name4'}[45]{'value'} forceString - ensures the result is a string and not an array ref or undef values. maxDepth - Maximum number of depths to try before giving up and returning nothing, default: infinate. Like getDatum but forces output to be an array ref or undef if not valid Dumps all data using the current variable scope. Forces the data input to be an array ref: Integer -> Array of indexes [ 0, 1, 2 ... $x ] Code -> Returned from code execution (cont) Array -> Returned Directly Hash -> Returns [ { name => $i, value => $j }, ... ] Forces the data input to be an hash ref: Code -> Returned from code execution (cont) Hash -> Returned Directly Other -> { value => $data } Martin Owens - Copyright 2007, AGPL
http://search.cpan.org/~doctormo/Template-Direct-1.16/lib/Template/Direct/Data.pm
CC-MAIN-2016-40
refinedweb
359
55.27
I am trying to solve a min value problem, I could obtain the min values from two loops but, what I realy need is also the exact values that correspended to output min. from __future__ import division from numpy import* b1=0.9917949 b2=0.01911 b3=0.000840 b4=0.10175 b5=0.000763 mu=1.66057*10**(-24) #gram c=3.0*10**8 Mler=open("olasiM.txt","w+") data=zeros(0,'float') for A in range(1,25): M2=zeros(0,'float') print 'A=',A for Z in range(1,A+1): SEMF=mu*c**2*(b1*A+b2*A**(2./3.)-b3*Z+b4*A*((1./2.)-(Z/A))**2+(b5*Z**2)/(A**(1./3.))) SEMF=array(SEMF) M2=hstack((M2,SEMF)) minm2=min(M2) data=hstack((data,minm2)) data=hstack((data,A)) datalist = data.tolist() for i in range (len(datalist)): Mler.write(str(datalist[i])+'\n') Mler.close() The big advantage of numpy over using python lists is vectorized operations. Unfortunately your code fails completely in using them. For example the whole inner loop that has Z as index can easily be vectorized. You instead are computing the single elements using python floats and then stacking them one by one in the numpy array M2. So I'd refactor that part of the code by: import numpy as np # ... Zs = np.arange(1, A+1, dtype=float) SEMF = mu*c**2 * (b1*A + b2*A**(2./3.) - b3*Zs + b4*A*((1./2.) - (Zs/A))**2 + (b5*Zs**2)/(A**(1./3.))) Here the SEMF array should be exactly what you'd obtain as the final M2 array. Now you can find the minimum and stack that value into your data array: min_val = SEMF.min() data = hstack((data,minm2)) data = hstack((data,A)) If you also what to keep track for which value of Z you got the minimum you can use the argmin method: min_val, min_pos = SEMF.min(), SEMF.argmin() data = hstack((data,np.array([min_val, min_pos, A]))) The final code should look like: from __future__ import division import numpy as np b1 = 0.9917949 b2 = 0.01911 b3 = 0.000840 b4 = 0.10175 b5 = 0.000763 mu = 1.66057*10**(-24) #gram c = 3.0*10**8 data=zeros(0,'float') for A in range(1,25): Zs = np.arange(1, A+1, dtype=float) SEMF = mu*c**2 * (b1*A + b2*A**(2./3.) - b3*Zs + b4*A*((1./2.) - (Zs/A))**2 + (b5*Zs**2)/(A**(1./3.))) min_val, min_pos = SEMF.min(), SEMF.argmin() data = hstack((data,np.array([min_val, min_pos, A]))) datalist = data.tolist() with open("olasiM.txt","w+") as mler: for i in range (len(datalist)): mler.write(str(datalist[i])+'\n') Note that numpy provides some functions to save/load array to/from files, like savetxt so I suggest that instead of manually saving the values there to use these functions. Probably some numpy expert could vectorize also the operations for the As. Unfortunately my numpy knowledge isn't that advanced and I don't know how the handle the fact that we'd have a variable number of dimensions due to the range(1, A+1) thing...
https://codedump.io/share/mDAgY0iNZbQO/1/python-how-to-find-which-input-value-in-a-loop-yielded-the-output-min
CC-MAIN-2018-09
refinedweb
532
68.87
I installed as per the instructions, checked each item against the example at github. I have 2 problems 1) Clearly Furry is not being activated in the desktop build. The build just runs, flurry does nothing. Is that right? 2) When deployed to my phone, I get: “W/Leap ( 2854): (null):0 ((null)): ERROR: The plugin “VPlay.plugins.flurry” (version “1.0” is not included in the GameWindow::licenseKey and also no valid plugin licenseKey is set. You can create a new license at as a Felgo Pro Customer.” I generated the app’s license key in the usual way, clicking “Select All” on the plugins select step. I have: import VPlayPlugins.flurry 1.0 GameWindow { id: window width: 600 height: 800 // Leap versioncode 14 licenseKey: "..." // as generated Flurry { id: flurry apiKey: '...' // from Flurry for my app // to use a a different API key for Android and iOS // apiKey: Qt.platform.os === "ios" ? "<ios-api-key>" : "<android-api-key>" } - This topic was modified 4 years, 3 months ago by GreenAsJade.
https://felgo.com/developers/forums/t/cant-license-flurry
CC-MAIN-2019-35
refinedweb
170
68.67
We have all been there, we want to integrate with a 3rd party API in Laravel and we ask ourselves "How should I do this?". When it comes to API integrations I am no stranger, but still each time I wonder what is going to be the best way. Sam Carré built a package early in 2022 called Saloon that can make our API integrations amazing. This article however is going to be very different, this is going to be a walk through on how you can use it to build an integration, from scratch. Like all great things it starts with a laravel new and goes from there, so let's get started. Now when it comes to installing Laravel you can use the laravel installer or composer - that part is up to you. I would recommend the installer if you can though, as it provides easy options to do more than just create a project. Create a new project and open it in your code editor of choice. Once we are there, we can get started. What are we going to build? I am glad you asked! We are going to be building an integration with the GitHub API to get a list of workflows available for a repo. Now this could be super helpful if you, like me, spend a lot of time in the command line. You are working on an app, you push changes to a branch or create a PR - it goes though a workflow that could be running one of many other things. Knowing the status of this workflow sometimes has a huge impact on what you do next. Is that feature complete? Were there issues with our workflow run? Are our tests or static analysis passing? All of these things you would usually wait and check the repo on GitHub to see the status. This integration will allow you to run an artisan command, get a list of available workflows for a repo, and allow you to trigger a new workflow run. So by now, composer should have done its thing and installed the perfect starting point, a Laravel application. Next we need to install Saloon - but we want to make sure that we install the laravel version, so run the following inside your terminal: 1composer require sammyjo20/saloon-laravel Just like that, we are a step closer to easier integrations already. If you have any issues at this stage, make sure that you check both the Laravel and PHP versions you are using, as Saloon requires at least Laravel 8 and PHP 8! So, now we have Saloon installed we need to create a new class. In Saloons terminology these are "Connectors" and all a connector does is create an object focused way to say - this API is connected through this class. There is a handy artisan command that allows you to create these, so run the following artisan command to create a GitHub connector: 1php artisan saloon:connector GitHub GitHubConnector This command is split into 2 parts, the first argument is the Integration you are creating and the second is the name of the connector you want to create. This means that you can create multiple connectors for an integration - which gives you a lot of control to connect in many different ways should you need to. This will have created a new class for you under app/Http/Integrations/GitHub/GitHubConnector.php, let's have a look at this a moment, and understand what is going on. The first thing we see is that our connector extends the SaloonConnector, which is what will allow us to get our connector working without a lot of boilerplate code. Then we inherit a trait called AcceptsJson. Now if we look at the Saloon documentation, we know that this is a plugin. This basically adds a header to our requests telling the 3rd party API that we want to Accept JSON responses. The next thing we see is that we have a method for defining the base URL for our connector - so let's add ours in: 1public function defineBaseUrl(): string2{3 return '';4} Nice and clean, we could even take this a little further so we are dealing with less loose strings hanging around in our application - so let's look at how we can do that. Inside your config/services.php file add a new service record: 1'github' => [2 'url' => env('GITHUB_API_URL', ''),3] What this will do is allow us to override this in different environments - giving us a better and more testable solution. Locally we could even mock the GitHub API using their OpenAPI specification, and test against that to ensure that it works. However, this tutorial is about Saloon so I digress... Now let us refactor our base URL method to use the configuration: 1public function defineBaseUrl(): string2{3 return (string) config('services.github.url');4} As you can see we are now fetching the newly added record from our configuration - and casting it to a string for type safety - config() returns a mixed result so we want to be strict on this if we can. Next we have default headers and default config, now right now I am not going to worry about the default headers, as we will approach auth on it's own in a little while. But the configuration is where we can define the guzzle options for our integration, as Saloon uses Guzzle under the hood. For now let's set the timeout and move on, but feel free to spend some time configuring this as you see fit: 1public function defaultConfig(): array2{3 return [4 'timeout' => 30,5 ];6} We now have our Connector as configured as we need it for now, we can come back later if we find something we need to add. The next step is to start thinking about the requests we want to be sending. If we look at the API documentation for GitHub Actions API we have many options, we will start with listing the workflows for a particular repository: /repos/{owner}/{repo}/actions/workflows. Run the following artisan command the create a new request: 1php artisan saloon:request GitHub ListRepositoryWorkflowsRequest Again the first argument is the Integration, and the second argument is the name of the request we want to create. We need to make sure we name the integration for the request we are creating so it lives in the right place, then we need to give it a name. I called mine ListRepositoryWorkflowsRequest because I like a descriptive naming approach - however, feel free to adapt this to how you like to name things, as there is no real wrong way here. This will have created a new file for us to look at: app/Http/Integrations/GitHub/Requests/ListRepositoryWorkflowsRequest.php - let us have a look at this now. Again we are extending a library class here, this time the SaloonRequest which is to be expected. We then have a connector property and a method. We can change the method if we need to - but the default GET is what we need right now. Then we have a method for defining the endpoint. Refactor your request class to look like the below example: 1class ListRepositoryWorkflowsRequest extends SaloonRequest2{3 protected ?string $connector = GitHubConnector::class;45 protected ?string $method = Saloon::GET;67 public function __construct(8 public string $owner,9 public string $repo,10 ) {}1112 public function defineEndpoint(): string13 {14 return "/repos/{$this->owner}/{$this->repo}/actions/workflows";15 }16} What we have done is add a constructor which accepts the repo and owner as arguments which we can then use within our define endpoint method. We have also set the connector to the GitHubConnector we created earler. So we have a request we know we can send, we can take a small step away from the integration and think about the Console Command instead. If you haven't created a console command in Laravel before, make sure you check out the documentation which is very good. Run the following artisan command to create the first command for this integration: 1php artisan make:command GitHub/ListRepositoryWorkflows This will have created the following file: app/Console/Commands/GitHub/ListRespositoryWorkflows.php. We can now start working with our command to make this send the request and get the data we care about. The first thing I always do when it comes to console commands, is think on the signature. How do I want this to be called? It needs to be something that explains what it is doing, but it also needs to be memorable. I am going to call mine github:workflows as it explains it quite well to me. We can also add a description to our console command, so that when browsing available commands it explains the purpose better: "Fetch a list of workflows from GitHub by the repository name." Finally we get to the handle method of our command, the part where we actualy need to do something. In our case we are going to be sending a request, getting some data and displaying that data in some way. However before we can do that, there is one thing we have not done up until this point. That is Authentication. With every API integration, Authentication is one of the key aspects - we need the API to know not only who we are but also that we are actually allowed to make this request. If you go to your GitHub settings and click through to developer settings and personal access tokens, you will be able to generate your own here. I would recommand using this approach instead of going for a full OAuth application for this. We do not need OAuth we just need users to be able to access what they need. Once you have your access token, we need to add it to our .env file and make sure we can pull it through our configuration. 1GITHUB_API_TOKEN=ghp_loads-of-letters-and-numbers-here We can now extends our service in config/services.php under github to add this token: 1'github' => [2 'url' => env('GITHUB_API_URL', ''),3 'token' => env('GITHUB_API_TOKEN'),4] Now we have a good way of loading this token in, we can get back to our console command! We need to ammend our signature to allow us to accept the owner and repository as arguments: 1class ListRepositoryWorkflows extends Command2{3 protected $signature = 'github:workflows4 {owner : The owner or organisation.}5 {repo : The repository we are looking at.}6 ';78 protected $description = 'Fetch a list of workflows from GitHub by the repository name.';910 public function handle(): int11 {12 return 0;13 }14} Now we can turn our focus onto the handle method: 1public function handle(): int2{3 $request = new ListRepositoryWorkflowsRequest(4 owner: $this->argument('owner'),5 repo: $this->argument('repo'),6 );78 return self::SUCCESS;9} Here we are starting to build up our request by passing the arguments straight into the Request itself, however what we might want to do is create some local variables to provide some console feedback: 1public function handle(): int2{3 $owner = (string) $this->argument('owner');4 $repo = (string) $this->argument('repo');56 $request = new ListRepositoryWorkflowsRequest(7 owner: $owner,8 repo: $repo,9 );1011 $this->info(12 string: "Fetching workflows for {$owner}/{$repo}",13 );1415 return self::SUCCESS;16} So we have some feedback to the user, which is always important when it comes to a console command. Now we need to add our authentication token and actually send the request: return self::SUCCESS;22} If you ammend the above and do a dd() on $response->json(), just for now. Then run the command: 1php artisan github:workflows laravel laravel This will get a list of workflows for the laravel/laravel repo. Our command will allow you to work with any public repos, if you wanted this to be more specific you could build up an option list of repos you want to check against instead of accepting arguments - but that part is up to you. For this tutorial I am going to focus on the wider more open use case. Now the response we get back from the GitHub API is great and informative, but it will require transforming for display, and if we look at it in isolation, there is no context. Instead we will add another plugin to our request, which will allow us to transform responses into DTOs (Domain Transfer Objects) which is a great way to handle this. It will allow us to loose the flexible array we are used to getting from APIs, and get something that is more contextually aware. Let's create a DTO for a Workflow, create a new file: app/Http/Integrations/GitHub/DataObjects/Workflow.php and add the follow code to it: 1class Workflow2{3 public function __construct(4 public int $id,5 public string $name,6 public string $state,7 ) {}89 public static function fromSaloon(array $workflow): static10 {11 return new static(12 id: intval(data_get($workflow, 'id')),13 name: strval(data_get($workflow, 'name')),14 state: strval(data_get($workflow, 'state')),15 );16 }1718 public function toArray(): array19 {20 return [21 'id' => $this->id,22 'name' => $this->name,23 'state' => $this->state,24 ];25 }26} We have a constructor which contains the important parts of our workflow that we want to display, a fromSaloon method which will transform an array from a saloon response into a new DTO, and a to array method for displaying the DTO back to an array when we need it. Inside our ListRepositoryWorkflowsRequest we need to inherit a new trait and add a new method: 1class ListRepositoryWorkflowsRequest extends SaloonRequest2{3 use CastsToDto;45 protected ?string $connector = GitHubConnector::class;67 protected ?string $method = Saloon::GET;89 public function __construct(10 public string $owner,11 public string $repo,12 ) {}1314 public function defineEndpoint(): string15 {16 return "/repos/{$this->owner}/{$this->repo}/actions/workflows";17 }1819 protected function castToDto(SaloonResponse $response): Collection20 {21 return (new Collection(22 items: $response->json('workflows'),23 ))->map(function ($workflow): Workflow {24 return Workflow::fromSaloon(25 workflow: $workflow,26 );27 });28 }29} We inherit the CastsToDto trait, which allows this request to call the dto method on a response, and then we add a castToDto method where we can control how this is transformed. We want this to return a new Collection as there is more than one workflow, using the workflows part of the response body. We then map over each item in the collection - and turn it into a DTO. Now we can either do it this way, or we can do it this way where we build our collection with DTOs: 1protected function castToDto(SaloonResponse $response): Collection2{3 return new Collection(4 items: $response->collect('workflows')->map(fn ($workflow) =>5 Workflow::fromSaloon(6 workflow: $workflow7 ),8 )9 );10} You can choose what works best for you here. I prefer the first approach personally as I like to step through and see the logic, but there is nothing wrong with either approach - the choice is yours. Back to the command now, we now need to think about how we want to be displaying this information: if ($response->failed()) {22 throw $response->toException();23 }2425 $this->table(26 headers: ['ID', 'Name', 'State'],27 rows: $response28 ->dto()29 ->map(fn (Workflow $workflow) =>30 $workflow->toArray()31 )->toArray(),32 );3334 return self::SUCCESS;35} So we create a table, with the headers, then for the rows we want the response DTO and we will map over the collection returned, casting each DTO back to an array to be displayed. This may seem counter intuative to cast from a response array to a DTO and back to an array, but what this will do is enforce types so that the ID, name and status are always there when expected and it won't give any funny results. It allows consistency where a normal response array may not have it, and if we wanted to we could turn this into a Value Object where we have behaviour attached instead. If we now run our command we should now see a nice table output which is easier to read than a few lines of strings: 1php artisan github:workflows laravel laravel 1Fetching workflows for laravel/laravel2+----------+------------------+--------+3| ID | Name | State |4+----------+------------------+--------+5| 12345678 | pull requests | active |6| 87654321 | Tests | active |7| 18273645 | update changelog | active |8+----------+------------------+--------+ Lastly, just listing out these workflow is great - but let's take it one step further in the name of science. Let's say you were running this command against one of your repos, and you wanted to run the update changelog manaually? Or maybe you wanted this to be triggered on a cron using your live production server or any event you might think of? We could set the changelog to run once a day at midnight so we get daily recaps in the changelog or anything we might want. Let us create another console command to create a new workflow dispatch event: 1php artisan saloon:request GitHub CreateWorkflowDispatchEventRequest Inside of this new file app/Http/Integrations/GitHub/Requests/CreateWorkflowDispatchEventRequest.php add the following code so we can walk through it: 1class CreateWorkflowDispatchEventRequest extends SaloonRequest2{3 use HasJsonBody;45 protected ?string $connector = GitHubConnector::class;67 public function defaultData(): array8 {9 return [10 'ref' => 'main',11 ];12 }1314 protected ?string $method = Saloon::POST;1516 public function __construct(17 public string $owner,18 public string $repo,19 public string $workflow,20 ) {}2122 public function defineEndpoint(): string23 {24 return "/repos/{$this->owner}/{$this->repo}/actions/workflows/{$this->workflow}/dispatches";25 }26} We are setting the connector, and inheriting the HasJsonBody trait to allow us to send data. The method has been set to be a POST request as we want to send data. Then we have a constructor which accepts the parts of the URL that builds up the endpoint. Finally we have dome default data inside defaultData which we can use to set defaults for this post request. As it is for a repo, we can pass either a commit hash or a branch name here - so I have set my default to main as that is what I usually call my production branch. We can now trigger this endpoint to dispatch a new workflow event, so let us create a console command to control this so we can run it from our CLI: 1php artisan make:command GitHub/CreateWorkflowDispatchEvent Now let's fill in the details and then we can walk through what is happening: 1class CreateWorkflowDispatchEvent extends Command2{3 protected $signature = 'github:dispatch4 {owner : The owner or organisation.}5 {repo : The repository we are looking at.}6 {workflow : The ID of the workflow we want to dispatch.}7 {branch? : Optional: The branch name to run the workflow against.}8 ';910 protected $description = 'Create a new workflow dispatch event for a repository.';1112 public function handle(): int13 {14 $owner = (string) $this->argument('owner');15 $repo = (string) $this->argument('repo');16 $workflow = (string) $this->argument('workflow');1718 $request = new CreateWorkflowDispatchEventRequest(19 owner: $owner,20 repo: $repo,21 workflow: $workflow,22 );2324 $request->withTokenAuth(25 token: (string) config('services.github.token'),26 );2728 if ($this->hasArgument('branch')) {29 $request->setData(30 data: ['ref' => $this->argument('branch')],31 );32 }3334 $this->info(35 string: "Requesting a new workflow dispatch for {$owner}/{$repo} using workflow: {$workflow}",36 );3738 $response = $request->send();3940 if ($response->failed()) {41 throw $response->toException();42 }4344 $this->info(45 string: 'Request was accepted by GitHub',46 );4748 return self::SUCCESS;49 }50} So like before we have a signature and a description, our signature this time has an optional branch incase we want to override the defaults in the request. So in our handle method, we can simple check if the input has the argument 'branch' and if so, we can parse this and set the data for the request. We then give a little feedback to the CLI, letting the user know what we are doing - and send the request. If all goes well at this point we can simply output a message informing the user that GitHub accepted the request. However if something goes wrong, we want to throw the specific exception, at least during develoment. The main caveat with this last request is that our workflow is set up to be triggered by a webhook by adding a new on item into the workflow: 1on: workflow_dispatch That is it! We are using Saloon and Laravel to not only list repository workflows, but if configured correctly we can also trigger them to be ran on demand :muscle: As I said at the beginning of this tutorial, there are many ways to approach API integrations, but one thing is for certain - using Saloon makes it clean and easy, but also quite delightful to use. Filed in:
https://laravel-news.com/api-integrations-using-saloon-in-laravel
CC-MAIN-2022-27
refinedweb
3,471
54.36
Welcome to Longer Life For Drivers Because of the high accident rates in countries like Colombia, this tutorial talks about how can be made an smart equipment for drivers, increasing the possibilities to survive and get better medical care by sending information about what is going on the driver's body while he/she drives, specially when takes place an accident. In summary, the wearable equipment consist in - A vest that provides data from the magnitude of a force applied to the thorax - A helmet that allows to know the severity of a head injury - Data from heart rate - Alerts from deformation in the vehicle - GPS by Web Next, we describe each one of the parts of the equipment based in the development board LinkIt One. 1. Making the LLFD-Vest For this, you will need the pressure sensors, some meters of medical hose, glue and of course a vest. The LLFD vest operates using the relation between pressure and force, as you know pressure is equal to the force applied in a determined area, then if we distribute the force in a constant area, knowing the pressure we can also know the force that is being applied. In this way, we can establish that a hit could have taken place. To measure the pressure at the vest you can use the medical hose, which must be distributed along the more critical parts of the thorax. Investigating medical theory, we concluded that these parts are all around the ribs, as this provide protection to the principal organs. Then, the purpose of measure the force is finding when a rib could be broken and hurting a vital organ. So, the first step to improve a regular vest is pasting the hose along those critical parts. For the chest the hose should be covering the medium ribs, where also are lungs and heart. Inside the hose there are air, which exerts a nominal pressure while there is no force applied, and a higher pressure when there is some force. You may think ¿What if the hit occurs between the hose?, Well, in an accident hits are not so precise, and they occurs from falls and strokes with large surfaces. To measure the pressure, was used the MPX5010 sensor, placing it at the hose end. This sensor has six pins, of which three are for adjustments and the rest are the more important ones. As the image, the first pin is the output voltage, the next is ground and the third is the input voltage, that must be +5V. At this moment the vest is ready to start coding, the pins in the LinkIt One to work are, 5V, gnd and A0 y A1, which have the value of voltage from the sensors. The code commented is at the end of the tutorial. If we have already the values from the two sensors, the next step is converting them to an useful magnitude, to do this, we need to do a characterization. The characterization consist in proving different forces and comparing to the voltage read by the LinkIt One, so, we can describe completely the behaviour for any force we could apply. We used three different masses generating a force equals to mass*acceleration, in this case the acceleration is the same as gravity. The forces' magnitude must be now printed in the serial monitor, but our objective is to have this information remotely, then, we use Ubidots. Ubidots allows the exchange of data between the LinkIt One and Ubidots webpage with some options to see the information. First, the previous code need some additional lines to get the connection using the Wi-Fi antenna, and send it out. The code is at the end. In Ubidots, create a variable, in Sources>Add Data Source>Add Variable. Next, in the Dashboard, add a Widget>Multi-line Chart At the moment we upload the code to the board, in Ubidots, there will be something like this 2. Preparing the LLFD-Bike The motorcycle is well known to be an widely used vehicle around the world, that can provide practical solutions to daily problems. However, the motorcycles have a great dissadvantage, the low security they offer to the driver. Due to the massive use of motorbikes, the great speed they can reach, the recklessness of drivers and many other factors, are the cause of the main number of deaths on the road. LLFD proposes a “motorcycle” prototype, which is able to provide information in the moment when an accident has happened. In this tutorial, it is exposed the use of one of many parameters that can determine if an accident happened, it is the deflexion of the covers. In order to accomplish this tutorial, you will need mainly some flex sensors, a plastic bottle and something to attach the sensors to the bottle. How was it made? For accomplish this tutorial you may need: By putting these sensors on a motorcycle, it can detect which side of the bike touched the ground. If we know that the motorbike fell down on its right side, we can generate a better diagnostic, because it's highly possible that the greatest injuries of the driver, are on it's right side, so the authorities can take that information and be ready to provide a better care to the wounded one. 3. Making the LLFD-Helmet The helmet is a fundamental piece for every motorcyclist, because it protects the head in case of impact. Although being mandatory its use, in many countries, the motorcyclists drive with helmets that don't accomplish the security rules and are used in a wrong way, so if an accident occurs, the most possible case of death is by cranial trauma. LLFD proposes the adaptation of a helmet that accomplishes the standart security rules, but also gives a sensor system, which is able to provide valuable information of the variables related to the helmet, especially when it is hit. For that, two linear vibration sensors were used, with the purpose of detecting serious shocks in the head. How was it made? For this tutorial you may need: This helmet works by using the data taken by the analog read of the sensor vibration, and doing a relationship with force, area of impact and other parameters. The characterization of the sensors was made by field tests, so we wanted to filter the vibrations caused by normal driving conditions, so we can ignore that data in order to get the real hits without mistake. It was made by taking the data that sensors provide, with the a motorcyclist using the helmet and accelerating his bike at a maximum of 12.000 rpm. Also by moving its suspension we emulated some irregular road conditions. Some of the collected data, are this ones: As we can see, the sensors didn't report high vibrations, so it is possible to use a filter that may ignore them. The sensor are in the safest place of the helmet, so it's logical to think that it's necessary a bigger amount of force to reach them. The codes used to this proves, are at the bottom of this tutorial. To test the measurement the sensors give with a specific force applied to it, we drop a weight on the helmet, releasing it from a specific height and hitting a certain point of the helmet. By physics we know that it is only needed the height and the weight to determine the force of a falling object on a specific point and depending on surface's texture, we have for example: Height = 1m, Mass = 1.5 Kg, Force received and that point= 147N Comparing the vibration with the result the sensors give, with a known force, we're sure it is able to detect a real accident. 4. Getting data from the body When a motorcyclist is involved in a serious accident and needs prompt attention, regularly dies because the authorities take a long time to get to the accident place and also because they don't have a previous diagnosis so the proper care lasts a long and vital time. Pulse-oximetry is a technique for the hemoglobin oxygen transported measurement , which travels through blood vessels, this data is obtained by a non-invasive device, known as pulse-oximeter. According to the philosophy of the project, it allows us to get an idea of whether the driver is alive or not through the heart rate, further enables us to obtain an idea of the respiratory status of the user through obtaining oxygen saturation, where health professional can observe and interpret it to generate a series of diagnostics. So we used a pulse-oximeter, with a shield upon an Arduino, connected to the Linkit One, in order to send some data to Ubidots. How was it made? For this tutorial you may need... It is not necessary to have the same device, any similar device that provides digital data of at least heart rate, should be ok. The shield needs some libraries in order to work, those can be found on- When removing the contents of this file,which is compressed into a zip file and copy the folder arduino libraries can create a sketch for biomedical data from sensors connected to the shield. The path where it should be copied these libraries is: C:\Program Files (x86)\Arduino\libraries (Windows 64 bits) or in C:\Users\xxxxx\Documents\Arduino\libraries. For monitoring pulse-oximeter data should be acquired sensor compatible with the shield. From this point you can write some code to acquire the information of oxygen saturation and heart rate. 5. Mixing some parameters In order to put the pulse-oximeter information on Ubidots, there's something that need attention. The pulse-oximeter we used, can not be directly connected to the LinkIt ONE, but with Arduino. That's why a small coupling is necessary in order to use serial communication between both devices. As it is being used two different boards, the Arduino One that receives data from the pulse-oximeter and the LinkIt One that receives and process different analog sensors, also it communicates with Ubidots to save and show the obtained data; it is necessary to realize a communication between both development boards. As this, the development boards have different pins to make communication protocols as UART, I2C. The Linkit One’s pins D0 and D1 are used for UART communication and for this, it must declare the following libraries at the beginning of this sketch. #include<HardwareSerial.h> #include<UARTClass.h> In the Arduino Uno’s case, it uses the library SoftwareSerial.h, but, in order to get it to work it is necessary to do some modifications, as this has problems with the PinChageInt.h library, these modifications there will be listed next: - Add the line #define NO_PORT2_PINCHANGES inside the file PinChangeInt.cpp - Comment /#if defined(PCINT2_vect) ISR(PCINT2_vect, ISR_ALIASOF(PCINT0_vect)); #endif in the file SoftwareSerial.cpp Because of pulse-oximeter functionalities, we can use the 4 and 5 Arduino Uno’s pins to do the serial communication, after realizing these changes. Now we can connect the pulse-oximeter with the Link It ONE y a proper way, here it's a more detailed explanation from the code's point of view. By accomplishing it, we can slowly add the other sensors we used and make an integral system for future works; and the possibilities are getting higher and higher, now you can see the last example we provided with the pulse-oximeter in real time, geo-localization and the motorcycle's flex detection: Now, we have each system working as previously thought, but you may think we have only data. It is not. Currently, there are four parameters known. To come to a conclusion, we think, two parameters in alert is enough, so with all these data we can make a diagnosis about what is really taking place with the driver. For example, it is known that a force of about 3500 Newton can break a rib, what allow us to suppose a serious injury when the pressure sensor is saturated. For the helmet we have some levels of gravity, (despising normal vibration from the motorcycle). When the level is above the medium, it indicates that the driver suffered a head strike. In addition, if the blood pressure is higher than the normal rate, it is possible to suppose something is happening, and if there is no blood pressure, the driver can be dead. These and another affirmations are part of the general diagnosis, which will be send besides the GPS coordinates, to a relative or the medical or traffic authorities.
https://www.hackster.io/10867/longer-life-for-drivers-f17f13
CC-MAIN-2020-10
refinedweb
2,118
54.76
This manual page is intended as a reference document only. For a more thorough description of make and makefiles, please refer to The options are as follows: There are six different types of lines in a makefile: file dependency specifications, shell commands, variable assignments, include statements, conditional directives, and comments. In general, lines may be continued from one line to the next by ending them with a backslash The trailing newline character and initial whitespace on the following line are compressed into a single space.. If the first or first two characters of the command line are and/or the command is treated specially. A causes the command not to be echoed before it is executed. A causes any non-zero exit status of the command line to be ignored. Any white-space before the assigned value is removed; if the value is being appended, a single space is inserted between the previous contents of the variable and the appended value. Variables are expanded by surrounding the variable name with either curly braces or parenthesis and preceding it with a dollar sign If the variable name contains only a single letter, the surrounding braces or parenthesis Ns 's environment. Global variables Variables defined in the makefile or in included makefiles. Command line variables Variables defined as part of the command line. Local variables Variables that are defined specific to a certain target. The seven local variables are as follows: Va .ALLSRC The list of all sources for this target; also known as Va .ARCHIVE The name of the archive file. Va .IMPSRC The name/path of the source from which the target is to be transformed (the ``implied'' source); also known as Va .MEMBER The name of the archive member. Va .OODATE The list of sources for this target that were deemed out-of-date; also known as Va .PREFIX The file prefix of the file, containing only the file portion, no suffix or preceding directory components; also known as Va .TARGET The name of the target; also known as The shorter forms and are permitted for backward compatibility with historical makefiles and are not recommended. The six variables and are permitted for compatibility with makefiles and are not recommended. Four of the local variables may be used in sources on dependency lines because they expand to the proper value for each target on the line. These variables are and In addition, make sets or knows about the following variables: Va $ A single dollar sign i.e. expands to a single dollar sign. Va .MAKE The name that make was executed with Va .CURDIR A path to the directory where make was executed. Ev MAKEFLAGS The environment variable may contain anything that may be specified on make Ns 's command line. Anything specified on make Ns 's command line is appended to the variable which is then entered into the environment for all programs which make executes. Variable expansion may be modified to select or modify each word of the variable (where a ``word'' is white-space delimited sequence of characters). The general format of a variable expansion is as follows: Each modifier begins with a colon and one of the following special characters. The colon may be escaped with a backslash Variable expansion occurs in the normal fashion inside both old_string and new_string with the single exception that a backslash is used to prevent the expansion of a dollar sign not a preceding dollar sign as is usual. Conditional expressions are also preceded by a single dot as the first chraracter of a line. The possible conditionals are as follows: Ic .undef Ar variable Un-define the specified global variable. Only global variables may be un-defined. Xo Test the value of an expression. Xo Test the value of an variable. Xo Test the value of an variable. Xo Test the the target being built. Xo Test the target being built. Ic .else Reverse the sense of the last conditional. Xo A combination of followed by Xo A combination of followed by Xo A combination of followed by Xo A combination of followed by Xo A combination of followed by Ic .endif End the body of the conditional. The operator may be any one of the following: As in C, make will only evaluate a conditional as far as is necessary to determine its value. Parenthesis may be used to change the order of evaluation. The boolean operator may be used to logically negate an entire conditional. It is of higher precendence than The value of expression may be any of the following: Ic defined Takes a variable name as an argument and evaluates to true if the variable has been defined. Ic make Takes a target name as an argument and evaluates to true if the target was specified as part of make Ns 's command line or was declared the default target (either implicitly or explicitly, see before the line containing the conditional. Ic empty Takes a variable, with possible modifiers, and evalutes to true if the expansion of the variable would result in an empty string. Ic exists Takes a file name as an argument and evaluates to true if the file exists. The file is searched for on the system search path (see Ic target Takes a target name as an argument and evaluates to true if the target has been defined. Expression may also be an arithmetic or string comparison, with the left-hand side being a variable expansion. The standard C relational operators are all supported, and the usual number/base conversion is performed. Note, octal numbers are not supported. If the righthand value of a or operator begins with a quotation mark a string comparison is done between the expanded variable and the text between the quotation marks. If no relational operator is given, it is assumed that the expanded variable is being compared against 0. When make is evaluating one of these conditional expression, and it encounters a word it doesn't recognize, either the ``make'' or ``defined'' expression is applied to it, depending on the form of the conditional. If the form is or the ``defined'' expression is applied. Similarly, if the form is or expression is applied. If the conditional evaluates to true the parsing of the makefile continues as before. If it evaluates to false, the following lines are skipped. In both cases this continues until a or is found. Table of Contents
http://www.fiveanddime.net/man-pages/pmake.1.html
crawl-003
refinedweb
1,075
54.12
In Part 1, we introduced GenServers by looking at a simple example that exposed a shared id map (string to integer). We'll expand on that example by having our in-memory id map periodically refreshed. This is the reason that we didn't use an Agent in the first place. Our original implementation doesn't require much change. First, we'll add a schedule_refresh function and call it in init defmodule Goku.IdMap do use GenServer def start_link() do GenServer.start_link(Goku.IdMap, nil, name: "idmap") end def init(nil) do schedule_refresh() {:ok, load()} end defp schedule_refresh() do # 60 seconds Process.send_after(self(), :refresh, 1000 * 60) end defp load() do %{"goku" => 1, "gohan" => 2} end end Process.send_after sends the specified message, :refresh here, to the specified process. We use self() to get the current running process id. Remember, init is invoked by GenServer.start_link and running in our newly created GenServer process. So, the above is the GenServer sending a message to itself, 60 seconds from now. Much like we used hande_call to respond to GenServer.call requests, we use handle_info to handle messages sent in the above fasion: def handle_info(:refresh, _currnet_state) do schedule_refresh() new_state = load() {:noreply, new_state} end Our handle_info matches the argument passed ( :refresh) and receives the current data/state of the GenServer process (which we won't use, here). All we have to do is schedule the next refresh (using the same schedule_refresh), reload the data and return that as our new state. That's really all we need to make this work. However, there's an opportunity to improve this and further expose the concurrency model we talked about in the previous part. Specifically, our handle_info code is being processed by our module's GenServer process. So while this code is executing, calls to get will block until handle_info is done and the process can fulfill pending call's. Remember, get uses GenServer.call which is synchronous and blocks until it receives a reply. If load is slow, you'll see noticeable latency spikes every 60 seconds. What can we do? What if we spawned a process specifically to load the new state? That would get us half way there, but that process wouldn't be able to update our GenServer's state (nothing can touch the data, for reading or writing, except the GenServer process itself). But is that really a problem? We've already seen that we can easily communicate with a GenServer. So, consider: def handle_info(:refresh, state) do schedule_refresh() spawn fn -> GenServer.cast(@name, {:refreshed, load()}) end # doesn't wait for the above to finish # so doesn't block the GenServer process from servicing other requests {:noreply, state} end Our handle_info still schedules a refresh 60 seconds from now, but instead of loading the new state directly, it spawns a process to do the loading. That new process will pass the newly loaded state back to the GenServer via the GenServer.cast function, which is the asynchronous equivalent to call (we could use call, but since we don't care for a reply, cast is more appropriate). Also, note that handle_info now uses the state parameter as part of the return value. That's because by the time we return from this function we're still using the same old state. Finally, we have to handle the cast call. This is done through handle_cast: def handle_cast({:refreshed, new_state}, _old_state) do {:noreply, new_state} end Hopefully you guessed that the above function would be this simple. It fits the GenServer patterns we've seen so far. In the end, we've minimized the complexity of the code running in our single process; much like we'd minimize the surface area of a mutex. But, there's zero risk that we've introduced a concurrency bug by making things too granular. Put differently, we spawn a new process to do the expensive loading, freeing our GenServer process to keep servicing requests. Once that loading is done, we pass the data back to the GenServer. At this point, the GenServer updates its state. Recapping, there are 4 functions that run in a GenServer process: init, handle_call, handle_cast and handle_info. init is the only that's required (to set the initial state), but you'll have at least one of the other ones (else, your GenServer can do nothing) and will often have a mix of them (we're using all three here). You'll also often have multiple version of the handle_* functions (pattern matching the first argument). And that's how GenServer's are used and a bit of how they work. At the risk of sounding like a broken record, I think there are two important things to understand. First, at first glance, it can seem more daunting than it is. Second, the strict ownership of data by the GenServer process is different than many other concurrent programming paradigms. It's easier to reason about, and thus harder to screw up, because there are no moving parts (more accurately, moving data) and never any shared access.
https://www.openmymind.net/Learning-Elixir-GenServer-Part-2/
CC-MAIN-2021-39
refinedweb
845
72.26
Redux abstractions on Swift for BetterMe projects and iOS community You can install ReduxCore via CocoaPods by adding it to your Podfile: pod 'ReduxCore' And run pod install. You can install ReduxCore via Swift Package Manager by adding the following line to your Package.swift: import PackageDescription let package = Package( [...] dependencies: [ .package(url: "", from: "2.0.0"), ] ) We use SPM in all examples. To run the example project, just clone the repo, open Examples folder, and choose a project you want. ReduxCore is released under the MIT license. See LICENSE for details. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/betterme-dev/ReduxCore
CC-MAIN-2021-39
refinedweb
103
60.31
jakzaprogramowac.pl All questions About the project How To Program How To Develop Data dodania Pytanie 2017-06-08 13:06 iOS - Today extension widget cleared over time » Situation as it should be We have a today widget that shows a maximum of 6 buttons depending on data set in the corresponding app. This data is sha... (0) odpowiedzi 2017-06-08 05:06 Expand one row at a time in UITableView Swift » I am working on expanding row when tapped on table view row. My logic is simple I am adding an extra row when tapped on visible row(i.e Expanding) and... (2) odpowiedzi 2017-06-07 09:06 Code migration from Swift 2.x to Swift 4 » We have big enough project which is built up with Swift 2.x and now Apple has just released Swift 4 so to move forward for latest version of Swift whi... (3) odpowiedzi 2017-06-06 18:06 Swift 3 Custom class CurrencyFormatter » I have a Swif 2.3 custom class currency formatter that I want to translate to Swift 3 but Im getting errors: class CurrencyFormatter : NumberFormatte... (0) odpowiedzi 2017-06-06 06:06 How do I do a cross platform encryption method working in both IOS and android (AES encryption only..)? » I have been recently assigned a task of encrypting my links and parameters i pass in dataTaskWithRequest in swift. The main headache is it should prod... (0) odpowiedzi 2017-06-02 07:06 Delay of less than one second, Swift 2 » I can't update Swift because the last time I tried to, it simply didn't work (see the tons of one star reviews on the app store), so other solutions I... (1) odpowiedzi 2017-06-01 07:06 How to insert the data in backend using Swift 2.0? » I've looking for correct post format using Swift 2.0 and multiple textfield data are also saved in backend process. ... (0) odpowiedzi 2017-05-30 13:05 Reloading UICollection view after data parse » I am trying to dynamically update a uicollectionview. I used this amazing tutorial on how to create a simple uicollection. It works great when using ... (1) odpowiedzi 2017-05-27 06:05 I made a table view, how can I save the items even after the app is closed? » I'm making my first app, and it has a task manager, for this, I made a table view in which you can input "tasks" through an alert. How can I save the ... (3) odpowiedzi 2017-05-25 19:05 how to parse the json using alamofire in swift 2? » I am having trouble with parsing json using alamofire (it is working fine using browser or postman),below is my code Alamofire.request(.POST, reqSt... (0) odpowiedzi 2017-05-25 14:05 BLE implements for iOS » I need one help. I am working for BLE in iOS, I am able to send message from one device to another and vice versa. Now my requirement is once I get me... (1) odpowiedzi 2017-05-25 06:05 swift3.0 Cannot convert value of type '[UnsafeMutablePointer<Int8>]' to expected argument type 'UnsafeMutablePointer<Int8>?' » This code worked well in Swift2.3 and now I am converting it to Swift3. So I am getting this error. Anyone has idea, how to fix this? var cmdLnConf: ... (1) odpowiedzi 2017-05-24 22:05 Swift 2 Instance member 'circleIndexes' cannot be used on type 'GameScene' » I am making a rhythm app, but I can't seem to randomize the circles. Here is my code: var alternator = 0 var fallTimer:NSTimer? var flag:Bool = true... (1) odpowiedzi 2017-05-24 22:05 Updated modern Swift syntax to modern Swift syntax and project will no longer compile » I recently was pasting a section of code from StackOverflow to my Swift 3 project, the code was written in Swift 2 so I highlighted the section of cod... (1) odpowiedzi 2017-05-24 04:05 Swift : Avatar image is mandatory in swift code » By default "no-profile-image" is set to imageview, User should upload the profile picture mandatory while registration, otherwise user should not allo... (0) odpowiedzi 2017-05-22 16:05 How to deal with favourite button » I have a favourite button when I select the button ,the button colour will be changed and append particular string to an array and when deselect the b... (0) odpowiedzi 2017-05-19 18:05 Make a swipe button in swift like Uber application » I want to create a button like uber driver application where driver swipe to start the trip. The arrow come from left to right as the driver swipe on ... (0) odpowiedzi 2017-05-19 08:05 How to concatenate the "+" operator in a string in swift » i am making a POST request to the server and my POST string is: let postString = "phone_number=+1234567890&compeleteCode=125435" and in the se... (1) odpowiedzi 2017-05-19 03:05 Reloading collection view when poped a view controller » I used collection view having 3 section 3 rows in a view controller and pushed that same view controller. I updated view controller containing collect... (0) odpowiedzi 2017-05-18 13:05 Why does Date formatter returns date correctly but time is showing as 00:00:00 when converting string to NSDate » I have a function where i have to retrieve a date from my own sqlite db of app. I have saved it using the formatter My work flow 1..Save a date to d... (1) odpowiedzi 2017-05-18 08:05 authorizationStatus() about MPMediaLibrary access » I want to access the media library to display songs list. So on precondition I am checking the authorization status for the media library. When we go ... (0) odpowiedzi 2017-05-17 12:05 Incorrect or ambiguous type Array Filter » for item in time_array { let tmp_array = student_result.filter(using: {$0["drillResultTime"] as! String == item as! String}) } Above Code is in Swif... (0) odpowiedzi 2017-05-16 21:05 Swift 2 Error: Argument labels '(value:)' do not match any available overloads » I am trying to randomize circles falling for my rhythm game, but I can't seem to get it to work. This is the closest I have gotten: var alternator = ... (2) odpowiedzi 2017-05-15 13:05 how to encrypt the string using md5 with unique key in swift 2 » basically i want to encrypt the string using md5 with unique key in swit 2 i encrypt the string in java like this: JAVA Code.... public class MCryp... (0) odpowiedzi 2017-05-12 20:05 Bad instruction error when calling child from firebase in swift 2 » We are trying to access a child in database, however we are using a string from a previous view brought in by a segue. It keeps giving the error of ba... (1) odpowiedzi 2017-05-12 07:05 My iPhone App crashes after getting push notification in some devices(especially ios_10.3.1) » I have just figured out how to send push notification correctly in my app. However when it started working correctly, a new type of error has arrived.... (3) odpowiedzi 2017-05-10 12:05 Swift Firebase sending data inside a closure » I am trying to send data to another view controller. However, the data cannot be reached at the second view controller. Here is my code: override fun... (1) odpowiedzi 2017-05-09 09:05 React to Mapkit object value change » I'm looking to react to the mapkit current location dot in real time. I can use LocationManager to get the position in intervals, however the annotati... (2) odpowiedzi 2017-05-09 07:05 Getting empty device token in iPhone 5 and iPhone SE » I am not getting device token in iPhone 5 (10.2.1) and SE(10.3.1) and other 5 related devices but successfully getting tokens in all iPhone 6 (includi... (0) odpowiedzi 2017-05-06 13:05 Error while testing SpriteKit project on iOS7 » I have developed SpriteKit Game targeting iOS7 Devices and later. I have added 10 SpriteKit scene files. I am using code for that to access each scene... (0) odpowiedzi 2017-05-06 09:05 Making table view section expand swift » I am following this tutorial for expanding and collapsing my table view section. As this demo is done in swift 2.2 I have made all the changes accordi... (2) odpowiedzi 2017-05-06 08:05 Issue while uploading image to server using NSInputStream » I Have issue while performing stream based image upload. i also have some parameters that need to be uploaded along with the image file too. I have b... (0) odpowiedzi 2017-05-03 07:05 Data load very slow on View Controller in swift 2.3 » I am displaying JSON Repsonse on View Controller but some data loads immediately with key(start date) but other takes time to load on View Controller ... (2) odpowiedzi 2017-05-03 04:05 FIRBase database UISearchBar string for child » I am stuck. New to searchbars Working: [String] "firstname" returns correct value when searching. If I have 3 people with "firstname" beginning with... (1) odpowiedzi 2017-05-03 02:05 I am having trouble loading a local HTML file. Here is my code. please help. let URL = NSBundle.mainBundle().pathForResource("index2", ofType: "html"...
http://jakzaprogramowac.pl/lista-pytan-jakzaprogramowac-wg-tagow/616/strona/3
CC-MAIN-2017-43
refinedweb
1,553
72.66
- Type: New Feature - Status: Reopened (View Workflow) - Priority: Major - Resolution: Unresolved - - Labels:None - Environment:Jenkins ver. 2.63 - Similar Issues: So, I'm having this problem that I described in a similar bug for the lockable-resource plugin ( JENKINS-45138). I said to myself, "oh, hey, I remember being able to throttle executions on a per-agent basis!" Imagine my surprise when I hit the documentation and find that throttle is only applicable inside a step. I need to acquire, use, and cleanup exclusive access to a resource on each agent. Will throttle work how I expect? step('foo') { throttle(['foo-label']) bat '... acquire the resource...' bat '... use the resource...' } post { always { bat '... cleanup the resource...' } } I tried Dmitry Mamchurs creative suggestion but on more recent versions this is explicitly prohibited: WorkflowScript: 2: pipeline block must be at the top-level, not within another block. @ line 2, column 5. pipeline { ^ Demo pipeline: throttle(['myThrottle']) { pipeline { agent { label 'mylabel' } stages { stage('first') { steps { sleep 60 } } } } } I've tested many other variants and I claim it is currently (with latest versions) impossible to get node throttling on a declarative pipeline. If someone has a counterexample I would appreciate that. Marcus Philip The secret sauce is having your pipeline defined in a shared library. vars/myPipeline.groovy def call() { pipeline { agent { label 'mylabel' } stages { stage('first') { steps { sleep 60 } } } } } jobs/my-pipeline/Jenkinsfile throttle(['myThrottle']) { myPipeline() } Je-s F-ng C-st! It's insane that that would make a difference but it does. So the 'pipeline block must be at the top-level' check is just on a file (textual) basis, not on the actual code structure. Thanks Dmitry Mamchur! You made my day! I honestly did not have much hope when I saw this issue having been updated in my e-mail this morning. Marcus Philip, I'll second your comment/excitement on finally having a solution to this mystery. Dmitry Mamchur, thank you so much! Our team already has our declarative and scripted pipelines largely live in libraries. I gave a couple attempts to implement the throttle as described by Dmitry Mamchur and here is a little more on how I think I'll `throttle` in our builds by renaming sharedPipeline to sharedPipelineInner and having sharedPipeline wrap the throttle category around the sharedPipeline() call. This way, I don't need to update 100+ repositories * number of branches. The current Jenkinsfile looks like this more or less... // library imports sharedPipeline() vars/sharedPipeline.groovy def call() { throttle(['throttle-category']) { sharedPipelineInner() } } vars/sharedPipelineInner.groovy def call() { pipeline { agent { label 'mylabel' } stages { stage('first') { steps { sleep 60 } } } } I did try to simply shift the pipeline config into a def within the original file, but that did not work. This defect asks for throttle within a step, which this solution does not provide, so I guess it will need to stay open. The docs for the plugin should be updated, for sure, with an example like this. Edit - Then again, the title says entire build so maybe this solution does apply and the example in the body does not. Anthony Mastrean, can you comment? I'm seeing what Guy Banay sees. I'm now testing a Declarative Pipeline workaround as Kyle Walker suggested – namely, putting the properties block outside the pipeline altogether – and it works, but it only honors the maxConcurrentTotal property, not the maxConcurrentNode one. Very simple repro (assuming a "ThrottleTest" category is configured globally): If I configure a maximum of 5 concurrent builds across all nodes, but only 1 per node, the only limit enforced is the total limit; a single build agent can still run as many builds of this job as it has executors. Only the maxConcurrentTotal takes effect.
https://issues.jenkins-ci.org/browse/JENKINS-45140
CC-MAIN-2020-24
refinedweb
618
56.45
af_afname, af_afpath, af_aftype, af_afuser, af_setarchpath, af_version - miscellaneous AtFS functions #include <atfs.h> char *af_afname (char *path) char *af_afpath (char *path) char *af_aftype (char *path) Af_user*af_afuser (uit_t uid) char *af_setarchpath (char *path) char *af_version (void) The functions af_afname, af_afpath and af_aftype extract name, syspath or type from a given (operating system dependent) file identification. In an UNIX environment, a given pathname of the form /usr/lib/libatfs.a leads to afname libatfs, afpath /usr/lib and aftype a. If no path (eg. otto.c), or no type (eg. /usr/hugo/Makefile) is given, the corresponding routine returns an empty string. A period as first character in a filename is always considered to be part of the name (e.g. .cshrc has the name .cshrc and an empty type string). "." and ".." are recognized as names. Archive file extensions and AtFS specific path extensions are stripped from the resulting name resp. pathname. Note: af_afname, af_afpath and af_aftype use static memory for the returned results. Subsequent calls of the same function overwrite former results. af_afuser returns an AtFS user identification which consists of the login name of the user identified by uid, the current host and the current domain. Uid_t is defined according to the return type of getuid (2) on your system. The Af_user type has the following structure typedef struct { charaf_username[MAXUSERNAMELEN]; charaf_userhost[MAXHOSTNAMELEN]; charaf_userdomain[MAXDOMAIN+1]; } Af_user; af_setarchpath defines the location of the AtFS archive files. A nil- pointer given as path-argument clears the former setting of the global archive path. af_setarchpath returns the old global archive path. Initially, no global archive path is set. In this case, all archive files are stored in a subdirectory called AtFS, relative to the directory where corresponding busy version resides. af_version returns a string that names the version and the creator of the currently used AtFS library. getuid(2)
http://huge-man-linux.net/man3/af_afuser.html
CC-MAIN-2018-13
refinedweb
307
58.08
[Idea] Data Entry not using a ui.TableView or dialogs This has probably done before, cant remnber seeing it though. But the code below is just using a view with a repeating number of labels and textfields to collect some data. What I have done is pretty crappy, but it does illustrate a different idea from using the dialogs module or a tableview to collect data. The difficulty to move away from them is the flexibility they offer thats built in. But this approach in my mind could be ok if you had modest needs. Hmmm, maybe. As I say It's just an idea. Look many things are missing from this idea, like a scrolling view. Maybe this type of an idea would be better moved in to a class. Maybe it should be disregarded altogether. I just wanted to try it out! import ui def text_form(items=None, width=320, **kwargs): if not items or not len(items): raise ValueError('items needs to be a list of strings or dicts') global _results input_flds = [] _results = None _current_y = 6 _gap = 6 v = ui.View(frame=(0, 0, width, 100), **kwargs) def obj_kwargs_setter(obj, **kwargs): ''' generic way to set the kwargs for a given object ''' [setattr(obj, k, v) for k, v in kwargs.items() if hasattr(obj, k)] def _collect_data(sender): ''' collect the data in the textfields ''' global _results _results = [{'key': obj.key, 'value': obj.text} for obj in input_flds] sender.superview.close() def _cancel_action(sender): sender.superview.close() def make_btn(name, title, action=None, **kwargs): ''' create what I think is a std btn. kwargs will overwite any attr ''' btn = ui.Button(height=32, name=name, title=title, border_width=.5, border_color='black', bg_color='white', corner_radius=6, action=action, ) btn.width = 80 obj_kwargs_setter(btn, **kwargs) return btn def make_field(fld_dict, y, **kwargs): ''' create what I think is a std label + textField. kwargs will overwite any attr of the textfield ''' current_y = y lb = ui.Label(frame=(6, current_y, 100, 32), text=str(fld_dict['title']), name=str(fld_dict['title']), ) fld = ui.TextField(frame=(82, current_y, 230, 32)) fld.key = fld_dict['key'] input_flds.append(fld) obj_kwargs_setter(fld, **kwargs) v.add_subview(lb) v.add_subview(fld) return fld.height + _gap flds = [] ''' step 1. checking to see if we have a list of strings or dicts. hmmm, only checking the first element :( This is imcomplete, just looking at a list of str's at the moment, but still creating dict items. Although they are still not finished yet ''' if isinstance(items[0], str): for l in items: flds.append(dict(type='Text', key=l, value='', title=l)) elif isinstance(items[0], dict): ''' Not implemented yet ''' pass # make the labels & fields for fld in flds: y = make_field(fld, _current_y) _current_y += y # make & position the ok and canel buttons ok_btn = make_btn('ok', 'OK', bg_color='purple', action=_collect_data, tint_color='white') v.add_subview(ok_btn) cancel_btn = make_btn('cancel', 'Cancel', _cancel_action, bg_color='deeppink', tint_color='white') v.add_subview(cancel_btn) ok_btn.y = _current_y + _gap ok_btn.x = v.frame.max_x - (ok_btn.width + _gap) _current_y += ok_btn.height + _gap cancel_btn.y = ok_btn.y cancel_btn.x = ok_btn.frame.min_x - (ok_btn.width + _gap) v.height = _current_y + _gap # make the first field ready for input, without having to tap it input_flds[0].begin_editing() v.present('sheet', animated=False) v.wait_modal() return _results if __name__ == '__main__': results = text_form(['Service', 'Account', 'Password'], bg_color='white', name='Add KeyChain Service') #results = text_form(['First', 'Last', 'Age', 'email'], bg_color='white', #name='Add Person') print(results) Why, in make_btn of ok, do you need action=... and in make_btn of cancel, not? @cvp , it was inconsistency poor on my part. action is an *arg, so its being accepted as a named *arg or a positional arg. To be consistent i should have done : cancel_btn = make_btn('cancel', 'Cancel',action=_cancel_action, bg_color='deeppink', tint_color='white') or left out the action specifier altogether in both calls, as they are positional arguments. ok_btn = make_btn('ok', 'OK', bg_color='purple', action=_collect_data, tint_color='white') cancel_btn = make_btn('cancel', 'Cancel', action=_cancel_action, bg_color='deeppink', tint_color='white') ok_btn = make_btn('ok', 'OK', bg_color='purple', _collect_data, tint_color='white') cancel_btn = make_btn('cancel', 'Cancel', _cancel_action, bg_color='deeppink', tint_color='white') Its not clear but should be equivalent, Thanks for your explanation, I didn't know this *arg, but, really, what do I know? Surely, not a lot 😭
https://forum.omz-software.com/topic/4581/idea-data-entry-not-using-a-ui-tableview-or-dialogs
CC-MAIN-2018-47
refinedweb
704
50.53
I'm trying to build a portable green screen photo booth. There's no way to know the lighting conditions ahead of time so I can't hard code the the color values for chroma key. I thought the easiest way to get around this issue would be to build a calibration script that will take a picture of the blank background, get the "highest" and "lowest" colors from it, and use those to produce the background mask. I'm running into trouble because while I can get the highest or lowest value in each of the channels, there's no guarantee that when the three are combined they match the actual color range of the image. UPDATE: I have changed to use only the hue channel. This helped a lot but still isn't perfect. I think better lighting will make a difference but if you can see any way to help I would be grateful. Here's what I have (edited with updates) import cv2 import numpy as np screen = cv2.imread("screen.jpg") test = cv2.imread("test.jpg") hsv_screen = cv2.cvtColor(screen, cv2.COLOR_BGR2HSV) hsv_test = cv2.cvtColor(test, cv2.COLOR_BGR2HSV) hueMax = hsv_screen[:,:,0].max() hueMin = hsv_screen[:,:,0].min() lowerBound = np.array([hueMin-10,100,100], np.uint8) upperBound = np.array([hueMax+10,255,255], np.uint8) mask = cv2.inRange(hsv_test,lowerBound,upperBound) cv2.imwrite("mask.jpg",mask) output_img = cv2.bitwise_and(test,test,mask=inv_mask) cv2.imwrite("output.jpg",output_img) screen and test images screen.jpg test.jpg HUE colors have specified intervals, get the green interval and then do an inRange using it, ignoring the saturation and value, that would give you all degrees of green, to minimize noise much, make the value range to be from 20% to 80%, that would avoid the too much light, or too much dark regions, and ensure you only get what's green anywhere in the screen. Detecting using only HUE channel is dependable.
https://codedump.io/share/OeguTCD0F6VL/1/get-the-range-of-colors-in-an-image-using-python-opencv
CC-MAIN-2018-26
refinedweb
324
66.23
Describes the ARM® C and C++ libraries. 1.1 Mandatory linkage with the C library. 1.2 C and C++ runtime libraries. 1.3 C and C++ library features. 1.4 C++ and C libraries and the std namespace. 1.5 Multithreaded support in ARM C libraries. 1.6 Support for building an application with the C library. 1.7 Support for building an application without the C library. 1.8 Tailoring the C library to a new execution environment. 1.9 Assembler macros that tailor locale functions in the C library. 1.10 Modification of C library functions for error signaling, error handling, and program exit. 1.11 Stack and heap memory allocation and the ARM C and C++ libraries. 1.12 Tailoring input/output functions in the C and C++ libraries. 1.13 Target dependencies on low-level functions in the C and C++ libraries. 1.14 The C library printf family of functions. 1.15 The C library scanf family of functions. 1.16 Redefining low-level library functions to enable direct use of high-level library functions in the C library. 1.17 The C library functions fread(), fgets() and gets(). 1.18 Re-implementing __backspace() in the C library. 1.19 Re-implementing __backspacewc() in the C library. 1.20 Redefining target-dependent system I/O functions in the C library. 1.21 Tailoring non-input/output C library functions. 1.22 Real-time integer division in the ARM libraries. 1.23 ISO C library implementation definition. 1.24 C library functions and extensions. 1.25 Compiler generated and library-resident helper functions. 1.26 C and C++ library naming conventions. 1.27 Using macro__ARM_WCHAR_NO_IO to disable FILE declaration and wide I/O function prototypes. 1.28 Using library functions with execute-only memory.
http://infocenter.arm.com/help/topic/com.arm.doc.dui0475m/chr1358938908603.html
CC-MAIN-2017-43
refinedweb
299
53.98
? The difference is that functionTwo is defined at parse-time for a script block, whereas functionOne is defined at run-time. For example: <script> // Error functionOne(); var functionOne = function() { } </script> <script> // No error functionTwo(); function functionTwo() { } </script> What is the difference between using call and apply to invoke a function? var func = function(){ alert('hello!'); }; func.apply(); vs func.call(); Are there performance differences between the two methods? When is it best to use call over apply and vice versa? The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly. Pseudo syntax: theFunction.apply(valueForThis, arrayOfArgs) theFunction.call(valueForThis, arg1, arg2, ...) Sample code: function theFunction(name, profession) { alert("My name is " + name + " and I am a " + profession + "."); } theFunction("John", "fireman"); theFunction.apply(undefined, ["Susan", "school teacher"]); theFunction.call(undefined, "Claude", "mathematician"); Possible Duplicate: Is there a better way to do optional function parameters in Javascript? I would like a JavaScript function to have optional arguments which I set a default on, which gets used if the value isn't defined. In ruby you can do it like this: def read_file(file, delete_after = false) # code end Does this work in JavaScript? function read_file(file, delete_after = false) { // Code } There are a lot of ways, but this is my preferred method - it lets you pass in anything you want, including false or null. ( typeof null == "object") function foo(a, b) { a = typeof a !== 'undefined' ? a : 42; b = typeof b !== 'undefined' ? b : 'default_b'; ... } !function () {}(); OK, so back to JavaScript syntax 101. Here is a function declaration: function foo() {} Note that there's no semicolon: this is a statement; you need a separate invocation of foo() to actually run the function. On the other hand, !function foo() {} is an expression, but that still doesn't invoke the function, but we can now use !function foo() {}() to do that, as () has higher precedence than !. Presumably the original example function doesn't need a self-reference so that the name then can be dropped. So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this: (function(){})(); I've always handled optional parameters in Javascript like this: function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; //do stuff } Is there a better way to do it? Are there any cases where using || like that is going to fail? Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative optionalArg = (typeof optionalArg === "undefined") ? "defaultValue" : optionalArg; In one of my project source files, I found this C function definition: int (foo) (int *bar) { return foo (bar); } Note: there is no asterisk next to foo, so it's not a function pointer. Or is it? What is going on here with the recursive call? In the absence of any preprocessor stuff going on, foo's signature is equivalent to int foo (int *bar) The only context in which I've seen people putting seemingly unnecessary parentheses around function names is when there are both a function and a function-like macro with the same name, and the programmer wants to prevent macro expansion. This practice may seem a little odd at first, but the C library sets a precedent by providing some macros and functions with identical names. One such function/macro pair is isdigit(). The library might define it as follows: /* the macro */ #define isdigit(c) ... /* the function */ int (isdigit)(int c) /* avoid the macro through the use of parentheses */ { return isdigit(c); /* use the macro */ } Your function looks almost identical to the above, so I suspect this is what's going on in your code too..)
http://boso.herokuapp.com/function
CC-MAIN-2017-26
refinedweb
616
63.59
In these days I worked on a project into which I have to rely on SSI (apache’s Server Side Includes) in order to read and use url parameters to dynamically include certain html files with “include virtual” directive. Unfortunately the documentations available online is not exhaustive, and I had to figure out some things by myself. Anyway, according to the docs, there are several global variables we can use in SSI, two of these are: DOCUMENT_URI and QUERY_STRING, which are the two we can use to handle the page url. The first returns the (%-decoded) URL path of the document, the second all the string starting with “?”. So, how we can extract our desired variables from these strings, since SSI doesn’t offer method such “substring”, “split”, “indexOf” and similar? The answer is: by using Regular Expression in a tricky and ingenious way! SSI offers a basic way to implementing decision flow (if, else, elif), the if command has an attribute expr which represents a declaration to be valuated, in this attribute is also possible to use a regex to test a given pattern. By knowing this, is possible to declare an SSI variable which represents the desired querystring parameter in the following way: <!--#if expr="$QUERY_STRING = /year=([0-9]{4})/" --> <!--ssi-comment: year found --> <!--#set var="year" value="$1" --> <!--#else --> <!--ssi-comment: year NOT found --> <!--#set var="year" value="$DATE_LOCAL" --> <!--#endif --> In the code above I’m looking to a querystring parameter called year which must be a 4 ({4}) digit number ([0-9]). If the pattern tested returns true, the matched value (returned by the regex) will be assigned to the SSI variable year, otherwise the current server date year ($DATE_LOCAL) will be assigned. Notes: 1. “ssi-comment:” is not a special syntax, but just a comment style I decided to adopt to be readable and understandable. 2. To get only the year from $DATE_LOCAL variable, you must config the format using “#config timefmt=”%Y””
http://www.daveoncode.com/tag/ssi/
CC-MAIN-2017-17
refinedweb
328
61.26
>> Bokeh be used to visualize multiple bar plots in Python? Bokeh is a Python package that helps in data visualization. It is an open source project. Bokeh renders its plot using HTML and JavaScript. This indicates that it is useful while working with web- Numpy Pillow Jinja2 Packaging Pyyaml Six Tornado Python−dateutil Installation of Bokeh on Windows command prompt pip3 install bokeh Installation of Bokeh on Anaconda prompt conda install bokeh Let us see an example − Example from bokeh.plotting import figure, output_file, show from bokeh.transform import dodge labs = ['label_1', 'label_2', 'label_3'] vals = ['val_1','val_2','val_3'] my_data = {'labs':labs, 'val_1':[2,5,11], 'val_2':[34,23,1], 'val_3':[25, 34, 23] } fig = figure(x_range = labs, plot_width = 300, plot_height = 300) fig.vbar(x = dodge('labs', -0.25, range = fig.x_range), top = 'val_1', width = 0.2,source = my_data, color = "green") fig.vbar(x = dodge('labs', 0.0, range = fig.x_range), top = 'val_2', width = 0.2, source = my_data,color = "cyan") fig.vbar(x = dodge('labs', 0.25, range = fig.x_range), top = 'val_3', width = 0.2,source = my_data,color = "blue") show(fig) Output Explanation The required packages are imported, and aliased. The figure function is called along with plot width and height. The data is defined in lists. The ‘output_file’ function is called to mention the name of the html file that will be generated. The ‘vbar’ function present in Bokeh is called, along with data. The ‘show’ function is used to display the plot. - Related Questions & Answers - How can Bokeh be used to visualize bar plot in Python? - How can Bokeh library be used to visualize stacked bar charts in Python? - How can Bokeh library be used to plot horizontal bar plots using Python? - How can Bokeh be used to visualize multiple shapes on a plot in Python? - How can Bokeh library be used to visualize twin axes in Python? - How can Seaborn library be used to visualize point plots in Python? - How can Bokeh be used to visualize different shapes of data points in Python? - How can Matplotlib be used to create multiple plots iteratively in Python? - How can multiple lines be visualized using Bokeh Python? - How can bar graphs be visualized using Bokeh? - How can Bokeh be used to generate sinusoidal waves in Python? - How can Bokeh be used to generate patch plot in Python? - How can Pygal be used to visualize a treemap in Python? - How can Bokeh be used to generate scatter plot using Python? - How can Tensorflow be used to visualize the data using Python?
https://www.tutorialspoint.com/how-can-bokeh-be-used-to-visualize-multiple-bar-plots-in-python
CC-MAIN-2022-33
refinedweb
419
69.99
At 04:35 PM 5/5/2009 -0500, Ian Bicking wrote: >Any ideas on this? Phillip? > >On Fri, May 1, 2009 at 5:07 PM, Ian Bicking ><<mailto:ianb at colorstudy.com>ianb at colorstudy.com> wrote: >So, a bit of a problem came up with pip and namespace >packages.Â. But >there's a problem when there's another namespace package elsewhere >on the path, that wasn't installed with pip (or Setuptools) and uses >pkgutils.extend_path(__path__, __name__). This doesn't get >imported because of that .pth file, and the .pth file doesn't itself >use extend_path, so the path isn't searched. This is currently >happening with Zope packages installed with plain distutils, then >another package installed with the zope namespace elsewhere with >pip. (When using easy_install, I think >pkg_resource.declare_namespace comes into play somewhere, and this >seems to handle this case, but I'm not sure why the installation is >different with pip.) > >So... what should pip be doing differently to make this work? Heck if I know. IIUC, this should work as long as the namespace declaration gets invoked at some point. But I don't know of any way to ensure that, except for pip to write its own __init__.py (invoking declare_namespace()) and gets rid of the nspkg.pth file.
https://mail.python.org/pipermail/distutils-sig/2009-May/011787.html
CC-MAIN-2019-26
refinedweb
222
76.01
Intruction: This script can align the move handler or scale handler to the average normal of the faces you selected. Align Move Pivot / Align Scale Pivot: choose which handler you want to align. Additional Fixing: Add an additional alignment to the handler, which will fix the orient problem caused by default algorithm. Reset Move Pivot / Reset Scale Pivot: set the move & scale tool settings to default; clear the pivot rotation. Usage: 1. put the script under your script path 2. run the following script in Maya: import JN_AlignPivot JN_AlignPivot.interface() Upgrade 1.0.5: fixed a bug when multiple faces were selected. Please use the Feature Requests to give me ideas. Please use the Support Forum if you have any questions or problems. Please rate and review in the Review section.
https://ec2-34-231-130-161.compute-1.amazonaws.com/maya/script/align-pivot-for-maya
CC-MAIN-2021-43
refinedweb
131
68.16
RECURSION • Self referential functions are called recursive (i.e. functions calling themselves) • Recursive functions are very useful for many mathematical operations Factorial: Recursive Functions • 1! = 1 • 2! = 2*1 = 2*1! So: n! = n*(n-1)! For N>1 • 3! = 3*2*1 = 3*2! 1! = 1 • 4! = 4*3*2*1 = 4 * 3! • Properties of recursive functions: • 1) what is the first case (terminal condition) • 2) how is the nth case related to the (n-1)th case Or more general: how is nth case related to <nth case Recursive procedure • A recursive task is one that calls itself. With each invocation, the problem is reduced to a smaller task (reducing case) until the task arrives at a terminal or base case, which stops the process. The condition that must be true to achieve the terminal case is the terminal condition. #include <iostream.h> long factorial(int); // function prototype int main() { int n; long result; cout << "Enter a number: "; cin >> n; result = factorial(n); cout << "\nThe factorial of " << n << " is " << result << endl; return 0; } long factorial(int n) { if (n == 1) return n; else return n * factorial(n-1); } Terminal condition to end recursion long factorial(int n) { if (n == 1) return n; else /* L#6 */ return n * factorial(n-1); } n=1 Return value Addr of calling statement L#6: return 2 * factorial(1) n=2 Return value Addr of calling statement L#6: return 3 * factorial(2) n=3 Reserved for return value Main program: result = factorial(3) Addr of calling statement 1 2*1 3*2 ****** Iterative solution for factorial: int factorial (int n) { int fact; for (fact = 1;n>0; n--) fact=fact*n; return fact } Recursive functions can always be “unwound” and written iteratively Example 2: Power function • xn = 1 if n = 0 • = x * xn-1if n>0 • 53 = 5 * 52 • 52 = 5 * 51 • 51 = 5 * 50 • 50 = 1 Return 1 float power(float x, int n) { if (n == 0) return 1; else return x * power (x, n-1); } X=5, n=0 5 * power(5,0) X=5, n=1 5 * power(5,1) X=5, n=2 5 * power(5,2) X=5, n=3 Power(5,3) ****** Power function xn • Thus for n= 3, the recursive function is called 4 times, with n=3, n=2, n=1, and n=0 • in general for a power of n, the function is • called n+1 times. • Can we do better? x7 = x (x3)2 int (7/2) = 3 We know that : x14 = (x7)2in other words: (x7 * x7) x3 = x (x1)2 xn = 1if n= 0 = x(xn/2)2if n is odd = (xn/2)2if n is even x1 = x (x0)2 x0 = 1 Floor of n/2 float power (float x, int n) { float HalfPower; //terminal condition if (n == 0) return 1; //can also stop at n=1 //if n Is odd if (n%2 == 1) { HalfPower = power(x,n/2); return (x * HalfPower *HalfPower): } else { HalfPower = power(x,n/2); return (HalfPower * HalfPower); } **** if (n == 0) return 1; if (n%2 == 1) { HalfPower = power(x,n/2); return (x * HalfPower *HalfPower): } else { HalfPower = power(x,n/2); return (HalfPower * HalfPower); } Can also use the call: return power(x,n/2) * power (x,n/2) But that is much less efficient! Recursive Power Function: divide & conquer • How many calls to the power function does the second algorithm make for xn? Log2(n)!!!! ** Parts of a Recursive Function: recursive_function (….N….) { //terminal condition if (n == terminal_condition) return XXX; else { … recursive_function(….<N….); } 1. 2. int main(void) { int z; z= f ( f(2) + f(5)); cout << z; } int f(int x) { int returnvalue; if (x==1) || (x== 3) return x; else return (x * f(x-1)) } Recursion Example What gets printed? (2 + 60)! / 2 ** Recursion: Example 4 Write a recursive boolean function to return True (1) if parameter x is a member of elements 0 through n of an array. Int inarray(int a[], int n, int x) { if (n<0) return FALSE; else if (a[n] == x) return TRUE; else return inarray(a,n-1,x); } What is a better name for this function? (i.e., what does it do?) • int main() • { • int RandyJackson[] = {1,2,3,4,5,6,7,8,9,99}; • int *paula; • paula = RandyJackson; • AmericanIdol(paula); • return 0; • } • int AmericanIdol(int *simon) • { • if (*simon == 99) return 0; • AmericanIdol(simon+1); • cout <<*simon<<endl; • return 0; • } What gets printed? • int r(int); • r(840); • return 0; • } • int r(int n) • { • cout << n <<endl; • if (n <= 4242) • r(2*n); • cout << n << endl; • return n; • } 840 • 1680 • 3360 • 6720 • 6720 • 3360 • 1680 • 840 Algorithm Analysis & Complexity We saw that a linear search used n comparisons in the worst case (for an array of size n) and binary search had logn comparisons. Similarly for the power function -- the first one took n multiplications, the second logn. Is one more efficient than the other? How do we quantify this measure? Efficiency • CPU (time) usage • memory usage • disk usage • network usage • 1.Performance: how much time/memory/disk/... is actually used when a program is run. This depends on the machine, compiler, etc. as well as the code. • 2.Complexity: how do the resource requirements of a program or algorithm scale, i.e., what happens as the size of the problem being solved gets larger. • Complexity affects performance but not the other way around. The time required by a method is proportional to the number of "basic operations" that it performs. Here are some examples of basic operations: • one arithmetic operation (e.g., +, *). • one assignment • one test (e.g., x == 0) • one read • one write (of a primitive type) Constant Time vs. Input Size • Some algorithms will take constant time -- the number of operations is independent of the input size. • Others perform a different number of operations depending upon the input size • For algorithm analysis we are not interested in the EXACT number of operations but how the number of operations relates to the problem size in the worst case. Big Oh Notation • The measure of the amount of work an algorithm performs of the space requirements of an implementation is referred to as the complexity or order of magnitude and is a function of the number of data items. We use big oh notation to quantify complexity, e.g. O(n), or O(logn) Big Oh notation • O notation is an approximate measure and is used to quantify the dominant term in a function. • For example, if f(n) = n3 + n2 + n + 5 • then f(n) = O(n3) • (since for very large n, the n3 term • dominates) Big Oh notation For n = 5, the values in the array get printed (25 gets printed). After each row a new line gets printed (5 of them) Total work = n2 +n = O(n2) • for (I = 0; I<n; I++) • { • for (j=0; j<n; j++) • cout << a[I][j] << “ “; • cout << endl; • } For n = 1000, a[I][j] gets printed 1000000 times, endl only 1000 times. Big Oh Definition • Function f is of complexity or order at mostg, written with big-oh notation as f = O(g), if there exists a positive constant c and a positive integer n0such that • |f(n)| <= c|g(n)| for all n>n0 • We also say that f has complexity O(g) |f(n)| <= c|g(n)| for all n>n0 Let f(n) = n2 + 5 Let g(n) = n2 so is f(n) = O(g(n)) or O(n2)? Yes, since there exists a constant c and a positive integer n0 to make the above statement true. For example, if c=2, n0 = 3 n2 + 5 <= 2n2for all n>3 This statement is always true for n>3 F(N) = 3 * N2 + 5. We can show that F(N) is O(N2) by choosing c = 4 and n0 = 2. This is because for all values of N greater than 2: 3 * N2 + 5 <= 4 * N2 F(N) != O(N) because one can always find a value of N greater than any n0 so that 3 * N2 + 5 is greater than c*N. I.e. even if c = 1000, if N== 1M 3 * N2 + 5 > 1000 * N N>n0 Running time O(n2) O(n) N Constants can make o(n) perform worse for low values Time n=1 n=2 n=4 n=8 n=16 n=32 1 1 1 1 1 1 1 logn 0 1 2 3 4 5 n 1 2 4 8 16 32 nln 0 2 8 24 64 160 n2 1 4 16 64 256 1024 n3 1 8 64 512 4096 32768 2^n 2 4 16 256 65536 4294967296 n! 1 2 24 40326 2.1x1013 2613x1033 Determining Complexity in a Program: 1. Sequence of statements: statement 1; statement 2; ... statement k; total time = time(statemnt 1) + time(statemnt 2) + ...time(statemnt k) 2. If-then-else statements: total time = max(time(sequence 1),time(sequence 2)). For example, if sequence 1 is O(N) and sequence 2 is O(1) the worst-case time for the whole if-then-else statement would be O(N). 3. Loops for (i = 0; i < N; i++) { sequence of statements } The loop executes N times, so the sequence of statements also executes N times. Since we assume the statements are O(1), the total time for the for loop is N * O(1), which is O(N) overall. Nested loops). Determining Complexity • look for some clues and do some deduction to • arrive at the answer. Some obvious things— • Break the algorithm down into steps and analyze the complexity of each. For example, analyze the body of a loop first and then see how many times that loop is executed. • Look for for loops. These are the easiest statements to analyze! They give a clear upper bound, so they’re usually dead giveaways.—sometimes other things are going on in the loop which change the behavior of the algorithms. • Look for loops that operate over an entire data structure. If you know the size of the data structure, then you have some ideas about the running time of the loop. • Loops, loops. Algorithms are usually nothing but loops, so it is imperative to be able to analyze a loop! General Rules for determining O 1. Ignoring constant factors: O(c f(N)) = O(f(N)), where c is a constant; e.g. O(20 N3) = O(N3) 2. Ignoring smaller terms: If a<b then O(a+b) = O(b), for example O(N2+N) = O(N2) 3. Upper bound only: If a<b then an O(a) algorithm is also an O(b) algorithm. For example, an O(N) algorithm is also an O(N2) algorithm (but not vice versa). 4. N and log N are "bigger" than any constant, from an asymptotic view (that means for large enough N). So if k is a constant, an O(N + k) algorithm is also O(N), by ignoring smaller terms. Similarly, an O(log N + k) algorithm is also O(log N). 5. Another consequence of the last item is that an O(N logN+N) algorithm, which is O(N(log N + 1)), can be simplified to O(NlogN). Bubble sort -- analysis • void bubble_sort(int array[ ], int length) • { • int j, k, flag=1, temp; • for(j=1; j<=length && flag; j++) • { flag=0; • for(k=0; k < (length-j); k++) • { if (array[k+1] > array[k]) • { • temp=array[k+1]; • array[k+1]= array[k]; • array[k]=temp; • flag=1; • } } } } N(N-1) = O(N2) Review of Log properties • logb x = p if and only if bp = x (definition) • logb x*y = logb x + logb y • logb x/y = logb x - logb y • logb xp = p logb x which implies that (xp)q = x(pq) • logb x = loga x * logb a log to the base b and the log to the base a are related by a constant factor. Therefore, O(N logb N), is the same as O(N loga N) because the big-O bound hides the constant factor between the logs. The base is usually left out of big-O bounds, I.e. O(N log N). // this function returns the location of key in the list // a -1 is returned if the value is not found int binarySearch(int list[], int size, int key) { int left, right, midpt; left = 0; right = size - 1; while (left <= right) { midpt = (int) ((left + right) / 2); if (key == list[midpt]) { return midpt; } else if (key > list[midpt]) left = midpt + 1; else right = midpt - 1; } O(logn) When do constants matter? When the problem size is “small” N 100*N N2/100 102 104 102 103 105 104 104 106 106 105 107 108 107 109 1012 Running Time • Also interested in Best Case and Average Case Mission critical -- worst case important Merely inconvenient -- may be able to get away with Avg/Best case Avg case must consider all possible inputs
https://www.slideserve.com/ganya/recursion-powerpoint-ppt-presentation
CC-MAIN-2021-49
refinedweb
2,166
65.35
As Spring MVC works on URL Pattern and every request for Image and Resources came from client is separate request, So Spring is finding the matching pattern for "/bootstrap.css" to identify is there anything to serve against this Pattern. And there is no resource mapped against this that is why you are getting this error. You can say Spring that these are my resources and don't go for any mapping finding, if request comes with mentioned URL. put below line in spring-servlet.xml file. <mvc:resources this will help you to get rid of css loading errors. but problem for js and image still be there, So try to keep all resources in one resource folder and give mapping like one below, <mvc:resources mapping="/reso You currently don't have any CUDA code, so I may can't give enough details. For your Qs: Linking object files including CUDA code requires nvcc compiler driver. You could first compile your code files with individual compilers, i.e. gcc for .c, g++ for .cpp, g77 for .f and nvcc for .cu. Then you can use nvcc to link all the object files .o; host and device code are explicitly declared in .cu file with __host__ and __device__. It's your responsibility not to invoke device code from other host code; Why are your passing a class to CUDA? If you want to replace your fortran code with CUDA, you only need to invoke CUDA functions in your C++ wrapper class, and invoking CUDA API functions uses the the same grammar as invoking c++ functions. Here is an example from my project. The executable Create a windows form. This will be your main form. Assuming your using Visual Studio this is realatively easy. Once you have your main form up, drag and drop a user controller onto your form. Have your main form contain the 5 buttons,and your data grid on the other form. Enyo's tutorial is excellent. I found that the sample script in the tutorial worked well for a button embedded in the dropzone (i.e., the form element). If you wish to have the button outside the form element, I was able to accomplish it using a click event: First, the HTML: <form id="my-awesome-dropzone" action="/upload" class="dropzone"> <div class="dropzone-previews"></div> <div class="fallback"> <!-- this is the fallback if JS isn't working --> <input name="file" type="file" multiple /> </div> </form> <button type="submit" id="submit-all" class="btn btn-primary btn-xs">Upload the file</button> Then, the script tag.... Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the Look at BackgroundWorker component it was specifically designed to allow you to do work in the background and report progress/change to the UI. Note that you're also pausing the UI thread by calling Thread.Sleep(1000) which probably won't end well. You can find documentation on background workers here - The static method SetTextForLabel doesn't have access to the controls of the instance of the class Form1. You have to provide a specific instance by passing a parameter or declaring a static member in the Form1 class. As mentioned in the comments, this won't work either since Application.Run() starts an application in the current thread so the code needs some refactoring as well. public partial class Form1 : Form { public Form1() { InitializeComponent(); ConnectUDP(); } private void ConnectUDP() { UdpClient subscriber = new UdpClient(8899); IPAddress addr = IPAddress.Parse("230.0.0.1"); subscriber.JoinMulticastGroup(addr); IPEndPoint ep = null; for (int i = 0; i < 10; i++) { byte[] pdata Android applications are "sandboxed". So, yo cannot integrate any third party application into your application. At the maximum you can launch that any third party application from your application if that application allows it. Also you can launch some of its specific features, if the application has set intent filter for them and you know them. It's probably not feasible or practical to attempt a Windows Form application on a Raspberry Pi and definitely an impossibility on an Arduino. The RaspberryPi.org site explicitly states that RaspberryPi will not run Windows applications: enter link description here The Arduino really does not have a GUI or a Window subsystem that would support that type of application. Really, the Arduino is just such a tiny little 8 bit cpu, 2k ram computer, it is just completely off the radar for a Windows application. You may want to investigate the possibility of writing a Python application in windows and porting that to a Raspberry Pi. To use classes from another projects (forms are classes): Classes must be public. You must add target project by right-clicking on your current solution and then Add, Existing project... and selecting your project Use classes by specifying their full name with namespace or use using directive. The second task is to use one form as a container for others. This article can help: How to: Create MDI Child Forms private void btnAdd_Click(object sender, EventArgs e) { string _webstring = @"http://"; string _website = _webstring + textBox1.Text; listBox1.Items.Add(_website); using (StreamWriter w = File.AppendText("websites.txt")) { WriteLog(_website, w); } using (StreamReader r = File.OpenText("websites.txt")) { DisposeLog(r); } } private void btnLaunch_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start("iexplore.exe", listBox1.SelectedItem.ToString()); } private void btnSave_Click(object sender, EventArgs e) { using (StreamWriter w = File.AppendText("websites.txt")) { foreach (string items in listBox1.Items) Just set up a property of textbox: textbox.UseSystemPasswordChar == true; and you can also set the char for password what ever you want: textBox1.PasswordChar = '*'; Just instantiate the Windows form in your WPF Form's/Viewmodels constructor and call ShowDialog: namespace WpfApplication11 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var form1 = new Form1(); form1.ShowDialog(); } } } Your UDPRecv() method will run on an I/O completion thread. Any attempt to update the UI from that thread is going to bomb your program. You'll have to use the form's BeginInvoke() method to pass the string to a method that runs on the UI thread. You will also have to deal with the socket getting closed when your program terminates, that requires catching the ObjectDisposedException that the EndReceive() call will throw. So make it look like this: Public Sub UDPRecv(ar As IAsyncResult) Try '' Next statement will throw when the socket was closed Dim recvBytes As Byte() = dgClient.EndReceive(ar, SiteEndPoint) Dim recvMsg As String = Encoding.UTF8.GetString(recvBytes) '' Pass the string to a method that runs on the UI thread Me.BeginInvoke(New try passing the parameters like so: C:whatever.exe -<your parameter> . Then read the parameter as an argument For example: if you have the exe as C:whatever.exe -<your parameter> in the void Main(string[] args) you would do the following: void Main (string[] args) { foreach (var item in args) { var parameter=item; // do whatever you wish with parameter } } Handle the ItemCheck event and read the NewValue property to determine if it's about to be checked or unchecked. private void myListView_ItemCheck(object sender, ItemCheckEventArgs e) { if (e.NewValue == CheckState.Unchecked) { //unchecked } else if(e.NewValue == CheckState.Checked) { //checked } } I am using a public property which gives address of the root folder of the application : public string StartPath { get{ return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6); } } Simply private void o(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.O) { openFileDialog1.ShowDialog(); } else if (e.KeyCode == Keys.P) { player.Play(); } } you may want to define only one event-handler, but you can check for several keys pressed. What do you mean by Decimal? Perhaps int? See itoa() in the C runtime, or template<typename T> std::string to_string(T num) { std::ostringstream stream; stream << num; return stream.str(); } and call TiXmlText(to_string(666).c_str()); There are many ways - you can use sockets, pipes, message queues, you can store information in a database, you can host a WCF service in the console application etc. But I won't get into a discussion of which of those is best here. Really, if you are having this problem, then very probably you should make your whole solution a Windows Forms/WPF application. It's a lot easier to pass information between forms of the same application, specially if they can reference each other amongst themselves. They just have to call each other's methods, or access each other's properties, or go for the same static class. All in the same environment, no application boundaries crossed. If you want to keep the console there, you could have the main form be hidden and open up a separate console app. Then yo You can simple send a Get/Post-Request to your PHP-Page: Generate HTTP Requests using c# and then Read the data via: $Get or $Post. You can do the same with ASP.Net, via QueryString: string cParam = Request.QueryString["param"];: Better approach would be this: var command = new SqlCeCommand("select top 1 * from Files where nameFile = @file",con); command.Parameters.AddWithValue("@file", name); var returned = command.ExecuteScalar(); if (returned != null) { returned = true; } and this should work fine. Also top 1 is for performance if you only want to check if file exists in database. Yes, you can easily create multiple instance of the same form. For example: new ChatWindowForm.Show(); Also see the Control.Show() method documentation. You can use BringToFront() to bring the Line (or any Control) forward in the z order. l.BringToFront(); From the fine manual: Application.Startup Event Occurs when the Run method of the Application object is called. Example XAML: <Application xmlns="" xmlns:x="" x: Example C#: using System.Windows; // Application, StartupEventArgs, WindowState namespace SDKSample { public partial class App : Application { void App_Startup(object sender, StartupEventArgs e) { // Application is running // Process command line args bool startMinimized = false; for (int i = 0; i != e.Args.Length; ++i) { if (e.Args[i] == "/StartMinimized") This happens when one of your text boxes has the focus. It ding-a-lings you to remind you that it doesn't know what to do with the Enter key. It only has a meaning if the box' MultiLine property is set to true. Of course it is not set. The Enter key is special, along with the Escape key, it is intended to operate the default button of the window. You have one, you like your Calculate button to be your default button. So select your form in the designer and change the AcceptButton property, pick your Calculate button from the combobox. Don't forget to add the code that checks that the text boxes have valid strings in them that can be converted to a number with, say, double.TryParse().' I believe that you can't, the idea is to have sandboxed applications that don't know about each other. You register them as share sources or targets and then a broker handles the interaction between them so there is never any direct contact. Looking at the available members on the objects used for the implementation I can't see anything that would provide information about where the share was made from. Provide some information about what you want to achieve. I found the solution for the issue from Adding the header param to the URL did the trick. Okay, assuming HttpRuntime.Cache is the only thing you're using from ASP.Net: HttpRuntime's class description from MSDN: Provides a set of ASP.NET run-time services for the current application. So, there's a little part of a web server living in System.web.dll and this is one main API for accessing it. The first time you make a call into System.web.dll things will have to be initialized, which takes some time (although minutes is surprising 10 - 20 seconds seems more likely). One thing you could try is initializing in a sub-thread: volatile bool isCacheReady = false; Cache cache = null; System.Threading.Thread t1 = new System.Threading.Thread(delegate() { cache = HttpRuntime.Cache; isCacheReady = true; }); t1.Start(); // periodically check if cache is available yet ( There are meny ways to do whay you want to do. the main question is why do you want to do it? if you have a normal program for personal use you can simply link it to the needed file, meaning using the file without actual knowledge that it's there. if it's for a task then you can zip them together, that way you'll know they are together, without adding them as resource. for other kind of use, or if you have to add them as resources, just add them like shown here for more reading on what do you need and how to do it i have here linked vs. Embeded resources good luck Well, the posts stating that such communication is not possible, are mostly right. There are 2 reasons, why this is prevented: Being able to communicate to an application outside the sandbox effectively breaks the sandbox. The Windows Store app is now suddenly able to do everything the desktop application can do: access file system, registry... Windows Store apps live in a sandbox for reason - to be safe for the user. The Windows Store app won't work after it is installed from the the store or from a package. It needs to have a desktop application installed and set up correctly as well. I would suggest you try to move your server part to a different machine and make it a proper server. If for some reason you really can't do that, you still have the following options available: You ca Its all documented, here is a great example: How to automate Microsoft Word to create a new document by using Visual C# So to pass the strings in the datagridview to word to print you do it like this: //Start Word and create a new document. Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = true; oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,ref oMissing, ref oMissing); //Insert a datagridview info into the document. DataTable dt = (DataTable)datagridview1.DataSource; foreach(DataRow dr in dt.Rows) { Word.Paragraph oPara1; oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing); oPara1.Range.Text = dr[0].ToString(); oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. oPara1.Range.InsertParagraphAft A Windows desktop application is nothing like an ASP.NET web application. You cannot call the different forms separately. (well you can hack the application, but if you do that, you can just as well remove any password protection) Hence forms authentication does not make any sense. You can create a login window as startup window, and check username and password against the database. And that's about it. It's a Windows application, you don't need membership provider, forms cookie ticket, etc. because unlike HTTP, Windows desktop applications are not stateless. PS: If you do a WinForms application, make the login via ActiveDirectory authentication. You have multiple questions. I will answer the "how to add empty row" one. For that After you populate your dataset and before you bind it to the Grid you should add an empty row to the top of this dataset. ' insert a blank row at the top Dim dr As DataRow = MyGrid.Tables(0).NewRow() dr("MyFiled") = "0" MyGrid.Tables(0).Rows.InsertAt(dr, 0) There are many articles on internet showing how to save data. If you have problem with those please write your specific code here. since you're in .NET I guess you should look into WCF - Windows Communication Foundation, you define the contracts (Service contract, data contracts), publish the service and use the service without worrying about the protocol since you can choose it by configuring the server and the client app. You can take a look at these links for some in information: Hope it helps, Cheers. Unlike Visual Studio, Eclipse CDT does not have a built-in wizard or options for automatically configuring compiler settings and libraries for building Windows GUI applications. You will need to know what you are doing. Do you intend to build the GUI using Win32/MinGW, or perhaps using some other GUI library, like Qt or wxWidgets? There are many options. If you are new to C++ and/or GUI development on windows, then there are easier options to get started with.
http://www.w3hello.com/questions/-Integrating-an-existing-ASP-NET-application-with-a-Windows-Form-application-
CC-MAIN-2018-17
refinedweb
2,742
56.96
- Content-Type: application/json - - // '1' and '0' as checked/unchecked options; checked - - // 'bar' and '0' as checked/unchecked options; not checked - - // 'bar' and '0' as checked/unchecked options; checked - - // 'bar' and 'baz' as checked/unchecked options; unchecked - - // 'bar' and 'baz' as checked/unchecked options; unchecked - - 'checked' => 'bar', - 'unChecked' => 'baz' - )); - // 'bar' and 'baz' as checked/unchecked options; checked - - - null, - - - // 'bar' and 'baz' as checked/unchecked options; unchecked - - - null, -: - - </label></p> - <p><label>Your Country: - - </label></p> - <p><label>Would you like to opt in? - - <: BaseUrl Helper While most URLs generated by the framework have the base URL prepended automatically, developers will need to prepend the base URL to their own URLs in order for paths to resources to be correct. Usage of the BaseUrl helper is very straightforward: - /* - * The following assume that the base URL of the page/application is "/mypage". - */ - /* - * Prints: - * <base href="/mypage/" /> - */ - <base href="<?php echo $this->baseUrl(); ?>" /> - /* - * Prints: - * <link rel="stylesheet" type="text/css" href="/mypage/css/base.css" /> - */ - <link rel="stylesheet" type="text/css" -. Currency Helper. - // within your view - $currency = new Zend_Currency('de_AT'); - $this->currency()->setCurrency($currency)->currency(1234.56); - // this returns '€ 1.234,56'. Cycle Helper The Cycle helper is used to alternate a set of values. Example #6 Cycle Helper Basic Usage To add elements to cycle just specify them in constructor or use assign(array $data) function - <?php foreach ($this->books as $book):?> - <tr style="background-color:<?php echo $this->cycle(array("#F0F0F0", - "#FFFFFF")) - : - <dl> - <dt>Mammal</dt> - <dd>Camel</dd> - <dt>Bird</dt> - <dd>Penguin</dd> - <dt>Reptile</dt> - <dd>Asp</dd> - <dt>Fish</dt> - <dd>Flounder</dd> - </dl>"> - - - </div> - <?php endforeach; ?> - <?php $this->placeholder('foo')->captureEnd() ?> - - <?php $this->placeholder('foo')->captureStart('SET', 'data'); - foreach ($this->data as $datum): ?> - <div class="foo"> - - - </div> - <?php endforeach; ?> - <?php $this->placeholder('foo')->captureEnd() ?>: Example - } You can also check if the doctype represents an HTML5 document. - if ($view->doctype()->isHtml5()) { - // do something differently - } Example #16 Choosing a Doctype to Use with the Open Graph Protocol To implement the » Open Graph Protocol, you may specify the XHTML1_RDFA doctype. This doctype allows a developer to use the » Resource Description Framework within an XHTML document. - $doctypeHelper = new Zend_View_Helper_Doctype(); - $doctypeHelper->doctype('XHTML1_RDFA'); The RDFa doctype allows XHTML to validate when the 'property' meta tag attribute is used per the Open Graph Protocol spec. Example within a view script: - <?php echo $this->doctype('XHTML1_RDFA'); ?> - <html xmlns="" - xmlns: - <head> - <meta property="og:type" content="musician" />: Gravatar View Helper The Gravatar view helper is used to received avatars from Gravatar's service. Example #17 Basic Usage of Gravatar View Helper Note: Of course we can configure this helper. We can change height of image (by default it is 80px), and add CSS class or other attributes to image tag. The above simply shows the most basic usage. Use a valid email address! The email address you provide the helper should be valid. This class does not validate the address (only the rating parameter). It is recommended to validate your email address within your model layer. Example #18 Advanced Usage of Gravatar View Helper There are several ways to configure the returned gravatar. In most cases, you may either pass an array of options as a second argument to the helper, or call methods on the returned object in order to configure it. The img_size option can be used to specify an alternate height; alternately, call setImgSize(). The secure option can be used to force usage of SSL in the returned image URI by passing a boolean true value (or disabling SSL usage by passing false). Alternately, call the setSecure() method. (By default, the setting follows the same security as the current page request.) To add attributes to the image, pass an array of key/value pairs as the third argument to the helper, or call the setAttribs() method. - // Within the view script (using HTML DOCTYPE) - - - - ); - // Or use mutator methods - $this->gravatar() - ->setEmail('example@example.com') - ->setImgSize(90) - ->setDefaultImg(Zend_View_Helper_Gravatar::DEFAULT_MONSTERID) - ->setSecure(true) - - /* Both generate the following output: - <img class="avatar" title="Title for this image" - - */ Options - img_size An integer describing the height of the avatar, in pixels; defaults to "80". - default_img Image to return if the gravatar service is unable to match the email address provided. Defaults to "mm", the "mystery man" image. - rating Audience rating to confine returned images to. Defaults to "g"; may be one of "g", "pg", "r", or "x", in order of least offensive to most offensive. - secure Whether or not to load the image via an SSL connection. Defaults to the what is detected from the current request. Zend_Service_Gravatar Options #19') - - 'href' => '/img/favicon.ico'), - 'PREPEND') - ->prependStylesheet('/styles/moz.css', - 'screen', - true, - - ?> - <?php // rendering the links: ?>'. $keyType may also be specified as 'property' if the doctype has been set to XHTML1_RDFA. $placement can be #20'); If you are serving an HTML5 document, you should provide the character set like this: - // setting character set in HTML5 - $this->headMeta()->setCharset('UTF-8'); // Will look like <meta charset="UTF-8">: Example #21 HeadMeta Usage with XHTML1_RDFA doctype Enabling the RDFa doctype with the Doctype helper enables the use of the 'property' attribute (in addition to the standard 'name' and 'http-equiv') with HeadMeta. This is commonly used with the Facebook » Open Graph Protocol. For instance, you may specify an open graph page title and type as follows: - $this->doctype(Zend_View_Helper_Doctype::XHTML_RDFA); - $this->headMeta()->setProperty('og:title', 'my article title'); - $this->headMeta()->setProperty('og:type', 'article'); - - // output is: - // <meta property="og:title" content="my article title" /> - // <meta property="og:type" content="article" /> #23: Example #24 #26: Example #27 #28: HTML Object Helpers #29 Flash helper Embedding Flash in your page using the helper is pretty straight-forward. The only required argument is the resource UR #30. - - '/path/to/file.ext', - 'mime/type', - - 'attr1' => 'aval1', - 'attr2' => 'aval2' - ), - - : TinySrc Helper Overview » tinysrc.net provides an API for automatic scaling and image format conversion for use with mobile devices. The API is quite simple: you simply create a standard HTML image tag, but append your image URL to a URL on the tinysrc.net domain: - <img src="" /> Their service then sizes the image appropriately for the device requesting it. You can control a number of aspects regarding image display, including: Image dimensions. You may specify a width and optional height. These dimensions can be in absolute pixels, or use one of the adaptive mechanisms tinysrc.net offers. One is subtractive; prepending a dimension with a minus ("-") indicates that the image should fill the maximum physical dimensions, minus the value given in pixels. The other is percentage based; prepending a dimension with an "x" tells the service to size that dimension by that percentage -- e.g., "x20" indicates "20%". Image format. By default, tinysrc.net autodiscovers the format. Internally, it supports only JPEG or PNG, and autoconverts GIF to PNG. You can specifically request that it should convert an image to either PNG or JPEG, however. The TinySrc view helper provides functionality around the tinysrc.net API, and gives you the ability to: selectively enable or disable whether it returns just the tinysrc.net URL or a fully-populated HTML img tag (enabled by default); specify default values for image format as well as width and height; specify a default value for the base URL used (uses the BaseUrl view helper by default); override the default options on a per-image basis, via passed in options. Quick Start The most basic usage is simply to pass the path to an image, relative to your document root or base URL, to create the appropriate image tag: You may specify default values for the base URL, conversion format, dimensions, and whether or not to create an img tag by default: - <?php $this->tinySrc() - ->setBaseUrl('') - ->setCreateTag(false) // disable tag creation - ->setDefaultFormat('png') // convert images to PNG - ->setDefaultDimensions('-5', 'x20'); // width should be 5 less than screen width; - // height should be 20% of total screen height - ?> Finally, you can also pass in values as an array of options, passed as the second parameter: Configuration Options - base_url The base URL, including scheme, host, and optionally port and/or path; this value will be prepended to the image path provided in the first argument. By default, this uses the BaseUrl and ServerUrl view helpers to determine the value. - create_tag A boolean value indicating whether or not the helper should return an HTML img tag, or simply the tinysrc.net URL. By default, this flag is enabled. - format Should be one of the values "png" or "jpeg". If specified, this value will be used to indicate the image conversion format. If not specified, the default format will be used, or the format will be auto-determined based on the image itself. - width This should be either null, or an integer (optionally prefixed by "x" or "-"). If specified, this value will be used to determine the converted image width. If null, neither a width nor a height value will be used. If not specified, the default dimensions will be used. - height This should be either null, or an integer (optionally prefixed by "x" or "-"). If specified, this value will be used to determine the converted image height. If null, no height value will be used. If not specified, the default height will be used. TinySrc Helper Options The following options may be passed to the $options (second) argument of the helper. Any other options provided will be used as attributes to the HTML img tag (if created). Available Methods - tinySrc ( $image = null, array $options = array()) Called with no arguments, returns the helper instance. This is useful for configuring the helper. If the $image argument is provided, it will either create and return the tinysrc.net URL for the image, or an image tag containing that URL as the source, depending on the status of the "create tag" flag (either the default value, or the value passed via $options). See the configuration section for details on the $options array. - setBaseUrl ( $url) Use this method to manually specify the base URL to prepend to the $image argument of the tinySrc() method. - getBaseUrl Retrieve the base URL for prepending to image URLs. By default, autodiscovers this from the BaseUrl and ServerUrl view helpers. - setDefaultFormat ( $format = null) Specifiy the default image conversion format. If none provided, the value is cleared. Otherwise, expects either "png" or "jpeg". - setDefaultDimensions ( $width = null, $height = null) Set the default dimensions for image conversion. If no $width is specified, an empty value is provided for all dimensions (setting the height requires a width as well). Passing no value for the height will set only a width. Dimensions should be specified as either pixel dimensions, or: A pixel value, preceded by a "-" sign. This will indicate the width should take the entire screen size, minus the number of pixels specified. A percentage of the total screen dimensions, expressed as "x" followed by the percentage: "x20" is equivalent to 20%. - setCreateTag ( $flag) Indicate whether the tinySrc() method should create an HTML image tag. If boolean false, only a tinysrc.net URL will be returned. - createTag Returns the status of the "create tag" flag. Examples Example #50 Returning only a tinysrc.net URL You may want to return only a tinysrc.net URL. To do this, you have two options: make this the default behavior, or specify in your $options not to create a tag. #51 #52 #53 #54 #55 #56 #57 #58 Change locale statically The above example sets 'it' as the new default locale which will be used for all further translations. Of course there is also a getLocale() method to get the currently set locale. Example #59 Get the currently set locale - // within your view - - // returns 'de' as set default locale from our above examples - $this->translate()->getLocale(); - $this->translate()->setLocale('it'); - $this->translate("Today is %1\$s in %2\$s. Actual time: %3\$s", $date); - // returns 'it' as new set default locale - $this->translate()->getLocale(); UserAgent View Helper Overview This view helper provides the ability to inject and later retrieve a Zend_Http_UserAgent instance for use in branching display logic based on device capabilities. Quick Start In most cases, you can simply retrieve the User-Agent and related device by calling the helper. If the UserAgent was configured in the bootstrap, that instance will be injected already in the helper; otherwise, it will instantiate one for you. - <?php if ($this->userAgent()->getDevice()->hasFlash()): ?> - <object ...></object> - <?php endif ?> If you initialize the UserAgent object manually, you can still inject it into the helper, in one of two ways. - // Pull the helper from the view, and inject: - $helper = $view->getHelper('userAgent'); - $helper->setUserAgent($userAgent); - // Pass the UserAgent to the helper: - $view->userAgent($userAgent); Available Methods - userAgent ( Zend_Http_UserAgent $userAgent = null) Use this method to set or retrieve the UserAgent instance. Passing an instance will set it; passing no arguments will retrieve it. If no previous instance has been registered, one will be lazy-loaded using defaults. - setUserAgent ( Zend_Http_UserAgent $userAgent) If you have an instance of the helper -- for instance, by calling the view object's getHelper() method -- you may use this method to set the UserAgent instance. - getUserAgent Retrieves the UserAgent instance; if none is registered, it will lazy-load one using default values.. Registering Concrete Helpers Sometimes it is convenient to instantiate a view helper, and then register it with the view. As of version 1.10.0, this is now possible using the registerHelper() method, which expects two arguments: the helper object, and the name by which it will be registered. - $helper = new My_Helper_Foo(); - // ...do some configuration or dependency injection... - $view->registerHelper($helper, 'foo');.
http://framework.zend.com/manual/1.11/en/zend.view.helpers.html
CC-MAIN-2015-18
refinedweb
2,259
55.34
C# and Java: Comparing Programming Languages Kirk Radeck, Windows Embedded MVP Senior Software Engineering Consultant October 2003 Applies to: Microsoft® Windows® CE .NET Microsoft Windows XP Embedded Microsoft Pocket PC Microsoft Visual Studio .NET Microsoft Visual C#® Summary: Learn about the differences between C# and Java. (68 printed pages) Whether you are a desktop applications developer or a developer of applications and Web services for Microsoft® Windows® Embedded devices, this technical article will compare and contrast the C# and Java programming languages from an application developer's point of view. This white paper, downloadable from the right-hand corner of this page, describes specifically what is similar, what is different, and the motivation behind the language syntax. It includes side-by-side keyword and code snippet example tables, with a complete usage analysis. It assumes that the reader has some knowledge about C# and/or Java, although it is sufficient to know C++, because both of these languages have C++ similarities, and C++ is often used for comparison. Contents Introduction What's Similar Between C# and Java? What's Different Between C# and Java? C# and Java Keyword Comparison "Interesting" Built-in Class Support Hits and Misses Conclusion Special Thanks Introduction Many programming languages exist today: C, C++, Microsoft Visual Basic®, COBOL, C#, Java, and so on. With so many languages, how does a software engineer decide which one to use for a project? Sometimes, a language is chosen because the developers of a company like it or know it, which may be reasonable. Sometimes a language is used because it is the latest and greatest, and this becomes a marketing tool to generate more public-relations interest in a product, which may not be reasonable in and of itself. In an ideal world, a programming language should be chosen based on its strengths for performing a certain task—the problem to solve should determine the language to use. This paper would quickly become a book or series of books if it attempted to compare strengths and weaknesses, platform support, and so on for many programming languages. Rather, to limit its scope, it will compare only C# and Java. Some languages, such as C++ and Pascal, will also be used for comparison, but only to help demonstrate potential motivations for the creation of the newer programming languages with their newer features. If some weakness exists and is exposed in the older language, and then shown to be nonexistent or hidden in the newer language, this may help understand the motivation for some change made by the architects of the newer language. Knowing this motivation is often important, because otherwise it is not possible to objectively critique a language. For example, if a so-called "feature" that existed in a previous language is removed from the newer language, then a developer may feel that the latter is not a worthy candidate to use because it doesn't have the power of the former. This may not be the case; the newer language may be actually doing him a favor by saving him from falling into some known trap. Naturally, Java came before C#, and C# was not created in a vacuum. It is quite natural that C# learned from both the strengths and weaknesses of Java, just as Java learned from Objective-C, which learned from C. So, C# should be different than Java. If Java were perfect, then there would have been no reason to create C#. If C# is perfect, then there is no reason to create any new programming language. The job would then be done. However, the future is unclear, and both C# and Java are good object-oriented programming languages in the present, so they beg to be compared. It is important to note that not everything can be covered here. The subject matter is simply too large. The goal is to give enough information so as to help managers and software developers make a better-informed choice about which language to use in certain situations. Maybe some little language quirk in C# may make someone choose Java. Maybe some blemish in Java will influence someone to pick C#. Either way, this document will attempt to dive deep enough into details to dig up some hidden treasures that aid in our goal. (Items in italics such as the paragraph below and subsequent sections have been highlighted to separate my opinion from the rest of the paper.) While I am not covering everything about C# and Java in this paper, I will attempt to supply some in-depth analysis on most of the topics that are covered. I don't believe that it is generally worthwhile just to say that some functionality exists in a language and therefore try to imply that the language is powerful. For example, I could simply say, "C# is a good language because it is object oriented." Naturally, that would assume that an object-oriented language is automatically good, which, from my experience, not everyone agrees with. So, I feel in this case that I have to show why writing object-oriented code is good first, which should strengthen the above assertion. This can get a little tedious, but I think that it is important. Also, I generally do not like to promote anything that I have not used. If I say below that the "language interoperability using Visual Studio .NET is outstanding because it is very easy," then I have run at least some basic tests to really see if it is in fact "easy." More than likely, while not everyone will agree with my opinions, I don't just "wave my hand" by just restating what others have said; rather I try to put what others have said to the test. What's Similar Between C# and Java? C# and Java are actually quite similar, from an application developer's perspective. The major similarities of these languages will be discussed here. All Objects are References Reference types are very similar to pointers in C++, particularly when setting an identifier to some new class instance. But when accessing the properties or methods of this reference type, use the "." operator, which is similar to accessing data instances in C++ that are created on the stack. All class instances are created on the heap by using the new operator, but delete is not allowed, as both languages use their own garbage collection schemes, discussed below. It should be noted that actual pointers may be used in C#, but they can only be manipulated in an unsafe mode, which is discouraged. This paper will not deal with writing "unsafe" C# code not only because it is discouraged, but also because I have very little experience using it; maybe even more important, because the comparisons with Java will nearly vanish as Java does not support anything like it. Garbage Collection How many times have you used the new keyword in C++, then forgot to call delete later on? Naturally, memory leaks are a big problem in languages like C++. It's great that you can dynamically create class instances on the heap at run time, but memory management can be a headache. Both C# and Java have built-in garbage collection. What does this mean? Forgetaboutit! At least forget about calling delete. Because if you don't forget, the compiler will remind you! Or worse, Tony might make you a Soprano. Don't be a wise guy; neither language gives you the permission to whack any object that's become expendable. But you may be asked to call new fairly often, maybe more than you'd like. This is because all objects are created on the heap in both languages, meaning that the following is frowned on in either language: class BadaBing { public BadaBing() { } } BadaBing badaBoom(); //You can't create temporary data //but you must use parens on a constructor The compiler will send a little message to you about this because you are attempting to create temporary storage. See, there's this thing you gotta do: BadaBing badaBoom = new BadaBing(); Now badaBoomis made and has at least one reference. Later on, you might be tempted to get rid of him yourself: delete badaBoom; //illegal in C# and Java - the compiler will complain Use badaBoomas long as you want, then the garbage collector will dispose of him for you when you decide to give someone else your reference. Waste management is a beautiful thing. Many developers complain about garbage collection, which is actually quite unfortunate. Maybe they want the control—"I'm gonna kill that puppy off now!" Maybe they feel that they're not "real" programmers if they can't delete an object when they created it. Maybe having a more complex and error-prone language guarantees code ownership by the original developer for a longer period of time. Regardless of these reasons, there are some real advantages to garbage collection, some of them being somewhat subtle: No memory leaks. This is the obvious advantage. Both garbage collection schemes promise to dispose of all objects at some point during program execution, but neither can guarantee when, except that no object shall be removed until at least all program references to it are removed. It rewards and encourages developers to write more object-oriented code. This is the subtle advantage. For example, in C++, developers creating class methods that must return data usually either set non-const reference or pointer parameters during method execution; or return a class instance of another type that holds a composite of all necessary data. I consider the latter "better" than the former. Who wants to call a function with 10 parameters? And more parameters passed between client and server code causes more coupling, which is not good. For example, if it is determined later that a function needs to return one more piece of data, then only this function's implementation needs to be changed with an addition to the composite class, which may only require a recompile for the client. Not only that, but when a function returns only one object, this function can be nested with other function calls, while returning data with in/out parameters disallows this nesting. When objects are returned with this "better" method, usually the developer once again has only two choices: return a copy of temporary data initialized and manipulated in the function; or create a new object pointer in the function, side-effect its de-referenced values, then return the pointer, which is safe since the compiler will not destroy pointers or heap data across functions calls. While returning a pointer has some advantages (a copy constructor won't have to be called so it may be faster, particularly with large data; a subclass of a pointer type can actually be returned to the caller for extendibility; and so on), it also has a serious disadvantage in C++: the client will now have to be concerned with memory management by eventually calling delete on the returned pointer. There are ways around this, one of them being to implement reference counting using generic templates. However, reference counting is not completely "visually" satisfying because of the template syntax; and most if not all counting implementations do not handle cycles correctly while both C# and Java garbage collection schemes do. (Here's a cycle example using simple reference counting: if two objects reference each other, and then only all outside references are released on both, neither will be deleted because they each still have one reference—namely each other—and an object is not deleted until its reference count reaches zero.) Therefore, developers generally take the safe approach, and just return a copy of a compile-time known class type. In contrast, because both C# and Java use garbage collection, developers are encouraged to return a new reference to data when writing function prototypes (instead of using in/out parameters, for example), which also encourages them to actually return a subclass of the defined return type, or a class instance implementing some interface, where the caller doesn't have to know the exact data type. This allows developers to more easily change service code in the future without breaking its clients by later creating specialized returned-type subclasses, if necessary. In this case the client will only be "broken" if the public interfaces it uses are later modified. Garbage collection makes data sharing easier. Applications are sometimes built which require object sharing. Problems can arise in defining responsibilities for clean-up: if object A and object B share pointer C, should A delete C, or should B? This eliminates the problem: neither A nor B should (or could) delete C using either C# or Java. Both A and B use C as long as they need to, then the system is responsible for disposing of C when it is no longer referenced by either (or any other). Naturally, the developer still must be concerned about critical sections while accessing shared data, and this must be handled in some standard way. Programs should automatically become more "correct." With less to worry about, application developers can concentrate on program logic and correctness rather than memory management, which should create less "buggy" code. This benefit is sometimes understated; it is very important. I am quite sure that there are other advantages that I can't even dream up right now. Both C# and Java are Type-Safe Languages Saraswat states on his Web page: "A language is type-safe if the only operations that can be performed on data in the language are those sanctioned by the type of the data." So, we can deduce that C++ is not type-safe according to this definition at least because a developer may cast an instance of some class to another and overwrite the instance's data using the "illegal" cast and its unintended methods and operators. Java and C# were designed to be type-safe. An illegal cast will be caught at compile time if it can be shown that the cast is illegal; or an exception will be thrown at runtime if the object cannot be cast to the new type. Type safety is therefore important because it not only forces a developer to write more correct code, but also helps a system become more secure from unscrupulous individuals. However, some, including Saraswat, have shown that not even Java is completely type-safe in his abstract. Both C# and Java Are "Pure" Object-Oriented Languages Any class in either language implicitly (or explicitly) subclasses an object. This is a very nice idea, because it provides a default base class for any user-defined or built-in class. C++ can only simulate this support through the use of void pointers, which is problematic for many reasons, including type safety. Why is this C# and Java addition good? Well, for one, it allows the creation of very generic containers. For example, both languages have predefined stack classes, which allow application code to push any object onto an initialized stack instance; then call pop later, which removes and returns the top object reference back to the caller—sounds like the classic definition of a stack. Naturally, this usually requires the developer to cast the popped reference back to some more specific object-derived class so that some meaningful operation(s) can be performed, but in reality the type of all objects that exists on any stack instance should really be known at compile-time by the developer anyway. This is at least because it is often difficult to do anything useful with an object if the class's public interface is unknown when later referencing some popped object. (Reflection, a very powerful feature in both languages, can be used on a generic object. But a developer would be required to strongly defend its use in this scenario. Since reflection is such a powerful feature in both languages, it will be discussed later.) In C++, most developers would use the stack container adapter in the Standard Template Library (STL). For those unfamiliar with the STL, Schildt (p. 5) states that it was designed by Alexander Stepanov in the early 1990s, accepted by the ANSI C++ committee in 1994 and available in most if not all commercial C++ compilers and IDEs today, including the eMbedded Visual Tools. Sounds like an encyclopedia's version of reality. Essentially, it is a set of containers, container adapters, algorithms, and more, simplifying C++ application development by allowing any C++ class (and most primitives) to be inserted and manipulated through a common template definition. Sounds like a nifty idea. However, there are issues with templates in C++. Say that a new stackof ints is created by: #include <stack> using namespace std; stack<int> intStack; The template definition is found, then an actual intstack. From a purist's perspective, it could be viewed as wasteful to have a new stackclass definition created and compiled for every type that a stackholds. A stack is a stack: it should only have a constructor, a destructor, a "push", a "pop", and maybe a Boolean "empty" and/or "size" method. It doesn't need anything else. And it shouldn't care what type it holds, in reality, as long as that type is an object. The STL's stack, however, doesn't work this way. It requires compile-time knowledge of what type it will hold (the template definition doesn't care, but the compiler does). And it doesn't have the "classic" set of stack functions. For example, the pop is a void function; the developer must first call top, which returns an address to the top of the stack, then call pop, which means that a single operation has now become two! The inherent problem in C++ that most likely motivated this awkward decision: if the popfunction returned an element and removed it from the stack, it would have to return a copy (the element's address would no longer be valid). Then if the caller decides he doesn't want the element after inspection, he would then have to push a copy back on the stack. This would be a slower set of operations, particularly if the type on the stackwas quite large. So a topor inspect method was added which would not side-effect the number of stackelements, allowing the developer to peek at a class instance before he removes it. But when a developer does access this top element, then calls some function on it, he may be side-effecting an element in the container, which may at least be bad style in some scenarios. The original STL architecture could have required that developers only use pointers with containers (in fact, pointers are allowed, but you still need to be concerned with memory management), which might have influenced a prototype change causing the popmethod to remove and return a pointer to the top element, but then the lack-of-garbage-collection issue returns. It appears as if the limitations and problems inherent to C++ required changing the STL's public stackdefinition from the "classic" view, which is not good. Why is this not good? One example that I am personally familiar with: the first time that a developer reads the specification for an STL stack, he is sad, for one. The first time that he uses the implementation and calls topbut forgets to call pop, and gets mad, for two. The only arguable advantage in C++ using stack templates compared to C#'s or Java's stack: no casting is required on the template's topmethod because the compile-time created stackclass has knowledge about what address type it must hold. But this is truly minor if the assertion above convinces a developer that he should know what type is allowed on his particular stackinstance anyway. In contrast, the public interfaces for the stack classes in both C# and Java follow the classic paradigm: pushan object on the stack, which places this object on the top; then popthe stack, which removes and returns the top element. Why can C# and Java do this? Because they are both OOP languages, and perhaps more important, because they both support garbage collection using references. The stack code can be more aggressive because it knows that the client won't have to handle cleanup. And a stack can hold any object, which any class must be implicitly. When I code in C++, I use the STL as much as possible, which may seem strange since I seem to complain about it so much above. In my opinion, the STL is a "necessary evil" when using C++. I once tried to build some C++ framework that was "better" than the STL by playing around with my own stack class, using pointers, inheritance, and memory management, just for fun. Suffice it to say that I was unable to do better than the STL, mostly due to problems dealing with destruction. The STL actually works very nicely within the limitations of C++.. When the stack's destructor is eventually called, delete could be called on any object left on the stack, implicitly calling the correct destructor. Methods on this stack could be created that would allow either a pop to remove the top pointer element and return it, which would require the developer to be in charge of its later destruction; or return a copy of the element then have the stack delete the pointer internally, for example. Templates would then be unnecessary.. There are many other reasons why it is preferable to use a "pure" object-oriented language, including application extensibility and real-world modeling. But what defines a "pure" object-oriented language anyway? Ask five separate people and you'll most likely get five wrong answers. This is because the requirements of a "pure" object-oriented are fairly subjective. Here's probably the sixth wrong answer: - Allows the creation of user-defined types, usually called a class - Allows the extension of classes through inheritance and/or the use of an interface - All user-created types implicitly subclass some base class, usually called object - Allows methods in derived classes to override base class methods - Allows casting a class instance to a more specific or more general class - Allows varying levels of class data security, usually defined as public, protected and private - Should allow operator overloading - Should not allow or highly restricts global function calls—functions should rather be methods on some class or interface instance - Should be type-safe—each type has some data and a set of operations that can be performed on that type - Has good exception-handling capabilities - Arrays should be first-class objects: a developer should be able to query one on its size, what type(s) it will hold, and more Since C++ was originally designed to be compatible with C, it fails at being a "pure" object-oriented programming immediately because it allows the use of global function calls, at least if applying the requirements described above. And arrays are not first-class objects in C++ either, which has been the cause of great agony in the developer world. Naturally, if a developer uses a subset of the C++ specification by creating array wrappers, using inheritance, avoiding global function calls, and so on, then his specific C++ code could arguably be called object-oriented. But because C++ allows you to do things that are not allowed in our "pure" object-oriented language definition, it can at best be called a hybrid. In contrast, both C# and Java seem to meet the above criteria, so it can be argued that they are both "pure" object-oriented programming languages. Is the above minimum requirement criterion set legitimate? Who knows. It seems as if only real-world programming experience will tell you if a language is truly object-oriented, not necessarily some slippery set of rigid requirements. But some set of rules must be established to have any argument at all. Single Inheritance C# and Java allow only single inheritance. What's up with that? Actually, it's all good—any class is allowed to implement as many interfaces as it wants in both languages. What's an interface? It's like a class—it has a set of methods that can be called on any class instance that implements it—but it supplies no data. It is only a definition. And any class that implements an interface must supply all implementation code for all methods or properties defined by the interface. So, an interface is very similar to a class in C++ that has all pure virtual functions (minus maybe a protected or private constructor and public destructor which provide no interesting functionality) and supplies no additional data. Why not support multiple inheritance like C++ does? Lippman (p. 472) views the inheritance hierarchy graphically, describing it as a directed acyclic graph (DAG) where each class definition is represented by one node, and one edge exists for each base-to-direct-child relationship. So, the following example demonstrates the hierarchy for a Panda at the zoo: What's wrong with this picture? Well, nothing, as long as only single inheritance is supported. In the single inheritance case, there exists only one path from any base class to any derived class, no matter the distance. In the multiple inheritance case there will be multiple paths if, for any node, there exists a set of at least two base classes which share a base of their own. Lippman's example (p. 473) is shown below. In this case, it is common for a developer to explicitly use virtual base classes, so that only one memory block is created for each class instantiation no matter how many times it is visited in the inheritance graph. But this requires him to have intimate knowledge of the inheritance hierarchy, which is not guaranteed, unless he inspects the graph and writes his code correctly for each class that he builds. While it should be possible for a developer to resolve any ambiguity that may arise by using this scheme, it can cause confusion and incorrect code. 1 In the single-inheritance-multiple-interface paradigm, this problem cannot happen. While it is possible for a class to subclass two or more base classes where each base implements a shared interface (if class Onesubclasses class Two, and Twoimplements interface I, then Oneimplicitly implements Ialso), this is not an issue, since interfaces cannot supply any additional data, and they cannot provide any implementation. In this case, no extra memory could be allocated, and no ambiguities arise over whose version of a virtual method should be called because of single inheritance. So, did C# and Java get it right, or did C++? It depends upon whom you ask. Multiple inheritance is nice because a developer may only have to write code once, in some base class, that can be used and reused by subclasses. Single inheritance may require a developer to duplicate code if he wants a class to have behavior of multiple seemingly unrelated classes. One workaround with single inheritance is to use interfaces, then create a separate implementation class that actually provides functionality for the desired behavior, and call the implementer's functions when an interface method is called. Yes, this requires some extra typing, but it does work. Arguing that single inheritance with interfaces is better than multiple inheritance strictly because the former alleviates any logic errors is unsound, because a C++ developer can simulate interfaces by using pure virtual classes which provide no data. C++ is just a little more flexible. Arguing the contra position is also unsound, because a C# or Java developer can simulate multiple inheritance by the methods discussed above, granted with a little more work. Therefore, it could be argued that both schemes are equivalent. Theory is great, but while coding user interfaces in Java, I ran into situations where I really could have used multiple inheritance. Since all items displayed to screen must subclass java.awt.Component, custom components that I built were required to cast to this base since Java uses single inheritance. This required me to use interfaces extensively for any additional general behavior that these components needed to implement, which worked, but was tricky and required much typing. From this experience I learned that it is often good to be conservative in the single-inheritance world. When building user interfaces, you don't have much choice—you must subclass some predefined base. But during the development of most code, think long and hard before creating some abstract base class for your classes to extend, because once a class extends another, it now can only implement interfaces. While it is possible to eventually toss an abstract base class, define its methods in an interface, then redo classes which previously subclassed this base and now implement an interface, it can be a lot of work. The lesson: if you feel that an abstract base class is necessary because this class requires quite a few methods, and most of these methods can be implemented in the base with potentially few subclass overrides, then feel free to do it. But if you find that the abstract base has very few methods, and maybe many of these methods are abstract too since it is unclear what the default behavior should be, then it may be best to just define and implement an interface. This latter method will then allow any class later on that implements the interface to subclass any other that it chooses. Built-in Thread and Synchronization Support Languages such as ANSI C++ give no support for built-in threading and synchronization support. Third-party packages that supply this functionality must be purchased, based on operating system, and the APIs vary from package to package. While development tools such as Visual Studio 6 supply APIs for C++ threading, these APIs aren't portable; they generally can only be used on some Microsoft operating system. Both C# and Java, however, both have built-in support for this functionality in their language specifications. This is important because it allows a developer to create multi-threaded applications that are immediately portable. It's usually "easy" to build a portable, single-threaded C++ application; try building a portable C++ multi-threaded app, particularly some graphical user interface (GUI) app. And most applications nowadays are multi-threaded, or if they aren't, they should be. But in C# and Java, a developer can use the built-in language thread and synchronization functions and feel very secure that programs will run in a similar fashion on different platforms, or at least similar enough to guarantee correctness. Java and C# differences and similarities will be explained in more detail later. Formal Exception Handling Formal exception handling in programming languages generally supplies a developer with program flow control during exceptional runtime conditions. This is supplied with the ability to throw an exception from a function if anything "bad" occurs during execution. It also supplies any application calling this function the ability to try and catch a potential error, and optionally finally do something after a method call no-matter-what. When a function throws an exception, no further code in the throwing function is executed. When a client handles the exception, no further code in the try block of a try-catch [finally] (TCF) statement is executed. The following C# example demonstrates some basics. using System; namespace LameJoke { //Stones is an instance of an Exception public class Stones : Exception { public Stones(string s) : base(s) { } } //All instances of People are poorly behaved - Creation is a failure public class People { /** * Throws a new Stones Exception. Shouldn't really do this in a * constructor */ public People() { throw (new Stones("Exception in constructor is bad")); } } //All GlassHouses fail during construction public class GlassHouses { //private data member. private People m_people = null; //Throws an Exception because all People throw Stones public GlassHouse() { m_people = new People(); } } //Main function static void Main() { GlassHouses glassHouses = null; //try-catch-finally block //try - always exectuted //catch - executed only if a Stones exception thrown during try //finally - always executed try { glassHouses = new GlassHouses(); } catch (Stones s) { //This block is executed only if all People are poorly //behaved . . . } finally { //. . .it's nearly over. . . } //glasshouses is still null since it failed to be constructed } } Both C# and Java have support for formal exception handling, like C++. Why do people feel the need for exception handling, though? After all, languages exist that do not have this support, and developers are able to write code with these languages that works correctly. But just because something works doesn't mean that it's necessarily good. Creating functions using formal exception handling can greatly reduce code complexity on both the server and client side. Without exceptions, functions must define and return some invalid value in place of a valid one just in case preconditions are not met. This can be problematic since defining an invalid value may remove at least one otherwise valid item in the function range. And it can be messy because the client must then check the return value against some predefined invalid one. (Other solutions have been tried, among them: 1) add an extra non-const Boolean reference to every function call, and have the method set it to true if success else false. 2) Set a global parameter, for at least the calling thread's context, which defines the last error that a client can test after function calls. These are far from satisfying, and they may require an application developer to have too much knowledge about how things work "under the covers.") Look at the System.Collections.Stack class supplied in Microsoft's .NET Framework, or Java's java.util.Stack class which is very similar. Both seem to be designed reasonably: a void Push(Object)method, and an Object Pop()method. The latter function throws an Exception if it is called on an empty Stackinstance, which seems correct. The only other reasonable option is to return null, but that is messy, because it requires the developer to test the validity of the returned data to avoid a null pointer exception. And popping an empty Stackshould be an invalid operation anyway, because it means that Pophas been called at least once more than Push, implying that the developer has done a poor job of bookkeeping. With .NET's Stackprototype and implementation, coupled with the exception handling rules in C# (C# does not require an exception to be caught if the developer knows that all preconditions have been met; or, if sadly, he could care less—or is that supposed to be "couldn't care less?". . .), there are several options: Stack s = new Stack(); s.Push(1); int p = (int)s.Pop(); In the previous case, the developer knows that an exception cannot be thrown from the Popmethod, because the Pushcall has been made previously on a valid object and no Pop has yet been performed. So he chooses "correctly" to avoid a TCF statement. In comparison: try { Stack s = new Stack(); s.Push(1); int p = s.Pop(); p = s.Pop(); } catch (InvalidOperationException i) { //note: this block will be executed immediately after the second Pop . . . } In this next case, for some reason the developer is not convinced that Pushis called at least as many times as Popon Stack s, so he chooses to catch the possible Exception type thrown. He has chosen wisely. However, in reality, a client really should make sure that he doesn't call Popmore often than he calls Push, and he really shouldn't verify this by lazily catching some Exception—it's at the very least considered "bad style" in this particular case. But the Stackcode cannot guarantee that the application using it will behave correctly, so the Stackcan just throw some Exception if the application behaves poorly. Not only that, if exception handling were not used or available, what should the Stackcode return if the client tries to Popan empty Stack? null? The answer is not completely clear. In some languages like C++, where a data copy is returned from functions in most implementations, NULL is not even an option. By throwing an exception, the Stackcode and its clients do not have to negotiate some return value that is outside the range of accepted values. The stack's Popmethod can just exit by throwing an exception as soon as some precondition is not met, and code in the first catch block on the client side which handles a castable type to the exception thrown will be entered. Yes, even exception handling uses an object-oriented approach! Code inside a TCF statement works nicely together, as there is an implied set of preconditions stating that no subsequent line in the block will be executed in case some previous line causes some exception to be thrown. This makes logic simpler as the client is not required to test for error conditions before executing any line of code in the block. And the class code can just bail out of a method immediately by throwing an exception if anything "bad" happens, and this exception implies that there will not be a valid return item. It should be noted that not all functions should throw exceptions. The Math.Cos function, for example, is defined over the set of all reals. For what value will the function throw an Exception? Maybe infinity. Negative infinity? It would be great if all functions were as well-behaved as Cosbecause exception handling would consume about zero percent of all code. In comparison, the Acos function is only defined for all reals between -1 to 1, inclusive. But it's not completely clear how an Acosfunction should handle an out-of-range value. Throw an Exception? Return an invalid value? Take a nap? The System.Math class's version in the .NET Framework returns a NaN value (not a number) but it could just as easily throw an Exception. But can you imagine having to use TCF statements every time a math function is called? Yuk. Any application code littered with TCF statements can get ugly in a hurry as well. What's the moral of the story? Exception handling is great, but it should be used with care. Oh, and Peoplein GlassHousesshould not throw Stones—at least not during construction. Maybe it's a recommendation that I should heed more often. . . . Built-in Unicode Support Both C# and Java use only Unicode, which greatly simplifies internationalization issues by encoding all characters with 16 bits instead of eight. With the proper use of other internationalization manager classes along with properties files, an application can be built which initially supports English but can be localized to other languages with no code change by simply adding locale-specific properties files. This feature is very important now, and will become vitally important in the future. Assuming that your application will only run in English is almost always unacceptable nowadays. This subject really deserves more explanation, but unfortunately time constraints force us to put it off for another day. Suffice it to say that both C# and Java have excellent support for internationalization. I should know; I have used them both. I, probably like you, visit Web sites almost every day that have no English support. If I really need some information, and I can't understand the text, then I'm pretty disappointed if the site appears to have the information that I need. Trying to understand these Web sites has given me more empathy for those who don't speak English. I have built a few ASP.NET Web applications for "fun," one of them a C# version for a demo showing how one Web site could be built that could display on almost any OS with almost any browser, with multiple language support. It was very nice when it displayed correctly on a Windows CE device, and it was awesome when I realized that the JavaScript, written behind-the-scenes for me by Visual Studio .NET, was even correct so that my application would work correctly for users with Netscape! Naturally, the built-in i18n support made things pretty simple. You may want to look into using these Web applications with ASP.NET Web services yourself. They work very well and really make your job easier. Oh, and your friends abroad will thank you for it to by spending money on your site. What's Different Between C# and Java? While C# and Java are similar in many ways, they also have some differences. If they didn't, there would have been no reason to develop C# at all, since Java has been around longer. Formal Exception Handling Wait a minute. It said above that both languages have formal exception handling in the "what's similar" section. And now it's in the "what's different section." So which one is it? Similar or different? Different or similar? Well, they are very similar, but there are some important differences. For starters, Java defines a java.lang.RuntimeException type, which is a subclass of the base class of all exceptions, java.lang.Exception. Usually, RuntimeExceptions are types that are thrown when a client will be able to test preconditions easily, or implicitly knows that these preconditions will always be met before making a method call. So, if he knows that a RuntimeException should not be thrown from the method, then he is not required to catch it. Simply stated: Java expects Exception acceptance except RuntimeExceptions by expecting Exception inspection using explicit expert exception handling. This just makes no sense at all. Why does Java clearly differentiate between Exceptions and RuntimeExceptions? Maybe what you really want to know: "How will I know when I must use a TCF statement? When I should? When I shouldn't?" The compiler may give you a hint in some situations. Any method that may throw an Exceptionmust include all possible Exceptiontypes by name in the method's throws list (a RuntimeExceptionsubclass is optional in this list, although it would be wise to add it there). The client calling the method must use a TCF statement if the method called may throw at least one non- RuntimeExceptionException (let's call it an NRE to make things clear, which should be the goal of any good document). The following mysterious example demonstrates some syntax and rules: public class Enigma { public Enigma() { //Do I really exist? } public void Riddle() throws ClassNotFoundException, NoSuchMethodException, IllegalArgumentException { //do something here } } Assuming that a client can call an existing public method with an empty formal parameter list on a properly initialized object instance, and this method might unexpectedly throw a NoSuchMethodException, an IllegalArgumentException or a ClassNotFoundException (hey, stuff happens): Enigma enigma = new Enigma(); try { enigma.Riddle(); } catch (ClassNotFoundException c) { //do something here } catch (NoSuchMethodException n) { //do something here } Since all throwables in Java and C# must subclass Exception, it should be noted that the client could simply use one catch block that catches the base type: Exception. This is completely acceptable if he will do the exact same thing no matter what "bad" thing happens during the method call, or if some other class developer who moonlights as a comedian decides to implement a method that throws 27 Exception types. It should also be noted that catching the IllegalArgumentExceptionis optional, as this type extends a RuntimeException. He probably made the right call by not catching the IllegalArgumentException, because his vast array of parameters should be valid in this case. In contrast, C# disallows the use of a throws list. From a client's perspective, C# treats all Exceptions like Java's RuntimeExceptions, so the client is never required to use a TCF statement. But if he does, the syntax and rules of C# and Java are nearly if not exactly identical. And like Java, every item that is thrown must be castable to Exception. So, which system is "better?" The exception handling rules of Java, or the exception handling rules of C#? They are equivalent, because any MS eMVP or MVP using C# with the Visual Studio .NET IDE and CLR running on XP with SP1 can simulate J# NREs using TCFs. It's that simple (ITS). So deciding which scheme is "better" is completely subjective. One completely subjective view is given below. It is my opinion that the Java rules of exception handling are superior. Why? Requiring a throws list in a method definition clearly signals to the client developer what exceptions he may catch, and helps a compiler help this developer by explicitly dictating which Exceptions must be caught. With C#, the only way for the developer to know which Exceptions may be thrown is by manually inspecting documentation, pop-up help, code or code comments. And it may be difficult for him to decide in which scenarios it is appropriate to use a TCF statement. Exceptions that may be thrown from a method really should be included in the "contract" between client and server, or the formal method definition or prototype. Why did C# choose not to use a throws list, and never require a developer to catch any Exception*? It may be due to some interoperability issues between languages such as C# and C++. The latter, which actually defines a* throw list as optional on a class method in a specification file, likewise does not require a C++ client to catch any "Exception" (any class or primitive can be thrown from a C++ function—it does not have to subclass some Exception class—which was a poor design decision). And J# does not require a client to catch any Exception*, like C#. Java is a language which generally is used by itself, while C#, C++, and any other language supported now or in the future using Visual Studio .NET, are supposed to work together when using managed code. Or it could be that C# architects simply believe that using TCFs should always be optional to a client. I have heard one theory that the original motivation was so that server code could be modified to throw different exception types without modifying client code, but that seems slightly dangerous to me in case the client does not ever catch the base exception.* At any rate, thumbs up from me to Java on this one. Java Will Run on "Any" Operating System One of the original motivations for creating Java was to create a language where compiled code could run on any operating system. While it is possible in some situations to, say, write portable C++ code, this C++ source code still needs to be compiled to run on some new targeted operating system and CPU. So Java faced a large challenge in making this happen. Compiled Java does not run on "any" operating system, but it does run on many of them. Windows, UNIX, Linux, whatever. There are some issues with Java running on memory-constrained devices as the set of supported libraries must be reduced, but it does a good job of running on many OSes. Java source code is compiled into intermediate byte-codes, which are then interpreted at run time by a platform-specific Java Virtual Machine (JVM). This is nice, because it allows developers to use any compiler they want on any platform to compile code, with the assumption that this compiled byte-code will run on any supported operating system. Naturally, a JVM must be available for a platform before this code can be run, so Java is not truly supported on every operating system. C# is also compiled to an intermediate language, called MSIL. As the online documentation describes, this MSIL is converted to operating system and CPU-specific code, generally a just-in-time compiler, at run-time. It seems that while MSIL is currently only supported on a few operating systems, there should be no reason that it cannot be supported on non-Windows operating systems in the future. Currently, Java is the "winner" in this category as it is supported on more operating systems than C#. One good thing about both the approaches that C# and Java have taken: they both allow code and developers to postpone decision making, which is almost always a good thing. You don't have to exactly know what operating system that your code will run on when you start to build it, so you tend to write more general code. Down the road, when you find out that your code needs to run on some other operating system, you're fine as long as your compiled byte-code or MSIL is supported on that platform. If you originally assumed that your code was to run on only one OS and you took advantage of some platform-specific functionality, then later determine that your code must run on some other OS, you're in trouble. With both C# and Java, many of these problems will be avoided. Naturally, if you are going to build applications, you need to know what operating systems your code will run on so that you can meet your customer's needs. But in my opinion, you don't necessarily have to know every dirty little detail about how the JVM works, for example, just that it does. Sometimes, ignorance can be bliss. C# and Java Language Interoperability While others like Albahari have broken interoperability into different categories such as language, platform, and standards, which is actually quite interesting to read, only language interoperability will be discussed in this paper due to time constraints. C# is a winner in this category, with one current caveat: any language targeted to the CLR in Visual Studio .NET can use, subclass, and call functions only on managed CLR classes built in other languages. While this is possible, it is no doubt more awkward in Java, as in other programming languages not yet supported in .NET. Grimes (p. 209) describes how "incredibly straightforward" it is to create Java code for a Windows-based operating system that can access COM objects. Inspecting his code, I do agree that the client code can be fairly simple to implement. But you still have to build the ATL classes, which can be some work. In contrast, using Visual Studio .NET, libraries can be built in J#, Visual Basic .NET, and managed C++ (with other languages to come) and subclassed or directly used in C# with extreme ease. Just looking at the libraries available to you in the online documentation, the developer has no idea if the classes were built in C++, C# or another. And he doesn't really care anyway, because these all work so nicely together. I decided to test how easy language interoperability is using Visual Studio .NET. So, I created a C++ managed code library by using the following procedure: - Open Visual Studio .NET. - On the File menu, click New Project. - In the left pane, click Visual C++ Projects. - In the Templates pane on the right, click Managed C++ Class Library. - Set the Name and Location of the project. - Click OK. The project created one class automatically, called "Class1" (nice name!) as follows: public __gc class Class1 The online documentation refers to this __gcas a managed pointer*. These are very nice in C++, because the garbage collector will automatically destroy these types of C++ objects for you. You can call delete if you want, but from some testing that I performed, you don't have to explicitly. Eventually, the destructor will be called implicitly. Wow*—C++ with garbage collection! Nifty. (Something else that is "nifty:" you can also create properties with managed C++ code by using the __property keyword, where these properties behave similarly to C#'s version below.) I defined and implemented a few simple member functions, compiled my library, then created a C# Windows application by using the following procedure: - Open Visual Studio .NET (another instance, if you want). - On the File menu, click New Project. - In the left pane, click Visual C# Projects. - In the Templates pane on the right, click Windows Application. - Set the Name and Location for the project. - Click OK. Then I imported the C++ compiled dll (all libraries are now dlls, which is actually good) into my C# project by using the following procedure: - Click Project/Add Reference. - Click the Projects tab (maybe not necessary? Seemed logical). - Click Browse. - Search for the dll built by the managed C++ project above and select it. - Click OK. I then created an instance of the C++ class in the C# project, compiled my project, and stepped through the code. It is very strange walking through C++ code in a C# project. Very strange but very nice. Everything worked. The C# code seemed to have no idea that the object was created in C++—the way it's supposed to be. I then created a C# class called Class2 (nice name by me) which subclassed the C++ Class1(!), and implemented a non-virtual method in the latter and a new method with the same signature in the former. Creating a new instance of Class2 and assigning it to a Class1 reference and calling this method on the reference, sure enough, the C++ version was called correctly. Modifying this method to be virtual in the base, and override in the subclass, recompiling, and running the code, sure enough, the C# version was called. Finally, I installed the J# plug-in for Visual Studio .NET, and created a J# library project similar to the method above for the managed C++ project. I imported the C++ dll into this project, and subclassed Class1 with a Java class, and implemented the virtual function implicitly. I then imported this J# dll into the C# project, ran similar tests with the new Java object, and the correct Java (implicit) virtual method was called in the C# code. I don't know much about Visual Basic, so I had to leave this for another day. I have written and modified some VBScript, but that is the limit of my knowledge. I apologize to you Visual Basic developers. . . . It would be fun to play with this for a couple of days, and test to see if everything works correctly. I cannot say that everything does, but it sure is cool, and it sure is easy. I can imagine creating applications with multiple libraries, where each library uses the language that is "most fit" for the specific problem, then integrating all of them to work together as one. The world would then be a truly happier place. C# Is a More Complex Language than Java It seems as if Java was built to keep a developer from shooting himself in the foot. It seems as if C# was built to give the developer a gun but leave the safety turned on. And it seems as if when C++ was built, they just handed the programmer a fully loaded bazooka with an open-ended license to use it. C# can be as harmless as Java using safe code, but can be as dangerous as C++ by clicking off that safety in unsafe mode—you get to decide. With Java, it seems as if the most damage that you can do is maybe spray yourself in the eye with the squirt gun that it hands you. But that's the way that the Java architects wanted it, most likely. And the C# designers probably wanted to build a new language that could persuade C++ developers, who often want ultimate firepower and control, to buy into it. Below, I will provide some proof to this argument that "C# is a more complex language than Java." C# and Java Keyword Comparison Comparing the keywords in C# and Java gives insight into major differences in the languages, from an application developer's perspective. Language-neutral terminology will be used, if possible, for fairness. Equivalents The following table contains C# and Java keywords with different names that are so similar in functionality and meaning that they may be subjectively called "equivalent." Keywords that have the same name and similar or exact same meaning will not be discussed, due to the large size of that list. The Notes column quickly describes use and meaning, while the example columns give C# and Java code samples in an attempt to provide clarity. It should be noted that some keywords are context sensitive. For example, the new keyword in C# has different meanings that depend on where it is applied. It is not used only as a prefix operator creating a new object on the heap, but is also used as a method modifier in some situations in C#. Also, some of the words listed are not truly keywords as they have not been reserved, or may actually be operators, for comparison. One non-reserved "keyword" in C# is get, as an example of the former. extends is a keyword in Java, where C# uses a ':' character instead, like C++, as an example of the latter. Supported in C# but Not in Java The following table enumerates keywords in C# that seem to have no equivalent atomic support in Java. If possible or interesting, code will be written in Java that simulates the associated C# support to demonstrate the keyword's functionality in C# for Java developers. It should be noted that this list is very subjective, because it is highly unlikely that two people working independently would arrive at the same comparison list. Supported in Java but Not in C# The following keywords are supported in Java but not in C#. Keyword Analysis Simply by looking at the above tables and counting the number of keywords reserved in each language, you may be tempted to say, "Game over, dude! C# rocks! Let's port our Java code to C#, then snag a six pack of snow cones and check out Jackass the Movie on the big screen!" It may be wise to think before you do. Have one fat free yogurt instead—it has to be healthier for you. And maybe see Life as a House at home on DVD. I highly recommend it. After all, quality is often more important that quantity. But more important, if you really feel the need to jump, make sure that you look before you leap—while watching Jackass is painful enough, you surely don't want to risk making an appearance in the sequel. 2 Returning to reality and the original argument, C# can reserve as many keywords as it wants, but if no one uses them, it doesn't matter. And more keywords in a language necessarily implies that the set of possible identifiers at a developer's disposal decreases (albeit by a very tiny number compared to what's possible). But there also is the danger that a language does not reserve a keyword that it should. For example, virtual is not reserved in Java. But what if Java wishes to extend itself in the future by defining virtual? It can't. It may break code written before the inclusion, which would ironically make code originally built to run on any operating system now run on none. There is nothing wrong with reserving an unused keyword and documenting that it currently has no meaning. But the explicit set of keywords that a language reserves tells very little in itself. What's really important? What's the implied meaning and context in which these keywords are used? Do they make the developer's job any easier? And they really only make the developer's job easier. After all, all programming languages are equivalent. There is nothing that can be done in C++ that can't be done in C# that can't be done in Java that can't be done using assembly language that can't be done using 1's and 0's by a good typist with an incredible memory. With this in mind, there is a set of keywords above that really stand out. Let's start out by discussing a smooth operator. . . . Operator The first, and maybe most important, is operator. This keyword allows operator overloading in C#, something that is not supported in Java. Naturally, operator overloading is not necessary, because a developer can always create a standard method that accepts parameters to perform the same function. But there are cases when applying mathematical operators is completely natural and therefore highly desirable. For example, say that you have created a Vectorclass for graphics calculations. In C#, you can do the following: public class Vector { //private data members. private double m_x; private double m_y; private double m_z; //public properties public double x { get { return (m_x); } set { m_x = value; } } //define y and z Properties here . . . public Vector() { m_x = m_y = m_z = 0; } public Vector(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } public static Vector operator + (Vector v2) { return (new Vector(x+v2.x,y+v2.y,z+v2.z)); } //define -, *, whatever you want here. . . } The C# client using this class can then do something like the following: Vector v = new Vector(); //created at the origin Vector v2 = new Vector(1,2,3); Vector v3 = v + v2; //sha-weet. . . In Java, the following could be done: public class Vector { private double m_x; private double m_y; private double m_z; public Vector() { m_x = m_y = m_z = 0; } public Vector(double x, double y, double z) { m_x = x; m_y = y; m_z = z; } public double getX() { return (m_x); } //define accessors for y and z below . . . public Vector addTwoVectorsAndReturnTheResult(Vector v) { return (new Vector(m_x+v.x,m_y+v.y,m_z+v.z)); } } Then the Java client would have to do something like: Vector v = new Vector(); Vector v2 = new Vector(1,2,3); Vector v3 = v.addTwoVectorsAndReturnTheResult(v2); //You killed operator overloading! What can you say about the C# code above? Well, if you appreciate my coding style and operator overloading: "Sha-weet. . . . ." What can you say about the Java code above? If you like or dislike my coding style, it's most likely, "You killed operator overloading!" (Maybe worse. But this isn't some television show aimed at kids, so we can't use really foul language here.) And you might still swear uncontrollably even if I had used some reasonable method name such as add in the Java's version—the long method name was only used for effect. While the C# code is completely natural to developers who have taken some math, the Java code is completely unnatural. While the intent of the C# client is immediately obvious, the Java client code must be inspected before the light bulb turns on. Some people may argue that operator overloading is not really important, and so it is not a "biggy" that Java does not allow it. If this is so, why does Java allow the '+' operator to be used on the built-in java.lang.String class, then? Why is the String class more important that any class that you or I build? So string operations are common, you may argue. But just by this example Java shows that it feels that operator overloading can be a good thing in some situations. I guess these situations only exist where Java has the control. Why did Java omit operator overloading? I don't know. One thing that I do believe: it was a mistake. Operator overloading is very important because it allows developers to write code that seems natural to them. It could be and has been argued ad nauseam that "operator overloading can be easily overused, so it shouldn't be allowed." That would be like saying that "cars are in accidents so let's make people walk." People can and do make mistakes but it would be a bigger mistake to make them walk 20 miles to work every day. If you can't trust programmers to make good decisions, then their code won't work anyway, even without operator overloading. Give me back my car—I get enough exercise when I run that stupid treadmill. And give me back my operator overloading—I get enough typing practice when I write these "smart" papers. Delegate A delegate in C# is like a function pointer in C++. They are both used in situations where some function should be called, but it is unclear which function on which class should be called until run time. While both of these languages require methods to follow a pre-defined signature, each allows the name of the individual function to be anything that is legal as defined by its respective language. One nice feature of both C++ function pointers and C# delegates is how they both handle virtual functions. In C#, if you create a base class that implements a virtual method with a signature matching a delegate, then subclass this base and override the method, the overriding method will be called on a delegate call if a base reference actually holds an instance of the subclass. C++ actually has similar behavior, although its syntax is more awkward. What is the motivation for delegates in C#? One place they come in handy is for event creation and handling. When something happens during program execution, there are at least two ways for a thread to determine that it has happened. One is polling, where a thread simply loops, and during every loop block, gains some lock on data, tests that data for the "happening," releases the data then sleeps for a while. This is generally not a very good solution because it burns CPU cycles in an inefficient manner since most of the tests on the data will return negative. Another approach is to use a publisher-subscriber model, where an event listener registers for some event with an event broadcaster, and when something happens, the broadcaster "fires" an event to all listeners of the event. This latter method is generally better, because the logic is simpler, particularly for the listener code, and it's more efficient, because the listener code runs only when an event actually occurs. Java uses this model to handle events, particularly but not limited to classes associated with GUIs. A listener implements some well-defined interface defined by the broadcaster, then registers with this broadcaster for callback in case an event of interest occurs. An example would be a java.awt.event.ItemListener, which can register for item changed events in a java.awt.Choice box. Another would be a MouseListener, which can listen for such events on a generic java.awt.Component such as mouseEntered or mousePressed. When an event occurs, the broadcaster then calls the pre-defined interface method on each registered listener, and the listener can then do anything it wants. In C#, an event and a delegate are defined and then implemented by some class or classes, so that an event can be broadcast to anyone registering for this event. Most if not all C# Controls already have logic to fire many different predefined events to registered listeners, and all you have to do is create a Control subclass instance, create a "listener" class that implements a delegate, then add that listener to the Control's event list. But C# even allows you to create your own events and event handlers by using the following procedure: 3 - Define and implement a subclass of System.EventArgs with any pertinent properties. - Define the delegate function prototype of the form public delegate void <delegateMethodName>(object sender,EventArgs e)at the namespace scope. - Define a class that internally defines an event of the form public event <delegateMethodName> <eventListName>and implement code that fires this event to its listeners when appropriate, by passing this and a new instance of the EventArgssubclass. - Define at least one class that implements the delegate method as a listener. - Create at least one listener and one broadcaster instance, and add the listener to the broadcaster's event list. It should be noted that, in some cases, the listener implementation code may want to spawn another thread so that other listeners may also receive this event in a timely fashion in case this code performs any lengthy processing. It should also be possible for the class firing the event to spawn a thread. But in these scenarios, you must be careful to use synchronization techniques on both the EventArgsdata and the object sender, since multiple threads may attempt to access these simultaneously. Just running some simple tests, it appears as if the delegate implementers are called in a queue-like fashion in which they were added, with the same parameter references, so take this into account. There are some differences in implementation between C# and Java in regards to creating, firing and receiving events, but overall, they are very similar since they both use a publisher-subscriber model. However, there are some very subtle differences, particularly in client implementation, that suggest some advantages and disadvantages in the approaches. One problem with the Java approach is that, while a single listener can register for events on multiple like-Components, the same method will be called on the listener regardless of which individual Component actually triggered the event. This happens because the broadcaster references this listener as a well-defined interface, and only one method exists for each event type on that interface.. In C#, however, a class that registers for some event can create one specific handler method for each Component that may trigger this event. Why can it do this? Because methods implementing a delegate must follow the delegate's exact signature except it may use any method name that it wishes. So C# avoids this problem. //Java Code public class MyButtonListener extends Window implements ActionListener { //two Buttons for accepting or rejecting some question. private Button m_acceptButton; private Button m_rejectButton; /** * For now just creates two Buttons and adds this as a listener */ public MyButtonListener() { m_acceptButton = new Button("OK"); m_acceptButton.AddActionListener(this); m_rejectButton = new Button("Cancel"); m_rejectButton.AddActionListener(this); //write code to add these Buttons to me and for layout } //ActionListener events /** * Called when a Button is pushed */ public void actionPerformed(ActionEvent e) { if (e.getSource() == m_rejectButton) { //write rejection code } else if (e.getSource() == m_acceptButton) { //write acceptance code } } //End ActionListener events //implement any other necessary code here } This may not seem like a big deal, but it does involve some bookkeeping, and it really isn't an object-oriented approach once you enter the event handling code—the Java developer above has become an "if-then [else] programmer," which is rarely good. In comparison, here is the same code in C#: //C# code public class MyButtonListener : Form { public MyButtonListener() { Button accept = new Button(); accept.Text = "OK"; accept.Click += new EventHandler(AcceptClick); Button reject = new Button(); reject.Text = "Cancel"; reject.Click += new EventHandler(RejectClick); //write code here to add and layout the Buttons } //Event handlers for our buttons private void AcceptClick(object sender, EventArgs e) { //only called if accept Button clicked } private void RejectClick(object sender, EventArgs e) { //only called if reject Button clicked } //end event handlers. } Note some items above: first, the C# code in this case automatically knows implicitly which System.Windows.Forms.Button triggered the event based upon which method was called, so it doesn't need to perform an additional test. Second, the C# code isn't required to hold references to the Buttons because it doesn't have to make comparisons in the event handler methods. To be completely fair, the Java code doesn't actually have to either, but it would then have to either set some Action on each java.awt.Button and get that information back out in its single handler method when called, which isn't too bad—it isn't perfect however since a test must still be performed; or it would have to inspect the label of the Button for the comparison, which isn't too good—it makes internationalization potentially impossible later. Another possible approach is to create a listener instance for each Component, but this naturally has the disadvantage of requiring more memory, and it still doesn't always solve this problem. Another problem may occur if you misspell the label on the Button, remember to fix this visual error later on the Button but forget to change the handler logic code at the same time. There are other possible solutions but none of them are very satisfying. Third, the delegate functions in C# may be declared as private, which is very nice. If this class instance is referenced by another for some reason independent of event handling, then the latter class will not be able to call these handler methods directly on the former, which is good. In Java, all interface methods must be public, so any class that implements an interface will not only expose these functions to the broadcasters but to everyone else, which is bad. It should be noted that the C# code above could also have defined and implemented one method to handle clicks on both Buttons, simulating the Java approach. But in this case it knows that it will only have two Buttons, and the action performed will be presumably Button-dependent, so it made the correct choice. So C# is a just little more flexible and discourages "if-then [else]" programming. One more item to consider about the above code: You will notice that Components have been added and modified by hand. Visual Studio .NET has the Form Designer, which sometimes makes building GUIs more simple for the developer by allowing him to drag child Components to a specific location on a parent Form, set properties in a separate panel, and create event handler stubs in a visual manner. While these tools are great, as they automatically write code for you behind-the-scenes, it is my belief that it is still best to build GUIs manually. Why? When you use drag-and-drop, it implies that you already know what your user interface will look like, which may not be the case and rarely is. Often, a form must change drastically at run time based on a single user action, and you can't build all possible combinations in the Form Designer beforehand, unless you have a thousand years or so. Just look at a pretty decent user interface, Internet Explorer. While it may know what types of Components that it may draw at compile time (although it only really has to have knowledge about some possible base interface, then create a Component instance by name and reference the interface, which would be better), it has no idea what specific Components it will create and load and how they will be laid out until a Web site is visited by the user. I would assume that the IE code is very dynamic, and most of the code is therefore written by hand. Paradoxically, you may often find that the amount of code in your application may actually be less when you build user interfaces by hand rather than using a designer, particularly if you recognize and take advantage of patterns learned while building user interfaces. This is because you are smarter than the designer, as you write generic, reusable code; the designer does a good job of writing correct, but very specific code to solve a single problem. So maintenance should be easier, too, if your design is good. Both Java and C# are very nice when it comes to basic GUI patterns: create a Component, set its properties, create and add event handlers for the new Component, define some layout scheme, and add it to its parent Component. This often suggests a very recursive and natural solution. While you can do similar things in languages such as C++ using Visual Studio and MFC, for example, it is not as easy for a number of reasons. In C# and Java, it is fairly straightforward. It is therefore my recommendation that you use tools such as the Form Designer when first learning a new language, graphics package or IDE because you can drag and drop, set some properties and create event handlers, then inspect specific code "written" by the designer and observe noticeable patterns for your development. Treat the Form Designer like your own personal trainer: use him then lose him. Oh, but don't forget to thank him after he teaches you how to write lean and mean code. One minor advantage of Java's approach to event handling is that it seems to be simpler to learn than C#'s version, maybe because most Java developers are already familiar with interfaces, and event handling is just built on top of them. And Java's approach seems to be somewhat more "elegant" from a purist's perspective. In C# you must learn first how to use delegates and events, so there are a few more "hoops" to jump through. But once you learn how each works, definition and implementation is done in both with approximately the same ease. C# appears to be superior in these cases. First, it allows delegates, which are not supported in Java, and thus allows developers to make dynamic method calls on any class without using reflection at run time. Even though the use of delegates should be held to a minimum, support exists just in case they are needed. Second, event handling built on top of delegates and events appears to also be superior to Java's method of using interfaces because of the above pragmatic issues. get/set/value (Properties) These are not reserved keywords in C#, although they probably should be. A developer can use these as identifiers, but it is best to avoid doing so just in case C# decides to reserve them in the future. They must be discussed together, because they all are used to define standard user-defined property accessor functions in C#. C# is not the first language to allow class properties. For example, ATL/COM allows you to create accessor functions on interface definitions using class implementations. The following example demonstrates how these are defined in ATL. //idl file [ object, uuidof(. . .), dual, helpstring("IMyClass interface"), pointer_default(unique) ] interface IMyClass : IDispatch { [propget, id(1), helpstring("property Number")] HRESULT Number([out, retval] long *pVal); [propput, id(1), helpstring("property Number")] HRESULT Number([in] long newVal)]; }; //header file class ATL_NO_VTABLE CMyClass: public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CMyClass, &CLSID_MyClass>, public ISupportErrorInfo, public IDispatchImpl<IMyClass, &IID_IMyClass, &LIBID_MYCLASSATLLib> { public: CMyClass() : m_Long(0) { } DECLARE_REGISTRY_RESOURCEID(IDR_MYCLASS) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CTicTacToeBoard) COM_INTERFACE_ENTRY(IMyClass) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); public: STDMETHOD(get_Number)(/*[out, retval]*/ long *pVal); STDMETHOD(put_Number)(/*[in]*/ long newVal); private: long m_Long; } //implementation file STDMETHODIMP CMyClass::get_Number(long *pVal) { *pVal = m_Long; return S_OK; } STDMETHODIMP CMyClass::put_Number(long newVal) { m_Long = newVal; return S_OK; } The ATL code for my COM object is more long-winded than this paper. Luckily, the client code using smart pointers is easier: IMyClassPtr myClass(__uuidof(MyClass)); myClass->Number = 3; long l = myClass->Number; //l gets 3 (Grimes, pp 84-89. His Easter example was used as a template for this COM example.) As you can see, ATL code can be quite complex. To be fair, the ATL class wizards in any version of Visual Studio will do the majority of work for you under-the-covers by creating and modifying files such as definition (.idl), header (.h), implementation (.cpp), and registry scripts (.rgs), where these files will be nearly complete minus most implementation code (even these are stubbed for you). But attempting anything beyond the basics will require hand-modifying these files, which can be somewhat tricky, and requires near-expert knowledge of the inner details of COM. In contrast, the following equivalent example demonstrates how simple and elegant both C# class implementation and client code can be: public class MyClass { //private data member private long m_long; //public property public long Number { get { return (m_long); } set { m_long = value; } } //constructor public MyClass() { m_long = 0; } } The client code could look like the following: MyClass m = new MyClass(); m.Number = 3; //m_int gets 3 long m = m.Number; //m gets 3 Which one is easier? I'll let you make the call. I've made my choice. So why are properties important? They allow a developer to access private data indirectly in a natural way. Why is it important to access this data indirectly? It allows the developer of the class which exposes these properties to perform other "bookkeeping," such as locking and unlocking the private data, make other function calls, and so on, during the get and set functions, and hide this functionality from the client code. And it is possible to declare a property as virtual, so that a subclass can override the implementation of this property if it so chooses. Another nice feature of properties: if a developer uses Reflection, he can access these properties more easily in a generic way. It is possible to use non-standard set and get accessor functions, but the syntax of these functions must be well-defined and negotiated beforehand for this to work without built-in language support. Some language extensions have simulated accessor functions by instructing classes to use the forms get_<property> and set_<property>, which implies that properties are important, since support is simulated after a language definition is defined. Are properties necessary? No. Java doesn't supply this functionality. (Although J#4 does, using the above simulation method. Even managed C++ does, too.) A developer can always use non-standard get and set accessor methods for variables. But it supplies a standard way for client and server code to interact and pass messages. Enum User-defined enumeration types are not supported in Java. A technical explanation: Yikes. 'Nuff said. OK; maybe not enough said here. But this one irritates me a little bit. While an enum should be used sparingly, because it doesn't really imply an object-oriented approach, there are situations where they make sense to use. They are very nice to use in situations where you don't want to create an entirely new class to describe data, particularly hidden inside a class where only a few options exist. While I would agree that they should be used sparingly, a language doesn't seem complete without them. In the words of an entertaining and controversial talk show host, "What say you, Java?" This C# allows indexers on classes, while Java does not. "This" is a very nice feature, when a class is designed to hold some enumeration of objects. You may only define one indexer on any class, but this is actually a good thing to avoid ambiguity. So, if your class will hold several different lists of objects, then it may be best to not use this functionality. If it holds only one, then it makes sense to use indexers. There are some interfaces and functionality that a class needs to implement to support this functionality, and I recommend that you read the online documentation about indexers. If you implement the correct interfaces on your class using this information, the client of your collection may apply the foreach statement on it, which is very nice. Struct Structs are allowed in C# but not Java. While this is not really a big deal (just use a class), there are some good things about C# structs, including being more efficient in some situations. I recommend reading about the differences between a struct and a class in the online documentation. I also highly recommend using a class instead in most circumstances. Think twice before committing your data to a struct. Then think about it again. out/ref These keywords allow a callee control over side-effecting the reference to formal parameters, so that the caller will see the change after the call is made. This is different than simply side-effecting internal data that the reference holds; it also allows side-effecting what the calling reference actually refers to. Examining the out keyword first, it is very similar to using a non-const "pointer to a pointer" in a C++ function call. When the method is called, the address of the original pointer is side-effected, so that it points at new data. Where would this be useful? Let's say that you are coding in C++, and you need to create a function which accepts an array, returns the index of the largest element and sets a passed-in pointer to access the actual element in the array that is the largest, just in case the developer wishes to modify this array element later. Maybe not the smartest or the safest thing to do, but hey, it's C++: we can do whatever we want. //PRE: ia and size initialized, and element either NULL or uninitialized //POST: index or largest element returned if possible else -1, and element points to largest element // else NULL //ia - the array to inspect //size - the size of array ia //element - after the call references the actual largest element in the array else NULL if empty //return - zeroth relative index of the largest element if array size > 0 else -1 int Largest(int* ia,int size,int** element) { //if array is empty then no largest element if (size < 1) { (*element) = NULL; return (-1); } //has one element. Default to zeroth element int nBiggest = (*ia); int nIndex = 0; (*element) = ia; int nCount = 1; //start the search at element one. We've already //seen and accounted for element zero. for (int* i = ia+1; nCount < size; i++) { if ((*i) > nBiggest) { nBiggest = (*i); nIndex = nCount; (*element) = i; } //always increment for the next element. nCount++; } //return the index number of the largest element return nIndex; } The C++ client code could then look like: int ia[] = {1,3,2,7,6}; int* i = NULL; int nBig = Largest(ia,5,&i); //nBig should be 3, and i should reference the '7' element (*i) = 6; //now i points to an int with the value 6, and the array's third element, zero-relative, //is 6 Sample C# prototype and client code could look like this: public class MyInt { private int m_int; public int Value { get;set; { public MyInt(); public static int Largest(MyInt[] ia,out MyInt element); } MyInt[] ia = {1,3,2,7,6); //pseudo MyInt i; int nBig = MyInt.Largest(ia,out i); //nBig should be 3, and I should reference the '7' element i.Value = 6; //now i's m_int value is 6, and the array's third-element, zero-relative, is 6 It should be noted that an int wrapper object was needed to simulate the behavior of the C++ code using C#. This is due to boxing, which implicitly converts value types to objects and vice versa in C#. While using an int does mostly work in this scenario by returning the correct index and element values, the actual element in the array cannot later be side-effected by changing ilater if it is of type int because it would then be a value type, not an object or an actual reference to the element in the array. Using the wrapper here works the same as the C++ version because this wrapper is an object. So, while boxing is generally a "good thing" in most scenarios, a developer should beware of some possibly unexpected but as-designed C# behavior in this situation. Another item of interest: Notice that the array passed into the C# Largestversion does not need a corresponding sizeparameter, because any array can be queried for its size through the Length property. Very nice, and very safe. It is very common to see C++ APIs littered with additional array size parameters that tend to clutter code. You will not see this in C# and Java. Returning to the new keyword modifiers supported in C#, if the caller and the callee add the out modifier to the parameter, then the actual object that the reference refers to may change during the function call. This works on primitives and objects in the same manner, with some slight differences with value types, as discussed above. The ref keyword has a very similar meaning to the out keyword. The only difference: the out parameter does not have to be initialized before the call is made, while the ref parameter does. Basically, a ref parameter implies that the method can safely inspect the parameter before modifying it in any way. I still believe in most circumstances that it is best to create a composite object if multiple items must be returned from a function call. But there are some situations where using out or ref would really come in handy. I found out that this functionality does not exist in Java, much to my dismay, when I was building user interfaces. I had a situation where I needed to create an object instance dynamically at runtime using reflection and set another data's field to this new object also dynamically, which meant that I had to also pass the parent object that held this field. If I were coding in C#, I can imagine that I could have just used an out parameter on a method call, and I would have then side-effected the actual parent object reference by setting it to the newly created object, so I wouldn't have needed to also pass this parent data. Bummer. foreach/in This defines a new looping statement in C#. This is supported in C# but not Java. The nicest thing about a foreach statement: it implicitly handles casting for the user during container iteration. While this statement is not necessary (use a for loop instead, for example) it simplifies stepping through an enumeration when all items need to be inspected. You may create objects yourself which will allow this statement to iterate through your object's enumeration. I recommend looking at this documentation, which will tell you what interfaces to implement and what to do to make this happen. virtual/override/new These three keywords go hand-in-hand in C#, allowing classes and their subclasses more control over static and dynamic binding. In Java, all methods are virtual by default and can only be made non-virtual by using the final keyword. In C#, all methods are non-virtual by default, and can only be made virtual through the same keyword. Since these languages are diametrically opposed on this issue, it seems to beg the question: Should methods be implicitly virtual, implying that Java got it right; or should they be implicitly non-virtual, which means that C# got it right? This question is truly subjective, almost philosophical, and there are advantages and disadvantages to both solutions. One disadvantage with C# is that the class designer has to guess which methods should be virtual and which methods should not, and if he guesses wrong, then problems ensue (Lippman, p 530). For example, what if a base class is built which is intended for derivation, where some but not all of the methods are declared as virtual? Then, another developer creates a subclass of this base class, and determines that he needs to override a non-virtual method for some reason—maybe there's a bug in the original implementation? Maybe he needs to perform some other function before the base class' method should be called? And so on. He simply can't override the base's functionality because it is non-virtual. He can create a function with the same signature, but this method will only be called if the compiler can determine the exact type of the object at compile time. This defeats the idea of inheritance and virtual functions anyway, since code is usually written so that the most abstract reference possible holds a derived instance so the caller doesn't know and doesn't care what version of the function will be called. So the "overriding" method won't be called in this scenario. The only workaround may be to redefine the base class method by adding the virtual modifier and then recompiling, which is not necessarily pretty or possible. For example, what if you are using a third-party library? Try calling a vendor at 3 AM and requesting a change. Another C# disadvantage is that the class designer and developers inheriting from this class must do more work. In Java, the class designer creates a class, and assumes that any method not declared as final may be overridden by any subclass. In C#, the class designer must choose which methods to declare virtual, which requires more brainpower. Both he and the developers who subclass this base are also required to do more typing and thinking. One advantage to C# is that the code should run faster, because there should be fewer virtual methods. The compiler will more often determine at compile-time which actual functions should be called. In Java, methods must almost always be treated as virtual so these decisions must be put off until run time. Another advantage to C# is control. There is an implied communication between a base class designer, and developers building subclasses. By defining a method virtual, the designer says, "If you feel the need to override my original method, go ahead." If he declares a base method as abstract5 then he is saying, "If you decide to create a subclass that you want to instantiate, then you must implement this method, but I will provide you with no default behavior because it is unclear what I should do." This control has some practical advantages, perhaps controversial and therefore rarely discussed. Sounds like fun to me, so here goes: in most companies, there are usually at least two tiers of developers—those who build the service code, and those who build the client code. The former group (rightly or wrongly) is often perceived as being more experienced, so these developers would generally take over class design work. If this perception is correct, then the interface architecture on these base classes should therefore be more solid. C#'s idea of forcing virtual definitions at compile-time will give more control to the base class designers and constrain the development of future client development code, which may be seen as desirable. So, back to the original question: did Java get it right, or did C# get it right? Maybe a good mature and real-world example is necessary to see some actual advantages and disadvantages of each approach. You are the class designer, and you have been commissioned to create an abstract base class named Bearin both Java and C#, and implement a method called HasHairwhich simply returns true, and accepts the default virtual or non-virtual behavior, respectively, defined by the language. You define a Bearsubclass called Teddy, create a Teddyinstance named FuzzyWuzzy, and assign him to a Bearreference. While Fuzzy's running, you chase him down and ask him if he has hair, and he pants "yes." This seems to be right and wrong simultaneously, because while FuzzyWuzzy was a bear, FuzzyWuzzy has no hair. So in both languages, you create a HairlessTeddyclass which subclasses Teddy, then override the default HasHairmethod in this subclass and return false. FuzzyWuzzy, who is still a Bear(and presumably always will be) now holds a reference to a newly created HairlessTeddyinstance, and when he starts running again (he stopped to either take a breather or to have "lunch," and you'd better hope it's the former—he may be cute, but he's still a bear, and all animals get hungry) you holler, "Fuzzy, do you have hair?"—you've given up chasing him by now since, even though he's a Teddy Bear, he can still run 40 miles per hour. In Java, he now says "no," which is right. But in C# he now says "yes," which is wrong. What's wrong? Is FuzzyWuzzy schizoid? Or has he lost his senses because he's just a little tired? Maybe both. But the real issue resides in C#: while you can create a method in a subclass with the same signature as a non-virtual base, this new6 method will not be called unless it can be determined at compile-time that the type held is actually an instance of the subclass. And in this case using either language, it is unknown that FuzzyWuzzy, who was and is a Bear, is and was a HairlessTeddyuntil he's running. This is not a bug in C#; it's "as designed" (remember the rules above?). The class designer guessed wrong when he or she designed Bear(remember the disadvantages above?). He or she should have made HasHaira virtual method returning true by default because most bears do have hair, which allows but does not require subclasses to override this behavior. But how many bears have no hair? Only one that I can think of. It seems reasonable to assume that if it is a bear, that it does have hair. Who would have thought that one bear who became follicly-challenged by taking an unfortunate spin in the washing machine would refuse to call the Hair Club for Bears? So cut the class designer some slack. I'm sure that you, I mean, he or she, will thank you. (Special thanks to Rudyard Kipling on Fuzzy Wuzzy.) So, did C# or Java get it right? No, I don't wanna. It wouldn't be fair to C# by not showing at least one example where Java can fail, so there. Here is a sample pitfall. Say that you have a class called SmartSortedList, which holds a list of objects. You want the client to be able to add and remove elements from the list, but you don't want to sort every time the list is modified, but rather only when the list is not guaranteed to be in sorted order and when the caller explicitly wishes a sort to be done. So, a private Boolean m_bDirtyfield is created with no accessors, and this field is set internally to false whenever the class can guarantee that its internal list is in a sorted state. When the addor removemethods are called, if the element can be added or removed, then the item is put on the back of the list or removed from it, and the field is set to true else it returns immediately. When the sortmethod is called and the field is false, then the function returns, else it sorts the list then sets the field to false and returns. So, the addmethod is defined and implemented in the base class, but the Java class designer forgets to make this method final. Some developer with incredible typing skills comes along and creates a subclass of SmartSortedListcalled NotSoSmartMayOrMayNotBeSortedList. Reading the helpful pop-up comments of the class designer in his favorite IDE, Visual Studio .NET, he realizes that the designer calls pushback(Object)in the base addmethod and the developer thinks that this is "stupid"—it should call pushfront(Object)instead—so the developer grumbles and overrides the add method in his derived class by just calling the protected pushfrontmethod in the base class. (Doh! The developer should also set the dirty bit to true, but can't; remember the protection above?). Proud of himself, he yells, "Woo hoo!" then creates an instance of his list, adds some elements to it, and compiles his code. Unfortunately, he sorts his list just before an overriding addcall is made, and there may or may not be a problem. He now calls sort, which returns immediately without sorting the list because the field is false. He now iterates the list, which may or may not be sorted. Good name for the new subclass. Bad night at the nuclear power plant. Hopefully it isn't disastrous for this homey. The default behavior of Java coupled with the mistake by the class designer sets the trap in this scenario, which wouldn't have happened in this case with the default C# behavior. So, one more time, back to the original question: did Java get it right, or did C# get it right? Final answer: this is more of a philosophical argument than a logical one. The examples above can be avoided if the developers make good decisions, but they do show the problems that can arise with the default behavior of both languages. C# can simulate Java—always make every method abstract or virtual in base classes. And Java can simulate C#—define any base method final unless it may be overridden, or abstract if a subclass must implement it. Would a developer use either of these simulations? Probably not, because they each defeat the original intent and strength of the language. But they demonstrate that C# and Java are actually equivalent in this area. We've all heard the overused statement, "Building software is a set of tradeoffs which must be negotiated. There isn't a right or wrong answer." This usually just sounds like a cop-out used when someone doesn't want to make a decision, or perhaps wants to come across as being uncontroversial. In this case, "there isn't a right or wrong answer" may actually apply. Synchronized This keyword is context-sensitive in Java. When used as a left unary operator, it locks the instance or class mutex on an expression (generally some object) at the beginning of the block, then releases at the end of the block. In C#, the lock keyword supplies the same functionality. Java also uses this as a class method modifier. If a synchronized method operates on a class instance then the instance mutex is locked and released at the beginning and end of the method call, respectively and implicitly. If used on a static method, it handles the class singleton lock in the same manner. If used as a class modifier, then it implicitly treats every class method as synchronized—a nice little "shorthand" technique. Naturally, there are some advantages and disadvantages of this language feature. The upside: it is very simple. Either declare the class as synchronized, and all of the methods are synchronized; or add this modifier only to methods which read and/or write private data that need to be protected in a multi-threaded environment. In most scenarios, it is easier to avoid deadlock internally in a synchronized class, because only one lock is used. Of course, if the class's private data are also internally synchronized then deadlock is possible in the usual situations. The downside of synchronized as a method or class modifier: it is somewhat simplistic and therefore encourages the developer to write code that may not be as efficient as possible. For example, many classes have more than one private data member. In Java, if you use synchronized methods or classes, you are actually locking the this item instead of the that7 item, where the that item is the private data itself. Why should you lock this entire class instance in case you are only reading or writing one of its variables? I don't get it—you locked the wrong item! Other member variables that are not being used are now locked too, because only one thread can own the instance lock at any one time. In contrast, if the operator lock or synchronized is used inside these method calls on the private data themselves, then seemingly multiple unrelated threads can run in separate contexts and access different class variables simultaneously and eventually tie-up a surprisingly well-behaved and cohesive program. Sounds like a familiar idea, but since I'm a slow-thinker, I just can't remember. Once again, C# can simulate Java and vice versa. Using C#, simply create a lock(this)statement in each method and only access data inside this block. In Java, use the synchronize operator on private data members inside of methods instead of using the same keyword as a class or method modifier. Just remember: no matter what language you're using, delay securing and manipulating your private members as long as you can. But once you do have them, always make sure you release as soon as you're finished. If you follow these simple rules as an application or service developer, you may feel like a new man (or woman) and sigh with satisfaction, "I am the Webmaster of my domain." Keyword Wrap-up C# and Java share many common keywords. C# has reserved many more, providing quite a range of additional built-in features over Java. But as stated before, more isn't always better. Developers must use this support for any noticeable difference in development ease. It is also clear that, if you can do it in C#, you can do it in Java. So these features don't really make C# a more powerful language, but they do seem to make programming more elegant (contemplate operator overloading) and easier (think foreach), in general. "Interesting" Built-in Class Support There is no way to discuss all of the built-in class support that exists in C# and Java because the libraries available to the developer are huge for both. However, there are some built-in support in both Java and C# that are interesting, particularly for comparison. How were these chosen? Well, naturally I had to have some knowledge of the classes and have used them. But another factor came into account: since this document is supposed to discuss the main language differences, what classes and libraries most help support your application in a general way? For example, while support exists in both Java and C# for accessing a database and are very useful, it could be argued that this is "less" important than say, Reflection, because the latter can be used in almost any application, while the former should only be used in those applications that access a database. It would also seem likely that the database libraries would use the Reflection libraries and not vice-versa, so this is how the distinctions were made. Strings Many programming languages do not have built-in strings. C++, for example, forces developers to either build their own string class or include those defined in the STL. These solutions can be less than satisfying, simply because of the lack of compatibility between varying string types. Worse: quite a bit of C++ code is littered with char*s, which I won't even get into. Both Java and C# have predefined String classes: java.lang.String and System.String, respectively. It's about time. Both are immutable, which means that when a Stringinstance is created it cannot be changed. Both cannot be extended. And both hold characters in Unicode. Right on. Also, both classes have quite a few member functions for comparison, trimming, concatenation, and so on, which makes your job easier. And these Stringclasses are both used exclusively in both languages in the built-in APIs, which makes conversion unnecessary. Threading and synchronization In Java, any class that wishes to run as a thread must implement the interface java.lang.Runnable, which defines only one method: A convenience class exists called java.lang.Thread, which extends Objectand implements Runnable. A developer is encouraged (but not required) to create a class that extends Threadand implements the runmethod. This runmethod usually just loops and does something interesting during each iteration, but in reality it may do nothing at all—you decide. Create an instance of this new class and call its start method, where startdoes some bookkeeping and then calls the actual runmethod. The reason for the Runnableinterface: a class may exist that already subclasses another that also needs to behave as a thread. Since multiple inheritance does not exist, the "workaround" is to have this class implement Runnableso that it can behave as a runnable object. This all works pretty well, and is generally very easy to implement. Naturally, there are synchronization issues that must be dealt with in case data is shared between multiple threads, but the synchronized keyword above helps with this. Also, Grand notes that each object has several base methods that help: wait, multiple versions, which puts a thread to sleep; notify, which wakes a single thread waiting on an object's monitor; and notifyAll, which wakes up all threads currently waiting on the monitor. These methods can be used for many synchronization techniques, including the "optimistic single-threaded execution strategy," which he describes as follows: "If a piece of code discovers that conditions are not right to proceed, the code releases the lock it has on the object that enforces single-threaded execution and then waits. When another piece of code changes things in such a way that might allow the first piece of code to proceed, it notifies the first piece of code that it should try to regain the lock and proceed." His simple example (p. 209), slightly modified, is below. import java.util.*; public class Queue extends Vector { synchronized public void put(Object obj) { addElement(obj); this.notify(); } synchronized public Object get() throws EmptyQueueException { while (size() == 0) { this.wait(); } Object obj = elementAt(0); removeElementAt(0); return obj; } } So, the code that accesses the Queueon a putsimply must gain the instance lock (which it does implicitly because the method is synchronized), add the element, wake up the first thread waiting on the lock, then return. The getmethod is a little trickier: it must gain the instance lock, loop and sleep until the Queueis no longer empty, remove the first element from the java.util.Vector base class and return it. The "putter" does not have to call notifyor notifyAllin this sample because Grand is assuming that only one thread is putting data on the Queueand one thread is removing data from the Queue, and the former never sleeps. Must be a tough gig. Naturally, there are many other possible scenarios, but this example shows many of the basics of threading and synchronization in Java. C# is somewhat different. While there is a System.Threading.Thread class in C#, it is sealed which means that it cannot be subclassed. A Threadconstructor takes a ThreadStart delegate, created by the developer, which is a function that is called after the Start method is called on the Threadinstance. This delegate function is analogous to the Java's runmethod, discussed above. While simple synchronization can be done in C# using the lock(object)statement, more complex operations, like the Java example above, are performed by using a separate System.Threading.Monitor class. All of the methods in this sealed Monitorclass are static, which can be shown to work nicely by comparing this with MFC. In MFC, it is common for a class to own a corresponding CCriticalSection member for each synchronized member variable held in a class. Before the synchronized member is inspected or modified, the related CCriticalSection's Lockmethod is called, keeping out any other well-behaved thread temporarily on the data. When the code block is done with the synchronized member variable, the CCriticalSection's Unlockmethod is called. While this is a reasonable solution that works, there is a drawback: for each piece of data shared by different threads, the corresponding CCriticalSectionobject must also be passed. In some situations, the use of multiple inheritance, or creating a class wrapper that holds both objects, may be a nice workaround, but may not always be possible. And it will always require more development work at the least. I'm not "knocking" MFC here; this class was created because there is no idea of a single lock on all C++ class instances, because classes do not subclass some abstract base class like object, discussed above. So MFC had little choice in this design decision. In contrast, with the C# scheme, since the Monitorclass methods are static and accept strictly the object to synchronize as a parameter, objects can fly around "solo" and be synchronized easily through this Monitorclass, where the Monitoracts like a well-trained air traffic controller by helping objects avoid nasty midair collisions. To access the data in the simplest manner, call the Monitor.Enter(object) method. When done, call the Monitor.Exit(object) method. The other methods that are available are Pulse and PulseAll, similar to Java's notifyand notifyAllrespectively; tryEnter, which is a nice addition because it allows you to test a lock with an additional timeout, including zero; and Wait, which is similar to Java's version but has the added feature of allowing the timeout mechanism, again. One caveat exists while using Monitor: in between the Enterand the Exitcalls, the developer must be careful that any exceptions thrown must be caught, because if the Entercall is made but the Exitcall is not made explicitly, then any thread attempting to access this data again will block permanently in some situations. In contrast, if the lock(Object)statement is used, and an exception is thrown inside this statement, the object will be unlocked implicitly by the compiler just before the lock statement is exited. But this is pretty standard stuff; the developer has to be responsible for handling some logic. Which approach is better? That is a tricky call. Java is maybe simpler for the developer: just create a Threadsubclass, implement a runmethod, and startthe thread. C# requires a little more work perhaps, but seems to be a little more powerful when it comes to synchronization support. And C# may be a little more flexible in the same way that its events are more flexible: the name of the ThreadStartdelegate can be anything, which avoids name collisions, and does not require another class to be created to define a thread. In contrast, the Java developer must create a specific class with a runmethod with the exact signature defined by the Runnableinterface. Overall, the "which approach is better" question is probably moot. It's most likely a tie, because they are very similar. What's really important: native thread and synchronization support in both of these languages, which allows for much greater code portability and ease. It's a win-win scenario. Reflection Both Java and C# have support for reflection, which allow a developer to do things like: - Create an instance of some class at runtime by only knowing the fully qualified class name as a string - Perform a dynamic method call on some object at runtime by either dynamically searching the object for the methods that it supports, or using the method name and parameter types to find and invoke the method - Set property values at run-time on an object by dynamically querying this object for a property by name, then setting that property by passing a generic object to it For Windows C++ developers, this is somewhat similar to functionality supported in ATL. Grimes (p. 206) notes that if you define an ATL interface by deriving from IDispatch, then dynamic calls in COM may be performed, for you COM developers. What good is this stuff, anyway? Why not just create an instance of an object and make method calls on it directly? That has to be faster. In fact, developers often complain about speed when using reflection, saying that reflection is too slow, which sometimes translates into an excuse for not using it. But it does come in handy in some situations. Say that you have some configuration file, perhaps an XML document, which has some schema that describes some data, and the properties and methods that should be called on that data, to build any object dynamically in a recursive manner. So, it could look something like: <?xml version="1.0" encoding="utf-8" ?> <object> <name>MyProject.MyClass</name> <properties> <property> <name>ClassProperty</name> <object> <name>MyProject.PropertyClass</name> <properties>. . .</properties> <functions> <function> <name>MyFunction</name> <params> <object>. . .</object> </params> </function> </functions> </object> </property> <property> . . . </property> </properties> </object> In C#, you could write code that would use the System.Xml.XMLDataDocument class perhaps, that loads and parses an XML document, then allows you to walk the DOM at runtime. Every time that an <object>node is seen, then a new object should be created using its fully qualified name. Every time a <property>node is seen, then its parent node's property should be set to some newly created object that will be shortly defined. And every time that a <function>node is seen, then the parent object created should have the function, by name, called on it using the parameters that are later defined. This would allow you to create any object type that you want, and set properties and call functions for initialization, in a very recursive manner. The code that does this will be surprisingly small because it takes advantage of recursion and the generic nature of reflection. Naturally, this can be overdone. The compiler will not give you very much help when you use reflection in either language, because it has very little knowledge of what you are intending to do, what object types you will hold, and what functions you will call, until run time—almost everything is handled as the most abstract class, object. And, sure, it can be slow; much slower that making direct calls on a well-known interface. But if you use reflection only at the time that data is created and initialized, then take this data and make direct calls afterwards perhaps by casting some object returned to some known interface or your own base class, then very dynamic and powerful code can be written that allows you to modify program behavior without recompiling—just modify the XML document and refresh will work in this scenario—while still enjoying an application that runs at a reasonable speed. While C# and Java are very similar, there are some differences in packages and libraries used. As a C# example, you might use the following classes and steps to create a new class instance and call some function on this new object (we are assuming that no Exception is thrown during these steps for simplicity, which you should not do in your code unless you can absolutely guarantee correct behavior—and by "absolutely" I mean agree to resign your cushy development position if it fails—at least this is what a boss once told me). It should be noted that there are many ways to do this, but this one will do: - Use one of the System.Reflection.Assembly class's staticLoad methods to return the correct Assembly which defines your class. - Call the returned Assembly instance's CreateInstance function which returns an object reference to your newly created class instance, as long as the class to instantiate has a constructor with an empty parameter list. - With the returned new object, call its GetType method to return the run-time System.Type of this object. - With this Typeobject (a Typeis an object!), call its GetMethod function by passing the name of the method as a string (and maybe the types of the parameters if the method is overloaded) which returns a System.Reflection.MethodInfo object. - Call this MethodInfo's Invoke function, by passing the new object returned from the Assembly.CreateInstance method above, and an array of object parameters on this object's function if necessary, and accept the object returned which represents the data returned from the dynamic invocation. Pretty simple? It's actually not as bad as it sounds, particularly when you write code that handles creating objects and method calls in a generic way. Returning to our xml sample above, it would be possible to create one function that hides these details from us, so we only have to "jump through some hoops" once by writing code that creates some object. Here is an equivalent set of steps using Java: - Use the java.lang.Class's static method forName(String) method, passing the fully qualified name of the class to create, and receiving a the Class object with name className. - With this Classobject, call its newInstance method, which returns a newly created object of type className, as long as the type to create has a constructor with an empty parameter list. - With the Class above, call its getMethod(string, Class[]) function, by passing the name of the method and a list of parameter types to pass to the method and receive a java.lang.reflect.Method object. - With this Method object, call its invoke method by passing the newly created Class instance above, and an array of actual object parameters, and receive the return object from the call. I would recommend that you take a day or so to "play" with reflection in either or both languages, just to see what you can do. It can be fun, and it can be powerful. Down the road, I guarantee that you will run into a situation where this feature can really make your programs more dynamic, and you will be glad that you know the basics so that you will be influenced to take advantage of this powerful language feature. As Socrates once said: "How can you know what you do not know?" I think that he was referring to reflection. One day now may save you weeks-or-more development time later if you are unfamiliar with this support and don't use it in your design early. While I have not experimented with the IDispatch functionality in COM above from a client's perspective, I have used reflection in both C# and Java, and they are very similar. From my experience, C# is a little trickier to "get started," because the System.Reflection.Assembly class is used first to load an assembly which defines and implements classes of interest. With the fully qualified name only of some class to load, you may have to write some C# parsing code to search first for the Assembly part, get a reference to this Assembly, then use the Assembly with the full name to create an object. In Java, simply use the fully qualified name to create an instance of a class using class Class (nice name for a class?). Naturally, there are tradeoffs, once again. The Java code may be easier to create an object, but it also may be the case that the C# and CLR infrastructure are easier from an administrative viewpoint over the additional classpath information which must be configured in your system using Java, regardless of operating system. But once you have this new object, both languages seem to be similar when it comes to making dynamic function calls and setting properties, for example (of course, Java does not support properties directly, however). Hits and Misses Both C# and Java have taken a different approach to programming than many languages that have come before them. Some of these are "hits," and some of these are "misses" or near misses. And some things could still be improved. But the majority of changes are very good. What Have Both C# and Java "Fixed?" There are some things that both C# and Java have fixed. Some of them are listed below. Boolean expressions C++, C#, Java, and other programming languages, support if statements of the form if (expression) statement1 [else statement2] While expression in languages like C++ can be nearly any expression, C# and Java require it to at least be castable to a Boolean type. So, the following for statement is legal in C++ int i; if (i = 3) { } because any expression that returns any non-zero value is considered to be true in C++. This statement would not compile in either C# or Java, because expression (i = 3)is not a Boolean expression; "3" cannot be implicitly converted to a Boolean. Rather, it is an assignment expression that simply returns the value "3." You may ask, "Why is this in the 'fixed' section? This seems to actually make things more difficult in C# and Java?" Well, if everyone could decide which values that "true" and "false" should map to, then you could reasonably argue that the C++ method is better. But even some C++ extensions have their own rules. For example, when defining Boolean types in ATL, VARIANT_TRUE must be -1 and VARIANT_FALSE must be 0. The Visual Studio 6 online documentation states: "To pass a VARIANT_BOOL to a Visual Basic dll, you must use the Java short type and use -1 for VARIANT_TRUE, and 0 for VARIANT_FALSE." So, if you load a dll in Java for a native call on a Windows operating system, a Java true value must first be mapped to -1 (minus one). Sounds pretty confusing. C# and Java therefore say: "true must be true, and false must be false." Sounds pretty ingenious. But this obvious change eliminates most programming error and ambiguities with their newly defined Boolean expressions. Arrays Developers love arrays. Always have, always will. But arrays can be the cause of many headaches, particularly in languages such as C++. Both C# and Java treat arrays as first-class objects. After creating an array, you may ask it its name, rank and serial number. Or at least its Length. And if you attempt to access the fifth element on an array of length five in these languages (potentially OK in Pascal, big trouble in C++) then the array will throw an Exception telling you that you are out of bounds. Naturally, in languages like C++, a developer can simulate this functionality through the use of templates. Lippman (pp. 480-4) has a decent specification and implementation of a range-checking array template that will do this for you. But both C# and Java already have this functionality built-in for every new array that is defined. While bounds checking is still optional in C++—just don't use a wrapper—it is mandatory in both C# and Java. Of course, people will complain about C# and Java, saying that it is slower than C++, particularly when using arrays. The speed tradeoff is well worth it, and in reality, is fairly minor anyway. Let C# and Java take the wheel, and ease off the gas pedal just a bit. Sometimes speed does kill, and both will pop out like a life-saving airbag when you most need it. What Has C# "Fixed?" There are disadvantages in being very young: You don't get much respect, and you have to go to school. But there are some advantages: You can learn from other's mistakes if you pay attention, and you don't have to pay taxes. At least I know that C# has gone back to school and it has been paying attention. Kinda like Rodney Dangerfield, except that it may get some respect someday. For statement For loops in almost any language are looping constructs which allow a developer to perform an internal code block any number of times desired. C#'s for loop takes the form: for ([initializers]; [expression]; [iterators]) statement which is similar to C++'s version. In C++, any variable defined in the initializers statement are available after exiting the for loop. This is problematic, because in some complex scenarios, it is not so obvious what the value of these variables should be after the loop terminates. And not only that, it just "feels" wrong because initializers at least visually appears to be part of a scope that no longer should be valid. C# has "fixed" this by hiding these variables after the for loop exits. This might make you mad because you now may have to create another variable before the for loop and side-effect this variable during each loop iteration if this information is necessary after loop termination. This might make you glad because your C# code may actually work correctly with this change. Either way, it's probably the right thing to do. I wish that C# would have made one additional change. I believe that a for loop's statement should actually be a block, requiring the use of { and } to wrap a statement list. Why? Even though curly brackets are currently optional when the for loop is designed to execute a single statement, I always use them in any looping statement, for a couple of reasons. First, it is a well-known problem that if a developer comes along later and decides to add additional statements to this list and does not add the brackets, then only the first statement will execute. For example: int j = 3; int k = 5; for (int i = 0; i < 5; i++) j++; k--; In the above for loop, it is obvious to you and me that the developer's intent is to increment jand decrement kduring each loop because of the indentation level used. But it is not so obvious to the compiler; the k-- code will not execute until the for loop terminates, meaning that code above will only be correct if all the planets align in the southern sky. The second reason is simply readability. It is easier to determine the programmer's intent when brackets are used in code. It seems that C# was modeled after C++ syntax, so this might have been the reason that C# did not force this change. I'm not sure. Just because the language doesn't enforce it doesn't mean that you shouldn't do it. I would recommend using the brackets, but I still wish that C#, and other languages, enforced them. Switch statement The switch statement is a control statement available in many languages whose logic is similar to an ITE statement, except that a switch statement generally deals with discrete values, while the ITE can examine more complex expressions. The nice thing about an ITE: only one block should be executed. The bad thing about the switch: multiple blocks of code can be executed, even if the developer's intent was to only execute one. One language where this can happen is C++, which allows "fall through" on case clauses. This so-called "feature" was added because the language wanted to give developers the ability to use one code clause to handle more than one input value in case the exact same action should be taken in a set of possible values. C++ requires the use of some jump-statement at the end of each clause only if the developer does not want "fall through" to happen. Naturally, developers often forget to jump, and when they do, the most likely scenario is that their code will not work as they intended. It's funny: Our Jackass friends above get hurt when they jump, while our C++ buddies get hurt when they don't. Go figure. . . . Anyway, one interesting language is Pascal and its use of a case statement. The case is very similar to C++'s switch, but the former has no "fall through" mechanism. At most only one clause may execute in the case statement, which is not a problem as it also allows the developer to create a comma-delimited list of constant values which map to its clause. For example: //global function integer SeeminglyUselessFunction(integer i) begin case (i) begin 1, 2: //do something if i is either 1 or 2 3: return i; end end //client code integer i := 3; integer j := SeeminglyUselessFunction(i); //j either gets i or the program crashes! Forgive me if my code won't compile—it has been a long time since I wrote a line of Pascal. And even if it will, I'm not saying that the syntax above is beautiful. Headington (p. A-38) has even observed that Pascal does have at least one problem with its case statement: if the expression value to the statement is not found defining any clause then the application behavior is undefined, as no default clause is allowed. So, if iwere actually set to 4, then I can't guarantee well-behaved program behavior, and neither can i. This means that you must usually "guard" a case statement by wrapping it inside an if statement, where the if's boolean expression verifies that the input value is in a predetermined set or range where the value is guaranteed to exist in some clause, which can be nasty. No, Pascal is not perfect, and neither is its case statement. But the comma-delimited list of discrete values is a great idea, and it's somewhat surprising that no one seems to want to "borrow" this idea (except for me, below, in my "new" programming language). And not allowing "fall-through" eliminates much error. C# has taken somewhat of a different approach. For one thing, it not only accepts integral values as input but it also allows string constants. For another, C# does not allow "fall through" in its switch statement, like Pascal, which eliminates errors. How does it do this? Each clause is required to end with some jump-statement. All in all, C#'s version of the switch statement is an improvement over most if not all languages that came before it. But what I would really like to see is some language that uses a combination of C#'s switch and Pascal's case. The following rules could be defined: - No "fall through" allowed, like both languages. - Jump statement not required at the end of each clause, like Pascal. - Each clause can map to a comma-delimited list of constant values, like Pascal, and maybe even a range of values! - default clause allowed, like C#. - const string values accepted as input, like C#. - (Maybe) allow non-const test expressions for clause execution (no one has allowed this yet so I'll admit that this might be a bad idea). One potential issue: two or more complex expressions could be written by the developer to define a clause which could return true, which would cause some ambiguity over which clause to execute. But it would be interesting to look into, at least. - Replace begin and end with { and } already. So, the sample above in the new language K++ could now look like: class MyClass { static int SeeminglyUselessFunction(int i) { switch (i) { case 1, 2 : //no-op - leave statement case 3: return i; default: return i; } return I; } } Method accessibility keyword modifiers and meanings Both C# and Java allow accessibility modifiers for methods. public, protected and private are allowed by both. Java is inconsistent and therefore unintuitive with the meanings of these keywords. For example, public means that a method is accessible to anyone outside the class, whether the method is static or not. private means that the method is only accessible from within the class. These make sense. But protected means that any code inside the enclosing package or subclass can access the method, which seems to be mixing metaphors. For example: public class MyClass { public MyClass() { } protected void Test() { } } //code outside of the MyClass class in the same package MyClass mc = new MyClass(); //from the global package level mc.Test(); //this is allowed in Java! It really shouldn't be. Neither C# nor C++ allow this. C# has not only "fixed" this problem, by defining protected as meaning that only the class or its subclasses may access the method, which is more consistent with the private and public modifiers and models the behavior of C++. But it also has added a couple more choices: internal, whose meaning is very similar to Java's protected keyword; and protected internal, which is once again similar to Java's protected plus access by any subclass. Java's use of the method modifier protected causes much confusion to developers, particularly to those that know C++. How do I know this? While I was coding in Java professionally, I used the protected keyword for quite awhile without knowing the meaning! I thought that a protected method could only be called by the class and any derived class! During some testing I noticed some strange behavior, and I initially believed that the compiler had a bug. I eventually had to return to my code and change protected methods to private, and in some cases, create accessor functions in base classes so that subclasses could access this data. Not nice, and not a good idea. Naturally, I should have done a better job of reading documentation. But it didn't even occur to me that the meaning of this keyword should or could have a different meaning, so I didn't even consider it. try-finally statement issues Gruntz notes on his Web page an issue with Java's try-finally statement, where this problem does not exist in C#. He notes that if an exception is thrown, or a return, break or continue are used in a try block, and a "return statement is executed in the finally block," then undesired and unexpected program behavior may occur. He also notes that this issue does not exist in C# as this language "does not allow (the developer) to leave the control flow of a finally block with a return, break, continue or goto statement." Constructors Two other issues in Java are noted by Gruntz on his Web page, both dealing with Constructors. The first is a "phantom" constructor. Java allows a method to have the same name as the enclosing class, while C# does not. The second issues deals with calling non-final methods from constructors in Java, which causes problems. C# has fixed both of these issues by adding certain restrictions, which he argues are reasonable. He also discusses other issues, which are quite interesting to read. What Has C# "Broken" Scope issues It appears as if C# might have a bug with variable declarations in some scope situations. For example, the following C++ code will compile, but will not compile in C#: for (int i = 0; i < 3; i++) { int j = 3; } int j = 5; The C# compiler complains that jhas already been defined in the second jassignment statement. It should be clear that the for loop's block is in a different scope as this second j, and that once the for loop is exited the first jshould no longer be accessible. Therefore, this code should be legal. I hope that the first jis not accessible once the for loop terminates! Bug? As designed? My guess and hope is the first, because I can't determine the motivation for making this illegal. Enum issues While it is great that C# allows enumeration types, it is still possible to set an enumeration variable to a value not sanctioned by the enum's enumerator-list. For example: enum Colors{red,green,blue}; defines a list of three possible color elements. If the following code is written, compiled and run: Colors c = (Colors)2; then chas the value blue, which appears correct, as all elements by default in an enumeration-list are zero-relative by default. But if the following code is used: Colors c = (Colors)4; then cwill have the value of 4. It seems as if the compiler should be able to flag this particular line of code as an error at compile-time, because "4" is a constant, and the min and max elements in Colorsare 0 and 2, respectively. Even if a variable were used where its value could not be known until runtime, it seems as if an exception should be thrown in this out-of-bounds scenario to guarantee that an enum type is truly "type-safe." It's great that C# allows enum types. Java does not, which I still believe was a mistake. And it's great that an enumeration variable may be set to a numerical value using a cast, for many reasons. But it should be possible to guarantee that enum variables are not set to illegal values, either at run time or compile time. In the above example, a Colorsvariable holding the value of '4' seems to have no meaning. What does '4' mean? What do you do in the scenario where some calculation must be performed as a function of a Colorwhose value is '4'? It's not so clear. Why did C# allow this? Was it for interoperability issues? I'm not sure yet. Just be careful. What Would Have Been "Nice" Additions to Both C# and Java Const method and formal parameter keyword modifier It would have been very nice if both languages would allow the use of const as a method and formal parameter reference modifier, with the same meaning as C++. Since all objects in both C# and Java are references, if a parameter is passed by a caller and side-effected in a method by the callee, then the former will see any changes made to his data after the call is complete. Sure, many C++ developers have complained about the use of const in C++, arguing that the "constness" of a parameter can be cast away anyway, making this functionality useless. However, it seems as if a simple rule could be added to C++ stating that "a const reference may only be cast as another const reference," which could be tested at compile-time and eliminate this problem at runtime. If this is true, then C# and Java could have included this functionality with this modified rule as well. In addition, an implied guarantee is only part of the contract between the caller and the callee anyway on a const function or parameter. Adding this const keyword gives a reminder to the caller and callee that the data is not supposed to be modified, which creates more self-documenting code. In particular, a developer following good programming habits will be reminded by the compiler with an error message if he is trying to modify const data. If he is trying to circumvent the rules, then he will be the one who suffers anyway, even if the compiler cannot catch the illegal operation. Readability is an important part of coding. This is a reminder of the debate over functions that return multiple values by side-effecting input parameters, which in some scenarios is reasonable. Some developers prefer non-const references, while others prefer pointers. It can be argued that the latter is "better." Why? Headington (p. 303) has two versions of a common swap function that will help me argue the point: void Swap(float* px, float* py) { float temp = *px; *px = *py; *py = temp; } void Swap(float& x, float& y) { float temp = x; x = y; y = temp; } The client code to use these functions could look like: float a = 1.5; float b = 2.0; Swap(&a,&b); //calling the pointer version Swap(a,b); //calling the reference version Looking at the client code, the second Swapappears cleaner. But if you write client code using the pointer function instead, then return to inspect your code much later, you are reminded that your parameters may be modified during this pointer Swapfunction call because of the additional "&" character on the client side, which is important, in a good way. However, the Swap(a,b)call gives no reminder to this effect, which may also be important, in a bad way. While both functions may be logically equivalent, it can be argued that the pointer method is "better" because of the extra communication that exists between the client and the server code, and increased readability. After playing with managed C++ code, which is actually pretty interesting but beyond the scope of this paper, I realized that this new .NET functionality also disallows the use of const as a method modifier. I received the compile-time error message: "'const' and 'volatile' qualifiers on member functions of managed types are not supported." And while it is legal to use the const modifier on a reference parameter, the constness must be cast away inside the method to make any method call on the parameter! Presumably, this is because the compiler cannot guarantee that any method called on the object address will not modify the object or its data since the const modifier is disallowed on instance methods, noted above. This begs the question: is it a waste of time to use the const modifier on reference parameters while using managed C++ code? The answer: not completely, as long as the class designer and implementer takes the above restrictions into account by defining, through comments, if an instance method should be in fact a const member function. Then if a const parameter address is received by a method, the developer can "safely" cast away the constness but call only simulated const methods on the object. This way, if managed C++ code is eventually ported back to unmanaged code, then the comments could be removed and the classes will work as designed, minus removing that nasty cast, of course. I realize that this advice immediately opposes my advice above: don't cast away the constness of a formal parameter address. But in my opinion, this does not break the "spirit" of the original advice, because the class builder still guarantees that the client data will not be modified, although this guarantee is now made by human inspection rather than compiler logic. And it is a workaround to a limitation that allows greater ease of future C++ portability, if necessary. All this leads me to believe that there may be some language interoperability issues that forced Microsoft's hand, because a const method must be negotiated by both caller and callee, but a const parameter address really only needs to be guaranteed by the latter (the C# code calling a method written in C++ couldn't care less about the const reference anyway, for example, since this can't be done in C#). If all this speculation is true, then I am assuming that Java may also have had the same problem during initial design since, even though it is trickier, Java can call functions written in other languages. Maybe managed C++ should have allowed the const modifier on an instance method with the understanding that the developer was in charge of verifying that no change is made to the internal data. Or maybe the const keyword should have been disallowed as a formal parameter modifier. I don't know. From a portability standpoint, the former solution might have been a better choice. From a behavioral viewpoint, the way that managed C++ works now makes some sense, since it works as designed. At any rate, this seems to be somewhat inconsistent, allowing const parameters but disallowing const instance functions with managed C++. I would recommend reading information about Cross-Language Interoperability in the online documentation. I know that I am going to have to now look into this some more myself. . .. Access modifiers for class inheritance Languages like C++ allow the use of class access modifiers while using inheritance. For example: class MyClassBase { } class MyClass : public MyClassBase { } in C++ means that MyClasssubclasses MyClassBase, and any code holding an instance of MyClassmay call any function declared public defined and implemented in MyClassBaseon this instance. If we used protected instead, then public methods on MyClassBasewould be private to the outside world when a MyClassinstance is held. private is also possible, but you get the drift. Neither Java nor C# allows the use of public, protected or private accessors in this manner, which is too bad. There are instances where a class should logically inherit from a base, where not all base methods should be accessible outside of either. For example, let's say that we have a class called AddArrayList, which extends the System.Collections.ArrayList class. The idea of our new class is to allow the client access to an array of elements, where this array can be added to, but no element can be removed, and therefore only allow a very small subset of functionality that the base class supports. If C# allowed accessor modifiers, we could then define our AddArrayListin the following manner: //currently illegal C# code public class AddArrayList : protected ArrayList //currently protected disallowed here { public override int Count { get { return (base.Count); } } public override object this[int index] { get { return (base[index])); } set { base[index] = value; } } public AddArrayList() { } public override int Add(object value) { return (base.Add(value)); } } Since this is not possible in either C# or Java, we would need our AddArrayListclass to hold a private data member of type ArrayListand create our methods that operate on this private data member. This sounds OK. After all, it's really no more difficult than the above solution. But it could be argued that AddArrayListreally is a special type of an ArrayList, so the former should really subclass the latter. Naturally, this can be abused: creating a Listclass for example that subclasses a protected stack would probably be inappropriate. But there are some situations where this makes sense, so it would have been nice if it were supported. Conclusion So, which language is superior? You have Java, which will run on many different operating systems without recompiling code. You have C#, which seems to have many more built-in language features, and will run on any operating system that has an installed CLR. Naturally, if you have limited development time and need an application that can run on almost any operating system, then Java seems to be the obvious current choice. But if you know that your application will run on Windows, and you have or don't have limited development time, using a good type-safe, powerful language like C# seems to a very excellent decision. Anywhere in-between, which most software falls, will require a more difficult analysis. I have used both languages professionally, so I know about some of the strengths and weaknesses of both. If it were my choice, and I were to create a new application that I knew would run on a Windows operating system, then I would choose C# over Java. From my experience, I know that even Java applications don't always behave the same way on different operating systems, particularly when building user interfaces. But I'm not trying to "dis" Java; it's a minor miracle that it works at all on so many platforms. Rather, I would choose C# over any language that I've used before, including C++, Smalltalk, Pascal, Lisp, and again, Java—you name it. C# is a very good pure object-oriented programming language, with lots of features. It is quite evident that the architects of C# spent a lot of quality time and quantity effort to build such a potentially quintessential language. It does have a few debatably minor snags, some of them described above, but the strengths far outweigh any of its minor weaknesses. But what I think doesn't really matter. What does matter is what language you will use to create your next application. That is up to you. If you have read this document to this point, I thank you. It is lengthier than I originally planned, but it could in reality be much longer—there is so much left to cover. But the ironic conclusion that I must come to is this: it doesn't matter which language is better, and maybe more important, which language to use. Why, you may ask, after all your devoted reading? Because C# doesn't even care. If you read the section above about language interoperability, you realize that C# doesn't even know what languages were used in the libraries that it imports and uses. To C#, compiled J# looks just like compiled C# looks just like compiled managed C++ looks just like compiled whatever-new-language-is-supported. If C# doesn't care, why should you? And in reality, the "C# versus Java" debate is just an either-or fallacy anyway; there are of course many language choices at your disposal. Use whatever you want. Personally, I will continue to use C# because I think that it is a solid language. But the introduction of Visual Studio .NET should make comparisons moot, because more and more languages should be supported by this development tool and platform in the near future, allowing you to use whatever language you choose. And at that point, any choice you make shouldn't be a bad one. Maybe we don't have to dream about that "fantasy world" any longer. Special Thanks I would like to thank Mike Hall from Microsoft for taking the time to read my initial outline, and providing some excellent suggestions. I would also like to thank Steve Makofsky for sending me emails every time he found some interesting information on the Web about C# and/or Java. Last but not least, Ginger Staffanson, for "convincing" me to write these white papers, and providing the initial editing pass. Notes 1 I ran some simple tests in Visual Studio 6 to see how well this IDE handles ambiguities for the developer. I created a class that subclassed two bases, where each of the bases shared a super class of its own. I created and implemented a virtual method in the super, then implemented it in both of the bases. I tried to create a class instance and it failed to compile. Then I removed the virtual method and created a private data member in the super class. Once again, I tried to create a class instance and it failed to compile. In both scenarios, the compiler wouldn't allow me to create an instance of the class because of the respective ambiguity. Replacing the virtual method in the super, I finally had to define the super class as a public virtual inheritance in each of the base's specification file, remove the virtual definition and implementation from one of the bases, and then create a class instance and assign a super pointer to it. The code compiled. Check. At run time, the instance had only one copy of the super's private data. Check two. The correct version of the virtual function was called on the super pointer. Check three. The compiler even warned me which virtual implementation would be called "via dominance." Bonus check. This IDE seems to do a good job of flagging ambiguities for the developer, and I am assuming that Visual Studio .NET may do even better. This seems to imply that, sure, multiple inheritance can cause problems, as many have argued before. But a good compiler can really help you avoid them now. 2 To be completely fair, I have not seen Jackass the Movie, and probably never will. Why, you may ask? Well, if I were to call this paper C# and Java for Dummies, would you read it? One more obligatory item: "We are not responsible for anyone who attempts the programming stunts discussed in this paper. Leave it up to the professionals." 3 A set of simple classes were built to derive these steps. I created a Button subclass that listened to itself for a press, then fired a new event type that I created to anyone listening for this new event. I then created a class that implemented the corresponding delegate method, and an instance of the Button and the listener and added the latter to the former's event list. Everything worked as advertised. While this is fairly straightforward, it is probably a good idea to do something simple like this at first before trying to do anything more complex. 4 I have only a little experience with J#. I downloaded the plug-in and installed it into Visual Studio .NET. While most of the language syntax remains faithful to Java, the APIs available are the same as those available to C# and C++, because these are meant to be managed code solutions which can play nicely together. So, classes such as ArrayList would be used in C# and J#, while classes such as Vector would be used in Java. 5 An abstract method in both C# and Java are used generally in base classes, which tells any subclass which wishes to be instantiated that it must provide definition and implementation code for this method. The abstract method definition is simply that; it has no implementation. It is very similar to any method defined in an interface. 6 Any method with the same signature in a subclass as a base class, where the latter's method is non-virtual, should include the keyword modifier new in the more specific class. While this is not required in this case, it signals to any subsequent client that this attempted overriding method will not be called in case a more abstract class reference holding a more specific instance is held at runtime. 7that is not a keyword in either language. It's only being used that way for effect, not that there's anything wrong with that. . . . Works Cited Albahari, Ben. A Comparative Overview of C#. Genamics. 2000. Computer Science Department, University of Massachusetts at Boston. Java Keyword Index. Boston, Mass, 1997. Grand, Mark. Java Language Reference. 1st Edition. Cambridge: O'Reilly, 1997. Grimes, Richard, et al. Beginning ATL 3 COM Programming. Birmingham, UK: Wrox, 1999. Gruntz, Dominik. C# and Java: The Smart Distinctions. Aargu, Switzerland. Headington, Mark R., and David D. Riley. Data Abstractions and Structures Using C++. Lexington, Massachusetts: D.C. Heath and Company, 1994. Lippman, Stanley B. C++ Primer. 2nd Edition. New York, NY: Addison Wesley, 1991. Saraswat, Vijay. Java is not type-safe. Florham Park, NJ: AT&T Research, 1997. Schildt, Herbert. STL Programming from the Ground Up. San Francisco, CA: Osbourne/McGraw-Hill, 1999.
https://docs.microsoft.com/en-us/previous-versions/windows/embedded/ms836794(v=msdn.10)
CC-MAIN-2018-43
refinedweb
26,236
59.64
Upgrade Dapr on a Kubernetes cluster Prerequisites Upgrade existing cluster to 1.4.3 There are two ways to upgrade the Dapr control plane on a Kubernetes cluster using either the Dapr CLI or Helm. Dapr CLI The example below shows how to upgrade to version 1.4.3: dapr upgrade -k --runtime-version=1.4.3 You can provide all the available Helm chart configurations using the Dapr CLI. See here for more info. Troubleshooting upgrade using the CLI There is a known issue running upgrades on clusters that may have previously had a version prior to 1.0.0-rc.2 installed on a cluster. Most users should not encounter this issue, but there are a few upgrade path edge cases that may leave an incompatible CustomResourceDefinition installed on your cluster. The error message for this case looks like this: ❌ Failed to upgrade Dapr: Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply The CustomResourceDefinition "configurations.dapr.io" is invalid: spec.preserveUnknownFields: Invalid value: true: must be false in order to use defaults in the schema To resolve this issue please run the follow command to upgrade the CustomResourceDefinition to a compatible version: kubectl replace -f Then proceed with the dapr upgrade --runtime-version 1.4.3 -k command as above. Helm From version 1.0.0 onwards, upgrading Dapr using Helm is no longer a disruptive action since existing certificate values will automatically be re-used. Upgrade Dapr from 1.0.0 (or newer) to any [NEW VERSION] > v1.0.0: helm repo update helm upgrade dapr dapr/dapr --version [NEW VERSION] --namespace dapr-system --wait If you’re using a values file, remember to add the --valuesoption when running the upgrade command. Ensure all pods are running: kubectl get pods -n dapr-system -w NAME READY STATUS RESTARTS AGE dapr-dashboard-69f5c5c867-mqhg4 1/1 Running 0 42s dapr-operator-5cdd6b7f9c-9sl7g 1/1 Running 0 41s dapr-placement-server-0 1/1 Running 0 41s dapr-sentry-84565c747b-7bh8h 1/1 Running 0 35s dapr-sidecar-injector-68f868668f-6xnbt 1/1 Running 0 41s Restart your application deployments to update the Dapr runtime: kubectl rollout restart deploy/<DEPLOYMENT-NAME> All done! Upgrading existing Dapr to enable high availability mode Enabling HA mode in an existing Dapr deployment requires additional steps. Please refer to this paragraph for more details. Next steps Feedback Was this page helpful? Glad to hear it! Please tell us how we can improve. Sorry to hear that. Please tell us how we can improve.
https://docs.dapr.io/operations/hosting/kubernetes/kubernetes-upgrade/
CC-MAIN-2021-43
refinedweb
431
56.76
Hi I've written a program that reads and prints text files that the user has chosen. I now want the program to encrypt the text in the file and for the user be able to choose the alphabetic shift. Could someone please show me how to do this? Here is what i have so far: Code: #include <stdio.h> int main(void) { FILE *file_in; char filename[20]; char ch; int shift; // file_in is the name given to the stream. filename will be the file that the user chooses. ch is the characters in the file. printf("What file do you want to open?: "); gets(filename); file_in=fopen(filename, "r"); //ask the user to enter the name of a file if(file_in==NULL) printf("Error! File did not open.\n"); //print message if the file can not be found while((ch=fgetc(file_in)) != EOF) putchar(ch); //prints the results on the screen and shows the end of the file fclose(file_in); //closes stream }
http://forums.devx.com/printthread.php?t=183489&pp=15&page=1
CC-MAIN-2016-26
refinedweb
163
84.47
In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator. It originally comes from BCPL, whose equivalent syntax for e1 ? e2 : e3 was e1 -> e2, e3[1]. Languages derived from BCPL tend to feature this operator. Conditional assignment ?: is used as follows: condition ? value if true : value if false The condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value if true if condition is true, but value if false otherwise. Usually the two sub-expressions value if true and value if false must have the same type, which determines the type of the whole expression.. Usage This ternary operator's most common usage is to make a terse simple conditional assignment statement. For example, if we wish to implement some C code to change a shop's opening hours to 12 o'clock in weekends, and 9 o'clock on weekdays, we may use int opening_time = (day == WEEKEND) ? 12 : 9; instead of the more verbose int opening_time; if (day == WEEKEND) opening_time = 12; else opening_time = 9; The two forms are nearly equivalent. Keep in mind that the ?: is an expression and if-then-else is a statement. Note that neither value if true nor value if false expressions can be omitted from the ternary operator without an error report upon parsing. This contrasts with if..else statements, where the else clause can be omitted. C Variants A GNU extension to C allows the second operand to be omitted, and the first operand is implicitly used as the second as well: a = x ? : y; The expression is equivalent to a = x ? x : y; except that if x is an expression, it is evaluated only once. The difference is significant if evaluating the expression has side effects. C# provides similar functionality with its coalescing operator a= x ?? y; (Unlike the above usage of "x ?: y", ?? will only test if x is non-null, as opposed to non-false.) C++ In C++ there are conditional assignment situations where use of the if-else statement is not possible, since this language explicitly distinguishes between initialization and assignment. In such case it is always possible to use a function call, but this can be cumbersome and inelegant. For example, if you want to pass conditionally different values as an argument for a constructor of a field or a base class, it is not possible to use a plain if-else statement; in this case we can use a conditional assignment expression, or a function call. Mind also that some types allow initialization, but do not allow assignment, or even the assignment operator does totally different things than the constructor. The latter is true for reference types, for example: #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char** argv) { string name; ofstream fout; if (argc > 1 && argv[1]) { name = argv[1]; fout.open(name.c_str(), ios::out | ios::app); } ostream& sout = name.empty() ? cout : fout; } In this case there's no possibility to replace the use of ?: operator with if-else statement. (Although we can replace the use of ?: with a function call, inside of which can be an if-else statement.) Furthermore, the ternary operator can yield an lvalue, i.e. a value to which another value can be assigned. Consider the following example: 0: #include <iostream> 1: int main () { 2: int a=0, b=0; 3: 4: const bool cond = ...; 5: (cond ? a : b) = 1; 6: std::cout << "a=" << a << ',' 7: << "b=" << b << '\n'; 8:} In this example, if the boolean variable cond yields the value true in line 5, the value 1 is assigned to the variable a, otherwise, it is assigned to b. Python The Python programming language uses a different syntax for this operator: value_when_true if condition else value_when_false This feature is not available for Python versions prior to 2.5, however. The Python programming FAQ mentions several possible workarounds for these versions, with varying degrees of simplicity versus semantic exactness (for example, regarding the short-circuit evaluation property of ?:). The most complete alternative, that has all the same properties as ?: and still works in Python versions prior to 2.5, would be: (condition and [value_when_true] or [value_when_false])[0] Note that value_when_true and value_when_false must be put in lists, because the expression would otherwise return value_when_false if value_when_true evaluated to False. Visual Basic .NET Although it doesn't use ?: per se, Microsoft Visual Basic .NET has a very similar implementation of this shorthand if...else statement. Using the first example provided in this article, you can do: Dim opening_time As Integer = IIf((day = WEEKEND), 12, 9) 'general syntax is IIf(condition, value_if_true, value_if_false) In the above example, IIf is a function, and not an actual ternary operator. As a function, the values of all three portions are evaluated before the function call occurs. This imposed limitations, and in Visual Basic .Net 9.0, released with Visual Studio 2008, an actual ternary operator was introduced, using the If keyword instead of IIf. This allows the following example code to work: Dim name As String = IIf(person Is Nothing, "", person.FirstName) Using IIf, person.Name would be evaluated even if person is null (Nothing), causing an exception. With a true short-circuiting ternary operator, person.Name is not evaluated unless person is not null. PHP <?php $arg = "T"; $vehicle = ( ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ); echo $vehicle; ?> Due to an unfortunate error in the language grammar, the implementation of ?: in PHP uses the incorrect associativity when compared to other languages, and given a value of T for arg, the PHP equivalent of the above example would yield the value horse instead of train as one would expect. To avoid this, nested parenthesis are needed, as in this example: <?php $arg = "T"; $vehicle = ($arg == 'B') ? 'bus' : (($arg == 'A') ? 'airplane' : (($arg == 'T') ? 'train' : (($arg == 'C') ? 'car' : (($arg == 'H') ? 'horse' : 'feet')))); echo $vehicle; ?> This will produce the correct result of train being printed to the screen. CFML (Railo only) <cfscript> arg = "T"; vehicle = ( ( arg == 'B' ) ? 'bus' : ( arg == 'A' ) ? 'airplane' : ( arg == 'T' ) ? 'train' : ( arg == 'C' ) ? 'car' : ( arg == 'H' ) ? 'horse' : 'feet' ); </cfscript> <cfoutput>#vehicle#</cfoutput> Result type number = spell_out_numbers ? "forty-two" : 42; will result in a compile-time error in most compilers. ?: in style guidelines Some corporate programming guidelines list the use of the conditional operator as bad practice because it can harm readability and long-term maintainability.[citation needed] Conditional operators are widely used and can be useful in certain circumstances to avoid the use of an if statement, either because the extra verbiage would be too lengthy or because the syntactic context does not permit a statement. For example: #define MAX(a, b) (((a)>(b)) ? (a) : (b)) or for (i = 0; i < MAX_PATTERNS; i++) c_patterns[i].ShowWindow(m_data.fOn[i] ? SW_SHOW : SW_HIDE); (The latter example uses the Microsoft Foundation Classes Framework for Win32.) When properly formatted, the conditional operator can be used to write simple and coherent case selectors. For example: vehicle = arg == 'B' ? bus : arg == 'A' ? airplane : arg == 'T' ? train : arg == 'C' ? car : arg == 'H' ? horse : feet; Appropriate use of the conditional operator in a variable assignment context reduces the probability of a bug from a faulty assignment as the assigned variable is stated just once as opposed to multiple times. See also References - ^ "BCPL Ternary operator (page 15)". BCPL Reference Manual.. This entry is from Wikipedia, the leading user-contributed encyclopedia. It may not have been reviewed by professional editors (see full disclaimer)
http://www.answers.com/topic/--299
crawl-002
refinedweb
1,280
58.38
The reduce() method is a HOF that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. Functional languages treat functions as first-class values. This means that, like any other value, a function can be passed as a parameter and returned as a result. This provides a flexible way to compose programs. function that take other function as parameters or that return function as results are called higher-order function. Advantages of Higher Order Functions Programming with higher order functions, such as map and foreach, has a number of advantages: - It is much easier to understand the program and the intention of the programmer is clearly expressed in the code. - Functions which take Funs as arguments are much easier to re-use than other functions. Anonymous Function An anonymous function‘s is a functions literal. A function’s which deosn’t contain a name in a anonymous function’s. An anonymous function’s provides a lightweight function’s definition. Simply the anonymous function’s mean without a name. These function’s are define as literal and are syntactic sugar for a more tedious long definition. (b:Int)=>b (b:Int)=>b*b Anonymous is a that has no name but works as a function’s. It is good to create an anonymous function’s. when you don’t want to reuse it latter. Function Currying Currying allows us to apply some arguments to the function’s now and others at a later time when required. Currying splits method with multiple parameters into a chain of functions, each with one parameter – basically its a method notation to write a partially applied in a better way. def sum(f:Int=>Int):(Int,Int)=>Int={ def sumF(a:Int,b:Int):Int= if(a>b) 0 elsef(a)+sumF(a+1,b) sumF() } Functions that accept functions The argument in the call are match one by one in the order of the parameters of the called function. Named arguments allow you to pass arguments in a different order. CODE: package NewCourse object HOF{ def main(args:Array[String]): Unit = { printInt(b=2,a=5); } def printInt(a:Int,b:Int): Unit = { println("a:"+a) println("b:"+b) } } OUTPUT: a:5 b:2 Example: FunctionImplementations- Conclusion:- HOF describes “how” the work is to be complete in a collection. Reference:-
https://blog.knoldus.com/all-you-need-to-know-about-higher-order-functions/
CC-MAIN-2022-21
refinedweb
398
54.02
This was the most helpful page I went to to learn how to do this. Thank you to whomever posted this. very gud coding....thanx i am designing a login form with the help of awt and jdbc and i wanna to add a banner and the image on my login form can u please solve my problem............ it's not displaying on frame? where we have to keep the image? This most helpful page Post your Comment Java Frame/ Applet /swing/awt Java Frame/ Applet /swing/awt I have produced a .exe file with the help of .jar file................... Now How can I Protect my software( .exe ) file bulid in Java from being Copy and Paste....????????? please reply add button to the frame - Swing AWT table with database data JFrame frame = new JFrame("View Patients... for more information. awt in java awt in java using awt in java gui programming how to false the maximization property of a frame Create a Frame in Java in java AWT package. The frame in java works like the main window where your components (controls) are added to develop a application. In the Java AWT, top-level... Create a Frame in Java   another frame by using awt or swings another frame by using awt or swings how to connect one frame to another frame by using awt or swings Image on Frame in Java AWT Image on Frame in Java AWT  ... on the frame. This program shows you how to display image in your application... the image on the frame in your application. These are explained below : main awt Java AWT Applet example how to display data using JDBC in awt/applet Calling awt Frame methods from subclass Calling awt Frame methods from subclass Calling awt Frame methods from subclass How to Create Button on Frame ; frame the topic of Java AWT package. In the section, from the generated output... a command button on the Java Awt Frame. There is a program for the best... How to Create Button on Frame   Hiding Frame in Java Hiding Frame in Java Introduction This section illustrates you how to hide the Java Awt frame... object will be visible. By default Java Awt Form is in the invisible state Frame refresh problem - Swing AWT Frame refresh problem Whenever I close a child frame and reload it using the button on parent frame controls on the child frame load twice...[] args){ JFrame frame=new JFrame(); JButton b=new JButton("Submit"); frame.add(b awt list item* - Swing AWT information. Thanks...awt list item* how do i make an item inside my listitem...*; public class ChoiceListDemo{ public static void main(String[] args) { Frame Java Frame Java Frame What is the difference between a Window and a Frame AWT code for popUpmenu - Swing AWT for more information. code for popUpmenu Respected Sir/Madam, I am writing a program in JAVA/AWT.My requirement is, a Form consists of a "TextBox" and a "Button how to set a image in frame? - Swing AWT how to set a image in frame? how to set a image in frame using swing How to create CheckBox On frame will learn how to create CheckBox on the frame. In the Java AWT, top-level windows... for the procedure of inserting checkboxes on the Java AWT Frame. You can understand very easily... with the full description. If you are fresher in java awt programming then you Java Dialogs - Swing AWT Java Dialogs a) I wish to design a frame whose layout mimics.../springlayout.html...: Java Applet Demo Thanks Hi Friend, a)Please What is AWT in java In this example We have create frame in java AWT package. The frame in java works.... In the Java AWT, top-level windows are represented by the Frame class and we... What is AWT in java In this Example we will describe awt in java Java AWT Package Example to be displayed on the frame. Image Size This Java awt (Abstract... This program shows you how to create a frame in java AWT package... illustrates you how to hide the Java Awt frame. Here, you have seen in the given java-awt - Java Beginners java-awt how to include picture stored on my machine to a java frame...()); JFrame frame = new JFrame(); frame.getContentPane().add(panel... { private Image img; public ImagePanel(String img) { this(new java - Swing AWT { JFrame frame = new JFrame("Frame in Java Swing"); frame.setSize(400, 400...Java Implementing Swing with Servlet How can i implement the swing with servlet in Java? Can anyone give an Example?? Implementing Frame query Frame query Hi, I am working on Images in java. I have two JFrame displaying same image. We shall call it outerFrame and innerFrame.In innerFrame i am rotating the image.After all the rotations i need to display this image Java AWT Java AWT What interface is extended by AWT event listeners java-swings - Swing AWT java-swings How to move JLabel using Mouse? Here the problem is i... frame = new JFrame("mouse motion event program...:// Thanks. Amardeep TextArea Frame in Java TextArea Frame in Java  .... Description of this program: This java program displays the text area using java AWT...; under the java awt package. Inside this class we are going to create Java - Swing AWT ("Paint example frame") ; getContentPane().add(new JPaintPanel.... java - Swing AWT java hello..sir.....plzzzzzzz help me to display selected image... { BufferedImage image; public DisplayImage() { try { System.out.println("Enter image name\n"); BufferedReader bf=new BufferedReader(new java - Swing AWT for upload image in JAVA SWING.... Hi Friend, Try the following code...java Hello Sir/Mam, I am doing my java mini project.In that, i want to upload any .jpg,.gif,.png format image from system & display HelpfulMichael Plautz June 18, 2011 at 2:33 AM This was the most helpful page I went to to learn how to do this. Thank you to whomever posted this. ratingjaspuneet August 12, 2011 at 10:07 AM very gud coding....thanx set the imagearun kamboj January 25, 2012 at 12:16 PM i am designing a login form with the help of awt and jdbc and i wanna to add a banner and the image on my login form can u please solve my problem............ for AWT image not displying on my pcrahul June 27, 2012 at 11:24 PM it's not displaying on frame? where we have to keep the image? java Pankaj kumar October 2, 2013 at 5:05 AM This most helpful page Post your Comment
http://roseindia.net/discussion/18426-Image-on-Frame-in-Java-AWT.html
CC-MAIN-2014-42
refinedweb
1,090
74.59
So, I used UTL_HTTP to query the Google Maps API for information about an address. The answer is returned in the form of an XML file in the KML vocabulary. An example of this is in my previous post. I put the KML in a temporary CLOB. Now I need to parse it and extract the coordinates as a latitude and longitude. Fortunately, Oracle's XML toolkit makes this pretty easy. First, I convert the CLOB to an XMLTYPE object. XMLTYPE is an object type just like any object you might create with the CREATE TYPE AS OBJECT command, except that it was created in SYS's schema as one of Oracle's built-in objects and packages. Since XML is really just formatted text, there is a CLOB at the heart of every XMLTYPE, and a constructor method for creating a new XMLTYPE object from a CLOB. Here is the code I use: DECLARE v_geocodes CLOB; r_geocodes XMLTYPE; BEGIN -- Initialize the temporary CLOB. DBMS_LOB.createTemporary(v_geocodes,FALSE); -- This procedure is the one that gets the KML file from Google, returning it in a CLOB. get_geocodes (query_text, v_geocodes); -- Create a new XMLTYPE object from the CLOB. -- You could also use "XMLTYPE.createXML(v_geocodes);" As far as I can tell, these are equivalent. r_geocodes := XMLTYPE(v_geocodes); If the CLOB does not contain valid XML, creating the XMLTYPE will raise an exception, so you need to have exception handlers. Now that we have an XMLTYPE, we can use XMLTYPE methods on the data. Many of these use XPATH syntax, which looks very much like the syntax for directories in a UNIX or LINUX file system. Here is my first method call, in which I am checking to see if the status code is in the KML data. IF r_geocodes.EXISTSNODE ('/kml/Response/Status/code', 'xmlns=""' ) > 0 THEN namespace := 'xmlns=""'; ELSIF r_geocodes.EXISTSNODE ('/kml/Response/Status/code') > 0 THEN namespace := NULL; ELSE RAISE unknown_namespace; END IF; EXISTSNODE returns 0 if the node doesn't exist. It is looking for a <kml> tag, a <Response> tag within that, a <Status> tag within that, and a <code> tag within that. It follows the hierarchical nature of all XML files. The namespace is indicated within the XML, and tells what vocabulary is being used - in this case, KML. I'm just making sure that the namespace was in fact specified - sometimes it is left out. Now, I want to extract that status code, because if there was a problem, the status code may be all that Google returned. EXTRACT uses the same XPATH syntax, with the "text" portion meaning to extract the contents of the specified tag as text. If the status code is greater than 400, I want to raise an exception. I've initialized an error_messages array with the possible errors that the Google Maps API might return. status_code := TO_NUMBER (r_geocodes.EXTRACT ('/kml/Response/Status/code/text()', namespace).getstringval ); IF status_code >= 400 THEN raise_application_error (- (20000 + status_code), error_messages (status_code) || ', q=' || query_text ); END IF; Now that I have either raised an appropriate exception, or have verified that Google returned usable data, I can return the XMLTYPE object to the calling procedure, which will extract the data that I need. I will finish this in my next post.
http://it.toolbox.com/blogs/jjflash-oracle-journal/parsing-the-kml-from-google-maps-api-19802
crawl-002
refinedweb
541
63.59
I'm writing a game using the Slick2D library. I recently added a loading screen using deferred loading. I use the Music class to load OGG files to be used as music. These take an excessive amount of time to load. I looked on the wiki for more information on deferred loading. I found: No one resource should take so long to load that it keeps the screen from refreshing for a significant amount of time (if it does, then the resource should probably be streamed anyway :)). So I altered my menu class as follows (this is just an example and I'm leaving out quite a bit): public class MainMenu extends BasicGameState{ private Music[] theme = new Music[1]; public void init(GameContainer gameContainer, StateBasedGame stateBasedGame) throws SlickException{ InputStream[] musicStream = {ResourceLoader.getResourceAsStream("/path/to/theme1.ogg")} try{ theme[0] = new Music(musicStream[0],"path/to/theme1.ogg"); }catch (Exception e){ e.printStackTrace; } } (rest of class) The music array is an array of org.newdawn.slick.Music So I thought I'd done what would reduce loading time. However, when loading, it took just as long, but instead of showing a file as the current resource, it showed the stream. I'd like to know how to do one or both of the following: I accidentally came across the answer. public void init(GameContainer gc, StateBasedGame game) throws SlickException{ try{ theme[0] = new Music("path/to/theme1.ogg",true); }catch (Exception e){ e.printStackTrace; } } Adding true after the file reference indicates that you want to stream the audio.
http://www.dlxedu.com/askdetail/3/0151d0773f54c463a87e544efb5c6046.html
CC-MAIN-2018-51
refinedweb
257
65.52
Wednesday Oct 27, 2004 Tuesday Aug 31, 2004 Cycling as a metaphor for Software Development By garypen on Aug 31, 2004 1 I'm not sure exactly what this figure is but I suspect it's something like 0.00000000000000000000000000000000000001 % Monday Aug 09, 2004 Using poolbind to execute jobs in different pools By garypen on Aug 09, 2004 poolbind(1M)to make it easier to run a processin a particular pool. For example, let's say that I wanted to run ls(1)in pool "listings". [1] bash-2.05b$ newpool usage: newpool <pool name> <command> [parameters] [2] bash-2.05b$ newpool listings ls poolbind: binding pid 100964 to pool 'listings': Not owner Bind operation failed [3] bash-2.05b$ su - Password: Sun Microsystems Inc. SunOS 5.10 s10_63 Jul. 03, 2004 SunOS Internal Development: gk 2004-07-03 [on10_63] bfu'ed from /bfu/s10_63 on 2004-07-22 Sun Microsystems Inc. SunOS 5.10 s10_37 May 2004 You have mail. # bash [4] bash-2.05b# newpool listings ls backup bin Documents mnt tmp bfu boot etc net TT_DB bfu.ancestor cdbuild export opt usr bfu.child cdrom home platform var bfu.conflicts Desktop kernel proc vol bfu.parent dev lib rootb bfu.realmode devices lost+found sbin bash-2.05b#What's going on here? - Run the script to display the usage message. It's fairly clear I think. - Now try to run the script as myself. Oops, I'm don't have the privileges to bind to a differnt pool. - I'll become root, I know I have enough privileges now ;-) - Run it again and this time it works. #!/bin/sh if [ $# -lt 2 ] then echo "usage: newpool <pool name> <command> [parameters]" exit 2 fi /usr/sbin/poolbind -p $1 $$ if [ $? != 0 ] then echo "Bind operation failed" exit 1 fi shift exec $\*I mainly use this script when I'm developing resource pools and I want to launch test programs into different pools. My requirements are fairly minimal, so the script is perfect for me. Let me know if you have ideas for enhancements that would help make this script more useful. Monday Aug 02, 2004 The nuances of poolbind By garypen on Aug 02, 2004 poolbind(1M)allows an authorized user to change the resource pool binding of a zone, project, task or process. However, what does this actually mean? As you might imagine, it means different things for the different pool-bindable entities. Here's a quick explanatory note that should help eliminate any confusion. The main point to note is this: any changes realized through poolbind(1M)are temporal in nature and will only affect the set of processes identified as belonging to the target process collective at that point in time. By this I mean that no permanent configuration is changed. For processes and tasks, this is a moot point since there is no way (currently) to specify that either a task or a process is associated with a resource pool. I can't really think of any reason why you would ever want such fine-grained resource management that you would want to have a configuration that specified this relationship; so this is unlikely to ever change. If you want to permanently change the binding of a project or zone to a resource pool then you must edit the configuration (favourite editor for /etc/project(4)or zonecfg(1M)for a zone). If you want the change to take place immediately, rather than the next time you boot your OS, then you must also use poolbind(1M)to execute the temporal change immediately. So what actually happens when you use poolbind(1M)to modify the binding of a resource pool bind-able entity? process The process stops consuming the resources associated with its existing resource pool and begins consuming the resources associated with the new resource pool. Any new processes which fork(2)from this process are also bound to the new resource pool. task All processes which belong to the task stop consuming the resources associated with their existing resource pool and begin consuming the resources associated with the new resource pool. Any new processes which fork(2)from one of these processes are also bound to the new resource pool. project All processes which belong to the project stop consuming the resources associated with their existing resource pool and begin consuming the resources associated with the new resource pool. Any new processes which fork(2)from one of these processes are also bound to the new resource pool. However, new processes which join the project after this operation completes will still be associated with the configured resource pool. zone All processes which belong to the zone stop consuming the resources associated with their existing resource pool and begin consuming the resources associated with the new resource pool. Any new processes which fork(2)from one of these processes are also bound to the new resource pool. Re-booting the zone will restore the configured resource pool binding. poolbind(1M)is a very powerful workload managment command, especially when applied to a process collective such as a zone or a project. I'll return to the subject of poolbind(1M)later and give some examples of how it can be used to manage workloads quickly and flexibly when problems occur. Thursday Jul 08, 2004 Event Ports By garypen. Wednesday Jun 23, 2004 Solaris 10 gets an XML tools upgrade By garypen on Jun 23, 2004 I look after the version of libxml2 and libxslt which ship with Solaris. Don't ask me why, it's got nothing to do with kernel development. An accident of history I suppose since many years ago in previous employment I used to use XML's ancestor (SGML) on a variety of projects. Be careful what you do, it only qualifies you to do more of it in the future!! libxml2 and libxslt along with their associated tools xmllint, xmlcatalog and xsltproc are shipped as part of Solaris 10 and occasionally the versions of these tools are upgraded. Usually the upgrade is triggered by a specific project which needs new functionality or a specific bug fix. In this case it's both, since a security fix was provided in libxml2 2.6.6 and the GNOME project requires new functionality from both lthe libxml2 and libxslt libraries. As of today, Solaris 10 incorporates version 2.6.10 of libxml2 and version 1.1.7 of libxslt. If you have a requirement to manipulate XML on Solaris then you should definitely investigate the use of these tools and libraries since their performance is good, especially when compared to their Java based equivalents. You can find out more about them here. Thursday Jun 10, 2004 Transforming a Resource Pools Configuration XML Document using XSL By garypen on Jun 10, 2004 pooladm(1M) poolcfg(1M), can be used to examine a Resource Pools configuration. Of course, like most text oriented utilities, the output of these commands is designed to be read by a human working with a shell. I thought it would be nice to be able to examine the Resource Pools configuration using a web browser. In order to do this you need a few things: - A tool to transform your XML document into HTML - A web server that can perform XSLT transformations - An XSL stylesheet which describes the transformation xsltproc(1)utility can be used to transform XML documents using XSL stylesheets. If you don't have Solaris 10, think about joining the Solaris Express program and getting early access to Solaris 10. Alternatively, you can download xsltprocas part of the libxsltpackage for Solaris 9 here. I've written a cgi-bin script which can be used to invoke xsltprocto perform transformations on input XML documents. Of course, you don't have to use xsltproc, many web servers have extensions that can perform XSLT transformations based on the document type. The virtue of this approach is that it is a "lowest common denominator" which doesn't require any web server configuration or addition module installation. This script relies on a utility program called pooldumpwhich is basically the program from my earlier post about dumping a pools configuration as an XML document. The script, xslt_proc, needs a little customization. Instructions are included at the top of the file. Finally, you need a stylesheet, pool_html.xsl, which will perform the transformation. I don't claim to be an XSLT expert, so please be gentle with any suggestions for improvements that you might want to make. It's good enough for my needs and I hope that you might find it useful.I keep this in my cgi-bin directory so that I don't need to set an explicit path to it in the xslt_proc script, but you can put it anywhere you like as long as it can be accessed when your cgi-bin script runs. You can download the cgi-bin script and stylesheet from here. If you want to see what the HTML output looks like before spending any time on this, here is a sample page that I generated on my workstation. Generating an XML Document from a Resource Pools Configuration By garypen on Jun 10, 2004 libpool(3LIB)provides an API for manipulating Resource Pools configurations. In particular, the pool_conf_export(3POOL)function may be used to create a file containing the XML representation of a configuration. pool_conf_export(3POOL)takes three arguments: conf - A valid pools configuration pointer location - The pathname you wish to write the configuration into format - This must be POX_NATIVE which is the native pools representation formatIt's not immediately obvious (and I say this with some shame since I defined this function) that POX_NATIVE == XML. Once you know that, it's fairly obvious how a program to dump a resource pools configuration in XML format can be written. One further tip, you can pass "-" as the location and the output will be directed to stdout. I'm sure that I don't need to say that the following program is completely unsupported and used at your peril, but I thought I would say it just to make it clear. Once you have your configuration as an XML document you can manipulate it easily using a wide range of tools. In a later post, I'll show how you can use an XSL stylesheet to transform the XML document into an HTML document using theOnce you have your configuration as an XML document you can manipulate it easily using a wide range of tools. In a later post, I'll show how you can use an XSL stylesheet to transform the XML document into an HTML document using the #include <pool.h> /\* ARGSUSED \*/ int main(int argc, char \*\*argv) { pool_conf_t \*conf; if ((conf = pool_conf_alloc()) == NULL) { return (2); } if (pool_conf_open(conf, pool_dynamic_location(), PO_RDONLY) != PO_SUCCESS) { pool_conf_free(conf); return (2); } if (pool_conf_export(conf, "-", POX_NATIVE) != PO_SUCCESS) { (void) pool_conf_close(conf); pool_conf_free(conf); return (2); } (void) pool_conf_close(conf); pool_conf_free(conf); return (0); } xsltproc(1)utility. Wednesday Jun 09, 2004 Introduction By garypen on Jun 09, 2004 About garypen
https://blogs.oracle.com/garypen/?page=1
CC-MAIN-2015-22
refinedweb
1,849
61.46
A program that stores 4 button presses in an array and then plays them on the LEDs. Example: If the user presses the button sequence 1-2-2-1, then the LEDs light up in the order 1-2-2-1. Personally I find this very difficult to do, so if anyone can give me some leads that would be great. Off the top of my head, and I don't have time to do any coding, this would as a start keep track of the four pressed buttons - Have a look at the state change detect example in the ide to see how to detect a button has become pressed - Put all the button pins in an array - Put all the led pins in an array - Have another array to hold the array index of each button that's newly pressed - Have a counter set to 0 initially, to count how many presses there have been - Continually monitor all the buttons (for loop across the button array) - When you detect a button is newly pressed store its array index in the presses array, using the counter value as the index into that array - Increment the counter, and when it's 3 (that would be 4 presses since arrays start at 0) you're done with that part - Then use the values in the presses array to be the indices into the led array to access the led pins and turn them on - You need some way to start over.... perhaps when you get a 5th button press, that counts as a new 1st press, and turn the leds all off, zero the counter and go again Very off the top of my head, that. What @void-basil said plus, familiarize yourself with arrays. For state change , debouncing, etc. get to know the first five demos in IDE -> file/examples/digital. consider byte pinsLed [] = { 10, 11, 12 }; byte pinsBut [] = { A1, A2, A3 }; #define N_BUT sizeof(pinsBut) enum { Off = HIGH, On = LOW }; #define LIST_SIZE 4 byte butList [LIST_SIZE] = {}; unsigned butIdx = 0; char s [80]; // ----------------------------------------------------------------------------- void setup () { Serial.begin (115200); for (unsigned n = 0; n < N_BUT; n++) { digitalWrite (pinsLed [n], Off); pinMode (pinsLed [n], OUTPUT); pinMode (pinsBut [n], INPUT_PULLUP); } } // ----------------------------------------------------------------------------- void chkButtons (void) { static byte butSt [N_BUT] = {}; for (unsigned n = 0; n < N_BUT; n++) { byte but = digitalRead (pinsBut [n]); if (butSt [n] != but) { butSt [n] = but; if (On == but) { butList [butIdx++] = n; #if 0 sprintf (s, "%s: %d %d", __func__, butIdx, butList [butIdx-1]); Serial.println (s); #endif } } delay (20); } } // ------------------------------------- void loop () { if (LIST_SIZE > butIdx) chkButtons (); else { for (unsigned i = 0; i < butIdx; i++) { #if 0 sprintf (s, "%s: i %d, list %d pin %d", __func__, i, butList [i], pinsLed [ butList [i]]); Serial.println (s); #endif digitalWrite (pinsLed [ butList [i]], On); delay (500); digitalWrite (pinsLed [ butList [i]], Off); delay (500); } butIdx = 0; } } This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.
https://forum.arduino.cc/t/storing-buttonclicks-in-an-array/701456
CC-MAIN-2021-39
refinedweb
486
54.49
just read through that message reference, bruce, and I do agree of course - I think the real problem with stdint/stdbool and friends is that it is just a nuisiance to make projects be portable to platforms that are not strictly up at '99 or better, and w.r.t. gstdint I can point to the fact that inttypes were introduced in 1992, being later part of unix98, and folded into C99. But I am not supposed to use these inttypes because there are many compilers and systems out there that do not have them, - I could adapt my local source code but I am not allowed to put them into public header files. It's making me sick, really :-( ... and in way the same account to bool/true/false series of defines, since one should think that all this is actually established programming practice but for the merits of portability, I do have to avoid that and start using those mylib_bool defines all over the public interfaces. Of course, instead of doing a mylib_bool for every project of mine, I could just as well extract that part into a seperate project (e.g. "autoposix" ;-)) and let my local one be dependent on it. And in a way, I would not be suprised that many people start using libglib just for the reason that it flattens the differences of the supported systems and returns, among other stuff, an up-to-date system interface to such established programming schemes like inttypes, dlopen and lwp-threading, and not to forget, gboolean. @paolo I agree with you too but on one thing: a programmer does not specifically need to copy stuff in over and over again, instead it is possible to make an #ifdef series like #if defined HAVE_STDBOOL_H #include <stdbool.h> #elif defined HAVE_GSTDBOOL_H #include <gstdbool.h> #error could not get either of stdbool or gstdbool, sorry #endif and let user code (of such a header file) be required to check for these. This happens to be of established autoconf practice to search in multiple headers for things that we need, and AC_HEADER_DIRENT might serve as an example for it. And in a way, it was also the reason I started with that gstdint microproject that is based on my m4 macro to check into the various possible locations for inttypes and have now a last resort being a dependency on the file that gstdint could install all out of itself. I have to admit that I am not quite convinced that it is the final answer to all the problems in this area but just a step more to detach myself from the problems there are around with multiple lib-headers to try to define stdxxx types in different locations all over again. So, in a way I would ask you to start such a microproject for gstdbool too - other projects could then check for bool in it's normal locations (possibly being predefined in the compiler) and have a third-party check for gstdbool.h, and just make a note in your project docs that you declare the bool-types as a precondition to be it around, and hint the user that this might be in the compiler, from a system extension or from that microproject one can hand out the url for. And autoconf could get a standard-macro ac_header_stdbool that would work just like header_dirent with one exception - it will also check for the header from from the microproject that has settled around the autoconf-people, and in a way it is the reason that I placed gstdint in a subdir of the ac-archive sfnet-fork as I see it as a thing very close to autoconf but not just in it. Anyway, even that I do not feel your stdbool macro should live in the autoconf core itself, I feel it could be great contribution to be memorized in the ac-archive, so that people shall not need to reinvent it. Amongst the various effects I could not that one would be able to make a standard for an is-already-defined macro that other header could check so they do not redefine the same symbols. Such a thing has been done for inttypes all the way long (since it overlaps with the bsdtypes stemming from network code), and it could be used for generated-header too, so that the generated header contains #ifndef _GENERATED_STDBOOL_H #define _GENERATED_STDBOOL_H xxxx #endif which will avoid redefinitions even when the macro and the header-generation is used in multiple places around the software world. Actually, it's another lesson that I had to learn around stdint and friends. And to emphasize it again, I am not sure if it is the last lesson I have to learn the hard way.... sorry for such a long talk on it, 'hope the things do not look that foggy as they do look to me sometimes, cheers, guido Es schrieb Bruce Korb: > > Guido Draheim wrote: > > being a person who has been doing some tricky stuff with a generated > > file called stdint.h, I would like to oject on generating a stdbool.h > <<reasons elided>> > I agree, with arguments about project focus and project bulk > to boot: > > > p.s. references are > > > > > > The downside to "gstdint" or "gstdbool" is that they are just > the tip of an ugly iceberg. If you were to assemble one project > for every fixable compatibility issue, you would find yourself > with a lot of projects. In my code sourcery contest entry I > proposed a single project that ran through the million known > compatibility issues and installed whatever was needed so that > a consistent interface was available for all supported platforms. > This would mean that a "stdint.h" and a "stdbool.h" headers > would be part of it and installed as needed. Then, instead of > bulking up every autoconf-ed project in the world with 300K > of duplicated configury overhead, a project can just have a > dependency on a minimum revision of the compatibility library. > Way, way, way simpler. Smaller distributions. "configure" > could focus on the with/without/enabled/disabled options for > each package. autoconf users would not need to be M4 quoting > experts. I suppose I'm just whistling in the wind? ;-) -- guido GCS/E/S/P C++$++++ ULHS L++w- N++@ d(+-) s+a- r+@>+++ y++ 5++X- (geekcode)
http://lists.gnu.org/archive/html/autoconf/2001-11/msg00048.html
CC-MAIN-2013-20
refinedweb
1,060
60.48
Creating a Facebook App with Java – Part 2 – Application, Hosting, and Basic Functionality The first article in our series took care of setting up and installing an IDE, some tools, and signing up for your new app at Facebook. Now we’ll begin creating the Web application with a landing page and some basic Facebook API calls. We’ll be creating our web application using Forge – where we left off in the part one. Because Forge allows us to start our new application very easily, and streamlines things like adding persistence (and eventually Arquillian, the testing framework) with a single command.It’s now time to create our project – we will ask forge to do this for us with the following command. Note how your project is automatically set up using the default Maven project format:Forge will then ask you if you also want to install extended APIs, you can use the default of ‘No’ (just hit <ENTER>). You should then see confirmation that Forge wroteNow create the Player object in the same fashion. Be aware that theWe are now ready to check our pulse. Make sure things work so far by using theForge may ask you to update the packaging to a [war] file which is what we want, so hit <ENTER> to accept the default. We also need to specify a REST endpoint. We again want the default of /rest/* (hit <ENTER> again). Verify your If you are not using Forge, or would like to know what the plugin has done for us, we need to make sure that the following lines are in Verify your We’ve also created a new file called Verify your We may at this point wish to check our POM file (pom.xml) to ensure that we have all of the proper dependencies for our application. Our POM should look something like this: At present, the current configuration of JAX-RS is assuming (and requiring) that you have a class set up with aThis will open the MyWebService.java file in your default editor. Clear out the entire file, and paste in the shell code below:We need to install Git, and a few other things before we can upload our project to the cloud, but fortunately should take only a few seconds (except maybe for the Windows users.) This command must be run from a non-Forge command prompt (all others may be run within Forge:)Now install the OpenShift Express Forge plugin. In Forge, type the following commands from any directory within your project:Once DNS resolution has finally completed and OpenShift is set up in our project, we can push our changes to Openshift with a simple set of commands. This is all we’ll need to do from now on:These commands will mark all files to be sent to the server, set the messages associated with this particular commit, and then upload the new git repository, build, and redeploy the application to the cloud for us in mere seconds! If you’d like, you can also store your code on GitHub as well, like I’ve done. Once you have created a GitHub account, and a new project to contain your code, you can push your code with just a few commands.The repository, aka MY_GITHUB_URL can be found directly on the GitHub project page; fortunately, after this initial setup, you can upload your code to GitHub at any time simply by repeating the following commands from the root folder of your project:We can now go to the OpenShift site () where our app is being hosted and test to make sure we see our Welcome header. (Mine is hosted here.)CONGRATULATIONS!!! You now have an official Facebook app (try not to laugh at the fact that it doesn’t yet do anything; now we’ll take care of adding functionality to it in part three.) From now on you’ll be able to access your site and updated code immediately after you upload it to OpenShift at any time by going to: Create Create Create a basic web project using JBoss ForgeJBoss Forge is an incredibly powerful tool for creating new applications; it’s possible to set up much functionality very quickly. We’re going to tap into only a small fraction of its extreme powers to jump start our Facebook app. If you don’t have your Forge console open, run Forge by opening a new terminal and typing forge. Once it’s is running, you can hit <TAB> at any time to see auto-completion suggestions. If you get an error saying forgeis not a recognized command, make sure you have correctly installed Forge. Re-run your profile, and try to open forge again. forge> new-project --named FBTutorialDemo --topLevelPackage com.example Set up the databaseNext, we will set up a persistence context so we can do things like handle user registrations and process game events. We’ll use JBoss’s Hibernate (via the standard Java Persistence API.) With Forge this is extremely easy to set up; otherwise, we would need to do a fair amount of XML configuration by hand. For now, the persistence context we set up will use an in-memory database, meaning it will only retain information during the time in which the application is deployed. In other words, every time you restart your server or redeploy, your application database will be wiped out and recreated on the next start up. Don’t worry though, we’ll set up a MySQL DB to store our data more permanently, later. In our Forge terminal, type the following command. Please note that if you are using GlassFish, you will need to use different parameters for both the provider and container arguments, but by pressing <TAB>, you will see a list of all available options: persistence setup --provider HIBERNATE --container JBOSS_AS7 pom.xmland persistance.xml. /src/main/resources/META-INF/persistence.xmlView complete file <persistence> <persistence-unit > </persistence> Create @Entity objects to describe our app’s database schemaWe will now continue to create several @Entityobjects to store Users having a facebookID: long, name: String, and imageURL: String. These will represent any/all basic Facebook Users; our players and each of their friends will be set up as a User. We’ll also create a Player object having a playerInfo: User, points: long, and friendList: ArrayList<Long>(to store FacebookIDs of all the friends of that User). In the Forge window type the commands to set up our User object, results should look something like this. entity --named User --package ~.domain field long --named facebookID field string --named name field string --named imageURL If you get stuck, remember to press <TAB> to get Forge to give you hints on what to type next. playerInfoand friendListfields have to be set up a little differently because of their non-native types. entity --named Player --package ~.domain field oneToOne --named user --fieldType ~.domain.User.java field long --named points field custom --named friendList --type java.util.ArrayList buildcommand. You should see this. Setup CDI, EJB,and RESTIf you are using Forge, you may perform this entire step by using the following command. Here we instruct forge to set up CDI, EJB, and JAX-RS (REST) and specify that we want to use /rest/*as the root URL from which REST Endpoints will handle requests. forge> setup beans ejb rest Verify your If you are not using Forge, or would like to know what the plugin has done for us, we need to make sure that the following lines are in web.xml web.xml. This configuration activates our JAX-RS WebService: Literally speaking, /src/main/webapp/WEB-INF/web.xmlView complete file <web-app> <servlet-mapping> <servlet-name>javax.ws.rs.core.Application</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app> <url-pattern>tells our application that we want to use JAX-RS, and specifies which requests will get routed to our endpoints. In this case, any request with a URL like*anything* will get caught and routed to our REST services. Verify your We’ve also created a new file called beans.xml beans.xml, which is repsonsible for activating CDI in our project. This file can be empty, or if desired, you can include the minimal XML. (We won’t add anything to this configuration beyond the empty file, so you can do what you like.) /src/main/webapp/WEB-INF/beans.xmlView complete file <beans /> Verify your We may at this point wish to check our POM file (pom.xml) to ensure that we have all of the proper dependencies for our application. Our POM should look something like this: pom.xml /pom.xmlView complete file <project> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>FBTutorialDemo</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>war</packaging> <dependencyManagement> <dependencies> <dependency> <groupId>org.jboss.spec</groupId> <artifactId>jboss-javaee-6.0</artifactId> <version>2.0.0.Final</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <dependencies> <dependency> <groupId>org.jboss.spec.javax.servlet</groupId> <artifactId>jboss-servlet-api_3.0_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.ws.rs</groupId> <artifactId>jboss-jaxrs-api_1.1_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.xml.bind</groupId> <artifactId>jboss-jaxb-api_2.2_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.enterprise</groupId> <artifactId>cdi-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.annotation</groupId> <artifactId>jboss-annotations-api_1.1_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.ejb</groupId> <artifactId>jboss-ejb-api_3.1_spec</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.jboss.spec.javax.transaction</groupId> <artifactId>jboss-transaction-api_1.1_spec</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <finalName>FBTutorialDemo</finalName> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project> Your POM file may contain different dependencies depending on whether or not you used Forge to set up your project, and which Forge version you’ve used. But the key point is that you need to have the JAX-RS, JPA, and CDI API libraries available for your project to compile. @Pathdefined. Since we need to define where we are going to route our requests when they hit our servlet-mappingof /rest/*. For now we can simply create a shell of our WebService class, but leave the implementation for a later article. forge> entity --named MyWebService --package ~.domain forge> edit Exhibit 4 package com.example.domain; import javax.ws.rs.Path; @Path("/webService") public class MyWebService { } Get caught upIf you had any trouble following along, simply grab the code to this point from github tag: v0.1.zip — Setup CDI, EJB, and REST. Register with OpenShift and get your project hostedNow that we have a few @Entityobjects in our project (even if it doesn’t quite do much at the moment), our next step is to host it somewhere. If you’d like, you can simply host it on your local machine at, but we’re going to take you through setting up an account and hosting at Red Hat’s OpenShift platform which is completely free. The huge benefit here is not having to worry about blackouts, or just needing to restart your machine for some reason, as well as giving your site more dedicated bandwidth. OpenShift also offers options to expand on size and bandwidth from their free version if/when your app takes off. Go to: and click the button to “Sign up and try it”; make sure to provide all of the necessary fields. OpenShift will then send you an email to the address you provided them. You’ll have to click the link in the email to validate your email address with them, retype your password, and sign in. Once logged in, you’ll need to accept the legal terms. sudo apt-get install git forge install-plugin openshift rhc-express setup You will need to re-type your OpenShift account information into the Forge console. Also note that it may take several minutes to complete this process. git add –A git commit –a –m “Comment Here” rhc-express deploy Make sure any time you are trying to save/upload changes that you are adding and commiting from the root of the .git repository (aka the project folder) to ensure all changes in the project get updated. git remote add github git push github master git add –A git commit –a –m "Description of change" git push github Test your cloud connectionWe’re going to do some fine tuning, adding specific code blocks to our project, and while some of these things can be done within Forge, it’s easier to use a full graphical editor for this step. If you created your project using Forge from within Eclipse, you can skip this step; otherwise, we need to import our project into the Eclipse workspace before moving forward. Open Eclipse and Click File -> Import -> Maven -> Existing Maven Projects. Browse to the maven project, import it, and create a new file called index.html in the scr/main/webappdirectory. (If the file already exists, you may simply delete its contents and replace them with the following HTML snippit.) This file will greet our users when they access our application. The above simply displays a heading welcoming you to the Tutorial Demo. We can now use this to confirm that our app is being loaded correctly. index.htmlView complete file <html> <body> <center> <H1>Welcome</H1> <P/> <H3>To Tutorial Demo</H3> </center> </body> </html> Save point – don’t lose your work!Lets rebuild and get this new code up to our OpenShift hosting service so we can check out our new landing page. Go back to the forge console and type: git add –A git commit –a –m “Initial Index html file” rhc-express deploy Make sure to replace “yourapp” with your application name, and “yourdomain” with your OpenShift domain name. Get caught upIf you had any trouble following along, simply grab the code to this point from github tag: v0.2.zip — Test your cloud connection. Configure Facebook to use your new DomainGo back to the Facebook app page at: Click the “Edit Settings” link (near the top right), and enter your OpenShift application’s web address into the Canvas URL and Secure canvas URL. OpenShift lets you use http:// or https:// to access your app through non-secure or secure respectively. Add Facebook connectivity using the Javascript APIThis guide references the Facebook Javascript SDK. I highly recommend you install a JavaScript editor plugin for Eclipse. Without such a plugin, simple formatting and/or styling issues can be tough to catch if there are errors in the code. Plus it just makes viewing the code easier. You can use Aptana by going into Eclipse and clicking to Help -> Install New Software, and using the URL: Many methods in many of the APIs haven’t been marked deprecated when Facebook wants to phase them out, they are just removed when made obsolete. Thus, code that would have worked when certain tutorials or blog/forum posts were written may not work anymore. This is just something to be wary of when taking code from online sources other than Facebook itself to try to get functionality working on your own app. It is important to note that there have been many versions of all the different Facebook APIs, and some may be no longer be supported. Even if the API is supported, make sure to check Facebook to ensure the API method you’re trying to use still exists when taking code from forums and tutorials for help. I originally got caught using an old version number of the PHP API in my first attempt at writing a Facebook app. When I found and logged issues Facebook’s solution was to have me use the most recent version of the PHP API instead. However, when I simply updated the version number other functionality no longer worked the same way, I eventually gave up and started over to write this tutorial using JavaScript. Update src/main/webapp/index.html /src/main/webapp/index.htmlView complete file <!DOCTYPE html> <html xmlns="" xmlns: <head> <meta http- <title>Welcome to Tutorial Demo</title> </head> <body> <!-- <fb:login-button </fb:login-button></p> --> <fb:login-button </fb:login-button> <div id="fb-root"></div> <script type="text/javascript"> window.fbAsyncInit = function() { FB.init({appId: ' YOUR_APP_ID', status: true, cookie: true, xfbml: true}); }; (function() { var e = document.createElement('script'); e.Get Your Info Here</a><BR /> <a href='friendsInfo.html'> Get Your Friends Info Here</a> </center> </body> </html> Make sure to replace the YOUR_APP_IDwith your own app’s actual appId(in this file, and all other htmlfiles throughout the tutorial.) <fb:login-button>tag will add a Facebook login/out button to the site. Facebook will handle all the logic around if the user is logged in or not, and all the credentials of valid username/password etc. The commented out version of the <fb:login-button>shows you how you can access more of the Facebook data model, however if you add additional permissions here, you will need to get each user to grant access for those permissions before you can access that type of data from their accounts. If the users do not want to allow the additional access, they can not enter your app at all, so be careful not to require permissions unless you really need them, as it could cost you some user base. The next block of code allows you to utilize the Facebook Javascript API library on our page. Lastly, we put links on the page for myInfo and friendsInfo where we will have our 2 API calls. Create src/main/webapp/myInfo.html Here we do the same thing with /src/main/webapp/myInfo.htmlView complete file <!DOCTYPE html> <html xmlns="" xmlns: <head> <meta http- <title>Tutorial Demo - My Info</title> </head> <body> <div id="fb-root"></div> <center> <h2>Here is your Facebook Data:</h2><p/> <div id="userMyInfo(); }); FB.getLoginStatus(function(response) { if (response.authResponse) { getMyInfo(); } }); }; (function() { var e = document.createElement('script'); e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js'; e.async = true; document.getElementById('fb-root') .appendChild(e); }()); function getMyInfo(){ FB.api('/me', function(response) { var userInfoElem = document.getElementById('user-info'); userInfoElem.innerHTML = '<img src="' + response.id + '/picture" style="margin-right:5px"/><br />' + response.name; }); } </script> </body> </html> <div id="fb-root">to add the FB Javascript API access to our page. However, notice that this time we are also adding some code to the window.fbAsyncInit = function()method to call our custom function getMyInfo()when the user either; (a) logs on through our button via: FB.Event.subscribe('auth.login', function(response) {, or (b) Facebook has determined the user is already logged on via: if (response.authResponse)respectively. Then we get to the heart of this page, our custom function getMyInfo(). This method uses Javascript to make a GraphAPI call to FB for "/me"which returns the current logged in FB users info. The info gets returned to us from Facebook in the response object. In this case we have access to response.id and response.name being the FacebookID and name of the current person logged in. We can get anyone’s FB profile image with their ID using the GraphAPI as the code does by using “ response.id/picture”. Create src/main/webapp/friendsInfo.html > Here we use the same tactics as myInfo.html to get the API and Events added to the page (this time calling getFriendsInfo() instead of getMyInfo()). In our custom function for this page Facebook returns to us response.data which is a list of all the friends of the current user. We use this to loop through the list and print out their picture (from their id), and their full name (from their name). The loop creates a String with all the HTML tags necessary to print out this info to a table, with 5 friends per table row. If you haven’t noticed before, we are actually using AJAX with these FB Javascript calls, which means we need to put <div> tags and then populate them asyncronysly with the results of the FB API calls once we get the response back. We can set the innerHTML of a div to whatever we want, and the browser will build the page just as if whatever is in the innerHTML property of the div tag was written in the html file directly once we get our response data back from Facebook. The last 2 lines of our method get the div element for 'friend-info' and set it to the String we built in the loop containing the HTML for the table. If you need more test-data, you can always register test users and friend them (all you need is an email address for each one which you can keep getting from gmail or other email providers). Save point – don’t lose your work! This is a good time to upload your changes to OpenShift and have it rebuild and redeploy these new files out to the facebook canvas site for us. Once you get the new index and 2 new pages working, you can move on. git add –A git commit -a -m "Description of change" git push github Get caught up If you had any trouble following along, simply grab the code to this point from github tag: v0.3.zip — Add Facebook connectivity. Conclusion Now that we have some minimal Facebook functionality on our site, our next article will dive into some of the slightly more advanced topics such as setting up our game logic, handling players, and saving information to our database. Players will be rewarded points for correct answers, and deducted points for incorrect answers. > If you need more test-data, you can always register test users and friend them (all you need is an email address for each one which you can keep getting from gmail or other email providers). git add –A git commit -a -m "Description of change" git push github Posted in Facebook, OpenSource […] should look something like this, and we are almost ready to create our actual application. In the next article we’ll utilize JBoss Forge to help give us a jump start to creating our application with just […] Incredible. I love the break down. Very organized and able to be understood. Hopefully more folks will start getting involved with the creation of apps on not only Facebook but the iPad and iMac’s too. hi, very nice tutorial, thanks! i think the forge command for creating the persistence.xml is wrong. you wrote instead of persistance setup –provider HIBERNATE –container JBOSS_AS7 persistEnce Updated, thank you both for catching this error 🙂 Hi, I’m using windows XP and things work great untill i have to setup the openshift account through Forge (i have an account with which i can log on). I get: [OpenShiftUnknonwSSHKeyTypeException: OpenShift does not support keys of type “”] Any suggestions? I do get the following warning when installing openshift: [ould not find a Ref matching the current Forge version [1.0.2.Final], building Plugin from HEAD.] Thanks, Maarten Figured out some things, including addind a ssh key to the openshift account. Now i get the following message when running rhc-express setup: [$where function:\nJS Error: TypeError: this.domains has no properties nofile_a:0\”, code: 10071 }’; code] it has to do with mongodb being used but i don’t get the message. Thanks, Maarten Glad to hear you got the OpenShift ssh keys set up. OpenShift does support MySQL 5.1, PostgreSQL 8.4, and MongoDB 2.0 databases, so you should be ok there. I’m not all that familiar with MongoDB, but this does appear to be a Mongo error. Without seeing more of your code, there’s not much at all I can do for you here, and as I mention, I’m not really familiar with that technology anyway. I would recommend searching Google for the error, if you still need help, (or instead of google) search StackOverflow. The following article looks like he has the same error as you: StackOverflow entry. If that didn’t help, you can always create your own StackOverflow account and post some of your code and the question there. You should get someone more familiar with MongoDB to help you figure it out very quickly on that site. somehow it started to work. As a test i create another project through the openshift console. Now i have a problem that on creation i can see the project being created in OpenShift but then i get the following output [***INFO*** Exception caught java.net.UnknownHostException: -.rhcloud.com ***ERROR*** OpenShift did not propagate DNS properly] Hi, thanks for writing this great HowTo. I could follow each step as you described but got stuck when it came to rhc-express setup. When I enter the (correct) credentials (bad ones are recognised) there’s just no further output in the console and I’m taken back to the command prompt. After doing so, git won’t work because there was no repository created. Do you have any idea how to fix this problem? Try going directly to OpenShift and click SIGN IN TO MANAGE YOUR APPS in the upper right corner. Try those same credentials. If you’re not able to get on, you can try the forgot password link, and have OpenShift reset your password. If it doesn’t even recognize your Email as being registered, try re-registering with OpenShift again, and then try the rhc-express setup again after that. If you’re getting to the point where its asking for credentials after the setup command, then the OpenShift-Forge plugin should be installed correctly, from there it’s just up to OpenShift to validate you with the credentials you supply. You probably also want to check that it’s not one of the common pitfalls of capslock or numlock being set to something other than you expect, since you can’t actually see the password you’re entering. Hello Craig, thank you for your answer although it didn’t help me to proceed. This is what I get in the eclipse forge view. [PresentPerfect] PresentPerfect $ rhc-express setup ? Enter the application name [PresentPerfect] [PresentPerfect] ***INFO*** If you do not have a Red Hat login, visit ? Enter your Red Hat Login [null] [null] johan…..mel@gmx.de ? Enter your Red Hat Login password ******* [PresentPerfect] PresentPerfect $ rhc-express setup ? Enter the application name [PresentPerfect] [PresentPerfect] ? Enter your Red Hat Login password ******* [PresentPerfect] PresentPerfect $ I didn’t enter anything when it asks me for the application name and just pressed Enter. As you can see if I try it a second time it’s not asking for the username anymore but still no output and after those steps rhc-express destroy/deploy is not available. Hi. It’s possible that the openshift plugin needs to be updated. Try reinstalling it in Forge. I know that there was some work being done on it in the past few days. I’ll try to see if anyone else has been having similar issues. […] Creating a Facebook App with Java – Part 2 – Application, Hosting, and Basic Functionali… […] Hi, i need help with Forge, that is not so well documented. I’m not able to reopen a project and continue the setup that i had to stop. Thank you for the help. Hi, Please ask this question in the Forge community forums, thanks: ~Lincoln Ok, let’s head to the desert forum 😉 Thanks anyway! [FBTutorialDemo] FBTutorialDemo $ rhc-express setup ? Enter the application name [FBTutorialDemo] [FBTutorialDemo] What do I do for the two [FBTutorialDemo] [FBTutorialDemo] ? It’s all failed at this point! Thank you in advance. I got an error when i try to install openshift-express plugin Here is : Connecting to remote repository []… connected! Wrote /home/baturay/.forge/httpsrawgithubcomforgepluginrepositorymasterrepositoryyaml.yaml ***ERROR*** [forge install-plugin] no plugin found with name [openshift-express] Same problem I believe this plugin is now just called -openshift-
https://www.ocpsoft.org/opensource/creating-a-facebook-app-new-web-application-hosting-and-basic-facebook-functionality/?replytocom=2826
CC-MAIN-2019-47
refinedweb
4,738
61.97
. - a 64-bit kernel (+ module set), but - a vanilla 32-bit Raspbian userland OS, with additionally - a 64-bit userland 'guest' OS (here, Debian Stretch), booted inside a systemd-nspawn container [1]. Here's a screenshot of the hybrid system in use, on an RPi3B+: If you'd like to try this out without having to build it first, I have a released a bootable RPi3 image on GitHub, here. Think of this as vanilla 32-bit Raspbian with a 'sidekick' 64-bit Debian Stretch guest OS always available, which you can enter at will from a Raspbian terminal using the ds64-shell command. You can also start 64-bit apps inside the guest from a Raspbian terminal using the ds64-run command. 64-bit apps started in this fashion can display on the host desktop, play sound and video, and access user pi's home directory, but are prevented from performing many harmful actions on the host. Package management in the guest is regular apt-get, with the full Debian aarch64 repository available, and day-to-day Raspbian operation (with the exception of anything needing e.g. MMAL or OpenMAX IL) is pretty much per the stock image. WiFi, Bluetooth, I2C etc. are all available. support provided by systemd-nspawn [1]. Benefits and Drawbacks The benefits of this hybrid approach are: - The 'normal' desktop, package set and functionality of 32-bit Raspbian is retained. Bluetooth, WiFi etc. all work and can be managed using the stock, familiar tools - in fact, there is surprisingly little impact to Raspbian when booted under a 64-bit kernel (we will discuss what doesn't work shortly). Bluetooth, WiFi, I2C, SPI etc. all work just fine. - No Raspbian-package-supplied files get 'clobbered' during the hybridization (and that even includes the original 32-bit kernel and modules [9]), so updates and new package installation can be done just as before (via apt-get, or the GUI application). So, for the most part, you should be able to follow along with other tutorials targeted at mainstream Pi users and so forth. - As we'll set it up, the containerized guest OS shares the default user's home directory, and can launch graphical apps on the main desktop. You can just use ds64-run to start a 64-bit app, and ds64-shell to enter a 64-bit shell, right from your 32-bit Raspbian console (you can see examples of this in the screenshot above). This makes it easy to e.g. run a 64-bit program alongside your regular 32-bit ones, a use case that comes up frequently in threads and support emails. To be clear, we won't be using KVM here, although, as the 'host' kernel we will be using supports it, you could if you wished [3]. - Since the guest OS we're going to use - viz., Debian Stretch - is what Raspbian is currently based on, package management inside the (64-bit) guest should feel very familiar (apt-get etc.) And since all package management in the host and guest is binary-based, there's no need to compile anything (unless you want to!) - Setup is quick; the whole thing can be built starting from a 'vanilla' Raspbian image in around an hour or two, without cross-compilation toolchains etc. - Reverting back to use your old (32-bit) kernel again, should you wish to do so, is an even faster process, and can be done on a temporary basis too (I'll provide instructions for that). - Similar to chroot, only parts of the host filesystem that are explicitly mapped will be visible within the guest; however, unlike chroot, the filesystem hierarchy is fully virtualized. - Also unlike a (vanilla) chroot, systemd-nspawn (via underlying Linux kernel containerization technology) limits the guest OS' access to various kernel interfaces to read-only (/sys, /proc/sys, /sys/fs/selinux), prevents it changing the host's system clock, creating new device nodes, loading kernel modules, restarting the host, etc.. - Similarly, although the host OS will be able to 'see' processes within the guest, unlike a chroot the converse will not be true. - As we'll arrange it here, the guest OS will actually be booted, so, again unlike a chroot, it will have its own (systemd, of necessity) init process, and this boot will happen automatically at system startup. This makes it easy to run e.g. services that require scheduling within the guest (e.g. a 64-bit cronjob of some sort), and also enables software with complex system or dbus interactions (such as a full-scale web browser) to be launched within the guest. - The process is very efficient: at the time of writing, booting Debian Stretch in a container took only a few seconds on an RPi3B+, and the resulting guest system consumed less than 10MiB of system memory (prior to any user apps being launched, of course). So there is really no penalty attached to bringing up the container automatically at boot (which is what we will arrange to do). - You can also (advanced point) have multiple instances of different guest operating systems in use simultaneously, should you wish, and even use the same OS filesystem tree for multiple instances - thanks to namespacing, their processes will not clash (although obviously the root filesystem will be shared). - The guest OS can easily be started with an ephemeral filesystem, in which all changes (to the guest) are lost once it is restarted (also an advanced point). - You can also easily more fully isolate your guest processes from the main OS, should you want or need to do that (also an advanced point). We're going to use a privileged container, and share the host's networking, in what follows, but you can relatively easily migrate to a unprivileged container with isolated networking, should you so wish (each of these changes makes administration and package management somewhat harder inside the container, which is why we're not going to pursue them for the proof-of-concept system here.) - As with all 64-bit (kernel) systems at the moment, the MMAL and OpenMAX IL layers do not work when booted in this way. So, for example, gpu-based video decoding is unavailable [4]. However, the so-called ARM-side (aka 'GL') video drivers are available (vc4-{f,}kms-v3d), and we will leverage this in what follows. - Although the userland Raspbian part of your system will be basically vanilla, booting under a 64-bit kernel is not currently officially supported, so you may find it somewhat harder to get support on these forums etc., if you go this route. - You will have to keep the repos up to date separately for host (Raspbian) and guest (Debian) systems. However, since both are binary distros, this isn't an onerous task. - The protection put in place by systemd-nspawn can sometimes be a double-edged sword: if, for example, you want to run a service that does something forbidden. But such a case is rare (and you can always chroot, or reduce the protections by parameter). - Only the 'pi' user is set up for easy cross-container filesystem access: if you add a new user, the same tricks won't work for them. Also, the pi users in the host and guest OSes are distinct; so setting the password for pi in Raspbian won't affect that in the Debian guest, and vice versa. - This isn't a true multi-lib approach (as you might get on a Linux PC say, in which the co-location of 32-bit and 64-bit applications and libraries within the same filesystem hierarchy is relatively common). Readers wanting to a taste of what that might look like on Raspbian should check out jdonald's raspbian-multiarch script. - Make sure you really do need this before proceeding! If the official, vanilla Raspbian OS (under a 32-bit kernel) is working well for you, and runs all the packages you need, stick with it (unless you just want to experiment, of course). Similarly, if you want to run a 'pure' 64-bit system, or (natively) run a different disto (such as Gentoo or Arch), you should use the appropriate dedicated 64-bit OS image, rather than this hybrid. You can browse here, and here, for discussion of some of the alternatives. - This tutorial assumes some basic knowledge of the command line. If you'd like to skip the actual setup and just try it out, I have a demonstrator image available for download on GitHub here. - Don't try hybridizing the Raspbian image you currently use for day-to-day work, particularly if you have anything of value on there! Instead, store that somewhere safe, and build up this system on a second, spare microSD card. That way, you'll easily be able to swap back to your original system at any time should you need to do so, or should anything go wrong. I've tried to make the tutorial comprehensive and easy to follow, but it's provided 'as is' and without warranty - proceed at your own risk! Always ensure you are in compliance with necessary laws if you intend distributing your modified image. Prerequisites To carry out the steps in this tutorial, you'll need: - A Raspberry Pi with a 64-bit capable processor. The RPi3B and RPi3B+ should both be fine, so I'll use the generic term 'RPi3' in what follows [5]. - A spare microSD card, on which to build up the image. You will need a card of capacity >= 8GB. - Some way of writing an image to the card prior to first boot on the RPi. Most people will use a PC with an appropriate adaptor for this. - Working internet connection that your Pi will be able to use (wired or WiFi). OK, if you have everything ready, then let's start! Setting up a baseline Raspbian System Begin by downloading an official Raspbian image from this page. At the time of writing, three Raspbian variants are available for downloading. I recommend the "Raspbian Stretch with desktop" one (and use that in what follows), as this boots to a graphical desktop (which most users will want) but ships with only a core set of applications preinstalled, which reduces the image size. You can of course install whatever additional packages you want once the system is up and running [6]. Once you have downloaded the compressed image, write it to your microSD card, following the official installation guide. For simplicity, do not use the NOOBS option mentioned on that page, but rather write the downloaded image directly to the card (the recommended program Etcher makes this process straightforward to perform safely [7]). Once you have the image written, boot your RPi3 with it, and perform the usual first-run wizard-driven setup, setting user pi's password, configuring WiFi etc. as required, and finally rebooting. When the system comes back up, ensure you have network connectivity established (you can ping out, browse the web etc.). NB: in what follows, I'm going to assume you have not deleted or renamed the default pi user during initial setup. Next, if you didn't elect to "Update Software" when prompted by the first-start wizard, do so now. Open a terminal window on your RPi3, and issue: Code: Select all [email protected]:~ $ sudo apt-get update && sudo apt-get -y upgrade If you did update software when the first-start wizard prompted you to, then the above will (almost surely) be a no-op and complete very quickly, but there is no harm in running it. Once complete (and after rebooting again, if necessary), you should next switch the graphics driver over to the 'fake kms' GL variant, as this will provide reasonable hardware acceleration even when booted under a 64-bit kernel. To do so, open a terminal and issue: Code: Select all You're now ready to add a 64-bit kernel! Installing a 64-bit Kernel Because the RPi3 SoC's CPU is an ARMv8a device, it can be booted up in either 32-bit or 64-bit mode. The former is used by stock Raspbian, but only 32-bit userland is supported in this mode. However, if started in 64-bit mode (with a 64-bit kernel), the system supports both 64-bit and 32-bit userlands. We'll exploit this fact here, to enable us to get (mostly) the 'best of both worlds' - regular (32-bit userland) Raspbian for day-to-day use, with the ability to drop into a 64-bit userland Debian 'guest' OS for those troublesome '64-bit only' applications. OK, so to move forward we need a 64-bit kernel (and module set) with an appropriate configuration for the RPi3. For this project, we will use the 64-bit bcmrpi3-kernel-bis package, which is automatically built and released once a week by a bot, for the gentoo-on-rpi3-64bit project. The released, prebuilt kernels are based upon the upstream "bcmrpi3_defconfig", so have all necessary Pi-specific options enabled, plus a few additions to support KVM etc. Don't worry, there's nothing inherently 'Gentoo-specific' about this kernel, and for avoidance of doubt, your original 32-bit Raspbian-based kernel (and module set) will not be affected by installing it (and may be rolled-back to in case of problems). As it is a binary package, you don't have to compile anything either [8]. To get it, open a terminal on your RPi3, and issue (as the regular pi user): Code: Select all Now, 'hold' the existing 32-bit raspberrypi-kernel package, to prevent its files being modified during future "apt-get upgrade" runs (which could overwrite the dtbs we're about to install): Code: Select all Code: Select all [email protected]:~ $ sudo mkdir -pv /boot/r32-dtbs [email protected]:~ $ sudo mv -v /boot/*.dtb /boot/r32-dtbs/ With that done, you can safely deploy the 64-bit kernel! This simply requires an untar: Code: Select all [email protected]: ~ $ sudo tar --exclude='COPYING.linux' \ -xJf bcmrpi3-kernel-bis-4.14.93.20190115.tar.xz -C / [email protected]: ~ $ sync - a bootable 64-bit kernel to /boot/kernel8.img; - the kernel's config to /boot/config; - the kernel's to symbol table to /boot/System.map; - a set of DTBs to /boot/<devname>.dtb; and - a matching module set into /lib/modules/<kernel release name>. Lastly, make a backup of the new device tree blobs too, for ease of rollback later: Code: Select all [email protected]:~ $ sudo mkdir -pv /boot/r64-dtbs [email protected]:~ $ sudo cp -v /boot/*.dtb /boot/r64-dtbs/ So next, reboot your RPi3. With luck, you should find it now starts up into the 64-bit kernel, and then continues into (32-bit userland, vanilla) Raspbian, just as before! You may see the message "dmi: Firmware registration failed." displayed during early boot. This may safely be ignored. Open a terminal, and check all is well: Code: Select all [email protected]:~ $ uname -a [email protected]:~ $ file $(which ls) [email protected]:~ $ lsmod Here's a screenshot of an RPi3 B+ at this stage in the process (your lsmod output etc. may vary slightly): Notice how the kernel ("uname -a") is aarch64, the vc4 driver module is loaded, and the userland (as shown, for example, by the "file $(which ls)" command) is aarch32. So far, so good: we're now ready to install our Debian guest! Installing 64-bit Debian Guest OS (Userspace) Let's begin by installing some components (in our 32-bit Raspbian userland) to enable us to create a Debian instance [10]. Issue: Code: Select all [email protected]:~ $ wget -c [email protected]:~ $ sha256sum debian-archive-keyring_2017.5_all.deb 6a38407c47fefad2d8459dc271d109f1841ee857f993ed3ce2884e33f7f0f734 debian-archive-keyring_2017.5_all.deb Code: Select all [email protected]:~ $ sudo apt install ./debian-archive-keyring_2017.5_all.deb [email protected]:~ $ sudo apt-get -y install debootstrap systemd-container pulseaudio zenity Now we can create the initial Debian filesystem. We'll do this in the special location /var/lib/machines, with top level directory name 'debian-stretch-64'. Issue: Code: Select all [email protected]:~ $ sudo mkdir -pv /var/lib/machines [email protected]:~ $ sudo debootstrap --arch=arm64 --include=systemd-container,pulseaudio,zenity stretch \ /var/lib/machines/debian-stretch-64 The debootstrap above will pull across and install a full baseline package set for an aarch64 (aka arm64) Debian Stretch system, with root directory /var/lib/machines/debian-stretch-64/. It will take some time to complete, perhaps up to 30 minutes, depending on the speed of your internet connection, so please be patient. You can select a different release keyword in place of "stretch" should you wish - see man debootstrap for further details. However, we'll stick with "stretch" in this walkthrough, as it matches the current Raspbian variant. Once it completes (you should see a message "I: Base system installed successfully."), you can remove the debian-archive-keyring package if you like (this step is optional): Code: Select all Booting the 64-bit Debian Guest OS Now you can try starting up your new 64-bit (userspace) Debian OS! What we're about to do is quite different from a chroot - the OS will actually be booted in a new process namespace, with its (fresh) systemd instance PID 1 in that namespace. However, before first boot, begin by setting a root password within the container (as Debian doesn't allow password-free first login). Issue: Code: Select all [email protected]:~ $ sudo systemd-nspawn --settings=no --directory=/var/lib/machines/debian-stretch-64 Spawning container debian-stretch-64 on /var/lib/machines/debian-stretch-64. Press ^] three times within 1s to kill container. [email protected]:~# Now set the password (be sure to remember it!) - issue (working at the container root prompt you just activated): Code: Select all [email protected]:~# passwd root Enter new UNIX password: <enter password> Retype new UNIX password: <enter password again> passwd: password updated successfully Code: Select all [email protected]:~# useradd --user-group --groups \ adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev \ --create-home --uid 1000 --shell /bin/bash pi Then, set user pi's password in the container (again, be sure to remember it!), and then exit the container shell. Still working at the container root prompt, issue: Code: Select all [email protected]:~# passwd pi Enter new UNIX password: <enter password> Retype new UNIX password: <enter password again> passwd: password updated successfully Code: Select all [email protected]:~# echo -e "127.0.0.1\tdebian-stretch-64" >> /etc/hosts [email protected]:~# logout Container debian-stretch-64 exited successfully. Code: Select all [email protected]:~ $ sudo systemd-nspawn --settings=no --machine=debian-stretch-64 --boot \ --bind=/home/pi --bind=/etc/resolv.conf Spawning container debian-stretch-64 on /var/lib/machines/debian-stretch-64. <...> Welcome to Debian GNU/Linux 9 (stretch)! <...> [ OK ] Reached target Remote File Systems. <...> [ OK ] Started Update UTMP about System Run level Changes. Debian GNU/Linux 9 raspberrypi console raspberry pi login: Notice in the above how we're bind-mounting user pi's home directory into the container, so that it becomes accessible to the pi user we just up inside the container too. We also bind-mount /etc/resolv.conf, so that DNS lookup works properly, even if one of the host's network interfaces is reconfigured. If you have created different users on your RPi3, you should of course modify these instructions. It is allowed to have multiple --bind entries. For more details, see the systemd-nspawn manpage here. With luck, this should bring you to a login prompt on the booted container 64-bit Debian OS, as shown above! Prior to logging in at this console however, take the chance to change the machine's internal host name, for ease of reference. While we could just do this as root from within the container, you can exploit systemd's container integration, to issue the necessary command from a terminal in your Raspbian system. To try this, open another terminal window on your RPi3 (leaving the one with the Debian login prompt showing open as well), and in this fresh terminal window issue: Code: Select all You can directly open a shell inside the container at any time as well (provided it is running). Try that now; working in the same terminal window where you just entered the 'set-hostname', issue: Code: Select all [email protected]:~ $ sudo machinectl shell [email protected] /bin/bash Connected to machine debian-stretch-64. Press ^] three times within 1s to exit session. [email protected]:~# In this shell, take a look at all the processes running inside the container, issue: Code: Select all You can also view the systemd journal and service manager status of the container from the host system. To illustrate this, open a third terminal window on Raspbian now, and in that new terminal issue: Code: Select all Code: Select all Code: Select all [email protected]:~ $ sudo systemctl --machine=debian-stretch-64 --failed 0 loaded units listed. Pass --all to see loaded but inactive units, too. To show all installed unit files use 'systemctl list-unit-files'. Code: Select all raspberrypi login: root Password: <enter the password for the container root account> Last login: <date> Linux debian-stretch-64 4.14.93-v8-24b08c0b745d-bis+ #2 SMP PREEMPT <date>]:~# Here's a screenshot after booting and logging-in to the container, as just described: Tweaks to the 64-bit Debian Guest OS Once logged into the container's console as root, update the (Debian stretch) package metadata, and install the package sudo (so that the pi user in the container, who we arranged to be in the sudo group earlier, can leverage this). Issue: Code: Select all [email protected]:~# apt-get update && apt-get -y upgrade [email protected]:~# apt-get install -y sudo Next, install the 'file' package, and use the eponymous command to check you really are running aarch64 userland software inside the container: Code: Select all [email protected]:~ $ sudo apt-get install -y file [email protected]:~ $ file $(which ls) /bin/ls: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, for GNU/Linux 3.7.0, BuildID[sha1]=a242161239cb1f4ea9b8a7455013295e5473e3ec, stripped Then, log out of the root account, and log in as the (container's) pi account. Issue: Code: Select all [email protected]:-# logout Debian GNU/Linux 9 debian-stretch-64 console debian-stretch-64 login: pi Password: <enter the password for the container pi account> <...> [email protected]:~ $ You can now carry out any necessary admin work using this account, elevating privileges using sudo when necessary. Begin by setting up a locale (you may have noticed warnings printed about this when running the journalctl command earlier); issue: Code: Select all [email protected]:~ $ sudo apt-get install -y locales [email protected]:~ $ sudo dpkg-reconfigure locales Code: Select all Code: Select all Now reboot the container to take up the changes (notice how the following command does not reboot your RPi3 itself!): Code: Select all Code: Select all Congratulations, that's the basic container setup done! Now we can just install a few small graphical applications, to test that these can be launched on the main desktop. Issue: Code: Select all Code: Select all This works because the pi user's .Xauthority file came across with the bind mount of pi's home directory. But what about /tmp/.X11-unix - why didn't we need to bind-mount that? The answer is because we haven't put this container in a separate network namespace, so the Unix abstract domain sockets for the desktop's X11 server are still visible, and that (together with a valid .Xauthority) is all an application needs to connect. See my notes on this point here. And in fact, that's just as well, since bind-mounts of entries in /tmp is broken in systemd-nspawn for systemd v232 (bug #4789), the version currently used by Debian Stretch (and Raspbian). Now we can deal with sound. To do this, we'll connect to the host's pulseaudio server. First, make sure all apps will use pulseaudio, not ALSA. Still working inside the container, issue: Code: Select all Code: Select all # Use PulseAudio by default pcm.!default { type pulse fallback "sysdefault" hint { show on description "Default ALSA Output (currently PulseAudio Sound Server)" } } ctl.!default { type pulse fallback "sysdefault" } Right, that's all the preparation within the guest OS done, so we can shut it down for now. Still working at the pi prompt within the container, issue: Code: Select all [email protected]:~ $ sudo poweroff [ OK ] Removed slice system-getty.slice. <...> [ OK ] Reached target Shutdown. <...> Container debian-stretch-64 has been shut down. [email protected]:~ $ Arranging for the 64-bit Debian Guest OS Container to Start Automatically on Boot Now we have a working container (which you can backup when not running simply by running "sudo cp -ax /var/lib/machines/debian-stretch-64 <backup-location>" incidentally, should you wish to do so), we will next arrange for it to be started automatically at boot. That way, it'll always be available, and you'll be able to get a shell using ds64-shell or machinectl (and launch apps using ds64-run or systemd-run) at any time (instructions follow). Fortunately, systemd has a built-in mechanism (the [email protected] template) for starting up containers stored in the /var/lib/machines/ directory, as ours is. To leverage it, we first need to create a config file for our container. To do so, working back within the Raspbian desktop again, issue: Code: Select all [email protected]:~ $ sudo mkdir -pv /etc/systemd/nspawn [email protected]:~ $ sudo nano -w /etc/systemd/nspawn/debian-stretch-64.nspawn Code: Select all [Exec] PrivateUsers=no Capability=CAP_NET_ADMIN [Files] Bind=/home/pi Bind=/run/user:/run/host-user/ Bind=/etc/resolv.conf [Network] Private=no VirtualEthernet=no When systemd automatically starts a container, the default behaviour is slightly different from when launched using systemd-nspawn from the command line (for further details, see this manpage), hence the entries in the configuration file above: - By default, containers started by [email protected]service are booted, so we don't need to specify this here. - However, also by default such containers will be launched in a private namespace. We turn this off using the PrivateUsers=no directive, as user mapping makes e.g. sharing the pi user's home directory problematic. - Not obvious, but automatically started containers drop the CAP_NET_ADMIN capability (unless they have a private network namespace), so we re-instate it. - Just as before, we have to specify the bind-mount for user pi's home directory into the container. - We also bind mount the special directory /run/user to /run/host-user in the container. This will allow connection to the pulseaudio server socket [12]. - We also bind mount the DNS servers file, /etc/resolv.conf, so that changes to this are propagated into the container. - By default, automatically started containers run in their own network namespace, and don't share network interfaces or configuration with host. We don't want that, so we restore the default command-line-launched behaviour with Private=no. - Similarly, by default automatically started containers get a veth tunnel created back to the host (a sort of inter-network-namespace wormhole); this implies Private=yes, so we explicitly turn it off, with VirtualEthernet=no. Now we can create the startup service instance. To do so, simply issue: Code: Select all [email protected]:~ $ sudo systemctl enable machines.target [email protected]:~ $ sudo systemctl enable [email protected] Code: Select all [email protected]:~ $ sudo systemctl list-machines NAME STATE FAILED JOBS raspberrypi (host) running 0 0 debian-stretch-64 running 0 0 2 machines listed. Code: Select all [email protected]:~ $ sudo machinectl --setenv=DISPLAY="$DISPLAY" shell \ [email protected] /bin/bash Connected to machine debian-stretch-64. Press ^] three times within 1s to exit session. [email protected]:~ $ Final Tweaks to the 32-bit Raspbian Host OS You can now do any operations you like within the guest, it is a fully booted instance. For example, launch the "xeyes" program on the host desktop, and log out of the shell: Code: Select all [email protected]:~ $ xeyes& [email protected]:~ $ logout Connection to machine debian-stretch-64 terminated. [email protected]:~ $ Code: Select all [email protected]:~ $ systemd-run \ --setenv=DISPLAY="$DISPLAY" \ --setenv=QT_AUTO_SCREEN_SCALE_FACTOR=0 \ --setenv=PULSE_SERVER="unix:/run/host-user/1000/pulse/native" \ --uid=1000 --gid=1000 --machine=debian-stretch-64 \ /usr/bin/xeyes Note how we had to specify that the process run as the pi user (uid 1000 gid 1000), since root (inside the container) has no .Xauthority for the display, as we have things set up currently. If that worked, next set up a convenience script ds64-run (on the host), so that you can launch graphical 64-bit applications easily from within 32-bit Raspbian. Issue: Code: Select all Code: Select all #!/bin/bash # Run the specified application, with any arguments, in the # 64-bit Debian container, using the host OS' X-server and pulseaudio # server. Also include a QT fixup for apps like vlc that need it. sudo systemd-run \ --setenv=QT_AUTO_SCREEN_SCALE_FACTOR=0 \ --setenv=DISPLAY="${DISPLAY}" \ --setenv=PULSE_SERVER="unix:/run/host-user/1000/pulse/native" \ --uid=1000 --gid=1000 \ --machine=debian-stretch-64 \ "${@}" Code: Select all Code: Select all You can also setup a simple shorthand script to open a shell. Issue: Code: Select all Code: Select all #!/bin/bash # Open a shell as the pi user into the 64-bit Debian container. exec sudo machinectl shell \ --setenv=QT_AUTO_SCREEN_SCALE_FACTOR=0 \ --setenv=DISPLAY="${DISPLAY}" \ --setenv=PULSE_SERVER="unix:/run/host-user/1000/pulse/native" \ --uid=1000 \ debian-stretch-64 \ /bin/bash Code: Select all Code: Select all [email protected]:~ $ ds64-shell Connected to machine debian-stretch-64. Press ^] three times within 1s to exit session. [email protected]:~ $ xeyes Remember, it'll still be closed when you close the shell, so the preferred way to launch desktop apps from the container is to use the ds64-run command we just defined, issued from a host (Raspbian 32-bit) terminal. Congratulations, the final tweaks to your setup are now complete! Installing Larger Apps in the 64-bit Debian Guest Remember, you can do whatever you like in your 64-bit container. So to close, let's try installing and running a large 64-bit application, firefox. Close Xeyes if still open on your host desktop, and then, in the container shell that should still be open, issue: Code: Select all Code: Select all If you do, use "ds64-run /usr/bin/firefox %u" in the Command: field; the %u allows a URL to be passed. That's it, have fun! Useful Command Cheatsheet Here are some useful commands for working with your new raspbian-stretch-64bit container; most of these are in the main text above, but are gathered here for convenience. There's a lot more you can do of course, think of these just as a necessary minimum set. All the below commands are issued from a terminal in the host (32-bit Raspbian) OS. Check the status of all containers: Code: Select all Code: Select all Code: Select all Of course, when logged into the container, you can issue commands like journalctl, systemctl etc. directly. Get a (regular user) shell inside your 64-bit container (see earlier for the definition of this shorthand command): Code: Select all [email protected]:~ $ ds64-shell Connected to machine debian-stretch-64. Press ^] three times within 1s to exit session. [email protected]:~ $ You can open as many concurrent shells as you like. To exit the shell, just type logout, press ctrl-D, or press ctrl-] three times within a second. Operations like poweroff issued inside the container only affect the container - not your Rpi3 itself. Note that issuing reboot will not work properly when the container is managed by a service as here; better to use machinectl (as shown next) to stop and then start the container again. Networking identical to the host system is available (provided your host Raspbian OS has it configured), so you can ping, wget, apt-get, run web browsers etc. all from withing the container. By default, the pi user's home directory (only) is mapped inside the container for access. Stop (poweroff) the 64-bit container (will stop any apps running from within it): Code: Select all And start (boot) it again: Code: Select all Run a 64-bit application in the container, displaying on the host's desktop, and using the host's pulseaudio server (see earlier for the definition of this shorthand command): Code: Select all Prevent the container from starting at boot: Code: Select all Code: Select all To access files in the container from the host, remember that user pi's home directory is already mapped. The container's root directory prefix is /var/lib/machines/debian-stretch-64. There are many other options available. Please take the time to read the machinectl, systemctl and systemd-run manpages. Also please remember this is 'proof-of-concept', so many bugs and issues may remain! Pre-Built, Bootable System for RPi3 B and B+ If these instructions have intrigued you, and you'd like to try out a fully-operational RPi3 B/B+ bootable image that incorporates them, then please see my raspbian-nspawn-64 project on GitHub, here. Screenshot: Full download and usage instructions are on the GitHub page linked above. Have fun, sakaki Notes [1] Actually, systemd-nspawnd leverages (init-system-agnostic) technologies in the Linux kernel (for example, various forms of namespacing) to do most of the heavy lifting. On non-systemd platforms, such as my OpenRC based gentoo-on-rpi3-64bit image, the same effect can be achieved via the firejail app: see for example my notes on this here. [2] However, if booted in aarch32 mode, only aarch32 userland processes are allowed (unless you resort to emulation of some sort). [3] For further details on using KVM, please see my notes here and here. [4] However, at the time of writing, H/W acceleration for 64bit mode is on the verge of becoming available via V4L2, see e.g. this post. [5] It should also work with the RPi3A, RPi2 Bv2, CM3 and CM3L, since they also have a 64-bit SoC, but I don't have examples of any of those to check (and you need appropriate DTB files too). [6] The actual version tested was the 2018-11-13 release of "Raspbian Stretch with desktop". [7] Advanced users can just use "unzip -p raspbian_latest > /dev/sd<x> && sync && partprobe /dev/sd<x>" or similar to write the image. [8] It is relatively straightforward to compile your own kernel if you want to. See e.g. these notes. Gentoo users may also be interested in my own cross-compilation notes, here. [9] The only exception here are the dtb files, but we'll back these up prior to switching to the 64-bit kernel, and put the Raspbian package "raspberrypi-kernel" (which provides these files) on hold, so they won't get overridden. These changes can easily be reversed and indeed I will show how to do that in a follow-on post. [10] The Arch wiki has some nice detail on this process (here). Some further references that might be useful are Containerizing Graphical Applications On Linux With systemd-nspawn by J. Ramsden and Systemd and Containers: An Introduction to systemd-nspawn by A. Yemelianov. For further background on the underlying Linux technologies (viz.: namespacing, seccomp-bpf and capabilities) leveraged by "concessionaire" apps like systemd-nspawn, firejail and docker, see e.g. my notes here, here and here (of course, other facilities such as cgroups are also used). For more an introduction to the interaction of systemd-nspawn with other systemd tools, see e.g., systemd for Administrators, part XXI "Container Integration". [11] Both because piggybacking on the host's networking is easier (you can ping, wget etc. out of the box), but also because turning it on would restrict access to the host's Unix abstract domain sockets, and we need such access, to be able to use the host's X11 server (since in systemd-232, due to bug #4789, bind mounts in /tmp don't work properly). [12] See e.g "Running Steam in a systemd-nspawn Container". Note that we don't take the approach of bind-mounting /run/user/1000/pulse directly, as that will fail (source path not yet created) when systemd tries to bring the container up at boot time. We also don't bind /dev/snd, nor any of the /dev/{dri,shm}, as Debian's mesa doesn't seem to be able to make use of them even if they are there. If running an enhanced mesa, you could consider binding these; remember to write-enable them (via entries in "systemctl edit [email protected]", as suggested here) if you do. Appendices follow in next post (char limit ><) Edit: fix minor typos, mkdir omission.
https://www.raspberrypi.org/forums/viewtopic.php?f=56&t=232415
CC-MAIN-2020-10
refinedweb
6,166
59.13
This page details optimizations which are unique to iOS deployment. Most of the functions in the UnityEngine namespace are implemented in C/C++. Calling a C/C++ function from a Mono script involves a performance overhead, so you can save to save about 1 to 4 milliseconds per frame using iOS Script Call optimization. To access iOS Script Call optimization, navigate to the Player Settings window (menu: Edit > Project Settings > Player) and select the iOS icon (shown below). Locate the Script Call Optimization* setting in the _Other Settings section. The options for this setting are:- Unity iOS allows you to change the frequency with which your application will try to execute its rendering loop, which is set to 30 frames per second framerate, change Application.targetFrameRate. If accelerometer input is processed too frequently then the overall performance of your game may suffer as a result. By default, a Unity iOS application will sample the accelerometer 60 times per second. You may see some performance benefit by reducing the accelerometer sampling frequency and it can even be set to zero for games that don’t use accelerometer input. You can change the accelerometer frequency from the Other Settings panel in the iOS Player Settings.
https://docs.unity3d.com/560/Documentation/Manual/iphone-iOS-Optimization.html
CC-MAIN-2020-45
refinedweb
203
51.28
I am trying to turn on and off the backlight for the 7" official touchscreen using the "echo 1 / 0" commands. When I run the script I get a syntax on the line with the backlight command but I can't see what the issue is. I run the on and off line command in the command prompt and the screen reacts as it should. Below is the code I'm using. Code: Select all import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.PUD_UP) shutdownStarted = False while True: if (GPIO.input(25) == False and not shutdownStarted): os.system("sudo shutdown -h -57") echo 1 > /sys/class/backlight/rpi_backlight/bl_power # This stops the code inside this if from being executed again even if the pin stays False shutdownStarted = True secs = 57 * 60 # Run this loop once per second for 57 mins as long as shutdown is still supposed to happen while (secs > 0 and shutdownStarted): if (GPIO.input(25) == True): # This now allows the shutdown -h code to be run again # assuming you want this to execute forever based on the while True you got goin on there shutdownStarted = False os.system("sudo shutdown -c") echo 0 > /sys/class/backlight/rpi_backlight/bl_power time.sleep(1) secs -= 1 time.sleep(1)
https://www.raspberrypi.org/forums/viewtopic.php?p=1494178
CC-MAIN-2020-34
refinedweb
221
63.9
Reduce mental energy with C# 9 Learn how C# 9 makes things cleaner, more maintainable, and minimizes mental energy. Note: Originally published five months before the official release of C# 9, I’ve updated this post after the release to capture the latest updates. This is a humbling yet completely accurate fact: you spend much more time reading code than writing it. Any experienced programmer will tell you the reading-to-writing ratio is easily 5-to-1 or even 10-to-1. You’re understanding how things work. You’re hunting for bugs. You’re scrolling past code with thoughts like, “Nope, doesn’t apply … doesn’t matter, doesn’t matter …” until you have to pause and think, and spend a silly amount of time trying to understand how something works. It could be a developer trying to be clever, or an unfortunate function with an arrow-shaped pattern … you know, a variety of things. Whatever the case, it interrupts your flow. When you think how much time you spend reviewing code, it adds up and can turn into a big annoyance. For example, let’s say you’re trying to figure out a bug and you come across this C# 8 code. if (!(dave is Developer)) This is getting a little ridiculous. Nobody has time for this negation logic and double parentheses. Best case, it interrupts your flow and mental model. Worst case, you scan it and misunderstand it. I might sound crazy, I get it - this may have only taken an extra few seconds. But for a large application, hundreds of times a day? You see what I mean? Why couldn’t I do something like this? if (dave is not Developer) See? I completely understand this: I can keep scrolling or stop and know I’ve found my bug. If only I could do this, you think. If you aren’t aware, you can. This syntax, and other improvements, are available in the C# 9 release, released with .NET 5 in November 2020. C# 9 has a lot, but this post is going to focus on improvements that help restore valuable mental energy that is required in a mentally exhausting profession. And before you ask: no, C# 9 isn’t full of FDA-approved health benefits, but I’ve found some great stuff that helps make code cleaner, more maintainable, and easier to understand, and prevents a lot of “wait, what?” moments. Let’s take a look at what’s coming. This is just scratching the surface, and I’ll write about more features in-depth as I come across them. I think you’ll find the more you dive into C# 9, the more you appreciate its adoption of the functional programming, “no side effects” model. This post covers the following topics. - Records - Data member simplification - With-expressions - Top-level programs - Logical patterns - New expressions for target types - Playing with the C# 9 preview bits Records One of the biggest features coming out of C# 9 is the concept of records. Records allow an entire object to be immutable, meaning you can do value-like things on them. Think data, not objects. Let’s take a Developer record: public record Developer { public string FirstName { get; init; } public string LastName { get; init; } public string PreferredLanguage { get; init; } } Wait, what is init doing there? That is an init-only property, also new to C# 9. Before this, your properties needed to be mutable for them to be initialized. With init accessors, it’s like set except it can only be called during object initialization. Anyway, our record now gives us access to some other cool stuff that makes for some clean code. Data member simplification If we initialize our objects using constructors like this: var dev = new Developer("Dave", "Brock", "C#"); …we can declare a record this way instead: public record Developer(string FirstName, string LastName, string PreferredLanguage); With-expressions Much of your data is immutable, so if you wanted to create a new object with much, but not all, of the same data, you would do something like this (your use cases would be much more complicated, hopefully) are probably used to doing something like this in regular C# 8 with classes. using System; var developer1 = new Developer { FirstName = "David", LastName = "Brock", PreferredLanguage = "C#" }; // ... var developer2 = developer1; developer2.LastName = "Pine"; Console.WriteLine(developer2.FirstName); // David Console.WriteLine(developer2.LastName); // Pine Console.WriteLine(developer2.PreferredLanguage); // C# public class Developer(string FirstName, string LastName, string PreferredLanguage); { public string FirstName { get; set; } public string LastName { get; set; } public string PreferredLanguage { get; set; } } In C# 9, try a with expression instead, with your records: using System; var developer1 = new Developer { FirstName = "David", LastName = "Brock", PreferredLanguage = "C#" }; var developer2 = developer1 with { LastName = "Pine" }; Console.WriteLine(developer2.FirstName); // David Console.WriteLine(developer2.LastName); // Pine Console.WriteLine(developer2.PreferredLanguage); // C# public record Developer { public string FirstName; public string LastName; public string PreferredLanguage; } You can even specify multiple properties to just include what you need changed. This C# 9 example above is actually an example of a top-level program! Speaking of which… Top-level programs This is my favorite, even if I don’t write a lot of console applications. Inside your Main method you would typically see: using System; public class MyProgram { public static void Main() { Console.WriteLine("Hello, Wisconsin!"); } } No more of this silly boilerplate code! After your using statements, do this: using System; Console.WriteLine("Hello, Wisconsin!"); This will need to follow the Highlander rule - there can only be one - but the same argument applies to the Main() entry method in your console applications today. Logical patterns OK, moving on from records (for now). With the is not pattern we used to kick off this post, we showcased some logical pattern improvements. You can officially combine any operators with and, or, and not. A great use case would be for every developer’s battle: null checking. For example, you can easier code against null, or in this case, not null: not null => throw new ArgumentException($"Not sure what this is: {yourArgument}", nameof(yourArgument)) New expressions for target types Let’s say I had a Developer type that takes in a first and last name from a constructor. To create the object, I’d do something like this: Developer dave = new Developer("Dave", "Brock", "C#"); var dave = new Developer("Dave", "Brock", "C#"); With C# 9, you can leave out the type. Developer dave = new ("Dave", "Brock", "C#"); Playing with the C# 9 preview bits Are you reading this before the C# 9 release in November 2020? If you want to play with the C# 9 bits, some good news: you can use the LinqPad tool to do so with a click of a checkbox - no install required! Play with the latest experimental C# 9 features in LINQPad, including records and init-only properties. Just click a checkbox; no install required! pic.twitter.com/Jw3UEgwXyB— LINQPad·Joe Albahari (@linqpad) June 17, 2020
https://www.daveabrock.com/2020/06/18/reduce-mental-energy-with-c-sharp/
CC-MAIN-2021-39
refinedweb
1,160
54.83
Stopping Spambots: A Spambot Trap 312 Neil Gunton writes "Having been hit by a load of spambots on my community site, I decided to write a Spambot Trap which uses Linux, Apache, mod_perl, MySQL, ipchains and Embperl to quickly block spambots that fall into the trap. " Elements of good design I'd missed (Score:4, Informative) Eliminate mailto - makes sense. You should have an http based "send me a message system" - force a live person to type stuff in instead of letting a program pick out addresses. Eliminating mailto alone would probably help in mot of my spam problems (as I have my "contact me" address right on the first page). Re:Elements of good design I'd missed (Score:5, Interesting) Re:Elements of good design I'd missed (Score:2) Re:Elements of good design I'd missed (Score:2) Re:Elements of good design I'd missed (Score:2) Re:Elements of good design I'd missed - P.Solution (Score:2, Interesting) As described at [joemaller.com] you can combine JavaScript and Images to protect your mail. Made very good expiriences with this one.... But, as stated on the Website: this game is an arms race... Re:Elements of good design I'd missed (Score:2) Re:Elements of good design I'd missed (Score:2, Informative) Re:Elements of good design I'd missed (Score:2, Funny) I'm sure you don't want THAT kind of lawsuit. Re:Elements of good design I'd missed (Score:2) Dunno about skating, but blind people do ski. They are preceded by a guide who shouts them directions (or uses a wireless intercom, in order to not disturb the other skiers). Have seen such pairs several times at 2 Alpes. It must still be a helluva difficult, but they manage to do it anyways. Re:Elements of good design I'd missed (Score:2, Informative) I put my email address in a jpeg image. Haven't found a spambot yet that can decipher that. But neither could blind internet users... Add an alt tag that describes how to email you. Eg, "The first part of my email address is 'username' and the second part is 'host.com' - the two parts are separated by an '@' sign." I've been doing the jpeg thing for three years; works great. Re:problem with not giving an email address ... (Score:2, Insightful) The only problem with the idea of using entirely http based "send me a message systems" is that some people, like myself, would much rather have an actual email address to use instead of having to use 50 different layouts and 50 different configurations and 50 different methods of communicating with someone or a company. Every html based contact system has its own quirks and problems, I'd rather just need to learn my email programs issues instead. Re:problem with not giving an email address ... (Score:2) $0.02USD, -l Re:Elements of good design I'd missed (Score:3, Insightful) You're 100% right. And fighting against spambots by relying on UserAgent is akin to... well.... security thru obscurity, albeit somehow in reverse. What also looks strange is that he doesn't consider that one can get a link directly to a page on the n-th level: as human browsers don't usually download robots.txt either, sounds like he's gonna ban some poor guys who got a link from a friend... Re:Elements of good design I'd missed (Score:3, Informative) other solution: flash 8) (Score:2) don't worry, and google wil adapt. They read even pdf and new thought: make a site written in Re:other solution: flash 8) (Score:2) Tom. Here's a Javascript that writes mailto: links... (Score:3, Informative). Instructions for use are included in comments. The script fragment that replaces mailto: links in the page will actually shorten your code -- it only requires entering the username and domain once. Also, the @ sign is added in by the script, so the address itself never appears in your HTML. /.ed (Score:2, Funny) Re:/.ed (Score:3, Funny) Slashbot (Score:3, Funny) "I have a truly marvelous demonstration of this proposition which this bandwidth is too narrow to transmit." Block? Are you kidding? (Score:5, Interesting) No way, man. If you realize you're serving to a bot, go on serving. Each time the bot follows the "next page" link, you Give it thousands, millions of addresses this way. Re:Block? Are you kidding? (Score:5, Interesting) Re:Block? Are you kidding? (Score:5, Funny) Why is this a bad thing? They are owned by Verisign. How about instead, returning pages with the email address abuse@domain-that-spambot-is-coming-from all over them... This is also a good idea. In fact, I have a script which does a traceroute to the IP of the bot, and then looks up the admin contact using whois for the last couple of hops, and returns these. Oh, and for additional fun, throw in a couple of addresses of especially loved "friends"... Re:Block? Are you kidding? (Score:3, Funny) Like hotline@mpaa.org, cdreward@riaa.org, senator@hollings.senate.gov for example? Re:Block? Are you kidding? (Score:2) Re:Block? Are you kidding? (Score:2) Most spambots know better than to send their crap to email addresses containing things like abuse, root, postmaster, Also, in regard to the problem of root servers being queried every time a @randomdomain.com is looked up, could you not just use random IP addresses? Better Addresses To Feed Spiders (Score:3, Informative) If you're not messing with DNS, though, there are lots of addresses that can cause trouble: Teergrubes and other traps for spammers (Score:3, Informative) And somewhere out there is a far nastier variant on a teergrube that can keep a typical smtp session up for hours with only a few kilobits/minute, using tricks like setting TCP windows very small, NAKing lots of packets so TCP retransmits them, etc. (It basically works by saying "No, SMTP/TCP/IP isn't a set of protocol drivers in my Linux kernel, it's a definition of a set of messages and there's no reason I should user a bunch of well-tuned efficient reliable kernel routines when I can send raw IP packets myself designed for maximal ugliness." Re:Block? Are you kidding? (Score:3, Informative) From the website: Wpoison is a free tool that can be used to help reduce the problem of bulk junk e-mail on the Internet in general, and at sites using Wpoison in particular. It solves the problems of trapped spambots sucking up massive bandwidth/CPU time, as well as sparing legitimate spiders (say, google) from severe confusion. Re:Block? Are you kidding? (Score:3, Interesting) The bots don't fall for it anymore. Some dorks in Washington state decided to make a couple requests a second to it once, but in the two years I've had it up, they're the only ones. Re:Block? Are you kidding? (Score:2) Liberally sprinkled postmaster@127.0.0.1 and abuse]@127.0.0.1. Re:Block? Are you kidding? (Score:3, Interesting) Good idea but, I'm sure spam software has been rejecting 127.0.0.1 for many years. How about a few people volunteering real FQDNs that all resolve to 127.0.0.1? I realize that people would be volunteering horsepower and bandwidth for DNS lookups, but it would be in the name of dramatically reducing spam. Then, keep a list of all the "loopback FQDN's" and let the rest of us feed those FQDN's into spam-trap generators. Eventually, there would be so many real-looking spam trap email addresses that the spam software wouldn't be able to keep up with the list of loopback FQDN's. To take it to the next level, you could hide the list of "loopback FQDN's" by making a reverse DNS lookup against a couple of volunteered IP addresses return a random FQDN from the list of loopback FQDN's at the time that the spamtrap page is dynamically generated. Spammers would never know the entire list of FQDN's that resolve to loopback. Re:Block? Are you kidding? (Score:5, Interesting) I agree. And, come on, how much technology do you need? This is my solution to stopping spambots. It's in a JavaServlet technology and I am posting it here to prevent my company's site from being slashdotted. It does not prevent the spammer from harvesting emails it just slows them down.... a lot :) If everyone had a script like this, spambots would be unusable. Feel free to use the code in anyway you please (LGPL like and stuff) Put robots.txt in your root folder. Content:User-agent: * Disallow: Put StopSpammersServlet.java in WEB-INF/classes/com/parsek/util:package com.parsek.util; import java.io.File; import java.io.StringWriter; import javax.servlet.ServletContext; import java.net.URL; import java.util.Enumeration; import java.lang.reflect.Array; public class StopSpammersServlet extends javax.servlet.http.HttpServlet { private static String[] names = { "root", "webmaster", "postmaster", "abuse", "abuse", "abuse", "bill", "john", "jane", "richard", "billy", "mike", "michelle", "george", "michael", "britney" }; private static String[] lasts = { "gates", "crystal", "fonda", "gere", "crystal", "scheffield", "douglas", "spears", "greene", "walker", "bush", "harisson" }; private String[] endns = new String[7]; private static long getNumberOfShashes(String path) { int i = 1; java.util.StringTokenizer st = new java.util.StringTokenizer(path, "/"); while(st.hasMoreTokens()) { i++; st.nextToken(); } return(i); } public void doGet (javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException { response.setContentType("text/html; charset=UTF-8"); java.io.PrintWriter out = response.getWriter(); try { ServletContext servletContext = getServletContext(); endns[0] = "localhost"; endns[1] = "127.0.0.1"; endns[2] = "2130706433"; endns[3] = "fbi.gov"; endns[4] = "whitehouse.gov"; endns[5] = request.getRemoteAddr(); endns[6] = request.getRemoteHost(); String query = request.getQueryString(); String path = request.getPathInfo(); out.println("<html>"); out.println("<head>"); out.println("<title>Members area</title>"); out.println("</head>"); out.println("<body>"); out.println("<p>Hello random visitor. There is a big chance you are a robot collecting mail addresses and have no place being here."); out.println("Therefore you will get some random generated email addresses and some random links to follow endlessly.</p>"); out.println("<p>Please be aware that your IP has been logged and will be reported to proper authorities if required.</p>"); out.println("<p>Also note that browsing through the tree will get slower and slower and gradually stop you from spidering other sites.</p>"); response.flushBuffer(); long sleepTime = (long) Math.pow(3, getNumberOfShashes(path)); do { String name = names[ (int) (Math.random() * Array.getLength(names)) ]; String last = lasts[ (int) (Math.random() * Array.getLength(lasts)) ]; String endn = endns[ (int) (Math.random() * Array.getLength(endns)) ]; String email= ""; double a = Math.random() * 15; if(a if(a if(a if(a if(a if(a if(a if(a if(a if(a if(a if(a if(a email = email + "@" + endn; out.print("<a href=\"mailto:" + email + "\">" + email + "</a><br>"); response.flushBuffer(); Thread.sleep(sleepTime); } while (Math.random() out.print("<br>"); do { int a = (int) (Math.random() * 1000); out.print("<a href=\"" + a + "/\">" + a + "</a> "); Thread.sleep(sleepTime); response.flushBuffer(); } while (Math.random() out.println("</body>"); out.println("</html>"); } catch (Exception e) { out.write("<pre>"); out.write(e.getMessage()); e.printStackTrace(out); out.write("</pre>"); } out.close(); } } Put this in your WEB-INF/web.xml<servlet> <servlet-name>stopSpammers</servlet-name& gt; <servlet-class>com.parsek.util.StopSpammersS ervlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>stopSpammers</servlet-name& gt; <url-pattern>/members/*</url-pattern> </servlet-mapping> Here you go. No PHP, no APache, no mySQL, no Perl, just one servlet container. Ciao Re:Block? Are you kidding? (Score:4, Informative) <QUIET ON> <html><head><title>Members area</title></head><body> <p>Hello random visitor. There is a big chance you are a robot collecting mail addresses and have no place being here. Therefore you will get some random generated email addresses and some random links to follow endlessly.</p> <p>Please be aware that your IP has been logged and will be reported to proper authorities if required.</p> <DBOPEN "SpamFood", "localhost", "login", "password"> <FOR I=1 TO 100 STEP 1> <SQL select * from names order by rand() limit 1> <LET FN="$Name"> </SQL> <SQL select * from lasts order by rand() limit 1> <LET LN="$Last"> </SQL> <SQL select * from addresses order by rand() limit 1> <LET AD="$Address"> </SQL> <a href="mailto:$FN.$LN@$AD">$FN.$LN@$AD</a> <br> </FOR> </body> </html> Re:Block? Are you kidding? (Score:3, Insightful) Way too much work. Here's similar Escapade [escapade.org] code: Not similar enough. That makes 300 queries per hit against your database, and I don't think you even used prepared statements. His code slowed their software to a crawl by sleeping. Yours will slow your software to a crawl by excessive database traffic. Re:Block? Are you kidding? (Score:3, Informative) However, the instructions for installating Wpoison more or less assumes that one has a single website to protect. I have around 20 virtual hosts. So instead of creating a renamed cgi-bin in every DocumentRoot, I added a single ScriptAlias /runme/ "/var/www/cgi-bin/" to httpd.conf and then linked it like this: <A HREF="/runme/addresses.ext"><IMG SRC="pixel.gif" BORDER=0></A> I also added a single transparent pixel to the link to keep it invisible but still fool the spiders. Add the runme directory as excluded in the robots.txt and you should be on your way. Muhahahah, and so on. Problem with wpoison... (Score:3, Informative) Re:Block? Are you kidding? (Score:3, Insightful) No way, man. If you realize you're serving to a bot, go on serving. Each time the bot follows the "next page" link, you Give it thousands, millions of addresses this way. This would be good to do with known bad addresses, but random addresses only add more unknowing people to the list. You may add 1000 email addresses to the list and slow them down, but if even 10 of those email addresses are real, you've added to the problem. The bad addresses will be taken out as they are found to be bad, and the good ones will be left in. You've signed JoeRandomUser@RandomDomain.com up for all the spam he can handle, even if he has taken great lengths to keep his email address off the spam lists. In theory this sounds like a great idea, until your the guy getting your email address randomly fed to the bots. Re:Block? Are you kidding? (Score:2) Better yet, use a Spam Troll-box (Score:2, Interesting) A troll-box gives Spam-bots a place to send their spam. When this box intercepts the spam, it reports it to the Vipul's Razor network, and everyone else on this network becomes aware of that spam (if they are also using Vipul's Razor to filter, which, chances are they are, it will filter that spam if they get it). If Vipul's Razor isn't enough, one can even use something like SpamAssassin [taint.org] in conjunction with Vipul's Razor to get even better results. Of course, this isn't cutting off Spam-bots at their source... but if enough sites were to cut them off at their source, then I'd imagine the Spam-bot authors would get wise to this and devise a way around it. Whereas with something like a SPam Troll-box, the Spam-bots seem to still be working to those running the Spam bots Re:Block? Are you kidding? (Score:3, Insightful) Add a couple of sleep(20); into the cgi script that generates the bot fodder. The bot will still stay busy waiting for your webserver's response, but your script will exactly consume zero resources. For additional kicks, set up a DNS teergrube. Re:Block? Are you kidding? (Score:4, Interesting) Zero resources, except for memory. A much better solution would be to point the bot at a set of "servers" with IP addresses where you're running a stateless tarpit. http-referrer (Score:2) hmm, just a wild guess, but does this technique involve using the http-referrer to see if there are too many clients coming from just a particalar address (which would obviously be a *bad* thingy), and subsequently block them too? might explain why we can't see it no more I want it too!!! it seems to work pretty good! Re:http-referrer (Score:2, Interesting) I believe the exact quote in regards to why robots.txt should still be used is: "Most bad spambots don't even check the robots.txt file, so this is mainly for protection of the good bots." Another thing I find appealing is that on a large enough system the DB could be shared amongst several servers to provide common protection for all. I've always taken a don't put an address on the page approach, but it's cool to see someone looking at how these bots operate from a technical standpoint. Some ISPs (like mine) have policies against SPAM that stipulate that in addition to not actually spamming people, using their resources to prepare/collect addresses to SPAM is just as bad. The advantage the database gives you is that you can track the most recent offenders. A quick lookup to who owns the address, with hard evidence of one of their subscribers abusing both your system, and their policy will, if nothing else, cause the cost of spamming to rise. The reason SPAM is so popular is because it is VERY cheap to do. Once its costs approach those of 'traditional' marketing, things might get a bit more selective rather than sending my three year old '1-3 inches in 6 weeks!','Stop paying for cable', or 'Get out of debt now!' messages. Hardly directed. (Now I don't want anyone marketing to my three year old, but I know it will happen so I'd like to at least think they would be reasonable things, perhaps a bit relevant) How I track spammers using PHP (Score:5, Interesting) As it turns out, I really haven't received that much mail to this address. About the only mail I've ever received to it is someone from trafficmagnet.net, who tells me that I'm not listed on a few search engines and that I can pay them to have my site listed. I need to send her a nasty reply saying that I don't care about being listed on Bob's Pay-Per-Click Search Engine, and that if she had actually read the page, she would have noticed that she was sending mail to an invalid address. Besides, the web server is for my inline skate club and we don't have a $10/month budget to pay for search engine placement. I think I've received more spam from my Usenet posting history, from my other web site, and from my WHOIS registrations than I've received from the skate club web site. Hammered already.... (Score:5, Funny) The Problem: Spambots Ate My Website s/Spambots/Slashdot/ Re:Hammered already.... (Score:2) re: spidertrap (Score:4, Interesting) removing mailto: a bad solution (Score:5, Interesting) Removing mailto: links is a bad solution to the problem. It might be the only solution, but it is bad. I hate the editor in my web browser. No spell check (and a quick read of this message will prove who diasterious that is to me), not good editing ability, and other problems. By contrast my email client has an excellent editor, and a spell checker. Let me pull up a real mail client when I want to send email, please! In addition, I want people to contact me, and not everyone is computer literate. I hang out in antique iron groups, I expect people there to be up on the latest in hot tube ignition technology, not computer technology. To many of them computers are just a tool, and they don't have time to learn all the tricks to make it work, they just learn enough to make it do what they want, and then ignore the rest. Clicking on a mailto: link is easy and does the right thing. Opening up a mail client, and typing in some address is error prone at best. Removing mailto: links might be the only solution, but I hope not. So I make sure to regualrly use spamcop [spamcop.org]. Simple solution! (Score:3) 2) Trash any email sent to dedicatedaddress that doesn't have the [Question] tag in the subject. Hope this helps. Re:Simple solution! (Score:3, Insightful) Re:Simple solution! (Score:3, Informative) This seems to work fine (the window comes upo with the right email address in the to: line and the '[Question]' tag in the subject: line) in Netscape 4.76 and Lynx Version 2.8.3rel.1 and Mozilla 0.9.7, which implies Netscape 6.x, and Galeon will work as well, though I haven't tested these. A better solution: obfuscate the mailto: link (Score:5, Insightful) (Yes, I've posted about this before [slashdot.org], but it does work for me.) Browsers render it so users get the address they want, but spambots try to grab it from the raw html and get something meaningless. Re:A better solution: obfuscate the mailto: link (Score:5, Interesting) Some spambots will render that correctly. Less likely, though, is if they'll render an email that has had this [jracademy.com] done to it: it's encrypted through javascript. It is a rather impressive piece of work. Uses honest-to-god RSA. You could also encrypt all email addresses, and then in your spambot trap, put really really CPU intensive javascript. You'll win either way: either the spambot doesn't do javascript, and it won't get your addresses, or it does do javascript, and they've just spent an eternity wasting time. It would work the same way as a tarpit, but it wouldn't eat nearly so many resources on your end. If you're really clever, you could have the javascript do useful work, and then have the results of that work encoded into links in the page. You could then retrieve the results when the spider follows the link. There was an idea called hashcash floating arount a while back. The idea was that an SMPT server would refuse to deliver email if the sender didn't provide a hash collsion of so many bits to some given value. The sender has to expend way assymetrically more resources to generate the collision than it takes the reciever to check it. That way on can impose a cost on sending a lot of email. It's not so much to be a burden on ordinary users, but if you need to send thousands of emails, it will add up. The WOrld is now safe. (Score:2, Funny) Similar to how the new ORBZ works? (Score:4, Interesting) Re:Similar to how the new ORBZ works? (Score:4, Interesting) This is the same method I have been using for a while. I have an e-mail account called "cannedham" that I had posted on several web sites as a mailto: anchor on a 1x1 pixel graphic. Any e-mail sent to that address updates my Postfix header_checks file to protect the rest of my accounts. It works like a charm. Re: SpamBots: PHP Code (Score:2) { echo "\n<font size=\"-5\" style=\"display:none\"><a href=\"mailto:$Email\" } SeedFakeEmail("uce@ftc.gov"); SeedFakeEmail("listme@dsbl.org"); SeedFakeEmail("hotline@mpaa.org"); SeedFakeEmail("cdreward@riaa.org"); SeedFakeEmail("senator@hollings.senate.gov"); Put that in your pageheader and smoke it! Take a look in the mirror (Score:5, Informative) Superior Labs spambot_trap mirror [superiorlabs.com] -Spack A tip (Score:5, Informative) Here's a tip for those of you writing spambot traps... How about not blindly responding to the faked Return-Path address? Now that should be illegal. You people whine about your 10 spams a day, try 10,000 from 2000 different email addresses. Idiot postmasters should be caught and jailed. Re:A tip (Score:2) Although, the MTA would be looking at the envelope sender if it's any good, but most of the time those are faked too. he suggests formmail, another spam tool (Score:5, Informative) formmail itself (even the most recent version) can still be abused by spammers to use your webserver as a bulk mail relay - see the advisory at [monkeys.com] o ry . df It's a shame he didn't suggest the more robust formmail replacement at nms [sourceforge.net] which is maintained, and attempts to close all the known bugs and insecurities. Re:he suggests formmail, another spam tool (Score:2) But there are later versions of formmail that are patched, aren't there? Re:he suggests formmail, another spam tool (Score:2) I've seen it happen to sites I administer a number of times in the past, where individuals apparently using some sort of AOL name harvesting tool were using the formmail.pl scripts to send mass messages. Looking at the User-Agent headers, it looks like there's a VB script out there designed specifically to automate this exploit. Removing the Mailto: may not be the best plan.. (Score:5, Interesting) <script>document.write("<A CLASS=\"link\" HREF=\"mailto: " + "myname" + String.FromCharCode(64) + "mydomain"</script> Seems to work fine. Anyone know of any reason it shouldn't, or have any other way to keep down spam without totally removing the Mailto: ? I know this won't work with *every* browser, but it beats totally removing mail links. And I don't think spammers can get it without having a human actually look at the page... Re:Removing the Mailto: may not be the best plan.. (Score:2) Re:Removing the Mailto: may not be the best plan.. (Score:4, Interesting) <img src="myemailaddress.jpg" alt="me at domain dot com"> that way people who use browsers that speak (ie. the blind) would still hear your address correctly, so long as spambots don't start to pick up on the spelling out of "at" and "dot". Re:Removing the Mailto: may not be the best plan.. (Score:2) Re:Removing the Mailto: may not be the best plan.. (Score:3, Interesting) We embed this JavaScript code on each page that needs mailtos: <script type="text/javascript" language="JavaScript1.3"> function n_mail(n_user) { self.location = "mailto:" + n_user + "@" + "yourdomain" + "." + "com"; } </script> And then make email address links of this form: <a href="javascript:n_mail('foo');">foo<!-- antispam -->@<!-- antispam -->yourdomain<!-- antispam -->.<!-- antispam -->com<!-- antispam --></a> Our addresses even show up correctly in lynx, but are "clickable" only in JavaScript-enabled browsers. Of course, it's probably only a matter of time before spambots can compensate for this code. A more secure approach would be to put email addresses "components" in borderless cells of tables, or as a previous poster suggested, in images. Similar setup without SQL requirements (Score:4, Interesting) Setup details at [bero.org] Another way to stop spambots (Score:3, Funny) Removing email addresses (Score:2) You can generate the code for your own email address here [pgregg.com] or, if you want some source code, then you can find an implementation of it here [uk.net]. my spambot trap (Score:4, Informative) script that traps bots (and others) that use your robots.txt to find directories to look through. Requires an robots.txt ################# User-agent: * Disallow: Disallow: Disallow: dont_go_here/index.php ############ $now = date ("h:ia m/d/Y"); $IP=getenv(REMOTE_ADDR); $host=getenv( $your_email_address=you@whatever; $ban_code = "\n". '# '."$host banned $now\n". 'RewriteCond %{REMOTE_ADDR} ^'."$IP\n". 'RewriteRule ^.*$ denied.html [L]'."\n\n"; $fp = fopen ("/path/to/.htaccess", "a"); fwrite($fp, $ban_code); fclose ($fp); mail("$your_email_address", "Spambot Whacked!", "$host banned $now\n"); Re:my spambot trap (Score:2) How about rewriting denied.html each time to contain a list of e-mail addresses in the format: abuse@banned_host [mailto] That way, the spammers might actually spam their own ISP's abuse account. Now THAT would be funny! :-) Other options.. (Score:4, Informative) A pretty good article, but being able to install modules into Apache may not be the best situation for everyone who wants to stop Spambots.. Shameless plug, but I've got an ongoing series in the Apache section of /. that deals with easy ways that administrators *and* regular users can keep Spambots off their sites: Stopping Spambots with Apache [slashdot.org] and Stopping Spambots II - The Admin Strikes Back [slashdot.org] Just some more options and choices to help people out! using images is bad for people with text browsers (Score:2, Insightful) And of course if he uses ALT text for the images, then he has the same problem he was trying to avoid, of creating something the spambots can read. Another Method (Score:2) How about sending a parameter to a page which redirects to the mailto: protocol? For example: index.html <a href="filename.php?x=info">E-Mail Me</a> filename.php <?php Header ("Location: mailto:" + $x + "@mydomain.tld") ?> Take this one step further... (Score:4, Interesting) You'd have a standardized spambot trap (like the one described in the article) on various webservers. The new spambot info could go into a "New SpamBots" database (which wouldn't be blocked). Once a day, the webserver would connect up with a central database and submit the new spambot info it's obtained. Then the server would download a mirror of the updated "SpamBots" database which it would use to block spambots. The centralized SpamBots database would take all of the new SpamBot info every day and analyze them in some manner as to detect abuse of the system (ensuring that only true spambots are entered). E-mails could be fired off to the abuse/postmaster/webmaster for the offending IP address. Finally, the new SpamBot info would be integrated into the regular SpamBot database. This way you'd be able to quickly limit the effectiveness of the Spambot-traps across many websites. Alas, not practical... (Score:2) Attn Spambot Authors (Score:5, Interesting) Thanks again for your interest. I hope that we were able to help you write the spambots of the future that will be able to detect and sidestep as many of the above protection schemes as possible. We tried to work all of our knowledge into one convienient thread for your development team to peruse. Thanks for your interest in SlashDot, home of too much information. wonder what this means.. (Score:2) Let's feed the serpent its own tail (Score:2, Interesting) Well, I didn't trust (1), and (3) just got me a voice mail box instead of a person I could chew out, which I didn't use. That left (2), and I had a wicked idea: I hit 2, and input the number that I should call if I was interested in the fax (which appeared in BIG text right above the little text). Their own response number should start eventually getting faxes from them or, as I tend to experience, hangups. Cute story, I know, but what does this have to do with defeating spambots? I went to the page indicated... And I scrolled to the bottom, and looked at the source code, and noted two faaaaaascinating things: First, the HTML on that page is rather clean; I can see no evidence of anti-spambot code on their page. And second, the "Contact Us" link at the bottom is a mailto:. By all appearances, their page is vulnerable to their own spambot. So I had the thought... what if those generated-random-email-address pages were geared to produce not-so-random email addresses? What if the email addresses on those generated-page traps were geared to generate random email addresses at the domains of the various spambot-- (err, I mean) harvester producing companies? Let them see what it's like when less than discerning spammers use their software for evil. Hundreds of Viagra-substitutes! Thousands of hangover cures! Tens of thousands of opportunities to refinance their home mortgage! This is just an off-the-top-of-my-head idea. Opinions? I use two methods on my site.... (Score:2) On stuff like my FAQs, I use igPay Latin Encoded Email: ahgaray atyay ahgaray otday omcay Note to self (Score:2, Funny) What I use (Score:3, Interesting) <A HREF="mailto:hosting%40slickhosting.com" onMousehostingsli <!-- Spam trap abuse@ (your domain) HREF="mailto:abuse@ (your domain) " root@ (your domain) HREF="mailto:root@ (your domain) " postmaster@ (your domain) HREF="mailto:postmaster@ (your domain) " uce@ftc.gov HREF="mailto:uce@ftc.gov" --> Don't stop spambots, feed them with Sugarplum (Score:3, Interesting) the danger of mailing lists.. esp. SuSE user list (Score:3, Informative) What about a Terms of Service page (Score:2, Interesting) The page could have a form with "Accept TOS" and "Reject TOS" buttons. I wonder how many spambots would submit a form? And to catch spambots that did submit the form, your TOS could have some clauses that make it a violation for evil spiders (ones that don't honor "robots.txt") to use the site. Maybe you could make||lose a few bucks suing the spambotters who go through the TOS and still harvest your email addresses. New Program - Mailwasher (Score:4, Interesting) Anyway, AFAIK, it's WinBlows only, and available at [mailwasher.com], although right now it seems the site is down, all I get is a 404! (Score:3, Informative) A friendlier solution. (Score:2) I wrote a bit of PHP a few months ago that applied some spamproofing ala SlashDot (only a bit less agressive) that some might find useful. Highlighted Source [aagh.net] Raw Source [aagh.net] It performs the following munging, depending on what you specify: freaky@aagh.net freaky (at) aagh (dot) net freaky@aagh.N0SPAM.net.SPAMN0 freaky@aag&# 104;.net random one of the above random with entity encoding all of the above MIRROR MIRROR (Score:2, Informative) How about trying this (Score:2, Interesting) How about writing something for these spambots using a special web server that slowly responds to it's requests (sends out a small packet every 10 seconds) so it won't time out and won't consume much cpu time, and just feeds it a line or two lines of junk with each packet. Have it randomly generate a never ending supply of useless information to keep the spambot happy. While it's busy with the useless site, it's not bothering other people nor is it getting any real addresses. Re:Now, let's fake the other end. (Score:2) Re:Pollute their database (Score:2, Insightful) Think about it. With the scarcity of domain names lately, chances are that while the garbage email addresses may not be valid, more than a few domain names would be valid. So then the spammer fills his database with these non-existant addresses on existing domain names. He then sends his spam to these addresses, and their mail servers not only have to process the message to determine that it's an invalid address, but they also have to bounce the message back as undeliverable. IMO this is going to use twice the bandwidth, since you now have to consider the bandwidth used by all of those bounces. You could always use some non-existant domain names for the garbage email addresses, but the spammer could just as easily check a domain name's validity before sending spam to it, making it trivial to remove all of the trash from his database. Remember, the spammer couldn't care less about sending mail to bad addresses, as long as the good addresses are spammed as well. It's left to the poor sysadmin to clean up the mess. Re:Pollute their database (Score:2) Remember, the spammer couldn't care less about sending mail to bad addresses, as long as the good addresses are spammed as well. True, but the their address lists will depreciate in value because the authenticity of most of the addresses would be in doubt. Re:Pollute their database (Score:2) I am fully aware of the non-com/net/org TLDs...just look at *mine* Re:Okay... (Score:2) Matter of fact, I think it'd be a good idea to have an open-source email harvester. . . it'd give the good guys an idea of what works and what doesn't, and of course the open-source version would be free, polite to webservers, and best of all would steal thousands of sales from the real bad guys, the fellows who write spambots. (ObPipeDream) With any luck one of them would steal the code and resell it, and the GPL could get a slam-dunk court test. Better than a honeypot.. (Score:2) 1. Publish false mailto: addresses on your web pages in the same colour font as your background 2. Change them to visible, valid addresses by munging them with DHTML properties and a JavaScript include file (sorry, Lynx users) 3. When a recognizable spam-bot comes in, refuse to load the javascript include file. mod_setenvif and mod_rewrite should help out here. 4. When a probable spam-bot comes in, serve up the page reaalllly slowly, don't close the connection until it goes in CLOSE_WAIT. This ties up sockets on the remote machine and reduces its ability to troll OTHER sites. You can do this by writing a handler for your base directory, checking the browser, and returning DECLINED for friendly people. That should be in, I think the "post read" phase. 5. When a recognized bad address comes through to your mail server (from step 1), slooooow the SMTP transaction down as much as you can (same idea as step 4), and throw an error at the end of the 354 DATA section a few times (to force him to come back!), etc. (Some sendmail internals hacking required here, although it would be much easier to hack if you don't have any real mail and just ran a script from inetd.) 6. Those fake email addresses. Make them all point to a common MX or group of MXes that you control the DNS for. Make sure those MX records aren't used by anything legitimate. Slooooow your in.named down for requests to that domain. A cool side effect, besides tying up sockets on the spammers end, IIRC some OSs can only make one resolver request at a time -- this'll effectively block all of his out outbound spam traffic while he's trying to look up your MX record! Also, make sure the TTL is set to about 10 seconds, just to make sure he comes back the glue trap very often. How's *that* for spam countermeasures? I wish I had time to write it.
http://tech.slashdot.org/story/02/04/12/122259/stopping-spambots-a-spambot-trap
CC-MAIN-2014-42
refinedweb
6,555
65.22
Hi I am just wondering I need to create multiple data object variables on lots of different JavaScript file throughout my project that all have the same keys. These object will be used as a data source for a package I have to use. for example { V1: 0, V2: 0, V3: 0. } var i = new iVar(); class outputData { constructor(){ this.O0 = 0; this.O1 = 0; this.O2 = 0; this.O3 = 0; this.O4 = 0; this.O5 = 0; this.O6 = 0; this.O7 = 0; this.O8 = 0; this.O9 = 0; this.O10 = 0; this.O11 = 0; this.O12 = 0; } } import '../OutPutDataClass.js'; var openingDeb = new outputData(); Uncaught ReferenceError: outputData is not defined(…) The issue isn't with your class definition (as far as I can tell, it's fine!) - it's with your understanding of how the ES2015 import syntax works. There's no 'global scope' so to speak - if you want to export/import something, you have to be explicit about it, like so: File 1: export default class OutputData { constructor(){ ... } } File 2: import OutputData from '../OutPutDataClass.js'; var openingDeb = new OutputData();
https://codedump.io/share/rirYOJZU6qpm/1/data-objects-amp-classes
CC-MAIN-2016-50
refinedweb
182
72.42
NDARRAY IN NUMPY In this tutorial, we are going to learn about ndarray in numpy and how to construct one. We will also learn about the syntax of an nd array and how to find out shape, type and data type of it. What is ndarray? ndarray is an array class in Numpy, it is also known as array. It is not as same the array.array that we use in Python because that only handles a single dimensional array and have limited functionality. Array object consists of a multidimensional array of fixed-size items. Arrays is a list of elements i.e. numbers of the same data type. You can access the elements present in Numpy by using square [ ] brackets. Elements in Numpy arrays are accessed by using square brackets and can be initialized by using nested Python Lists. You can find out about the number of dimensions of an array through its shape. The common syntax of declaring a numpy array is: array_name = module_name.array( [ list of numbers ] ) The number of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers that specify the sizes of each dimension. For example, let’s construct a 2-dimensional array of 2×2. First import numpy in your python editor: import numpy as np arr = np.array([[ 1, 2], [ 4, 2]]) arr Think of 2-D arrays as matrices that has rows into columns (r x c), you can always specify the rows and columns of an array by utilizing the shape method, similarly you can find the type and data type of the array as well by using the type and data type methods: import numpy as np arr = np.array([[ 1, 2], [ 4, 2]]) print(arr) #Shape of an array print("Shape of an array is: " , arr.shape) #Type of an array print("Type of an array is: ", type(arr)) #Datatype of an array print("Data type of an array: ", arr.dtype)
https://python-tricks.com/ndarray-in-numpy/
CC-MAIN-2021-39
refinedweb
332
71.55
Hi, I've been trying to get a simple perforce edit command working... this is what I have so far:! This is the signature of the exec command (look at \Sublime Text 2\Packages\Default\exec.py) def run(self, cmd = ], file_regex = "", line_regex = "", working_dir = "", encoding = "utf-8", env = {}, quiet = False, kill = False, # Catches "path" and "shell" **kwargs): If I was you, I first try to set the working_dir argument and/or the shell argument (set it to true).If I remember well, the executed command is printed in the console. Good luck. Ok, I tried adding those options... not sure if I did it right, import sublime, sublime_plugin, os class P4EditCommand(sublime_plugin.TextCommand): def run(self, edit): if self.view.file_name(): folder_name, file_name = os.path.split(self.view.file_name()) self.view.window().run_command('exec', {'cmd': 'p4', 'edit', file_name], 'working_dir':folder_name, 'shell':True} ) All it outputs now is: Perforce -- the Fast Software Configuration Management System. p4 is Perforce's client tool for the command line. Try: p4 help simple list most common commands p4 help commands list all commands p4 help command help on a specific command usage generic command line arguments p4 help views help on view syntax The full user manual is available at. Server 2010.2/322263. [Finished] I've checked the values of the variables and this seems to work from the command line just fine. BTW, is there an easy way to print debug text to the python console from inside sublime? I'm sure this is a simple syntax thing, but I'm having trouble finding examples of anything similar. What you see is the exec output buffer, to show the console go to menu View -> Show ConsoleTo print something in the console from Python plugin: print "My text:", file_name Doesn't know Perforce client so difficult to help you, look like something wrong with the arguments. You could try to make a Build file () maybe you will have better luck.The Build system use the exec command, so if your Build file work, there must be an exec command that work the same. Thanks for the help... got this working ok now. I added a status bar notification. I put everything in a gist here: Enjoy!
https://forum.sublimetext.com/t/executing-a-shell-command-with-proper-environment/1908
CC-MAIN-2016-44
refinedweb
372
64.3
If you're not logging, you're doing it all wrong. (part 1) Guest Author: Pure Krome - If you're not logging, you're doing it all wrong - Levelling up your Logging Part 1: If you're not logging, you're doing it all wrong. . What this is not about: - Not an opinion piece about why you should be logging your code. Google for that, then come back when you're convinced that you need it. - This is not a lesson in Dependency Injection. Don't know that? Google it then come back. - Nor is this a lesson in NLog, AutoFac or NancyFX / ASP.NET MVC (sample tools we use in this example) - Nor will I explain how to setup an account and 'hosts' with LogEntries (what the hell is LogEntries? I'll explain that later). - Nor will I explain what/how are web.config transformations. If you're not logging, then you're doing it all wrong. You build websites or mobile/desktop applications. Awesome. Therefore, you need to know what is happening during runtime of your live/production application, otherwise you're flying blind. The trick to logging a .NET application is to make sure that you leverage a logging interface all over your code. Based upon your solution's configuration (ie. DEBUG or RELEASE or ANY_OTHER_CUSTOM_CONFIG) we leverage web.config transformations to use the appropriate logging targets, based on the configuration. Note: Target = a fancy word for where we dump our logging information to. This could be the console or a file or another gui-application (more on this, later) or some internet website (also more on this magic, later). Tools - we need tools! Then general idea is this - Code your message(s): "Hi, I'm here." or "OMG, BOOM" or "Just created a new user. UserId: '1'.". - NLog sends the message somewhere: your GUI app, or email, or a logging website. - View the messages: use Sentinal (localhost) or LogEntries (production). And where do we visualize this data again? - Sentinal: A free windows app that displays log information, as it streams in live. (yes, ~~streams~~ in …) - LogEntires: A website that stores your log entry information, which you can view it at any time. Also has a live stream. Free account limits data retention to a week .. which for most people (especially when you're testing/debuging) is totally sufficient. Okay so when to use what? - Sentinal: use this for localhost debugging. - LogEntires: use this for live/production system. Pro Tip: Yes, you can use Sentinal for live/production if you really want to. But this involves setting up NAT rules in your firewall, opening ports on your local firewall, etc. Basically - a PITA vs using LogEntries which is for free. Show me some code, already! Sheesss… Fine. Let's do this: LEEEEROOYYYYY JENKINNNNNSSSSSSS…… Step 1. Download & install Sentinal. Step 2. Create/Setup a new solution. eg. File -> New -> Web Application. Step 3. Lets add some logging information. First, we need an existing logging interface package. Next we'll use DI/IOC to inject the logging instance, so lets wire that up first. NancyFX: (This is using TinyIOC for IoC (which is built into NancyFX)) protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); // NOTE: Use a specific constructor, which is why we have to use the delayed registration. var loggingService = new NLogLoggingService(); container.Register<ILoggingService>((c, p) => loggingService); // Register any other singleton services. // … } ASP.Net MVC (This is using AutoFac for IoC) public static class DependencyResolutionConfig { public static void RegisterContainers() { var builder = new ContainerBuilder(); // Register our services. builder.Register(c => new NLogLoggingService()) .As<ILoggingService>(); // Register our controllers (so they will use constructor injection) builder.RegisterControllers(typeof(MvcApplication).Assembly); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } Now we'll use constructor injection for our logging interface. Side Note: I do not consider injecting an ILoggingService into classes as an Anti-Pattern because IMO I usually log things in all methods (I'll touch on this, below) so therefore, logging is a fundamental part of each class that contains business logic. As such, my class has a logging dependecy throughout. Not on 1 or some methods, only. NancyFX using System; using Nancy; using Shouldly; using SimpleLogging.Core; namespace SimpleLogging.Samples.NancyFX.Modules { public class HomeModule : NancyModule { private readonly ILoggingService _loggingService; public HomeModule(ILoggingService loggingService) { loggingService.ShouldNotBe(null); _loggingService = loggingService; Get["/"] = _ => GetHome(); } private dynamic GetHome() { _loggingService.Trace("GetHome"); _loggingService.Debug("Current DateTime: '{0}'", DateTime.UtcNow); return View["home"]; } } } ASP.NET MVC using System; using System.Web.Mvc; using Shouldly; using SimpleLogging.Core; namespace SimpleLogging.Samples.MVC.Controllers { public class HomeController : Controller { private readonly ILoggingService _loggingService; public HomeController(ILoggingService loggingService) { loggingService.ShouldNotBe(null); _loggingService = loggingService; } // // GET: /Home/ public ActionResult Index() { _loggingService.Trace("Index"); _loggingService.Debug("Current DateTime: '{0}'", DateTime.UtcNow); return View(); } } } Step 4. Add an NLog file. Add this new file to the root website / application folder. nlog.config <?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="" xmlns: <!-- NLog example: --> <targets async="true"> <target xsi: </targets> <rules> <logger name="*" minlevel="Trace" writeTo="sentinal"/> </rules> </nlog> Step 5. Run Sentinal Step 6. Run the website. Recap. So now we've started sprinkling logging messages throughout our code. This gives us some Serious.KickAss™ insights into what is going on under the hood with our code. We view this logging data locally with our Sentinel app. It's not hard to add logging to your website / application. Please start to get into the habbit of TRACEing and DEBUGing your code so you can see what's going on under the hood - when you really need to. NEXT: Part 2 - Levelling up your Logging In the next part, I take all this simple logging magic to the next level : doing this for your live / production website / application!comments powered by Disqus
http://www.philliphaydon.com/2014/04/23/if-youre-not-logging-youre-doing-it-all-wrong/
CC-MAIN-2017-09
refinedweb
962
52.66
pusher-js 3.0.0 released offered native WebSocket support and used an in-browser Flash proxy fallback mechanism for older browsers called web-socket-js. In 2013 we released 2.0.0 and added multiple HTTP-based fallback options. In 3.0 we are removing the legacy Flash fallback. Right now connections via Flash represent only 0.2% of all our connections and we hope to get this down to 0 by the end of the year. Any traffic that previously used Flash fallback will now use the HTTP fallback mechanisms. UMD wrapper & published to NPM In order to support modern JavaScript development practices we’ve added a UMD (Universal Module Definition) wrapper to pusher-js and published pusher-js to NPM. The UMD wrapper makes it easier to use the library with tools such as Browserify, webpack and jspm. This means you can write code as follows where you can require('pusher-js'): var Pusher = require('pusher-js'); Pusher.log = function(msg) { console.log(msg); }; function App() { this.pusher = new Pusher('YOUR_KEY'); } var app = new App(); Or as follows using an ES6 transpiler such as Babel: import Pusher from 'pusher-js'; class Main { constructor() { Pusher.log = function(msg) { console.log(msg); }; var pusher = new Pusher('YOUR_KEY'); } } var main = new Main(); There’s a simple pusher-js NPM basics repo if you’d like to investigate this further. Help us improve our libraries Our documentation, developer tooling and libraries provide an essential first impression of the Pusher product, so the developer experience needs to be a great one. Our libraries in particular are the integration point between our customers apps and our service so they need to be rock solid, well engineered, simple to install, have great documentation and be highly intuitive to use. So, we’re looking for developers to joint a new team in our Engineering department who will improve on the features of our current product and develop new ones to go alongside it. Please head to to find out more.
https://blog.pusher.com/pusher-js-3-0-0-released/
CC-MAIN-2018-26
refinedweb
335
55.44
A question I often receive via my blog and email goes like this: Hi, I just got an email from a Nigerian prince asking me to hold some money in a bank account for him after which I’ll get a cut. Is this a scam? Hi, I just got an email from a Nigerian prince asking me to hold some money in a bank account for him after which I’ll get a cut. Is this a scam? The answer is yes. But that’s not the question I wanted to write about. Rather, a question that I often see on StackOverflow and our ASP.NET MVC forums is more interesting to me and it goes something like this: How do I get the route name for the current route? How do I get the route name for the current route? My answer is “You can’t”. Bam! End of blog post, short and sweet. Joking aside, I admit that’s not a satisfying answer and ending it there wouldn’t make for much of a blog post. Not that continuing to expound on this question necessarily will make a good blog post, but expound I will. It's not possible to get the route name of the route because the name is not a property of the Route. When adding a route to a RouteCollection, the name is used as an internal unique index for the route so that lookup for the route is extremely fast. This index is never exposed. Route RouteCollection The reason why the route name can’t be a property becomes more apparent when you consider that it’s possible to add a route to multiple route collections. var routeCollection1 = new RouteCollection(); var routeCollection2 = new RouteCollection(); var route = new Route("{controller}/{action}", new MvcRouteHandler()); routeCollection1.Add("route-name1", route); routeCollection2.Add("route-name2", route); So in this example, we add the same route to two different route collections using two different route names when we added the route. So we can’t really talk about the name of the route here because what would it be? Would it be “route-name1” or “route-name2”? I call this the “Route Name Uncertainty Principle” but trust me, I’m alone in this. Some of you might be thinking that ASP.NET Routing didn’t have to be designed this way. I address that at the end of this blog post. For now, this is the world we live in, so let’s deal with it. I’m not one to let logic and an irrefutable mathematical proof stand in the way of me and getting what I want. I want a route’s name, and golly gee wilickers, I’m damn well going to get it. After all, while in theory I can add a route to multiple route collections, I rarely do that in real life. If I promise to behave and not do that, maybe I can have my route name with my route. How do we accomplish this? It’s simple really. When we add a route to the route collection, we need to tell the route what the route name is so it can store it in its DataTokens dictionary property. That’s exactly what that property of Route was designed for. Well not for storing the name of the route, but for storing additional metadata about the route that doesn’t affect route matching or URL generation. Any time you need some information stored with a route so that you can retrieve it later, DataTokens is the way to do it. DataTokens I wrote some simple extension methods for setting and retrieving the name of a route. public static string GetRouteName(this Route route) { if (route == null) { return null; } return route.DataTokens.GetRouteName(); } public static string GetRouteName(this RouteData routeData) { if (routeData == null) { return null; } return routeData.DataTokens.GetRouteName(); } public static string GetRouteName(this RouteValueDictionary routeValues) { if (routeValues == null) { return null; } object routeName = null; routeValues.TryGetValue("__RouteName", out routeName); return routeName as string; } public static Route SetRouteName(this Route route, string routeName) { if (route == null) { throw new ArgumentNullException("route"); } if (route.DataTokens == null) { route.DataTokens = new RouteValueDictionary(); } route.DataTokens["__RouteName"] = routeName; return route; } Yeah, besides changing diapers, this is what I do on the weekends. Pretty sad isn’t it? So now, when I register routes, I just need to remember to call SetRouteName. SetRouteName routes.MapRoute("rName", "{controller}/{action}").SetRouteName("rName"); BTW, did you know that MapRoute returns a Route? Well now you do. I think we made that change in v2 after I begged for it like a little toddler. But I digress. MapRoute Like eating a Turducken, that code doesn’t sit well with me. We’re repeating the route name twice here which is prone to error. Ideally, MapRoute would do it for us, but it doesn’t. So we need some new and improved extension methods for mapping routes. public static Route Map(this RouteCollection routes, string name, string url) { return routes.Map(name, url, null, null, null); } public static Route Map(this RouteCollection routes, string name, string url, object defaults) { return routes.Map(name, url, defaults, null, null); } public static Route Map(this RouteCollection routes, string name, string url, object defaults, object constraints) { return routes.Map(name, url, defaults, constraints, null); } public static Route Map(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces) { return routes.MapRoute(name, url, defaults, constraints, namespaces) .SetRouteName(name); } These methods correspond to some (but not all, because I’m lazy) of the MapRoute extension methods in the System.Web.Mvc namespace. I called them Map simply because I didn’t want to conflict with the existing MapRoute extension methods. System.Web.Mvc Map With these set of methods, I can easily create routes for which I can retrieve the route name. var route = routes.Map("rName", "url"); route.GetRouteName(); // within a controller string routeName = RouteData.GetRouteName(); With these methods, you can now grab the route name from the route should you need it. Of course, one question to ask yourself is why do you need to know the route name in the first place? Many times, when people ask this question, what they really are doing is making the route name do double duty. They want it to act as an index for route lookup as well as be a label applied to the route so they can take some custom action based on the name. In this second case though, the “label” doesn’t have to be the route name. It could be anything stored in data tokens. In a future blog post, I’ll show you an example of a situation where I really do need to know the route name. As an aside, why is routing designed this way? I wasn’t there when this particular decision was made, but I believe it has to do with performance and safety. With the current API, once a route name has been added to a route collection with a name, internally, the route collection can safely use the route name as a dictionary key for the route knowing full well that the route name cannot change. But imagine instead that RouteBase (the base class for all routes) had a Name property and the RouteCollection.Add method used that as the key for route lookup. Well it’s quite possible that the value of the route’s name could change for some reason due to a poor implementation. In that case, the index would be out of sync with the route’s name. RouteBase Name RouteCollection.Add While I agree that the current design is safer, in retrospect I doubt many will screw up a read-only name property which should never change. We could have documented that the contract for the Name property of Route is that it should never change during the lifetime of the route. But then again, who reads the documentation? After all, I offered $1,000 to the first person who emailed me a hidden message embedded in our ASP.NET MVC 3 release notes and haven’t received one email yet. Also, you’d be surprised how many people screw up GetHashCode(), which effectively would have the same purpose as a route’s Name property. GetHashCode() And by the way, there are no hidden messages in the release notes. Did I make you...
http://haacked.com/archive/2010/11/28/getting-the-route-name-for-a-route.aspx
CC-MAIN-2013-20
refinedweb
1,404
73.47
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Mikael, As I mentioned in #debian-mentors yesterday, I find it difficult to justify a Debian package for a tool that could be replaced by existing tools like "awk /foo/,EOF" much less a package and binary name that are so generic. We try to avoid generic program names in the $PATH namespace (like "node", for instance...). I realise that you've done a lot of work learning how to package this and you'd like to see your work included in Debian. Perhaps I could encourage you to contribute to existing packaging teams where you can see packages already in (hopefully) good shape from which you can learn. Working within a team can also help you be more productive in a shorter time. If you're not sure where to look for teams that want help, the "rc-alert" or "wnpp-alert" commands can give you a list of packages and bugs that pertain to what is installed on your system. cheers Stuart - --.12 (GNU/Linux) iEYEARECAAYFAlEGVuEACgkQn+i4zXHF0ai/DwCgrciD5+w5PFr4hQaiNEBOc5+j GpYAn2gyx+OEd5jCdVQnRMcNVBqW5EcM =oozT -----END PGP SIGNATURE-----
https://lists.debian.org/debian-mentors/2013/01/msg00182.html
CC-MAIN-2017-43
refinedweb
185
63.43
Bernd, On Fri, 08 Dec 2006 14:20:15 +0100 Bernd Holzm=FCller <bernd.holzmueller@...> wrote: > I would like to use the function >=20 > treeCtrlHitTest :: TreeCtrl a -> Point -> Ptr CInt -> IO TreeItem >=20 > but I cannot find out from the wxHaskell documentation how to create /=20 > use the Ptr argument, which stands for an "out" parameter. You can create a pointer using functions from Foreign.Marshal.Alloc, and read/write it using functions from Foreign.Marshal.Storable. For example, using alloca and peek, you can write a simple wrapper around treeCtrlHitTest, which returns a pair instead of requiring a Ptr. myHitTest :: TreeCtrl a -> Point -> IO (TreeItem, CInt) myHitTest w point =3D alloca $ \ptr -> do r <- treeCtrlHitTest w point ptr flags <- peek ptr return (r, flags) Regards, Takano Akio I would like to use the function treeCtrlHitTest :: TreeCtrl a -> Point -> Ptr CInt -> IO TreeItem but I cannot find out from the wxHaskell documentation how to create / use the Ptr argument, which stands for an "out" parameter. Can someone tell me how to create a value of type Ptr CInt to apply it to the treeCtrlHitTest function? Thanks, Bernd On Thu, 07 Dec 2006 11:55:29 +0900, shelarcy <shelarcy@...> wrote: > Because current VC project for wxWidgets-2.6.3 doesn't works well my > environment, and I was busy. Jeremy changed VC project from > "..\..\wxWidgets-2.6.3\lib\vc_lib\mswu" to "..\..\wxWidgets-2.6.3\lib\mswu" > in "Update VC++ project file to reflect updated DLL version supporting > wxWidgets 2.6.3" patch. It breaks building my environment but I don't find > where causes problem, soonly. Oops, I am wrong. wxWidgets-2.6.x's wx_adv.dsp generate setup.h in lib\vc_lib instead of just lib. So this is not my environments problem. wx_adv.dsp:890:# Begin Custom Build - Creating ..\..\lib\vc_lib\mswu\wx\setup.h wx_adv.dsp:893:"..\..\lib\vc_lib\mswu\wx\setup.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" wx_adv.dsp:894: copy "$(InputPath)" ..\..\lib\vc_lib\mswu\wx\setup.h wx_adv.dsp:900:# Begin Custom Build - Creating ..\..\lib\vc_lib\mswud\wx\setup.h wx_adv.dsp:903:"..\..\lib\vc_lib\mswud\wx\setup.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)" wx_adv.dsp:904: copy "$(InputPath)" ..\..\lib\vc_lib\mswud\wx\setup.h So I wonder about Jeremy changed this part that regardless of lefting other chaged point /libpath:"..\..\wxWidgets-2.6.3\lib\vc_lib". Best Regards, -- shelarcy <shelarcy capella.freemail.ne.jp> Hi Conal, On 07/12/06, Conal Elliott <conal@...> wrote: > Hi Jeremy, > > Thanks for the detailed pointers about wxWidgets, GUIs, and multi-threading. > My use is actually very simple. The only reason I wanted multiple > (sequential, not concurrent) invocations of 'start' is for convenience of > use in ghci. > > I recently switched from wxWidgets 2.4.2 to 2.6.3, and I remember that this > problem was worked around in 2.4.2 for use with ghci. Is there really no > way to fix the situation with 2.6.3? This is what Daan said (in passing, in the context of another message about the new wxHaskell maintenance team): "Finally, I am not convinced that we should always use the latest wxWidgets version: In particular, the 2.4.2 version is the only one that lets you start and restart wxhaskell apps under GHCI under window. The newer versions use static c++ classes and the destructors are not called once the dll is loaded under GHCI (fixing this requires fixing wxWidgets or letting GHCI reload DLL's too)." > Do wxWidgets-2.4.2, wxHaskell-0.10.1 and ghc-6.6 get along together, > including unicode issues? I believe so (translation: I managed to get it to work on my PC under WinXP). I understand that Unicode support in 2.4.2 is not so thorough as for 2.6.3, although my Unicode requirements are minimal, so I wouldn't expect to have seen any significant issues. Eric is working on ways to test Unicode support more thoroughly. He's already published one darcs patch. In a couple of days (i.e. when it works...) I will be recompiling my wx 2.4.2 based installation to test the new NMAKE makefile for wxc (intention is to avoid the messy editing of Visual Studio project files and create something easier to maintain). I'll let you know how that goes. > Does anyone use ghci with wxHaskell-0.10.1 and ghc-6.6? Yes, although it's not my primary platform by a long way. Jeremy
https://sourceforge.net/p/wxhaskell/mailman/wxhaskell-users/?viewmonth=200612&viewday=8&style=flat
CC-MAIN-2017-43
refinedweb
744
59.7
Hi, I have spent a few days looking into coding the following feature for my site. I like the repeater to show my filtered data when I click on the button, but somehow, it always come out blank. Is my code correct? import wixData from 'wix-data'; export function sectordropdown_change (event) { $w("#dataset1").getItems() } export function button1_click (event) { $w("#dataset1").setFilter(wixData.filter() .eq("legalStructure", $w("#sectordropdown").value)) $w("#dataset1").getItems() } When I load the page, all data appears in result (Image 1). But when i select another option (under sector) and click "search", it all disappears.I have mapped my dropdown list to a saparate dataset. What could be the problem?
https://www.wix.com/corvid/forum/community-discussion/need-help-in-dataset-filter-repeater-coding
CC-MAIN-2020-05
refinedweb
112
68.77
On Tue, Jan 4, 2011 at 3:22 PM, Philippe CASTAGLIOLA <philippe.castagliola@univ-nantes.fr> wrote: > I wrote a simple complex number library in pure lua. If you are interested, > you can go to > Monkey patching standard namespaces, at least if not requested by the user, is often unnecessary and frowned upon: function math.abs(x) local z=tonumber(x) if z then return math_.abs(z) elseif is.complex(x) then return complex.abs(x) else error("bad argument #1 to 'abs' (real or complex number expected, got %s)",type_(x)) end end A similar concern recently came up in [1]. [1]
http://lua-users.org/lists/lua-l/2011-01/msg00323.html
CC-MAIN-2022-21
refinedweb
104
50.53
On Sat, May 26, 2012 at 09:29:30PM +0700, Ivan Shmakov wrote: > …?) These days I'd argue that multi-user is such a corner case that it's not worth optimizing for it as far as defaults are concerned. If you're trying to run a secure multi-user system, you need to be an expert system administrator, keep up with all security patches, and even then, good luck to you. (The reality is that these days, no matter what OS you're talking about, shell == root. And that's probably even true on the most unusably locked down SELinux system.) What I'd do in that situation is to use per-user /tmp directories, where each user would get its own mount namespace, and so each user would have its own /tmp --- either a bind-mounted $(HOME)/tmp to /tmp if you want to enforce quotas that way, or a separate tmpfs for each user --- and then you can specify the size of the per-user tmpfs mounted on each user's version of /tmp. Cheers, - Ted
https://lists.debian.org/debian-devel/2012/05/msg01220.html
CC-MAIN-2017-09
refinedweb
179
60.69
When building applications with frontend frameworks, one aspect that generates a lot of opinions is the concept of data fetching. In basic scenarios, you would handle your data using a combination of an HTTP client (e.g Axios) and Vue’s lifecycle methods. More complex situations such as larger applications with multiple components, which in most cases will be routed, will require a different approach. Also, the sequence in which data is to be fetched — before or after certain components have been loaded — is also a concern. In this post, we’ll take a look at the best practices for fetching data in advanced scenarios when working with Vue. We’ll also learn how we can use Vue 3’s composition API to leverage the stale-while-revalidate technique in data fetching. Data fetching while navigating routed components Data fetching when various routed components are involved could get complex. In some cases, we may want to display some data while a particular route is being navigated. Vue Router handles this properly by providing options to either fetch the data before navigation is made or after. Let’s take a look at both scenarios. Data fetching before navigation Vue Router provides a number of hooks to handle data fetching before navigation: - The beforeRouteEnter()hook which takes three arguments – to, from, and next. Like the name suggests, it is used to fetch the data needed in a component before navigation is done to that component - The beforeRouteUpdate()hook which also takes the same arguments as beforeRouteEnter(), is used to update the component with the data which has been fetched We have an app with two routed components that display the current and ledger balances of our bank account. When displaying our ledger balance, we want to fetch the data before navigating to the component. First, we’ll create the script that provides the data for our ledger balance: // LedgerBalance.js export default (callback) => { const LedgerBalance = "1500 USD"; setTimeout(() => { callback(null, LedgerBalance); }, 3000); }; Next, we’ll create our ledger balance component: <!-- LedgerBalance.vue --> <template> <div>Hello, your ledger balance is {{ balance }}</div> </template> <script> import ledgerBalance from "../scripts/LedgerBalance"; export default { name: "Ledger", data() { return { balance: null }; }, // Here the component is yet to be loaded beforeRouteEnter(to, from, next) { ledgerBalance((err, balance) => { next(vm => vm.setBalance(err, balance)); }); }, // On calling beforeRouteUpdate, the component is loaded and the route changes beforeRouteUpdate(to, from, next) { this.balance = null; ledgerBalance((err, balance) => { this.setBalance(err, balance); next(); }); }, methods: { setBalance(err, balance) { if (err) { console.error(err); } else { this.balance = balance; } } } }; </script> In LedgerBalance.vue, the beforeRouteEnter() hook ensures that data is fetched from LedgerBalance.js before the Ledger component is loaded. Next when Ledger is loaded and the route changes, the setBalance() method within beforeRouteUpdate() is then used to set the data. Then we’ll define the route path for our ledger balance: // main.js import Vue from "vue"; import VueRouter from "vue-router"; import App from "./App"; import Ledger from "./components/LedgerBalance"; Vue.use(VueRouter); const router = new VueRouter({ routes: [ { path: "/Ledger", component: Ledger } ] }); new Vue({ render: (h) => h(App), router }).$mount("#app"); After defining the route path, we’ll include it in the main view: <!-- App.vue --> <template> <div id="app"> <div class="nav"> <router-linkLedger Balance</router-link> </div> <hr> <div class="router-view"> <router-view></router-view> </div> </div> </template> <script> export default { name: "App" }; </script> When navigating to the Ledger component, we can observe the delay (due to the setTimeout() function in LedgerBalance.js ) as the data is fetched before navigation: Data fetching after navigation In some cases, we may want to fetch our data after we’ve navigated to our component. This could be useful where we are working with data that changes in real-time. Such as the current balance of an account. In this instance, we would first define the function which handles the data for our current balance: // CurrentBalance.js export default (callback) => { const CurrentBalance = "1000 USD"; setTimeout(() => { callback(null, CurrentBalance); }, 3000); }; Next, when creating our CurrentBalance component, we’ll use the created() lifecycle hook to call fetchBalance(), our data fetching method: /<!-- CurrentBalance.vue --> <template> <div>Hello, your current balance is {{ balance }}</div> </template> <script> import currentBalance from "../scripts/CurrentBalance"; export default { name: "Current", data() { return { balance: null }; }, created() { this.fetchBalance(); }, methods: { fetchBalance() { currentBalance((err, balance) => { if (err) { console.error(err); } else { this.balance = balance; } }); } } }; </script> Taking into account that the data will be fetched after navigation occurs, a loading component such as a progress bar or a spinner would be useful so it doesn’t look like there’s been an error: Stale-while-revalidate in Vue Traditionally, Vue apps used the mounted() hook to fetch data. To fetch data from an API would be something similar to the code sample below: <template> <div : {{ car.carmodel }} </div> </template> <script> export default { name: 'Cars', data() { return { cars: [] } }, mounted() { fetch('/api/cars') .then(res => res.json()) .then(carJson => { this.cars = carJson }) } } </script> Suppose more data is required here, this could result in fetching data from multiple endpoints. This isn’t feasible as navigating between different components will result in making an API request for each navigation. These multiple API requests could slow things down and create a poor experience for users of this app: <template> <div v- <div>{{ about.car.model }}</div> <div>{{ about.bio }}</div> </div> <div v-else> <Loading /> </div> </template> <script> export default { name: 'Bio', props: { model: { type: String, required: true } }, data() { return { about: null } }, mounted() { fetch(`/api/car/${this.model}`) .then(res => res.json()) .then(car => fetch(`/api/car/${car.id}/about`)) .then(res => res.json()) .then(about => { this.about = { ...about, car } }) } } </script> Ideally what’s needed is an efficient way of caching already visited components such that each component which has already been visited presents data readily, even when it is navigated away from and back. Here’s where the “stale-while-revalidate” concept is useful. Stale-while-revalidate (swr) enables us cached, already fetched data while we fetch additional requested data. In the above code sample, every request to view the car’s bio would also re-trigger the request to view the car’s model even if that has been seen. With swr, we can cache the car’s model so when a user requests for the car’s bio, the model is seen while the data for the car’s bio is being fetched. In Vue, the stale-while-revalidate concept is made possible through a library (swrv) which largely makes use of Vue’s composition API. Employing a more scalable approach, we can use swrv to fetch details of our car like this: import carInfo from './carInfo' import useSWRV from 'swrv' export default { name: 'Bio', props: { model: { type: String, required: true } }, setup(props) { const { data: car, error: carError } = useSWRV( `/api/cars/${props.model}`, carInfo ) const { data: about, error: aboutError } = useSWRV( () => `/api/cars/${car.value.id}/about`, carInfo ) return { about } } } In the code sample above, the first useSWRV hook uses the API’s URL as a unique identifier for each request made and also accepts a carInfo function. carInfo is an asynchronous function which is used to fetch details about the car, it also uses the API’s URL as a unique identifier. The second useSWRV hook watches for changes from the first hook and revalidates its data based on these changes. The data and error values are respectively populated for successful and failed responses to requests made by the carInfo function. Summary Concepts to fetching data while navigating routed components and caching already fetched data are awesome ways to create an impressive user experience in your application if used properly. To get a deeper dive into stale-while-revalidate, I recommend you take a look at Markus Oberlehner’s post on the topic..
https://blog.logrocket.com/advanced-data-fetching-techniques-in-vue/
CC-MAIN-2020-40
refinedweb
1,294
53
Reactive programming in Frontend Web Development makes sense as it's a paradigm focused on reacting to events. The user interacts with the DOM, which broadcasts events. RxJS is the Swiss Army Knife of Reactive Programming. It gives us a push-based pattern that allows us to respond to events created by the user. 😱 But there's one major problem. Debugging RxJS Streams can be a nightmare! This article will introduce you to a new community-owned RxJS Operator aiming to help streamline debugging and provide the ability to do some additional robust debugging techniques. 🔥 The debug() Operator What is this magical operator? It's the debug() operator (you can find out more here) and can be installed pretty easily: NPM: npm install rxjs-debug-operator Yarn: yarn add rxjs-debug-operator It's also pretty easy to use! Just pipe it into any stream you already have set up: obs$.pipe(debug()); 🤔 But what does it do? In short, it helps you figure out what is going wrong, or right, with your RxJS Streams. By default, it'll simply log values to the console. const obs$ = of('my test value'); obs$.pipe(debug()).subscribe(); // OUTPUT // CONSOLE // my test value However, it is so much more flexible than that and can be a powerful tool for diagnosing problems or even reporting critical errors in user pathways that could negatively impact the business! 💡 How can I take full advantage of it? There are endless use-cases that you could employ to take advantage of the operator. A common one is to see how the value changes throughout a series of operations in the stream. This can be made even easier to work with thanks to the handy label option: const obs$ = of('my test value'); obs$ .pipe( debug('Starting Value'), map((v) => `Hello this is ${v}`), debug('Finishing Value') ) .subscribe(); // OUTPUT // CONSOLE // Starting Value my test value // Finishing Value Hello this is my test value We'll look at some more specific use cases below! 🎸 Examples Hopefully, these examples will come in useful and show the power of the operator! 📝 Simple logging Without Label const obs$ = of('my test value'); obs$.pipe(debug()).subscribe(); // OUTPUT // CONSOLE // my test value With Label const obs$ = of('my test value'); obs$.pipe(debug('Label')).subscribe(); // OUTPUT // CONSOLE // Label my test value You can even change what happens on each notification: const obs$ = of('my test value'); obs$ .pipe( debug({ next: (value) => console.warn(value), }) ) .subscribe(); // OUTPUT // WARNING // my test value const obs$ = throwError('my error'); obs$ .pipe( debug({ error: (value) => console.warn(value), }) ) .subscribe(); // OUTPUT // WARNING // my error 👩💻 Only logging in dev mode You can also only log when in dev mode. There are two ways you can do this, globally for all instances of debug() or locally, on a case-by-case basis. Globally import { environment } from '@app/env'; setGlobalDebugConfig({ shouldIgnore: !environment.isDev }); const obs$ = of('my test value'); obs$.pipe(debug()).subscribe(); // When environment.isDev === false // Nothing is output Locally import { environment } from '@app/env'; const obs$ = of('my test value'); obs$.pipe(debug({ shouldIgnore: !environment.isDev })).subscribe(); // When environment.isDev === false // Nothing is output ⏱️ Measuring the performance of a set of operators Now for something potentially very cool. We can use the debug operator with custom next notification handlers to measure the performance/time of a set of piped operations to a Stream. The example below shows it being used to measure the time it takes for a switchMap to a network request, however, the approach could be taken with any set of operators. import { of } from 'rxjs'; import { ajax } from 'rxjs/ajax'; import { switchMap } from 'rxjs/operators'; import { debug } from 'rxjs-debug-operator'; const obs$ = of('my test value'); obs$ .pipe( debug({ next: () => console.time('Measure Perf'), }), switchMap((ar) => ajax.getJSON('') ), debug({ next: () => console.timeEnd('Measure Perf'), }) ) .subscribe(); // OUTPUT // Measure Perf 14.07653492ms 🖥️ Remote logging for increased observability rxjs-debug-operator has a Global Config that also allows you to change the logger that is used. As such, you could potentially use something like Winston as your logger! import { DebugLogger, setGlobalDebugConfig } from 'rxjs-debug-operator'; const winston = require('winston'); const sysLogger = winston.createLogger({ level: 'info', format: winston.format.json(), transports: [ // // - Write all logs with level `error` and below to `error.log` // - Write all logs with level `info` and below to `combined.log` // new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }), ], }); const debugLogger: DebugLogger = { log: (v) => sysLogger.info(v), error: (e) => sysLogger.error(e), }; setGlobalDebugConfig({ logger: debugLogger }); const obs$ = of('my test value'); obs$.pipe(debug()).subscribe(); // OUTPUT // 'my test value' written to `combined.log` 🤩 Conclusion This all started as a joke. How many times do developers tap(console.log)with RxJS? But it has flourished into so much more! Hopefully, this article shows what is possible with such a simple operator, and I look forward to seeing what weird and wonderful things developers start to do with it! If you notice any problems or have a feature request, open an issue over on the Repo! If you have any questions, please ask below or reach out to me on Twitter: @FerryColum. Discussion (0)
https://dev.to/coly010/improve-rxjs-debugging-3iph
CC-MAIN-2021-17
refinedweb
861
50.63
"Nobody likes bugs." Most articles about testing utilities start with this sentence. And it's true--we would all like our code to act exactly as we planned it to work. But like a rebellious child, when we release our code into the world it has a tendency to act as if it has a will of its own. Fortunately, unlike in parenthood, there are things we can do to make our code behave exactly as we would like. There are many tools designed to help up test, analyze, and debug programs. One of the most well-known tools is JUnit, a framework that helps software and QA engineers test units of code. Almost everyone that encounters JUnit has a strong feeling about it: either they like it or they don't. One of the main complaints about JUnit is that it lacks the ability to test complex scenarios. This complaint can be addressed by doing some "out of the box" thinking. This article will describe how JUnit can perform complex test scenarios by introducing Pisces, an open source JUnit extension that lets you write test suites composed of several JUnit tests, each running on a remote machine serially or in parallel. The Pisces extension will allow you to compose and run complex scenarios while coordinating all of them in a single location. Two basic objects in JUnit are TestCase and TestSuite. The TestCase provides a set of utility methods that help run a series of tests. Methods such as setup and teardown create the test background at the beginning of every test and take it down at the end, respectively. Other utility methods do a variety of tasks, such as performing checkups while the test is running, asserting that variables are not null, comparing variables, and handling exceptions. Developers that want to create a test case need to subclass the TestCase object, override the setup and teardown methods, and then add their own test methods while conforming to the naming convention of testTestName. Here is what a simple TestCase subclass might look like: public class MyTestCase extends TestCase { /** * call super constructor with a test name * string argument. * @param testName the name of the method that * should be run. */ public MyTestCase(String testName){ super(testName); } /** * called before every test */ protected void setUp() throws Exception { initSomething(); } /** * called after every test */ protected void tearDown() throws Exception { finalizeSomething(); } /** * this method tests that ... */ public void testSomeTest1(){ ... } /** * this method tests that ... */ public void testSomeTest2 (){ ... } } TestSuite is composed of several TestCases or other TestSuite objects. You can easily compose a tree of tests made out of several TestSuites that hold other tests. Tests that are added to a TestSuite run serially; a single thread executes one test after another. ActiveTestSuite is a subclass of TestSuite. Tests that are added to an ActiveTestSuite run in parallel, with every test run on a separate thread. One way to create a test suite is to inherit TestSuite and override the static method suite(). Here is what a simple TestSuite subclass might look like: public class MyTestSuite extends TestSuite { public static Test suite() { TestSuite suite = new TestSuite("Test suite for ..."); // add the first test MyTestCase mtc = new MyTestCase("testSomeTest1"); suite.addTest(mtc); // add the second test MyTestCase mtc2 = new MyTestCase("testSomeTest2"); suite.addTest(mtc2); return suite; } } Running a test or a test suite is easy, as there are several GUIs you can use, starting with the GUI provided by JUnit and going all the way to IDEs such as Eclipse. Figure 1 shows how the Eclipse IDE presents a TestSuite. Figure 1. JUnit integration with Eclipse Because it is not the main subject of this article and because there are many articles about JUnit, this article will only provide a brief overview of the basic concepts of JUnit. See the Resources section for articles that cover JUnit in greater depth. JUnit Strengths and Weaknesses JUnit is an easy-to-use and flexible open source testing framework. As with every other project, it has many strengths but also some weaknesses. By using the automated JUnit testing framework, which does not need human intervention, one can easily accumulate a large number of JUnit tests and ensure that old bugs are not reproduced. In addition, JUnit helpfully integrates with build utilities, such as Ant, and with IDE utilities, such as Eclipse. JUnit's weaknesses are also well known. It supports only synchronous testing and offers no support for call backs and other asynchronous utilities. JUnit is a black-box testing framework, so testing problems that do not directly affect functionality (such as memory leaks) is very hard. Additionally, it does not provide an easy-to-use scripting language, so you must know Java to use JUnit. Another big limitation is that JUnit tests are limited to only one JVM. This limitation becomes a big issue when one is trying to test complex and distributed scenarios. The rest of this article covers this problem and ways to solve it. Every agent runs a set of JUnit tests and each test may write information to the default out. Because it is important that the tester or developer gets this information while the test is running, the default out is copied to the main local test suite's console. This process eliminates the need to go and look at each of the agent consoles in the test suite. Communication between the agents and the main local test is a complex matter, and Pisces must be able to work in a range of different environments and network topologies. In order to accommodate this issue, Pisces has a pluggable communication layer. Each of these implementations solves the problems that occur in their specific network environments. Two basic communication layers are provided by Pisces by default--a multicast implementation, which is easy to configure but works only in a LAN environment, and a JMS implementation, which requires the installation of Message-Oriented Middleware (MOM) but works in most environments. Configuring and Running Pisces Agents As I mentioned before, the Pisces test suite is composed of several JUnit tests running on remote agents. Each agent is a Java application that, according to instructions it receives from the main test runner, runs the JUnit test and reports its result and the default out printouts back to the main test runner. The easiest way to run an agent application is to configure and run the relevant executable script in the scripts folder provided in the Pisces build. Alternatively, you can also build your own script based on those already provided. The script allows users to configure general parameters for the agent, such as a unique identifier, and for the communication layer, a multicast IP and port. For example, a script for running an agent with a multicast communication layer on Linux OS might look like this: The executable script for a Pisces agent that uses a JMS provider is similar in most ways; the JMS communication layer takes as a parameter the name of a loader class that returns aThe executable script for a Pisces agent that uses a JMS provider is similar in most ways; the JMS communication layer takes as a parameter the name of a loader class that returns a #!/bin/sh # the folder were the agent can find junit.jar export JUNIT_HOME=/opt/junit3.8.1 # the folders were the agent can find # the junit tests export JUNIT_TEST_CLASSPATH=../examples/ # the multicast port that the communication # layer uses export PISCES_MCP=6767 # the multicast IP that the communication # layer uses export PISCES_MCIP=228.4.19.76 # the unique name of the agent export AGENT_NAME=remote1 java -classpath "$JUNIT_HOME/junit.jar:../pisces.jar:$JUNIT_TEST_CLASSPATH" \ org.pisces.RemoteTestRunnerAgent \ -name $AGENT_NAME -com multicast \ -mcp $PISCES_MCP -mcip $PISCES_MCIP ConnectionFactoryof your JMS provider. Configuring and Running Pisces-Enabled Test Suites After configuring and running all of the relevant agents, we still need to configure and run our Pisces-enabled test suite. First, we have to add the communication layer configuration to the beginning of our TestSuite, as shown below: // create the multicast communication layer MulticastRemoteTestCommunicationLayer com = new MulticastRemoteTestCommunicationLayer( RemoteTestRunner.name ,"228.4.19.76",6767); // set the communication layer RemoteTestRunner.setCom(com); Then, we need to create an instance of aThen, we need to create an instance of a TestSuiteand add a test to it to be run remotely. This is achieved by specifying the JUnit class (with an optional test method), as well as the name of the agent that should run this specific test. Here is an example of how this is done: // create a regular TestSuite TestSuite suite = new TestSuite("Test for org.pisces.testers"); // create a wrapper for a regular case RemoteTestCase rtc = RemoteTestCase.wrap(RemoteTestTestCase.class ,"someTestMethod", "remote1"); // add test case to TestSuite suite.addTest(rtc); The next section of this article will provide an example of a distributed test scenario and the code of its TestSuite. Let's say we have a web application. A user logs in, gets a service, and then logs out. We want to make sure that our security module prevents a single user from concurrently logging in on two different computers. We have created a MyTestCase test case object, as shown before, that has two test methods. The first, testLogin(), makes sure we can log in for the first time, and a second one, testLoginFails(), makes sure that the second login fails. Here is what a test suite that utilizes Pisces might look like: public class RemoteTestSuiteExample extends TestSuite { public static Test suite() { // configure and start the com layer JMSRemoteTestCommunicationLayer com = null; try { com = new JMSRemoteTestCommunicationLayer (RemoteTestRunner.name, new MantaConnectionFactory()); } catch (JMSException e) { throw new RuntimeException(e); } RemoteTestRunner.setCom(com); // do the JUnit thing TestSuite suite = new TestSuite("Test for org.pisces.testers"); // run method testLogin in class MyTestCase // on remote agent remote1 RemoteTestCase rtc = RemoteTestCase.wrap(MyTestCase.class, "testLogin", "remote1"); suite.addTest(rtc); // run method testLoginFails in class MyTestCase // on remote agent remote2 RemoteTestCase rtc1 = RemoteTestCase.wrap(MyTestCase.class, "testLoginFails", "remote2"); suite.addTest(rtc1); return suite; } } If all goes well, the remote agent (called remote1) tries to log in and succeeds. When the other agent (called remote2) tries to log in with the same user and password, it fails because the user is already logged in on a different computer. This test could have been more complex; for example, by adding a testLogOut() method and performing other security checks, but as an example I wanted to keep it simple. In this example, I have utilized a serverless JMS provider called MantaRay, an open source messaging middleware package that is based on peer-to-peer technology. In the latest release of Pisces, you can find several examples that utilize a JMS communication layer and other examples that use a multicast communication layer. Bugs are not fun, but with the help of JUnit, a widely used open source framework for automated testing, the task of running multiple test cases becomes much easier. Many projects extend the functionality of JUnit, but up until now, tests always had to be limited to one machine. With the help of Pisces and some "out of the box" thinking, we can now finally create complex and distributed test scenarios. Amir Shevat is a senior software developer with eight years of experience in computing. Return to ONJava.com.
http://www.onjava.com/lpt/a/6036
CC-MAIN-2014-35
refinedweb
1,877
52.7
Opened 11 years ago Closed 11 years ago #3524 closed (invalid) Models: Sub String for a character field Description I was wondering if in a Model you can substring For example State = models.Charfield(maxlength=3) Fileid = models.Charfield(maxlength=10) Date = models.DateField and the following definition def save(self): d = self.Date state = self.State self.Fileid = dateformat.format(d, "Y")+self.state(1,1) <------- This is where I would substring I assume. super(case_file, self).save() #Calls the real Save function This doesn't appear to work, would you have any suggestions? Regards Please post support requests to the mailing list. This is for bug reports. Thankyou.
https://code.djangoproject.com/ticket/3524
CC-MAIN-2017-43
refinedweb
110
61.33
Recent Notes Displaying keyword search results 1 - 10 In the case proposed by Diony , signing multiple elements by id, simply change the newSignedInfo to: // Create the SignedInfo final List transforms0...I must admit that I don't understand transformations, so take my example code with a grain of salt. Also, signing a doc fragment by PATH does not work, simply because there's no way to identify the fragment with a URI without referring to it by id. Reference ode from org.jcp.xml.dsig.internal.dom.DOMURIDereferencer : // Check if same-document URI and register...... The C function strtok tokenizes a string when you call it repeated with a NULL pointer. It should be mentioned that it destroys (alters) the original string. #include <stdio.h> #include <stdlib.h> #incl... First, the test command that sleeps random number of seconds ( sleeper.sh ): #!/bin/bash stime=$[$RANDOM % 20] sleep $sti...As comparison, synchronous pipe code: #include <sys/wait.h> #include <stdio.h> #in...Asynchronous pipe code: #include <sys/wait.h> #include <stdio.h> #in... Example 1, from the pipe man page. The parent then writes the string contained in the program's command-line argument to the pipe, and the child reads this string a byte at a time from the pipe and echoes it on standard output. #include <sys/wait.h> #include <stdio.h> #in...Example 2, child execs command given at the command line, then writes to stdout (of child), which is piped to parent. Parent reads from pipe and writes to stdout (of parent). #include <sys/wait.h> #include <stdio.h> #in...... According to wikipedia , only two characters are invalid in a file name: In Unix-like file systems the null character, as that is the end-of-string indicator and the path separator / are prohibited. Sample C program to read the whole stdin input into a char buffer until EOF: #include <stdio.h> #include <stdlib.h> #incl... If forgotPasswordForm.error is a String and not null, you cannot test the error condition with: <!-- This does not work! --> <c:if test="${forg...You have to use "not empty": <c:if test="${not empty forgotPasswordForm.error}"...
http://www.xinotes.net/notes/keywords/null/string/p,1/
CC-MAIN-2014-42
refinedweb
356
67.76