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
Undisputed one of the most popular programming languages these days, Python is a hot choice for both established and beginner programmers. And, ease of the language helps develop some interesting Python Projects that are applicable in the real world. Its simplicity and ease of use lend to its popularity. Not to mention, it is the language of choice for the data science and data visualization fields, along with R. That being said, Python is a very important language for anyone’s toolkit. And if you are someone who is demonstrating your fluency in it through an interview, then the below questions will make for good practice and warming-up. Apart from these questions, you will also be given code snippets where you have to deduce the resulting value or statement (or the lack of it). These cannot be predicted and will be dependent on your programming practice. Q 1) What is the difference between a module and a package in Python? A 1) Each Python program file is a module that imports other modules like objects. Thus, a module is a way to structure the program. The folder of a Python program is called a package of modules. Q 2) What are the built-in types available in Python? A 2) There are mutable and immutable built-in types. The mutable ones include: - List - Sets - Dictionaries The immutable types include: - Strings - Tuples - Numbers Q 3) What is lambda function in Python? A 3) It is often used as an inline function and is a single expression anonymous function. It is used to make a new function object and return them at runtime. Q 4) What is meant by namespace? A 4) The namespace can be visualized as the plot / land where a particular name lives. It is a box containing the mapping of a variable to an object. Whenever we look for this variable, the corresponding object is also searched. Q 5 ) Explain the difference between a list and a tuple? A 5) The list is mutable while the tuple is not. Tuples can be hashed as in the case of making keys for dictionaries. Q 6) Difference between pickling and unpickling? A 6) Pickling is the process whereby the pickle module accepts any Python object and gives its strong representation, then dumps it into a file using the dump function. Reversing this process- retrieving the original object from the string- is known as unpickling. Q 7) What are decorators in Python? A 7) A Python decorator is a specific change made in the Python syntax for the easy alteration of functions. Q 8) Difference between generators and iterators? A 8) In Python, iterators are used to iterate over a group of elements (in a list, for example). The way of implementing these iterators is known as generators. It yields an expression in the function, but otherwise behaves like a normal function. Q 9) How to convert a number into a string? A 9) We can use the inbuilt str() function. For an octal or hexadecimal representation, we can use the other inbuilt functions like oct() or hex(). Q 10) What is the use of the // operator in Python? A 10) Using the // operator between 2 numbers gives the quotient when the numerator is divided from the denominator. It is called the Floor Division operator. Q 11) Does Python have a Switch or Case statement like in C? A 11) No, it does not. However, we can make our own Switch function and use it. Q 12) What is the range() function and what are its parameters? A 12) The range() function is used to generate a list of numbers. Only integer numbers are allowed, and hence, parameters can be both negative and positive. The following parameters are acceptable: range(stop) Where ‘stop’ is the no. of integers to generate, starting from 0. Example: range(5) == [0,1,2,3,4] range([start], stop[, step]) Start: gives the starting no. of the sequence Stop: specifies the upper limit for the sequence Step: is the incrementing factor in the sequence Q 13) What is the use of %s? A 13) %s is a format specifier which transmutes any value into a string. Q 14) Is it mandatory for a Python function to return a value? A 14) No Q 15) Does Python have a main() function? A 15) Yes, it does. It is executed automatically whenever we run a Python script. To override this natural flow of things, we can also use the if statement. Q 16) What is GIL? A 16) GIL or the Global Interpreter Lock is a mutex, used to limit access to Python objects. It synchronizes threads and prevents them from running at the same time. Q 17) Before the use of the ‘in’ operator, which method was used to check the presence of a key in a dictionary? A 17) The has_key() method Q 18) How do you change the data type of a list? A 18) To change a list into a tuple, we use the tuple() function To change it into a set, we use the set() function To change it into a dictionary, we use the dict() function To change it into a string, we use the .join() method The above list of questions, paired with your own practice on the PC, will help you to crack any and every Python interview ever. Apart from the basics, the only thing left is to practice so that while the interviewer is asking you questions, your mind is already writing and executing the code with it. For further reference, you can also download the PDF version of Python Interview Questions and Answers mentioned below.
https://www.upgrad.com/blog/python-interview-questions-answers/
CC-MAIN-2020-05
refinedweb
949
73.47
Kulla Project: A REPL for Java - | - - - - - - Read later Reading List to obtain quick results, for example in algorithm exploration. The corresponding JEP for Java's REPL states that a few items are out of scope: graphical interfaces, debugger support, and IDE-like functionality. The motivation is that immediate feedback is important when learning a programming languages, and due to that omission many schools are moving away from Java. Interactive evaluation is much more efficient than traditional edit/compile/execute. As stated in the JEP: Without the ceremony of class "public static void main(String[] args) {", short scripts written in Java become practical. Some currently available REPL alternatives for Java are: - Groovy Console - Eclipse's Java Scrapbook Page - Beanshell 2 - The Scala REPL - Java REPL - IntelliJ IDEA's REPL plugin (based on Java REPL) According to its JEP, a Java REPL will be shipped with JDK 9. However, OpenJDK's JDK 9 does not list it as a feature. Martin Odersky, founder of Scala, was recently asked what he thought about using REPL in Java. His response: "The problem for Java here is that it is a fundamentally statement-oriented language. You write a statement, and when it executes, it has an effect. REPLs by contrast are expression-oriented: You write an expression, and the REPL shows the result, much like a calculator would. While a REPL is certainly possible for Java, it won't be as useful as for an expression-oriented language." A REPL can become an essential part of learning a new language. It remains to be seen if its quick feedback will encourage novices to learn Java over useful to extend this to a script execution demon by Rüdiger Möller Also relax rules where classes can be defined (allow >1 public class per script-java file, no main method required). This would enable use of Java for adhoc tooling/scripting/small programs in a similar way to python. Re: Would be useful to extend this to a script execution demon by David Dawson Well, apart from the system daemon thing, that's something everyone in the JMV world is waiting for ....
https://www.infoq.com/news/2014/09/repl-for-java
CC-MAIN-2018-34
refinedweb
354
50.06
This notebook demonstrates how to grab an image from a video camera using OpenCV's VideoCapture object. Firstly, we'll import all the libraries we'll be using: # Use the 'pylab' system for plotting. This is IPython-specific. %pylab inline Welcome to pylab, a matplotlib-based Python environment [backend: module://IPython.zmq.pylab.backend_inline]. For more information, type 'help(pylab)'. # Under 'normal' Python, you'd import the functions directly from matplotlib and numpy from matplotlib.pyplot import * import numpy as np # Use OpenCV import cv2 # Set default figure size to be a bit bigger rcParams['figure.figsize'] = (12,12) Video grabbing in OpenCV is managed by an object of type VideoCapture. We need to initialise a new object: capture = cv2.VideoCapture() The capture object has a number of useful methods. Refer to the VideoCapture documentation for more information. dir(capture) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'get', 'grab', 'isOpened', 'open', 'read', 'release', 'retrieve', 'set'] We must firt open the video stream we want. We could pass the name of a video file here but we want to capture from a video device. To do so we pass the numeric index of the camera to capture from. I only have one camera on my computer so that makes things easier. Pass 0 to use the default device: capture.open(0) True Let's double-check that the capture device is open: capture.isOpened() True The OpenCV VideoCapture object separates grabbing the frame from actually retrieving it. There is a convenience method, read, which will do both for us. It returns a flag indicating if a frame was grabbed and, if so, the frame itself. grabbed, frame = capture.read() print('Frame grabbed: {0}'.format(grabbed)) Frame grabbed: True The grabbed frame should be a colour image. Let's look at it's shape: # The 'shape' of the frame is a 3-tuple giving the number of rows, columns and colour components frame.shape (480, 640, 3) We can use OpenCV to convert the colour image to a greyscale: # NB the image returned from the camera has the colour components ordered: Blue, Green and Red, just to be annoying. frame_grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) And let's take a look: imshow(frame_grey, cmap=cm.gray) <matplotlib.image.AxesImage at 0x33f3f90> Beautiful! It so happens that my camera is an HD one and can capture in 1280x720 resolution. We can use the set method on the VideoCapture object to set camera properties. This may not work on your camera, it depends on the model. Also the constants specifying caprutre properties appear only to be defined in the cv package. (As opposed to cv2.) import cv capture.set(cv.CV_CAP_PROP_FRAME_WIDTH, 1280) capture.set(cv.CV_CAP_PROP_FRAME_HEIGHT, 720) False We can now grab the frame just as before: grabbed, frame = capture.read() frame_grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) imshow(frame_grey, cmap=cm.gray) print('Frame grabbed: {0}'.format(grabbed)) Frame grabbed: True Recall that the frame is annoyingly in BGR order and not RGB. We essentially want to re-order the frame matrix along its third dimension. Fortunately the powerful slicing and indexing syntax of NumPy comes to our rescue. Trying to plot the frame naively results in the wrong colours: imshow(frame) <matplotlib.image.AxesImage at 0x5dc38d0> But we can re-order the third dimension by simply specifying the correct indices: imshow(frame[:,:,(2,1,0)]) <matplotlib.image.AxesImage at 0x3546b90>
http://nbviewer.jupyter.org/gist/anonymous/7101844
CC-MAIN-2016-18
refinedweb
575
68.16
Comment Re:Moo (Score 1) 5 That almost makes sense. That almost makes sense. Cool stuff. Please, fill us in with your journal. Because i hate Java, by extension, i hate Android development. The language is insane as it is, but the verbosity that Android adds is ridiculous. Of course, the namespace is equally retarded. But these all make sense to Java coders, so, who cares? I like the idea of a browser for the front end, only because browsers are omnipresent and does not require installing potentially harmful code. However, apps are completely different, if only in that the code would require downloading, regardless. I hate Java, i hate Android development, but i repeat myself. And that's exactly what i hate about them. In Android, objects have their own namespaces, under R. There's R.class, R.mipmap, R.layout, R.color, R.integer, and many more. So, the namespace of the layout (where you usually add objects) is under R.layout, the image on a button can be under R.mipmap. Nice. OIC. Nah, java is just a redundant language which promotes this form of idiocy. Anyway, in this case, it's not the value of the checkbox. It's a method that accepts true or false as its argument. Hence, my argument. The expression must evaluate to true or false, and those are both valid values for the checkbox's method, regardless of if there are also others. If an If()'s true block set something to true, and it's false block set's it to false (or vice-versa) and nothing else, there's absolutely no reason to use an if(). Here's the latest example of something i have seen way too often: if(getListView().getCount()==checkedItemCount) chk.setChecked(true); else chk.setChecked(false); What's the point of obfuscating your code with an if()? This isn't conditional. You want to set it to the same boolean value as the evaluated expression. Obviously, the clearest way to write this (without changing names) is: As mentioned in one of my last exciting posts, i purchased a Google Cardboard. I bought it and was wowed last night. It was easy to put together, easy to get running, and the forehead part had a piece of tape (ostensibly, to protect against sweat stains). The strap worked well, and the Nerf dart shaft made a comfortable nose piece. I seem to be seeing more often a weird sentence formulation. A book talks of passing to a function a variable, an article mentions "signed into law a bill," and plenty lately of others. While normal to be found this formulation in other languages, it sounds in English rather awkward. You can do a search to setup play. There's an article on XDA about it. I took the longer method, because i don't feel right getting rid of the ads. I saved $15 by "saying" i would view them. I have not used it extensively. The OS is made to use and sell Amazon services, and has a somewhat different feel than regular Android. Continuing from the last exciting edition of what is Chacham buying today, I decided to try out the Plantronics Explorer 50 for $23.19 on ebay. Weird that it's cheaper from the UK. Anyway, i was thinking of purchasing the 3 for the 10% discount, but that's too big a gamble for a product i have not tried. If i like it, i may buy another 1 or 2. Or, purchase 3 and see if i can sell one on Amaz Yeah, but i was hoping anyway. Thanx for the hint on the app. Not sure that will work when i get home, but that is useful. Looking for an update to Galen's De Temperamentis in English, i emailed the lady at Cambridge Press again and received a prompt response: The manuscript for Galen: Works on Human Nature has still not yet been submitted to the Press - the editors say that they are anticipating now to submit in June 2016. It is much harder to find a job than to keep one.
https://slashdot.org/users2.pl?page=1&uid=981&view=usertag&fhfilter=%22user%3AChacham%22+%22tag%3Amozilla%22
CC-MAIN-2017-43
refinedweb
693
74.79
I’m trying to get st.camera_input to work for my application. I can access the uploaded picture, so the core functionality works fine. But I found that by default the dimensions/resolution of the picture depends on the camera element size in the browser window… usually the image is just too small. How do I explicitly set the resolution of the uploaded picture (without changing the size of the element in browser)? Update: Link to feature request on github Update 2: some code to try for yourself: import streamlit as st from PIL import Image import numpy as np imgbuffer = st.camera_input('cam') if imgbuffer: img = Image.open(imgbuffer) imgnp = np.array(img) st.write(imgnp.shape) Thanks Johannes
https://discuss.streamlit.io/t/st-camera-input-control-resolution-of-uploaded-image/21318
CC-MAIN-2022-40
refinedweb
120
59.3
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Migrations & Schema Builder8:41 with Hampton Paulk Migrations & Schema Builder - 0:00 Before we get into Eloquent, what we're gonna wanna do next, is manage how we - 0:05 create our database, create our tables, add - 0:08 fields, remove fields, updates, so and so forth. - 0:12 So far, we've just been going into SQL Pro, and just creating a to do list table, - 0:18 we've created our database, we've added some information, - 0:22 doing all this manually is fine for right now. - 0:25 But as you move forward into the project, - 0:28 your gonna wannna have a level of version control. - 0:31 So that other people can work on the project with you. - 0:33 So that you roll things back or add new features in and have - 0:37 a way to go backwards and forwards easily without having to manually update things. - 0:42 A name here and there, an ID here and there, one or two fields is nothing. - 0:46 But when you start changing large things in an application, the version - 0:50 in control, in our case I'm gonna call them Migrations is extremely important. - 0:55 So, [INAUDIBLE] has a great migration system built into it and - 0:59 also has a good scheme of builder to help us build - 1:01 out what we need, how we're gonna use creations and destroy, - 1:04 so on in order to help us deal with this exact issue. - 1:09 So, let's start by getting rid of everything we've done so far. - 1:13 So I'm just gonna delete this table completely. - 1:16 Now, there is lots of documentation - 1:19 here on creating migrations under laravel.com/docs/migrations. - 1:23 But I'm gonna do it right here in terminal. - 1:25 So we're gonna jump right over. - 1:27 And we are still inside of our vagrant box. - 1:30 And we're gonna to create a migration with artisan. - 1:35 So artisan command or migrate is as follows. - 1:39 PHP artisan migrate. - 1:41 And then we're gonna make a migration. - 1:42 And then next thing we gonna have there is name - 1:46 of the migration so you wanna be very verbose here. - 1:48 Use underscores instead of spaces the entire time. - 1:51 And we are going to create a to do lists table. - 1:55 And then we're going to pass an option to create and then the - 1:58 name of our table which is going to be to do underscore lists. - 2:02 So let's run that. - 2:04 And that says it has generated a migration for us which is the time stamp - 2:08 with the date and time now and then the name create to do lists table. - 2:13 So, let's go ahead and switch back over to our editor as soon as - 2:17 it's complete, and we'll take a look at the migration that's been created for us. - 2:23 So, here under App, and under database, you're gonna see migrations. - 2:28 And here you'll see our migration. - 2:29 Now, there are namespaced some, classes here so blueprint and migration. - 2:34 You'll see the class is create to do list tables. - 2:38 Extending migration. - 2:40 And we have two methods. - 2:41 One of the methods is up, and the other method is down. - 2:44 So, when we run the migration going forward, or creating it, it's going - 2:48 to create as you can see here, scheme create to do list table using - 2:53 blueprint passing through the table and then we're going to have increments ID - 2:58 which is automatic, and timestamps which is our created on and updated at columns. - 3:04 So we're gonna need a little more here, so we're gonna wanna add in our own column. - 3:09 So in order to add a column, we can add it anywhere we want here. - 3:13 I'm just gonna add it right in the middle. - 3:14 We're gonna use the table variable, which is - 3:17 actually a class of blue print class object. - 3:20 And then we're going to say string. - 3:23 And then that string is going to be called name. - 3:27 After the end. - 3:29 Now, where do we find this information how do - 3:31 we know all of the different column types we have? - 3:34 We'll just go over to our documentation. - 3:36 And then we're going to look for our column types. - 3:40 So, - 3:45 that's going to be inside of the schema builder, and then adding columns. - 3:51 Okay? - 3:51 And here are our column types. - 3:53 So you see table, there it is, passing through string email. - 3:57 So for us we're looking at string. - 4:01 String email, it is a VARCHAR equivalent column, and we can also - 4:05 specify a length, there are text - 4:08 equivalent, time, timestamps, so on so forth. - 4:11 A lot of things that are important. - 4:13 One of the things that's important is adding an index, so we ran into - 4:17 an issue a moment ago where we wanted to add something to make it unique. - 4:22 So, here an index that we can add to the - 4:24 table, is unique for email or so on so forth. - 4:28 Here, you just chain it on to the - 4:30 end by using the object operator and method unique. - 4:34 So, I'm gonna actually go into our text. - 4:39 And then now that means that name for each of - 4:42 the lists will be forced to be unique through the database. - 4:46 Now this does not give us front end validation. - 4:49 This will actually throw an exception. - 4:50 But this is one of the ways that we can - 4:52 make sure that no duplicate entries are made into the database. - 4:57 Our next method here is the down. - 5:00 And that just means if we rollback the migration, we - 5:02 go backwards in our version control, what are we gonna do? - 5:05 Well, we're just creating a new table and we're adding all these columns. - 5:09 Well we're not gonna need that table at all or any of the columns if we roll back. - 5:13 So we're just gonna drop the to do list table. - 5:15 And that's exactly what it's doing. - 5:17 So, once we have what we need here, we're - 5:19 just going to go ahead and run the migration. - 5:22 So we need to go back to our terminal to run the migration. - 5:27 All right. - 5:27 So PHP artisan migrate. - 5:33 Okay. - 5:33 So migration table successfully created. - 5:37 Let's go back over to our sequel pro installation and see if we see our table. - 5:42 Let's hit Refresh. - 5:47 So now we have our migration's table which shows us - 5:49 our versions and then a to do list which is great. - 5:52 So here we have ID, we have name and we've created an update App. - 5:56 If we go to Structure, we can see that we - 5:58 actually have a key or a to do list name unique. - 6:04 And that will give us an index to make sure that it has to be unique. - 6:07 Great. - 6:08 So in order to see all the commands that artisan has for us revolving - 6:11 around migrate we can just type in - 6:13 PHP artisan and see what commands are available. - 6:17 And you see under Migration we have - 6:19 Migrate Install, Make publish, Refresh, Reset or Rollback. - 6:23 So what we wanna do in this - 6:25 particular case is rollback the last database migrations. - 6:29 So we will clear our screen and then run PHP artisan migrate. - 6:36 And then roll back. - 6:39 Okay, so now we've successfully rolled it back. - 6:42 We can verify this by going here and hitting Refresh. - 6:46 Now you see that we have a migration, but we don't have our table which is good. - 6:50 That's exactly what we wanted. - 6:52 So now we'd be able to go in and run what we need to do. - 6:55 Make our changes for instance we could go - 6:58 to our migrations and add in something new here, - 7:06 in this case description. - 7:08 That would actually want to be text not a string. - 7:12 That way it has more characters. - 7:15 All right, now I actually don't wanna run this migration, - 7:17 but I wanna see if it's valid, if it would succeed. - 7:20 So let's go back over to our terminal. - 7:23 And we'll do a PHP artisan help migrate. - 7:29 And here you're gonna see there's an option for dash dash pretend. - 7:32 So, we're just going to look at the SQL querie, - 7:36 see what would happen, but we're not actually running the migration. - 7:40 So, we'll do PHP artisan migrate dash dash pretend. - 7:48 Okay, so, if you look at the commands here. - 7:50 Actually let's clear this and look at it again. - 7:52 All right, so we see create table, to do list, that's what we want. - 7:57 We are creating a couple of columns here and if you look - 8:00 one of our columns there is going to be text description not null. - 8:06 That, that is our change to the migration, but it's showing no errors. - 8:09 It's showing everything we need, so we could actually run - 8:12 the migration right now if we wanted to, without the pretend. - 8:15 I'm gonna switch back over and remove that line, cuz I don't want it in there. - 8:19 We don't need a description. - 8:21 And then, I could do another pretend and see that it's not doing description. - 8:26 Remove the pretend, then run the migration. - 8:31 Now if we head back over, hit Refresh, now you can see we actually - 8:36 have our to do lists and it is here with our time stamps and everything.
https://teamtreehouse.com/library/laravel-4-basics/laravel-and-databases/migrations-schema-builder
CC-MAIN-2016-50
refinedweb
1,861
81.12
how do i make this linehow do i make this lineCode:#include<iostream> using namespace std; void reverseInput(); void main(){ reverseInput(); } void reverseInput(){ cout<<"Enter 0 to end."; cout<<"Enter a number: "; int num; cin>> num; int first; if(num !=0){ first = num; reverseInput();//will keep calling until it reaches 0. cout<<"The numbers in reverse order are "; cout<<" "<<first<<", "<<endl;//now it prints from the end. } } "The numbers in reverse order are "; to display only once when i end the input by entering 0. right now when i end the input by entering 0, that line will print when each number is printed.
http://cboard.cprogramming.com/cplusplus-programming/96311-recursivle-function-help.html
CC-MAIN-2014-42
refinedweb
104
72.16
Spectral clustering for image segmentation¶ In this example, an image with connected circles is generated and spectral clustering is used to separate the circles. In these settings, the Spectral clustering approach solves the problem know as ‘normalized graph cuts’: the image is seen as a graph of connected voxels, and the spectral clustering algorithm amounts to choosing graph cuts defining regions while minimizing the ratio of the gradient along the cut, and the volume of the region. As the algorithm tries to balance the volume (ie balance the region sizes), if we take circles with different sizes, the segmentation fails. In addition, as there is no useful information in the intensity of the image, or its gradient, we choose to perform the spectral clustering on a graph that is only weakly informed by the gradient. This is close to performing a Voronoi partition of the graph. In addition, we use the mask of the objects to restrict the graph to the outline of the objects. In this example, we are interested in separating the objects one from the other, and not from the background. # Authors: Emmanuelle Gouillart <emmanuelle.gouillart@normalesup.org> # Gael Varoquaux <gael.varoquaux@normalesup.org> # License: BSD 3 clause Generate the data¶ import numpy as np l = 100 x, y = np.indices((l, l)) center1 = (28, 24) center2 = (40, 50) center3 = (67, 58) center4 = (24, 70) radius1, radius2, radius3, radius4 = 16, 14, 15, 14 circle1 = (x - center1[0]) ** 2 + (y - center1[1]) ** 2 < radius1**2 circle2 = (x - center2[0]) ** 2 + (y - center2[1]) ** 2 < radius2**2 circle3 = (x - center3[0]) ** 2 + (y - center3[1]) ** 2 < radius3**2 circle4 = (x - center4[0]) ** 2 + (y - center4[1]) ** 2 < radius4**2 Plotting four circles¶ img = circle1 + circle2 + circle3 + circle4 # We use a mask that limits to the foreground: the problem that we are # interested in here is not separating the objects from the background, # but separating them one from the other. mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) Convert the image into a graph with the value of the gradient on the edges. from sklearn.feature_extraction import image graph = image.img_to_graph(img, mask=mask) Take a decreasing function of the gradient resulting in a segmentation that is close to a Voronoi partition Here we perform spectral clustering using the arpack solver since amg is numerically unstable on this example. We then plot the results. from sklearn.cluster import spectral_clustering import matplotlib.pyplot as plt labels = spectral_clustering(graph, n_clusters=4,() Plotting two circles¶ Here we repeat the above process but only consider the first two circles we generated. Note that this results in a cleaner separation between the circles as the region sizes are easier to balance in this case. img = circle1 + circle2 mask = img.astype(bool) img = img.astype(float) img += 1 + 0.2 * np.random.randn(*img.shape) graph = image.img_to_graph(img, mask=mask) graph.data = np.exp(-graph.data / graph.data.std()) labels = spectral_clustering(graph, n_clusters=2,() Total running time of the script: ( 0 minutes 0.491 seconds) Gallery generated by Sphinx-Gallery
https://scikit-learn.org/dev/auto_examples/cluster/plot_segmentation_toy.html
CC-MAIN-2022-21
refinedweb
514
54.32
Diverting trains of thought, wasting precious time A couple of times recently I've found myself wanting to create ELF files with custom program headers. This post explains what that means, why you might want it, why there's a practical difficulty in doing so using a standard linker, and my slightly hacky way of solving it. Program headers are metadata within ELF files. They describe a contiguous chunk of the file's address space. There are several different kinds of program header, of which the most critical is LOAD, signifying that the relevant part of the file should be loaded (or mapped) into memory, forming a segment within the program's memory image. Besides LOAD, other program headers are used to attach particular meanings to specific ranges within the binary. For example, the DYNAMIC program header tells the loader where the dynamic-linking metadata resides. The INTERP program header identifies to the (in-kernel) loader a string naming the program interpreter (the dynamic linker, which will actually do the loading proper). Some vendor extensions exist for adding features within the loading process, such as GNU_RELRO (which records a range that can be made read-only after relocation, bringing security benefits) or GNU_STACK (which does not identify an associated range, but exists as a flag to tell the loader whether the stack needs to be made executable). If you run readelf -l on some ELF binary, you'll see a dump of its program headers. On my machine I see something like this. $ readelf -Wl /bin/true Elf file type is EXEC (Executable file) Entry point 0x4014320058b4 0x0058b4 R E 0x200000 LOAD 0x005e10 0x0000000000605e10 0x0000000000605e10 0x000404 0x0005f0 RW 0x200000 DYNAMIC 0x005e28 0x0000000000605e28 0x0000000000605e28 0x0001d0 0x0001d0 RW 0x8 NOTE 0x000254 0x0000000000400254 0x0000000000400254 0x000044 0x000044 R 0x4 GNU_EH_FRAME 0x004b4c 0x0000000000404b4c 0x0000000000404b4c 0x00023c 0x00023c R 0x4 GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10 GNU_RELRO 0x005e10 0x0000000000605e10 0x0000000000605e10 0x0001f0 0x0001f0 R 0x1 Two reasons for wanting to add custom program headers are to add custom features to the loading process, or to make new uses of features it already provides. My first use case was an instance of the latter: to create a heap area at load time, as an additional segment, rather than the usual way of making explicit syscalls during execution. I was building ELF files for the ppcmem emulated execution environment. This doesn't implement any system calls, but does implement an ELF loader. By adding an extra LOAD program header providing an allocation arena, I could write a malloc() that does not require system calls—its heap arena is mapped at start-up by the ELF loader inside ppcmem. (Although I could have allocated space using a big char array, or by hacking the linker script to leave a big gap, a separate segment is logically cleaner, and a disjoint address range for heap allocations is helpful.) The second use case for custom program headers comes from liballocs. When passed through the liballocs toolchain, a binary also generates extra metadata binaries which can optionally be loaded at run time to supply extra metadata similar to debugging information. Currently these files live outside the main binary, in a separate /usr/lib/allocsites hierarchy, which is a pain for deployment: if you move or copy an executable, you must move or copy its metadata as an extra step. I'd like to bundle the metadata into the binary somehow, and record its presence using a custom program header. The way to specify the program headers is in the linker script. The problem with creating custom program headers is that a GNU-style linker's script language requires you to specify the entire set of program headers if you specify any program header at all. You can't just add one extra. Worse, the default set of headers is not even made explicit anywhere. The PHDRS command is what specifies the program headers, but the default linker script (try ld --verbose to see it) doesn't use it. Rather, it falls back on the linker's hard-coded default behaviour, which is to create all the familiar headers that we see above. If we write our own PHDRS command we can create all the program headers we want—but we have to create them all ourselves, meaning manually creating all the ones that the linker would otherwise create for us. The set of headers created by hard-coded logic in the linker has grown over the years, to include things such as the GNU_STACK and GNU_RELRO headers I mentioned earlier. Re-creating this “standard” set of program headers is therefore quite a detailed platform-specific task, and is subject to change as new features are added; a burden we don't want to take on. So, I came up with a way of getting the effect we want: “please create this extra program header, in addition to all the normal ones”. It is not pretty and not perfect, but it works as follows. Run the linker once, without any custom program header directives. Remember what program headers the linker generated, and what sections it assigned to them. Dump the linker script used during that link, and annotate it so that each output section is labelled with its program header assignment. Then, apply a diff to the linker script adding only the program header we care about. Finally, re-link with the diffed script. The obvious downside is that we link twice. We're also a bit fragile to the organisation of the default linker script. Still, I'm prepared to pay these prices. I've implemented this approach with a pleasingly nasty (but small) pile of shell scripts, make rules and m4 macros. It now works pretty well for me. Here's a brief tour. First, we have some makerules to dump the default linker script. default-dynexe.lds: $(shell which ld) $(LD) --verbose 2>&1 |\ LC_ALL=C\ sed -e '/^=========/,/^=========/!d;/^=========/d'\ -e 's/\. = .* + SIZEOF_HEADERS;/& _begin = . - SIZEOF_HEADERS;/'\ > "$@" (Thanks to Dan Williams for the sed script, which I took from his page about creating a custom dynamic loader, which is well worth a read.) Next, we have some makerules to turn such a script into an m4'ised macro-script. Essentially, this macroisation adds two “hooks” into the script: one to include a file describing the “normal” program headers and insert any new ones; and one to wrap each output section in a macro invocation that will decorate it with its corresponding program header names. This macroisation rewrite is easily done with regular expressions. %-dynexe.lds.phdrify.m4: %-dynexe.lds cat "$<" | sed 's#SECTIONS#PHDRS\n{\n\tinclude(phdrs_dynexe.inc)\n\tinclude($(srcdir)/phdrs_extra.inc)\n}\nSECTIONS#' | \ tr '\n' '\f' | sed -r \ 's@(\.[-a-zA-Z0-9\._]+)[[:space:]\f]+(([^\{]*[[:space:]\f]*)?\{[^\}]*\})@expand_phdr([\1], [\2])@g' | \ tr '\f' '\n' > "$@" Next, our phdrified linker script contains output section blocks that used to look like this .rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) } now wrapped in macro invocations, like this. expand_phdr([.rodata], [: { *(.rodata .rodata.* .gnu.linkonce.r.*) }]) Once we have a macroised linker script, we need to m4-process it with some macro definitions that turn it back into the script we want. We need two kinds of definition for this. The first is a list of the program headers in the file as it was originally linked. The easiest way is to use readelf to dump the existing ones. As a wart: since (on my machine at least) the linker doesn't understand the full range of symbolic (named) values for the program header's type field, we use the C preprocessor to macro-expand the symbolic names down to hex literals (as defined in elf.h), which it does understand. The second kind of definition is going to expand each output section to explicitly mention which program headers it belongs to. Note that a section can be in more than one program header. I used a bash script with associative arrays, again operating over readelf output, which handily outputs the mapping from segments to section lists. The script inverts this mapping, into a section-to-segment-list mapping. This generates a single m4 macro whose body is a giant if-else chain testing the argument section name against all the sections in the file, and yielding the list of program headers that the section is in. The easiest way is to use readelf to dump the existing ones. The result is a chunk of m4-ified text that describes the program headers in the original link, looking something like this. phdr0 6; phdr1 3; phdr2 1; phdr3 1; phdr4 2; phdr5 4; phdr6 0x6474e550; phdr7 0x6474e551; phdr8 0x6474e552; After all that. we then simply m4-include a second file describing the custom ones, and use m4 to expand out the program header assignments. Our output section before has now become .rodata : { *(.rodata .rodata.* .gnu.linkonce.r.*) } :phdr2 i.e. recording that the read-only data is in program header named phdr2 (the first LOAD in the dump we saw early on; this is the text segment, which also holds read-only data). When we re-link with this script, we can add whatever extra linker inputs we want to go into our custom segment, and also apply a diff to the linker script. A simple diff looks like this, where the stuff in sections whose names begin .insert will end up in a new segment. --- default-dynexe.lds 2016-09-14 23:12:31.000000000 +0100 +++ insert-dynexe.lds 2016-09-14 23:13:46.000000000 +0100 @@ -187,6 +187,9 @@ . = ALIGN(64 / 8); _end = .; PROVIDE (end = .); . = DATA_SEGMENT_END (.); + /* srk: new segment! */ + . = ALIGN(CONSTANT (MAXPAGESIZE)) + (. & (CONSTANT (MAXPAGESIZE) - 1)); + .insert : ALIGN(0x1000) { *(SORT_BY_NAME(.insert*)) } :insert /* Stabs debugging sections. */ .stab 0 : { *(.stab) } .stabstr 0 : { *(.stabstr) } The .insert output section will also be aligned to a 4kB boundary, and be placed in the program header called “insert” by the script. If the input section is allocatable, it will also go into a LOAD header. By varying this patch, you can put whatever section you like in your program header, aligned however you like. There are some warts in all this. One is that I found increasing the number of program headers would confuse the GNU linker into placing some of its implicitly generated sections, .gnu.build-id and .note.ABI-tag, at a silly offset in the file, and that would mess up the address assignment, by causing the file header no longer to be mapped at virtual address 0. To hack around this, I inserted a one-line sed command which explicitly places the .note.ABI-tag section. Another wart was that the PHDR header was no longer generated properly: it was coming out with an address of 0, not of the executable's start address (0x400000). This turned out to be because no LOAD header was including the region of the file containing the file and program headers themselves. To hack around this, we add a little more rewriting magic to our shell scripts, to put the PHDR and FILEHDR linker attributes to any program header entry with type PT_PHDR, and also to the text segment's LOAD program header (usually the first), then updating the latter's file offset and memory addresses so that the segment actually spans that part of the file. I mentioned that I wanted to use custom program headers to embed one ELF file (a metadata object) inside another. How can we do this? Firstly, we embed the metadata ELF file into the enclosing ELF file and mark it with a custom program header. Secondly, at run time, when we want to load the metadata, we locate the program header and get a file descriptor pointing at the embdded content. Then we need a dynamic linker that can dlopen() from a file descriptor; we can hack the existing GNU dynamic linker for this fairly easily (not shown, but I've done it; ask me). Finally though, we need to handle the fact that file offsets in the embedded content will not match file offsets on this file descriptor! So we need to translate all the ELF file offsets in the embedded file by a fixed amount. File offsets live in the ELF header, program headers and section headers. (They might also live in other sections, but I'm not aware of any.) I wrote a simple C program to add a fixed offset to these. There's also some guesswork needed to figure out what that offset should be, since the linker will be in control of the in-file placement of the extra output section. This could be made reliable using one more link pass (bringing the total to three). There's a GitHub repository containing these recipes and examples, here. It's all a bit GNU-specific and underdocumented for now. All this effort to achieve a fairly simple task: package one ELF object inside another so that the “inner” object is loadable when running the “outer” object. What's another way of looking at this problem? We can think of ELF files as describing an initial state of the program (or, in the case of a library, a fragment of state). What we'd like them to be able to do is specify that this state includes a given file of a particular name and contents. In other words, we'd like them to describe not only aspects of the memory state, but also aspects of the filesystem state. Linkers already do something a bit this, namely static linking: objects that might not be on the destination filesystem can be bundled into the file, albeit losing their identity as files. Thinking of binaries as “partial initial program states” in this way, there's a clear relationship between ELF executables, Docker images and other collections of memory(-mappable) objects. Our “embedded ELF file” requirement would be trivial if segments were nameable as files in the first place. This is of course a design feature of Multics, as was dynamic linking. Although the latter has now been picked up by Unix, files and segments have still not been fully re-unified. Maybe it's time? Dynamic linking is one of two key mechanisms, along with filesystems in userspace (whether this or this) that allow us to prototype extensions to Unix without pushing our changes into the kernel. There are usually performance, security or correctness reasons why such extensions are better off ultimately residing at least partly in the kernel. But making a playground entirely in user space is valuable for research and experimentation, and is something I'm working up to. The “embed part of a filesystem inside your binary” idea is one example of the sort of feature that we want to be easily prototyped in such a system. The core features we need—serving the content, and then binding it into the process's namespace”are already provided by the OS, so it's a matter of joining them together. [/devel] permanent link contact By popular request, I'm going to run a couple of articles explaining how native Unix debuggers like gdb or lldb work. In this one, we'll take a quick cross-section of what's going on. I'll say “gdb” but I could be talking about any similar debugger. When you start a program in a debugger like gdb, it does a variation of the usual fork()–exec() trick, in which it sets itself up as a tracer of the child process before it exec()s the program you want to run. Alternatively, the same API can attach to a process already running. Either way, the effect is that any signals received by the “tracee” process will be delivered first to the debugger, and any system calls made by the tracee will also generate a signal. These signals can be inspected, discarded or modified as the debugger wishes, using the ptrace() API. In effect, the process (tracee) and the debugger (tracer) execute by mutual hand-off, suspending and resuming each other. Using the same API, gdb can access the raw memory image of the debugged program, and its register file. (Note that when gdb is active, the program is suspended, so its registers are saved in memory.) It can use this to walk the stack and print a backtrace: the register file gives us the program counter and stack pointer. If we have a nice simple stack which saves frame pointers, it simply walks the chain in memory. To print symbolic function names, it can use either the symbol table (if we must) or the compiler-generated debugging information (better; more on that in a moment). To print a local variable, the debugger uses the same compiler-generated debugging information to look up where that variable is currently located. This lookup is keyed on the program's current program counter, to handle the way that locals get moved around between registers and the stack from instruction to instruction. The result of the lookup might be a memory location, a register number, or even, sometimes, something composite like “first 8 bytes in register X, rest in memory location Y”. To set a breakpoint on a particular source line, gdb uses a different part of the debugging information which encodes a mapping between binary locations (program counter values) and source file/line/column coordinates. A small subset of program counter values are specially identified as “beginning of statement” instructions; these are normally the ones the user wants to break on. Sometimes, hardware debug registers can be used to implement breakpoints (up to some maximum); the CPU generates a trap on reaching the program counter value stored in the register. More classically, the “soft” method is for the debugger to overwrite the instructions with trap instructions, saving the old instruction. This trap will cause a signal to be generated when the program executes it. To resume from a software breakpoint, a bit of juggling is required. Recall that we overwrote the original instruction. We can replace it, then ask the OS to single-step the program (using the hardware's single-step mode), then re-set the trap. This is racy in multithreaded programs when the other threads aren't stopped. So instead a good debugger will emulate the instruction itself! This means using an internal interpreter for the target instruction set, backed by the memory and register file access that it already has via ptrace(). If we have a conditional breakpoint, we also need to be able to evaluate expressions when we take the trap (and silently resume if the expression is false). For this, the debugger has a parser and interpreter for each source language it supports. These interpreters are very different from an ordinary interpreter: the expression's environment comes from the binary contents of the debugged program's image, rather than being a structure the interpreter itself maintains. (The interpreter keeps a small amount of local state, such as for subexpression results, but it's mostly in the debuggee.) To evaluate expressions containing function calls, we need to be able to run code in the debuggee. To do so, we craft a special frame on the debuggee's stack, a safe distance away from its actual top-of-stack. Having evaluated the arguments as usual, we put them in the relevant registers (saving what was there), tweak the saved stack pointer to point to this crafted state, set the instruction pointer to the callee, and set the debuggee going again. The function runs as normal, and on return it uses an on-stack return address that the debugger supplied. This points at a breakpoint-like instruction that raises a signal, returning control to the debugger. This then cleans up the stack as if nothing happened, and resets the registers accordingly. (Disclaimer: I haven't actually dug through gdb's code here, so I might have one or two things subtly wrong. At least, the above is how I'd implement it. Let me know if you know better.) There's lots more, but if you understand the above, you've probably got the gist. All that seems like a big bag of tricks. What are the principles at work in this design? Although the system has “grown” rather than being “designed”, and has a generous share of quirks and unstandardised corners, there are some surprisingly strong principles lurking in it. I've written a little about these in my paper at Onward! last year. Next time, I'll cover briefly some of the same observations, and a few others, hopefully thereby re-explaining how debuggers work, a bit more systematically . [/devel] often find myself writing code that does introspection at the ELF level. This is for things like looking up symbols, walking the link map, figuring out which shared object a particular memory address belongs to, which memory regions are executable, and so on. These are fairly common things to want to do in ptrace()- or LD_PRELOAD-based tools, or binary interpreter-like (Valgrind-style) ones. This post is about how to do these things robustly from within a process, where “robustly” brings some particular restrictions. What does our address space look like? To spare myself the pain of drawing diagrams, we can ask Linux to dump a somewhat-pictorial view of a simple cat process by doing cat /proc/self/maps. I have reversed the order of the lines so that higher addresses go higher up, and tweaked the formatting slightly. address range flgs offset dev inode pathname or other name ------------------------------------------------------------------------------------------------------------ ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] 7fff301fe000- 7fff30200000 r-xp 00000000 00:00 0 [vdso] 7fff301a5000- 7fff301c7000 rw-p 00000000 00:00 0 [stack] 7f4a574bc000- 7f4a574bd000 rw-p 00000000 00:00 0 7f4a574bb000- 7f4a574bc000 rw-p 00023000 08:01 889388 /lib/x86_64-linux-gnu/ld-2.19.so 7f4a574ba000- 7f4a574bb000 r--p 00022000 08:01 889388 /lib/x86_64-linux-gnu/ld-2.19.so 7f4a57493000- 7f4a574ba000 rw-p 00000000 00:00 0 7f4a57298000- 7f4a572bb000 r-xp 00000000 08:01 889388 /lib/x86_64-linux-gnu/ld-2.19.so 7f4a57293000- 7f4a57298000 rw-p 00000000 00:00 0 7f4a57291000- 7f4a57293000 rw-p 001bf000 08:01 889403 /lib/x86_64-linux-gnu/libc-2.19.so 7f4a5728d000- 7f4a57291000 r--p 001bb000 08:01 889403 /lib/x86_64-linux-gnu/libc-2.19.so 7f4a5708e000- 7f4a5728d000 ---p 001bc000 08:01 889403 /lib/x86_64-linux-gnu/libc-2.19.so 7f4a56ed2000- 7f4a5708e000 r-xp 00000000 08:01 889403 /lib/x86_64-linux-gnu/libc-2.19.so 7f4a56c09000- 7f4a56ed2000 r--p 00000000 08:05 2750795 /usr/lib/locale/locale-archive 00838000- 00859000 rw-p 00000000 00:00 0 [heap] 0060c000- 0060d000 rw-p 0000c000 08:01 286233 /bin/cat 0060b000- 0060c000 r--p 0000b000 08:01 286233 /bin/cat 00400000- 0040c000 r-xp 00000000 08:01 286233 /bin/cat This picture is a refinement of the usual OS textbook diagram of a Unix address space. As usual, we have the executable's text segment (bottom), read-only and then writable data (next two up), heap (next up), a stack (much higher) and the kernel region (up top). (Actually the kernel region is not shown, except for one small part, the vsyscall page, which is the only user-accessible area.) The biggest difference is that we have not only the executable but some libraries—primarily the C library (since cat doesn't use others), but also the dynamic linker (itself a library) and the mysterious vdso. All these are ELF objects. In general, a large subset of a process's structure is actually defined by the collection of loaded ELF objects and a little per-process structure also defined by ELF. Our problem is now: how can we acquire a view on this ELF-level structure, from within the program itself at run time, efficiently and robustly? (The above listing also shows a few other flavours of mapping that won't concern us here: a memory-mapped file /usr/lib/locale/locale-archive, and two anonymous mappings, beginning at 0x7f4a57493000 and 0x7f4a57293000, which are almost certainly heap areas—we can have many heaps, not just the one that grows out of the executable's data segment. And of course, although we see only one mapping labelled [stack], in a large multithreaded process there will be many such.) The basics of ELF linking were first defined in System V Release 4 in 1988, and eventually adopted by non-commercial Unices starting in the mid-1990s (1995 for Linux, with kernel 1.2; 1998 for FreeBSD, with version 3; NetBSD and OpenBSD in 2001 and 2003 respectively). The “classic” picture of a loadable ELF file (direct from the spec) looks like the following. But actually, that omits some of the most interesting stuff! Let's try again. Dynamic symbols, program headers and the miscellaneous dynamic linking metadata are what we're interested in introspecting on. The POSIX libdl API offers one interface for doing introspection at the ELF level, at least for looking up symbols by name. Non-portable extensions, like SunOS/Solaris's dladdr() and the later-added dladdr1(), together with GNU's dlvsym() and dl_iterate_phdr(), get us a bit further, walking program headers and looking up symbols by address or version. We get further still if we allow ourselves OS-specific features, like Linux's helpful maps file in the /proc filesystem that generated the dump above, together with the auxv file or its associated library call getauxval(). If we're happy to parse the ELF file itself, by doing file I/O, we can get at anything we like. There are problems with all of the preceding approaches. Portability is lacking from many—only the POSIX APIs and ELF file I/O are widely portable. Robustness is lacking from all of them, in the sense that it may not be safe or reliable to use them from “sensitive contexts” where ELF introspection may be required. The main kind of “sensitive context” is one where making system calls or library calls would cause unwanted reentrancy. For example, if we want access to metadata from instrumentation logic that runs in the middle of a malloc() call, calling out to a library which might itself call malloc() is a bad idea. If we're instrumenting the code paths that make system calls (ask me how!), calling out to the OS might also be a bad idea. These unintended reentrancies can easily cause infinite loops, deadlock or state corruption. There are also security reasons why system calls and library calls are less reliable than working entirely within the process: the filesystem might have changed since the filenames in our maps or link map were recorded, for example. So, how much ELF introspection can we do without the help of system calls, library calls or non-portable code? The answer surprised me: quite a lot, but not quite everything. There is some low-hanging fruit, then some that we can just about reach (provided a couple of assumptions which, although not strictly portable, probably hold for most platforms), then some that absolutely no portable method can let us get (without resorting to file I/O). Let's state our problem slightly more precisely. Our address space includes a selection of objects (the executable and all loaded libraries), mapped at particular addresses. We'd first like to enumerate these mappings, giving us a look-up from load addresses to the object's originating binary file (pathname)—more-or-less the structure we saw in the /proc/self/maps listing earlier. Furthermore, each object defines some symbols. We'd like to be able to resolve symbols in each object, as well as any other useful other metadata, like their soname, the libraries they depend on, the locations of support structures like procedure linkage table (PLT), and the relocations performed when they were loaded. This is what we saw in the elaborated ELF file picture. The symbols-and-addresses stuff is the most important; the relocation and miscellaneous information isn't useful as often, but we'd like to have it anyway. Finally, there's some useful metadata that the operating system has passed down about the process, in an ELF-defined structure called the auxiliary vector. It turns out that we'll use this to get at some of the other metadata, but some other parts of it are useful in its own right—they tell us the process ID, page size, and various properties of the hardware. To enumerate the mapped objects, we need access to a structure called the link map. The portable interface for walking the link map is the mysterious r_debug protocol. This is surprisingly murky in its origins, but it probably comes from SunOS; it was definitely included in System V release 4 (the only solid reference I know is the relevant Programmer's Guide). It's actually not specified in most ABIs, although some seem to do so. The r_debug protocol defines a structure containing pointers to the link map. From an executable, it's easy to find this structure: we usually have a DT_DEBUG entry in PT_DYNAMIC, and the dynamic linker updates to points to a r_debug structure it allocates. This contains a pair of pointers to the link map, represented as a doubly-linked list. What about from a shared library? Getting a pointer to the r_debug is trickier here, because shared libraries don't usually have a DT_DEBUG entry. This is a chicken-and-egg problem: we need the executable's r_debug to get to other objects, but if we're not starting in the executable, how do we get there? So here comes our first somewhat-non-portable assumption: that a global symbol _r_debug is available, and marks the r_debug structure in the dynamic linker. This symbol is commonly present, but I don't believe it's standard—POSIX generally specifies programmer-facing APIs, not linker-level symbols. (As we'll see shortly, another method for getting at it is available, but it is also non-portable and imposes some other requirements. Anyway, by combining these two options, we have a pretty good chance that we can find the link map. So, let's continue on the assumption that we have the link map.) Once we have the link map, we'd like to do symbol lookups in each object. For this, we need (at least) the dynamic symbol tables, which we can find via the PT_DYNAMIC segments of each object. (We probably also want the symbol hash tables; the method is similar.) The link map helpfully keeps a pointer to this specific segment (rather than to the overall program header table). The segment's content consists of key-value pairs, and it's the pair whose key is DT_SYMTAB that points to the dynamic symbol table. (On most ABIs, a short cut to get a pointer to the containing object's PT_DYNAMIC segment is to make a link-time reference to the symbol _DYNAMIC. But this only lets us get the containing object's PT_DYNAMIC, whereas walking the link map gets us all of them.) One caveat about symbol lookups is that only dynamic symbols are looked up. The other symbols, if there are any (not needed for dynamic linking, but useful for debugging), live in a different table, .symtab, which needn't be mapped at run time. Depending on how your object was linked, perhaps most symbols became dynamic symbols (--export-dynamic) or perhaps only a minimal selection did. If you've ever tried to look up stat() in the GNU C library, using dlsym(), and been surprised not to find it, this is why. The stat() function is one of a few that are always linked statically, even when the rest of the C library is linked dynamically. In general, not all code or data in our dynamic objects is actually described by dynamic symbols. I'll return to this shortly. The link map gave us a list of loaded objects and their base addresses, but it doesn't tell us where each individual segment is mapped. This is where we begin our voyage into the not-really-portable. In the case of the executable, we can get the program headers via another useful metadata structure: the auxiliary vector. This is created by the operating system to supply various information of use to startup code (typically the bowels of the C library) and the dynamic linker (which, if one is used, also mutates the metadata to make it look as though the executable was loaded directly). (If we failed to get the link map using the previous _r_debug symbol method, we can also use the auxiliary vector to get to the executable's DT_DEBUG, and hence to the link map.) Here's a very nice article all about auxiliary vectors. The auxiliary vector lives high on the initial thread's stack, a fixed offset above the stack pointer when the program's first instruction receives control. If we could walk the main thread's stack right to the top, we could find the auxiliary vector easily. However, nowadays, since we lack frame pointers, that means making a library call to something like libunwind, and that might allocate memory. Even then, it's not guaranteed that we can walk the stack all the way to the top, since unwind information might be patchy up there. So we'll need a different approach. I devised a nasty but ultimately pleasing hack for this. When we say “auxiliary vector” we really mean specifically a list of key-value pairs containing the useful metadata I mentioned. But there's also a bunch of other things up there, in a large contiguous structure (see the helpful article for a diagram): the environment strings (a blob of characters), argument strings (ditto), and vectors of pointers into these blobs (our initial environ and argv). Instead of walking the stack, can we get hold of a pointer into one of these blobs, and then parse the surrounding memory to find the start of the key-value pairs? It's very likely that we can, since we can expect to find a handy global variable, environ, that points into them. Now, it's important to note that this isn't completely robust. The auxiliary vector only records the initial environment. A program can modify the current environment strings to its heart's content by using C library calls like putenv() and getenv(). These will mutate and, if necessary, reallocate the vector pointed at by environ. However, unless a program deletes its entire initial environment, and assuming the C library doesn't eagerly copy things out of it, that vector should always contain one or more pointers into the initial environment blob. So, we want to walk environ and look for such a pointer. The next problem: how will we recognise such a pointer when we see it? For this, we need to fix some more very-likely-true assumptions. Firstly, we assume either that the initial stack is the highest user mapping in the process, or that if something is higher, it's a shared object (perhaps Linux's vdso) which we can identify in the link map. (Put differently: what's not allowed is for there to be a memory-mapped file above the initial user stack, other than a shared object. This doesn't seem too restrictive; we could even imagine an ABI-level guarantee from the kernel that it will never create such mappings.) This assumption gives us an upper bound to compare our environment pointers against. What about a lower bound? For that, we assume that the caller can supply us one, in the form of a pointer higher than any other stack-allocated string in environ. The address of a local variable in main() could be one such pointer. In fact, any address on the initial stack will probably be good enough, since putting a stack-allocated string in your environment would be a very quirky thing to do. Anyway, we suppose that our caller, the client code which wants to get hold of the auxiliary vector, can give us a such a pointer. Now we're ready to go. We scan *environ for pointers to strings within these bounds. Then we navigate downwards in memory to find the end of the auxiliary vector, then keep going to find its beginning, after which we'll see the terminator of the argument or environment pointer vector. Once we have the auxiliary vector, we have the executable's program headers, from which it's easy to get at most other things we need, again using the link map to access other objects. One challenge remains for us: getting at shared objects' program headers. The problem here is that these headers needn't, in principle, be found anywhere in memory. (The ELF format allows a file to require that its program headers are mapped, using PT_PHDR, but it's not required and its use is uncommon.) Typically a dynamic linker will always keep each object's program headers in memory somewhere, but it's not obliged to do so. Even if it does, that memory might be anywhere. The GNU dynamic linker sometimes stores just a malloc'd copy of the data, perhaps originally read through a file descriptor rather than a memory mapping. Either way, the pointer it maintains to the header data lives in private state (in extra non-public fields in the link map structure); there's no portable access to it. So, to get shared objects' program headers there's no avoiding the use of some platform-specific (and loader-specific) code to fish it out. The major limitation of doing without program headers is that we don't have a complete map of the address space. The link map lets us enumerate objects and their start addresses, and we can then use the symbol tables to do a “forward lookup” from symbols to addresses. We can invert the symbol tables to give us a partial backward lookup from addresses to symbols. But we can't do quite as complete a backward lookup as the dladdr() function can. If you give dladdr() an address that falls within an object's mappings but isn't covered by an exported symbol, it can still tell you which object it's in. Only the program headers contain the information necessary for this. Another thing we can't figure out is which memory access permissions a segment was mapped with—again, that means looking at the relevant program header. Armed with these observations, we could imagine dynamically rewriting the binaries on our system slightly to optimise for ELF introspectability. Firstly we would insert a PT_PHDR, and define a symbol (maybe _PHDR), roughly analogous to _DYNAMIC), to help us find it. Secondly, going back to the restriction that only dynamic symbols were available for lookup, we could export all .symtab entries as “hidden” dynamic symbols. The obvious objection to this is that it will slow down linking. However, symbol lookup by name happens via the hash table (DT_HASH or GNU_HASH). I haven't checked all the details yet, but it appears that adding them to the symbol table needn't necessarily mean including them in the hash table. There has to be a hash-chain “next pointer” per symbol, but it's permitted not to hook that entry into any bucket. Since link-time lookups occur via the hash table, leaving the hidden symbols out of the hash table seems to defeat the objection. They'd be present for a “deep” introspector to find, by scanning the symbol table. But they wouldn't interfere with the symbol lookup process, nor with code using dlsym(). If you'd like to use this introspection goodness, I've coded it all up in a single header, relf.h, which is fairly self-contained and should be self-explanatory. Please let me know if you find it useful! [/devel]
http://www.cl.cam.ac.uk/~srk31/blog/index.html
CC-MAIN-2017-30
refinedweb
6,678
60.04
by Tomas PetricekOctober 2007. We will start by writing a generic class Lazy<T>, which represents the delayed computation. This class can be described as a class that will execute a chunk of code once someone asks for a result and it will cache the result, so the chunk of code is executed at most once. How can we write such class in C#? It is easy: we can use a Func delegate to represent the “chunk of code” that will be executed, and we can use generics to write a class that can represent computations returning any .NET type: using System.Linq; public class Lazy<T> { private Func<T> func; private T result; private bool hasValue; public Lazy(Func<T> func) { this.func = func; this.hasValue = false; } public T Value { get { if (!this.hasValue) { this.result = this.func(); this.hasValue = true; } return this.result; } } } The class has three fields: the func field is a delegate that will be executed when someone will access the value, the hasValue field is a logical value saying whether we already called the delegate, and finally, the result field stores the result after calling the delegate. All the important logic of the class is in the Value property, which returns a value calculated by the delegate. The getter of the property first tests if we already have the result, and if not, it calls the delegate and stores the result. Otherwise we can just return the result that was calculated earlier. Let’s now look at how can we use this class. Its constructor expects a value of the type Func<T> (from the System.Linq namespace), which is new in .NET 3.5 and represents a delegate that doesn’t have any arguments and returns a value of type T. The advantage of using this type is that we can use C# 3.0 anonymous functions to write code that will be executed in a very compact way directly when creating an instance of the Lazy<T> value. In the following example we create a lazy value that will return a numeric value once it is executed, but it will also print a string to the console window when it is executed, so we can trace when the code runs: Lazy<int> lazy = new Lazy<int>(() => { Console.WriteLine("calculating..."); return 42; }); Console.WriteLine("starting..."); Console.WriteLine("result = {0}", lazy.Value); Console.WriteLine("result (again) = {0}", lazy.Value); In this code we first created a variable called lazywhich represents our lazy value, then printed a string to the console window, and finally we used the Value property of the lazy value to read the result of the computation (even twice!). As you may have expected, the output of this program is following: starting... calculating... result = 42 result (again) = 42 What exactly happened? When we created a lazy value, the program just created a delegate from the anonymous function, but it didn’t execute it when creating the value, so it didn’t print anything to the screen. Later the first WriteLine executed and printed the "starting..." string. Next, when calling the second WriteLine, we accessed the Value property of our lazy value, so the anonymous function was executed, printed the "calculating..." string and returned the result. The result was given as an argument to the WriteLine function and it printed the string "result = 42". Finally, we accessed the Value property again, but since the value was already calculated, the lazy value just returned the cached result and the last WriteLine call was performed printing the string "result (again) = 42". Before moving to more interesting and far more useful examples, we will do one more improvement to the way we write lazy values. The syntax used for creating lazy value in the previous example is somewhat too verbose, because we had to write Lazy<int> twice. Luckily, we can easily simplify it by using C# type inference. In C# it is possible to omit the type arguments when calling a generic method, so we will write a simple static helper class with a static method for creating a lazy value. (Helper classes like this exist in other places of the .NET Framework; for example, System.Nullable has a similar purpose.) public static class Lazy { public static Lazy<T> New<T>(Func<T> func) { return new Lazy<T>(func); } } Using this class, we can create a lazy value just by calling Lazy.New instead of writing new Lazy<int>. To get even more compact syntax, we can also combine this syntax with the new C# 3.0 var keyword, which tells the compiler to infer the type of a variable automatically depending on the expression used to initialize the variable. Additionally, this little helper class also enables using C# 3.0 anonymous types. These, of course, can be used only locally (inside a method), but may often be useful, as demonstrated in the following example, where we use anonymous type to create a lazy value representing both the sum and product of two numbers: int a = 22, b = 20; var lazy = Lazy.New(() => { Console.WriteLine("calculating..."); return new { Mul = a*b, Sum = a+b }; }); Console.WriteLine("Mul = {0}, Sum = {1}", lazy.Value.Mul, lazy.Value.Sum); In the introduction I mentioned that one of the aspects of eager evaluation(used in most programming languages, including C#) is that arguments of a method are evaluated before calling the method, which may not be the best thing to do if the calculation can take a long time to complete and a method may not actually need the value. On the other side, in lazy evaluation, the arguments are never evaluated unless the value is actually required in the method body ,and indeed this behavior can be nicely simulated using our lazy values. The following method takes two lazy values, but in fact uses only one of them: static Random rnd = new Random(); static void UseRandomArgument(Lazy<int> a0, Lazy<int> a1) { int res; if (rnd.Next(2) == 0) res = a0.Value; else res = a1.Value; Console.WriteLine("result = {0}", res); } To call this method, we create two lazy values (using the Lazy.New method), and to demonstrate how the code behaves, we also add a Console.WriteLine call to the anonymous function used for calculating the value. var calc1 = Lazy.New(() => { Console.WriteLine("Calculating #1"); return 42; }); var calc2 = Lazy.New(() => { Console.WriteLine("Calculating #2"); return 44; }); UseRandomArgument(calc1, calc2); UseRandomArgument(calc1, calc2); Since the UseRandomArgument function randomly uses only one of the arguments, we can get a different result every time we execute the application. The purpose of this example is to demonstrate that the code to calculate the argument may not be executed (if the argument is never used), which may happen, for example, when the function chooses to read a value of the first argument ( calc1) in both calls. In such a case, the second value ( calc2) is never used and we get the following output: Calculating #1 Result = 42 Result = 42 Note that the line that would be printed when calculating the second argument ( "Calculating #2") isn’t present in the output. Of course, if the function uses a different argument in each call, we can get output like following, in which case both of the lazy values were forced to execute: Calculating #1 Result = 42 Calculating #2 Result = 44 As a last thing in this article we will use the Lazy<T> class to write a more interesting application. As you can see in Figure 1, the application contains a drop-down list with font families, and the font preview is shown when the font is selected. How can we use our lazy values in this application? We don’t want to draw previews of all the font families when populating the list, but we would like to draw the preview bitmap for every font only once to save some CPU time—and this is exactly what the lazy values are good for! Figure 1: The form for the Font Application contains a drop-down list of font names and an area where the selected font can be previewed. We will need a data type for storing information about the font, so we define a class with two properties: one is the font name, which is an ordinary string, and the other is a lazy value storing a bitmap (the preview of the font). In addition, we can use C# 3.0 automatic properties to save some time when implementing the class. (When using automatic properties, the C# compiler generates a trivial getter and setter for us.) private class FontInfo { public Lazy<Bitmap> Preview { get; set; } public string Name { get; set; } } Before looking at the interesting part of the code, we will also need a utility method to draw the preview of the font. The DrawFontPreview method from the following code sample does exactly that: it uses System.Drawing classes to draw a white rectangle with some text using the specified font family. private void DrawFontPreview(FontFamily f, Bitmap bmp) { Rectangle rc = new Rectangle(0, 0, 300, 200); StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; string lipsum = "Lorem ipsum dolor sit amet, consectetuer " + "adipiscing elit. Etiam ut mi blandit turpis euismod malesuada. " + "Mauris congue pede vitae lectus. Ut faucibus dignissim diam. "; using (Font fnt = new Font(f, 15, FontStyle.Regular)) using (Graphics gr = Graphics.FromImage(bmp)) { gr.FillRectangle(Brushes.White, rc); gr.DrawString(lipsum, fnt, Brushes.Black, rc, sf); } } Let’s look at the code that populates the list. First we use the FontFamily.Families property to get an array with information about all the installed fonts. Now, we want to create a list containing a FontInfo instance for every font family in the array. We could indeed allocate an array and use a for loop to do this, but it is much easier to take advantage of another new .NET 3.5 feature and use the Select query operator. Select is an extension method for all IEnumerable types, so we can use it for an array as well. It takes a delegate as an argument, calls this delegate for every element in the sequence, and returns an IEnumerablecontaining results returned by the delegate. In our case we give it an anonymous function with a body that builds a lazy value for drawing the preview and returns a FontInfo value for every font family. After creating this IEnumerable value, we use it to populate the items in the drop-down list using data-binding: private void FontForm_Load(object sender, EventArgs e) { var fontInfo = FontFamily.Families.Select(f => { // Create a lazy value for drawing the preview var preview = Lazy.New(() => { Bitmap bmp = new Bitmap(300, 200); DrawFontPreview(f, bmp); return bmp; }); // Return a font info with the family name and the preview return new FontInfo { Name = f.Name, Preview = preview }; }); // Use data-binding to populate the drop down list fontCombo.DataSource = fontInfo.ToList(); fontCombo.DisplayMember = "Name"; } The last missing piece of the application is an event handler that displays the preview of the selected font when the user selects an item in the drop-down list. To do this we simply read the SelectedItemproperty of the drop-down list, cast it to the FontInfotype that we used to store information about the font, and we get the preview bitmap from the Preview lazy value using the Value property, which forces the evaluation of the value. private void fontCombo_SelectedIndexChanged(object sender, EventArgs e) { FontInfo fnt = (FontInfo)fontCombo.SelectedItem; fontPreview.Image = fnt.Preview.Value; } In this article we looked at representing lazy values in C# using the Lazy<T> class, which can be a very useful pattern in situations where you want to delay a computation of some expression until the result is actually needed, but you want to keep the code simple and readable. We also examined an example that demonstrates using the lazy pattern to solve a more real-world problem. Finally, we used some of the new C# 3.0 language features (including type inference, anonymous functions, query operators and anonymous types) to make the code more compact and easier to read.
http://msdn.microsoft.com/ja-jp/vcsharp/bb870976(en-us).aspx
crawl-002
refinedweb
2,024
52.8
Yesod for non-Haskellers May 31, 2011 Michael Snoyman Introduction My wife (Miriam Snoyman) has been wanting to make a recipe site for a while now. Instead of me just writing it for her, she decided she would take this chance to learn a bit more about web programming. She has done some programming in the past, and has knowledge of HTML/CSS (no Javascript). She's also never done any Haskell. So being the brave sport she is, she agreed to let me blog about this little adventure. I'm hoping that this helps out some newcomers to Yesod and/or Haskell get their feet wet. Given that our schedule is quite erratic and dependent on both kids agreeing to be asleep, I don't know how often we will be doing these sessions, or how long they'll last each time. Getting Started The first step is using the yesod executable to generate a scaffolded site. The scaffolded site is a "template" site and sets up the file/folder structure in the preferred way. A few other optimizations like static file serving. It gives you a site that supports databases and logins. Start with yesod init. Some of these questions (like name) are for the cabal file. Other questions (database) actually change the scaffolded site. The "Foundation" is the central datatype of a Yesod application. It's used for a few different things: - It can contain information that needs to be loaded at the start of your application and used throughout. For example, database connection. - A central concept in Yesod is a URL datatype. This datatype is related to your foundation via a type family, aka associated types. The foundation is often times the same as the project name, starting with a capital letter. Once you have your folder, you want to build it. Run cabal configure and yesod build. We use "yesod build" instead of "cabal build" because it does dependency checking for us on template files. You should now have an executable named "dist/build/<your app>/<your app>". Go ahead and run it. If you used PostgreSQL, you'll get an error about not having an account. We need to create it. To see how it's trying to log in, look in config/Settings.hs. A few notes: - Top of file defines language extensions. - Haskell project is broken up into modules. The "module Settings (...) where" line defines the "export list", what the module provides to the outside world. - Then the import statements pull code in to be used here. "qualified" means don't import all the content of the module into the current namespace. "as H" gives a shortcut as you can type "Text.Hamlet.renderHtml" as "H.renderHtml". - Note that there's a difference between things starting with uppercase and lowercase. The former is data types and constructors. The latter is functions and variables. - #ifdef PRODUCTION allows us to use the same codebase for testing and production and just change a few settings. connStr contains our database information. We need to create a user and database in PostgreSQL. sudo -u postgres psql > CREATE USER recipes password 'recipes'; > CREATE DATABASE recipes_debug OWNER recipes; > \q Now try running your app again. It should automatically create the necessary tables. Open up the app in your browser:. You should see a "Hello" and "Added from JavaScript". Entities/Models We store everything in the database via models. There is one datatype per table. There is one block in the models file per entity. The models definition file is "config/models". By default, we have "User" and "Email", which are used for authentication. This file is whitespace sensitive. A new block is not indented at all. An entity is a datatype, so it needs a capital letter. It makes more sense to use singular nouns. Fields are all lowercase. First give a field name, and then a datatype. Some basic datatypes are "Text" and "Int". If you want something to be optional, you put a "Maybe" after the datatype. We work off of SQL's relational approach to datatypes. Instead of having a "recipe" with a list of "ingredients", we will have a recipe, and each ingredient will know which recipe it belongs to. (The reason for this is outside our scope right now.) This kind of a relationship is called a one-to-many: each recipe can have many ingredients, and each ingredient belongs to a single recipe. In code: Recipe title Text desc Text Maybe Ingredient recipe RecipeId name Text quantity Double unit Text You can think of RecipeId as a pointer to an actual recipe, instead of actually holding the recipe itself. We can always come back and make modifications later. Persistent migrations will automatically update the table definitions when possible. If it's not possible to automatically update, it will give you an explanation why.
http://www.yesodweb.com/blog/2011/5/yesod-for-non-haskellers
CC-MAIN-2015-06
refinedweb
810
76.52
{-# LANGUAGE TypeSynonymInstances #-} -- |A value of type TIO represents the state of the terminal I/O -- system. The 'bol' flag keeps track of whether we are at the -- beginning of line on the console. This is computed in terms of -- what we have sent to the console, but it should be remembered that -- the order that stdout and stderr are sent to the console may not be -- the same as the order in which they show up there. However, in -- practice this seems to work as one would hope. module Extra.TIO ( module Extra.CIO -- * The TIO monad , TIO , runTIO , tryTIO --, liftTIO ) where import Extra.CIO import Prelude hiding (putStr, putChar, putStrLn) import Control.Exception import Control.Monad.RWS import qualified System.IO as IO data TState = TState { cursor :: Position -- ^ Is the console at beginning of line? } deriving Show data Position = BOL -- Beginning of line | MOL -- Middle of line | EOL -- End of line deriving (Show, Eq) type TIOT = RWST TStyle () TState type TIO = TIOT IO -- |Perform a TIO monad task in the IO monad. runTIO :: TStyle -> TIO a -> IO a runTIO style action = (runRWST action) style initState >>= \ (a, _, _) -> return a -- |Catch exceptions in a TIO action. --tryTIO :: TIO a -> TIO (Either Exception a) tryTIO task = do state <- get liftTIO (try' state) task where try' state task = do result <- try task case result of Left e -> return (Left e, state, ()) Right (a, s, _) -> return (Right a, s, ()) liftTIO :: (IO (a, TState, ()) -> IO (b, TState, ())) -> TIO a -> TIO b liftTIO f = mapRWST f -- |The initial output state - at the beginning of the line, no special handle -- state information, no repositories in the repository map. initState :: TState initState = TState {cursor = BOL} -- |The TIO instance of CIO adds some features to the normal console -- output. By tracking the cursor position it is able to insert a -- prefix to each line, and to implement a "beginning of line" (BOL) -- function which only adds a newline when the cursor is not already -- at BOL. It also allows verbosity controlled output, where a verbosity -- level is stored in the monad state and output requests are given a -- verbosity which must be greater or equal to the monad's verbosity -- level for the output to appear. instance CIO TIO where hPutStr h s = do style <- ask state <- get case (cursor state, break (== '\n') s) of (_, ("", "")) -> return () (BOL, ("", (_ : b))) -> prefix style >> newline >> hPutStr h b (MOL, ("", (_ : b))) -> newline >> put (state {cursor = BOL}) >> hPutStr h b (EOL, ("", (_ : b))) -> newline >> put (state {cursor = BOL}) >> hPutStr h b (BOL, (a, b)) -> prefix style >> write a >> put (state {cursor = MOL}) >> hPutStr h b (MOL, (a, b)) -> write a >> hPutStr h b (EOL, (a, b)) -> newline >> prefix style >> write a >> put (state {cursor = MOL}) >> hPutStr h b where prefix style = liftIO (IO.hPutStr IO.stderr (hGetPrefix h style)) -- >> io (IO.hFlush h) newline = liftIO (IO.hPutStr IO.stderr "\n") -- >> io (IO.hFlush IO.stderr) write s = liftIO (IO.hPutStr IO.stderr s) -- >> io (IO.hFlush h) -- | A "virtual" newline, this puts us into the EOL state. From -- this state, a newline will be inserted before the next output, -- unless that output itself begins with a newline. hBOL _h = do state <- get put (state {cursor = if cursor state == BOL then BOL else EOL}) -- |Return the "effective verbosity", or perhaps the effective -- quietness. If this value is zero or less the output will be -- complete. By convention, if it is one, the output will be brief. -- If it is a two or more no output is generated. ev v = do style <- ask return (verbosity style - v) -- |Modify the current style for this action setStyle styleFn = local styleFn -- |Implementation of try for the TIO monad tryCIO = tryTIO _test :: IO () _test = runTIO (defStyle {> bol >> -- No extra newline putStr "(some text)" >> putStr "(some more on same line)" >> -- This should be right after abc bol >> putStr "(newline)\n\n(after a blank line)" >> -- This should show up on a new line bol) -- Newline before exit
http://hackage.haskell.org/package/Extra-1.42/docs/src/Extra-TIO.html
CC-MAIN-2016-36
refinedweb
661
66.07
Automate Selenium testing with Jenkins - AWS, DevOps, Git, Technology, Testing Selenium is a tool widely used for automating testing of web applications. One step ahead, integrating the selenium with Jenkins takes it to the next level. In this blog, we would be configuring Jenkins to run selenium test cases on an ubuntu environment. Scenario: Configure Jenkins to perform Selenium test cases with one click. I am using Amazon EC2 server which has Ubuntu running on it and has Jenkins server installed on it. Since most of the test cases are running on firefox in my case, so I have installed firefox on the server. Prerequisites: - Install Maven Integration plugin: I am considering this plugin since most of the developers use Maven as a build tool for running their test cases. - Install Xvnc plugin: This plugin is required as it creates a web browser instance in memory where all the test cases run. - GIT plugin: I am assuming the code of the test cases is pushed on git, so we would need this plugin to pull the code. Let’s create a Jenkins job for our scenario as below: - Login into your Jenkins server and create a new “Maven Project” in Jenkins console. - Make the build parameterized if the test cases parameters to be passed to them. - Provide your git repository and branch/tag in after selecting git under “Source Code Management”. - Under “build triggers”, select “Build whenever a SNAPSHOT dependency is built” which tells Jenkins to check the snapshot dependencies from the <dependency> element in the POM, as well as <plugin>s and <extension>s used in POMs. - Under “Build environments”, select “Run Xvnc during build”. This will provide an X display for the web browser to run the test cases. - Under “Build”, provide the path of pom.xml and pass the Goals such as clean, test etc with your profile by using “-P” if you are using multiple profiles in test cases. If your build is parameterized, the options will be passed with goals and profile with “-D”. - In “Post Build” steps, the report generated by Selenium can either be mailed or served from the server using HTTP or can be pushed to AWS S3. I found the last option better as AWS S3 is cheap and provide unlimited storage. After uploading the report on AWS S3, the report can be deleted from the server and can be shared using AWS S3 URL so we do not need to serve the report from the server. To upload the report to AWS S3 use “ Jenkins S3 publisher plugin” plugin and provide the AWS S3 bucket path where the reports would be uploaded. The report URL from S3 could be shared over mail or can be printed in the Jenkins’ logs. - In case, we need to analyze previous reports, another Jenkins job can be created which can list the desired number of links to the previous reports uploaded on AWS S3. - Now, anyone can run the selenium test cases with a single click by accessing the Jenkins’ job. For more customisation and as per the needs of the developer, the job can be configured to run on multiple web browsers and it can be passed as a parameter to the Jenkins’ job. I am getting following error on build now against my nightwatch tests configured as job over Jenkins: Error retrieving a new session from the selenium server Connection refused! Is selenium server started? { Error: socket hang up at createHangUpError (_http_client.js:254:15) at Socket.socketCloseListener (_http_client.js:286:23) at emitOne (events.js:101:20) at Socket.emit (events.js:188:7) at TCP._handle.close [as _onclose] (net.js:498:12) code: ‘ECONNRESET’ } npm ERR! Test failed. See above for more details. Build step ‘Execute shell’ marked build as failure Finished: FAILURE Can you please advise how to resolve this? Regards Rohit | 9871998357 Hello Navjot, Exactly I’m looking for same, that you have given in above. Can you please tell what can be src/test/java test file that will work in Ec2 instance, Because I’m using package MavenDemo; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class testFacebook { @Test public void TestFireFox(){ WebDriver driver=new FirefoxDriver(); driver.manage().window().maximize(); driver.get(“”); driver.quit(); } } above file, for which testing.xml is generated in Eclipse. Its working fibe in eclipse if create a build, but it is failing in ec2 instance. Hope issue is with firefox driver instance,I haven’t installed any firefox in ec2, But how to deal same with Ec2-instance. please share if any sample you have. Thanks in Advance I believe the system on which eclipse is installed in Windows where firefox is already installed. Which AMI are you using for ec2? Windows or Linux. If Windows, install firefox as you did it on your system and for linux do following: For ubuntu: sudo apt-get update;sudo apt-get install firefox -y For centos: sudo yum update, sudo yum install firefox -y
https://www.tothenew.com/blog/automate-selenium-testing-with-jenkins/
CC-MAIN-2020-45
refinedweb
841
64.2
'" ." Need to Know. (Score:3, Informative) That's why you need to know that some moron thinks your laptop is valuable. This has not always been the case. Paw shops have traditionally shied away from computers because they are tricky to fix and their value falls too quickly. Ebay has changed that. The reality of the situation is not as important as what the dirtbags think. It's a trend and it will spread as). Re:A simple precaution (Score:2).:2) Robbery != Theft. (Score:5, Informative) The key word here is robbery, which means violence or intimidation being used to steal the property. I'm sure the number of laptop thefts is vastly higher. I worked at one company in the south of market area a few years back that was broken into several times and lost nearly 10 laptops alone. SF only, not Bay Area (Score:2, Flamebait) ."! PC Phone Home (Score:4, Informative) - Load an application that would have the laptop occasionally contact a server to see if it's been reported stolen, and if it has been, start reporting IP and MAC addresses it hears on WiFi in its vicinity, connections it has made for landline internet, perhaps taps on email going through it, and so on - and turn on the WiFi transmitter to broadcast the occasional "Here I Am" packet for direction finding. - Record the WiFi MAC address of the PC and sniff for it once it's stolen. - Record whatever info the PC will use to identify itself to Microsoft if/when somebody tries to register/authorize a fresh load of one of their products. (Here's where Microsoft could do the law abiding a service by reporting IP address and date/time to law enforcement when a stolen machine is reauthorized.) Sort of a software LoJack. If the theives don't eload the software the PC will "phone home" once the ultimate recipient starts running it, and it will be trackable. If they DO reload it the may call the cops down on themselves directly - and even if they do workarounds they still need to leave enough identity info on the machine for it to be usable - and forgeries in a global namespace also leave tracks. Wardrivers could do a service by reporting approximate locations of reported-as-stolen MAC addresses, as a starting point for a direction-finding bunny hunt. A public-service distributed application (in the same vein as SETI-at-home) could do the same - or could blanket userland with beacons of known location for a WiFi-only replacement for GPS that would let the phone-home software identify its own location (if it can't do that adequately via currently known WiFi beacons such as hotspots.) Recover a few (and identify and question the people who got them, with the threat of a "receiving stolen property" bust if they don't cooperate) and police can work back up the reselling chain to the thieves. And yes I'm QUITE aware of how such systems could be abused. Note that some of these can be done privately and in a moderately secure fashion. (For instance: open source phone-home app with strong encryption, using an owner-generated key to enable its reporting functions.):5, Informative) This company loves for customers to hang out for hours (and truth be told, many hang out all day and night several days a week) because they invariably buy more stuff the longer they stick around. The longer they stay, the more relaxed they become. When it comes time to get a new book, many will simply get up and walk away from their unattended laptop for anywhere between 1 and 20 minutes (don't get me started on table camping). Many days I've stood there during slow periods in amazement at the amount of very expensive hardware just left in the open with no one to watch it. It's inevitable that thieves will begin to exploit this as I've seen the same level of carelessness at similar retailers and sister stores in several states. There really isn't much I can do about it other than make friendly reminders when talking to customers - which risks offending the all-too-common customer with the over-inflated sense of self importance who finds any suggestion that they alter their behavior in any way (even if it will benefit them) as a severe insult. I try to keep an eye on things, even though it's not my responsibility, and I'm usually too busy to notice what's going on in the seating area unless there is a major disturbance (in other words: never). "Casual" laptop theft is going to increasingly be a problem, but not one that I fear to any great extent as in most cases it can be defeated with the help of common sense which itself is a rare commodity these days..
https://slashdot.org/story/06/04/10/2318223/wifi-and-laptops-adds-up-to-theft?limit=0
CC-MAIN-2017-26
refinedweb
823
64.34
Closed Bug 1328167 Opened 4 years ago Closed 3 years ago Ctrl+Shift+I keyboard shortcut for "Developer Toolbox" does not work; conflicting with Ctrl+Shift+I for "Chat" Categories (Thunderbird :: Mail Window Front End, defect) Tracking (thunderbird51 unaffected, thunderbird52 affected, thunderbird53 affected) Thunderbird 58.0 People (Reporter: aryx, Assigned: thomas8) References Details Attachments (1 file, 1 obsolete file) Thunderbird 53.0a1 20170102030205 and 52.0a2 20170102004003 (both 32-bit) on Windows 8.1 64-bit Shortcut to open Chat tab and to open the Developer Toolbox is the same (Ctrl+Shift+I). See menu Go > Chat and menu Tools > Developer Tools > Developer Toolbox. status-thunderbird51: --- → unaffected status-thunderbird52: --- → affected status-thunderbird53: --- → affected The same shortcut is also used by DOM Inspector, if you have that add-on installed. Accel+Shift+I is the shortcut used to toggle tools in Firefox, I'd argue that it is best to use that and change chat, even if that means that people using Accel+Shift+I for chat would be at a loss. I guess we could go with Alt+Accel+Shift+I, which is used in Firefox to open the Browser Toolbox, but if you are regularly debugging this is a lot of buttons to press. I am not too worried about DOM Inspector because the developer toolbox provides an inspector. Florian, what do you think? Flags: needinfo?(florian) Let's fix this please! Richard, Florian, can you please comment on the following: * Not having an out-of-the-box working keyboard shortcut for Developer Tools is really annoying because it is used frequently by those who need it most, and it's a third-level menu entry which requires complex precise navigation. Developers are also quite important for the product :) * I don't think Ctrl+Shift+I is very intuitive for modern-day chat users, who may not remember IRC. * Otoh, Ctrl+Shift+I is very intuitive for Developer Toolbox, because of ux-consistency with FF, and long tradition. Proposal: Ctrl+Shift+I -> Developer Toolbox (ux-consistent with FF) Ctrl+Shift+H -> Chat Reasons for Ctrl+Shift+H: - Only available Shortcut using character from the word "Chat" - Reasonable mnemonic value: H -> "Hello!", "Hi!" which is a common way of starting chats. - Also, H might be seen as an iconic representation of two I's (two people) who are linked with a direct horizontal line of communication: I-I = H - Imo unlikely to be used for anything else in the future. Checking alternatives: * Ctrl+Shift+C is taken for "Calendar"; Ctrl+C is "Copy". * Ctrl+H is available, but should be reserved for "Replace" in quick replies. * Ctrl+Shift+A is taken for "Select Thread"; Ctrl+A is "Select All". * Ctrl+Shift+T is taken for "Undo Close Tab", Ctrl+T is "New Tab" (reserved for future use). Flags: needinfo?(richard.marti) Clearing Florian's needinfo to ping him again. Flags: needinfo?(florian) Florian, there's a needinfo request for you from Philip some time ago, and a new one from me for my proposal of comment 3. Speak now or be forever silent on this matter ;) Flags: needinfo?(florian) Summary: Shortcut to open Chat tab and to open the Developer Toolbox is the same (Ctrl+Shift+I) → Ctrl+Shift+I keyboard shortcut for "Developer Toolbox" does not work; conflicting with Ctrl+Shift+I for "Chat" I don't understand the problem, Cmd+alt+I opens the devtools in both Firefox Nightly and Thunderbird Daily. Cmd+shift+I was the former dom inspector shortcut, which doesn't seem to be used anymore on Firefox. So... wontfix? But I agree Cmd+shift+I isn't intuitive for Chat users... I actually didn't even remember about it myself :-(. Flags: needinfo?(florian) The 'I' came probably from 'I'nstant messenging. Ctrl+shift+I is still used to inspect the content in FX and also shown in the menuitem. I'm okay with the Ctrl+Shift+H as it's the only one. Flags: needinfo?(richard.marti) So let's fix it. Ctrl+Alt+I for Dev Toolbox is MAC-only, on Windows it's Ctrl+Shift+I, but Chat key is cross-platform Accel+Shift+I, that's why we have this conflict in Windows. > <key id="key_devtoolsToolbox" > #ifdef XP_MACOSX > #else > #endif > Assignee: nobody → bugzilla2007 Status: NEW → ASSIGNED Attachment #8924452 - Flags: review?(richard.marti) Comment on attachment 8924452 [details] [diff] [review] Patch V.1: Change Chat shortcut key to Accel+Shift+H It's good the key name changes because at least de uses the same key and this is a heads up to change it too. Attachment #8924452 - Flags: review?(richard.marti) → review+ Ah, and please use a uppercase 'P' for Paenglab in the commit message. r=Paenglab Attachment #8924452 - Attachment is obsolete: true Attachment #8924682 - Flags: review+ Pushed by mozilla@jorgk.com: Change keyboard shortcut for Chat to Ctrl+Shift+H/Cmd+Shift+H. r=Paenglab Status: ASSIGNED → RESOLVED Closed: 3 years ago Resolution: --- → FIXED Just for my education: Why did the string ID have to change? Target Milestone: --- → Thunderbird 58.0 (In reply to Jorg K (GMT+2) from comment #13) > Just for my education: Why did the string ID have to change? At least some, if not all locales share the same keyboard shortcuts, and unfortunately, changing the string ID is the only way to notify other l10ns that they must update their strings. Note the difference between real shortcut keys for commands, which can be cross-language, and access keys for menu navigation (which are obviously locale-specific, because access key is a character taken from the localized string which differs). Having to change keys for what is essentially the same string does not make sense imo; it's easy to imagine a better and simpler system where if you change a string in the (en-US) master template, all localizations get notified, but if you just edit en-US locale, they don't get notified. I think there's a bug on record.
https://bugzilla.mozilla.org/show_bug.cgi?id=1328167
CC-MAIN-2021-10
refinedweb
996
53.1
If you’re writing C# code, you should be using ReSharper. It’s a Visual Studio plugin that examines your code in real time (as you edit), helping you avoid common errors and write better code. I admit that I found ReSharper annoying when I first started using it, but after a week or so I found it invaluable. I found it so useful at work that I purchased a license myself so that I can use it at home. It’s not exactly cheap (about $150), but I find that it improves my code and saves me time. Well worth the price. But sometimes its suggestions are just annoying. One in particular drives me bonkers. Consider this fragment from my heap selection code: while (srcEnumerator.MoveNext()) { if (ExtractCompare(srcEnumerator.Current, _numItems, _numItems, 0) > 0) { // The current item is larger than the smallest item. // So move the current item to the root and sift down. Swap(0, _numItems); SiftDown(0); } } ReSharper suggests that I “Invert ‘if’ statement to reduce nesting.” If I tell it to perform the transformation, it turns the code into this: while (srcEnumerator.MoveNext()) { if (ExtractCompare(srcEnumerator.Current, _numItems, _numItems, 0) <= 0) continue; // The current item is larger than the smallest item. // So move the current item to the root and sift down. Swap(0, _numItems); SiftDown(0); } So rather than having a simple conditional and a short bit of subordinate code, it inverts the conditional and adds an extra logical branch in the flow. All for no good reason. Rather than saying “If condition do x,” the code is now saying “If not condition go on to the next iteration, otherwise do x.” Negative logic and a more complicated control flow does not, in my opinion, constitute an improvement. ReSharper is suggesting that I make my code harder to read and harder to understand. Ostensibly, ReSharper is helping to avoid the arrow anti-pattern, but it’s being too aggressive. I fully agree that one should avoid writing such hideous code. However, the arrow anti pattern involves “excessive nested conditional operators.” One conditional operator is not nested. What we have here is a simple conditional that ReSharper should ignore. I can change ReSharper options to disable that suggestion, or I could annotate my code to disable that suggestion in this particular case. I won’t do the former because I want ReSharper to suggest improvements that make sense, and I definitely want to avoid the arrow anti-pattern. I won’t add ReSharper-specific (or any other tool-specific) annotations to my code because those annotations are not germane to the problem being solved. They’re just clutter. It’s bad enough that I have to suffer those XML documentation comments in the code. ReSharper got that one wrong, and there’s nothing I can reasonably do to prevent it from displaying the warning. ReSharper also warns me when I write something like this: private int _head = 0; It says, “Initializing field by default value is redundant.” And ReSharper is right. But the redundancy is harmless and even helpful at times. I like this particular redundancy because it explicitly states what the initial value of that variable is. I don’t have to think, “Oh, right. The default value is zero.” I’ve turned this warning off because there is no context in which I want to be told that my preference for explicit initialization is redundant. Besides, the compiler will silently remove the redundancy, so there’s no inefficiency in the generated code. Come to think of it, I’d like an option to flag code that doesn’t explicitly initialize something. I’d enable that option in a heartbeat. All that said, I really like ReSharper. As annoying as it can be from time to time, I find that it really does help me write better code. Highly recommended. Actually, this “Initializing field by default value is redundant.” can make sense. I looked it up the other day, and it seems to be a performance hit (10-20% on first initialisation lateron, you can just search the issue at stackoverflow), if you declare stuff to early and or without good reason. I suppose you will set the value anyways lateron, so try to live with the implied default values null and 0 whereever its possible. (Eventhough I personally think its more readable) But i found another thing with resharper. so be careful with it, look at the code (Form1 Solution) and resolve a few issues, ylu will see it yourself: using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private readonly Foo _foo; public Form1() { InitializeComponent(); _foo = new Foo(); string s; s = _foo.AddReturn(1); s = _foo.AddReturn(2); s = _foo.AddReturn(3); Console.WriteLine(s); Debug.Assert(Convert.ToInt32(s) == _foo.Count); Bar(); MessageBox.Show(@”Saving the world from a Virus”); } void Bar() { Console.WriteLine(@”Please let me Excecute, resharper!”); Console.WriteLine(@”Avoiding local variable issue for {0}”, _foo); Application.Exit(); } } internal class Foo : List { internal string AddReturn(int i) { Add(i.ToString(CultureInfo.InvariantCulture)); return this[Count – 1]; } } } I’d be pretty surprised to see any performance hit from that default initialization redundancy. If the C# compiler doesn’t remove it as redundant, I’d fully expect the JIT compiler to do so. It’s a trivial transformation. Considering the other optimizations that the compilers perform, it wouldn’t make sense for them to ignore this one. Furthermore, that single assignment is not enough to make for a “10-20%” performance hit in the initialization of a class. Not unless the class is nothing more than a bunch of variables. I’d like to see where you got your information. Do you have a.
http://blog.mischel.com/2014/02/26/resharper-annoyances/
CC-MAIN-2016-18
refinedweb
966
58.48
Please read my disclaimer. SunPower Corp., my employer, has open sourced a solar panel mismatch estimation tool called PVMismatch at the Python Package Index with a standard 3-clause BSD license. The documentation, source code and releases are also available at the SunPower Organization GitHub page. PVMismatch can be used to simulate mismatch between cells, modules and strings in a PV system. Mismatch can be caused be differences in irradiance, say by shading or by changes to the electrical characteristics of the cells such as series resistance or dark current, and these changes can lead to a difference in the current-voltage relation of the cell (aka its I-V curve). For a module made from solar cells in series, the cells must carry the same current, leading to different voltages in each cell, and so the effective I-V curve of the panel will differ from an individual cell. In some cases a cell may be forced to operate in reverse bias in order to pass the current imposed on it. There is a detailed example in the Quickstart section of the documentation, but here's a shorter demonstration of the basic features and usage: from pvmismatch import * # this imports pvcell, pvmodule, pvstring and pvsystem # create a default PV system from 10 strings of 10 300[W] panels each pvsys = pvsystem.PVsystem() f = pvsys.plotSys() # plot the system f.show() If you find any issues, please report them on GitHub. Also, if you want to contribute, there's lots to do, so please fork the repo.
https://poquitopicante.blogspot.com/2017/01/pv-power.html
CC-MAIN-2017-39
refinedweb
257
59.03
error 1119 VideoEvent - flash cs5.5Lesto May 26, 2011 4:20 AM I receive error 1119 when i try to add a listener ( all video events) the code: import fl.video.*; display.autoPlay = false; display.source = "video/olivia_intro.f4v"; function readyHandler(event:VideoEvent):void { // Pause until the video can play till the end display.pause(); display.playWhenEnoughDownloaded(); } display.addEventListener(VideoEvent.READY, readyHandler); stop(); The video work if display.addEventListener(VideoEvent.READY, readyHandler); is commented and display.play(); is added. display is an instance of FLVplayback or FLVplayback 2.5 any help? 1. Re: error 1119 VideoEvent - flash cs5.5Ned Murphy May 26, 2011 5:23 AM (in response to Lesto) It is possible you need to import the VideoEvent class explicitly. 2. Re: error 1119 VideoEvent - flash cs5.5Lesto May 26, 2011 5:38 AM (in response to Ned Murphy) Thanks Ned I tried importing explicity fl.video.VideoEvent ......no way! ...i use cs5.5 MACOSX .... in cs5 it work!! always 3. Re: error 1119 VideoEvent - flash cs5.5socalfish Jul 24, 2011 6:33 AM (in response to Lesto) I just discovered this same problem in CS5.5. Could there be something corrupted in the AS properties? Below is the error message I am receiving to the COMPLETE event. Scene 1, Layer 'Layer 2', Frame 1, Line 8 1119: Access of possibly undefined property COMPLETE through a reference with static type Class. Here is my code I have used forever... import flash.events.*; import fl.video.*; stop(); theVideo.addEventListener(VideoEvent.COMPLETE, VideoStopped); function VideoStopped(e:VideoEvent):void{ trace("VIDEO STOPPED"); }//end Anyone come across this? Is there a solution? THANKS Message was edited by: socalfish 4. Re: error 1119 VideoEvent - flash cs5.5kglad Jul 24, 2011 9:53 AM (in response to socalfish) this is an old thread but if anyone else checks it looking for a solution: publish for fp 10 or 10.1, not 10.2 5. Re: error 1119 VideoEvent - flash cs5.5socalfish Jul 24, 2011 9:58 AM (in response to kglad) Thanks Kglad. There were a couple of postings. Here is the link to the other one where I found the answer. Thanks for the reply. 6. Re: error 1119 VideoEvent - flash cs5.5Nafem Aug 19, 2011 7:15 AM (in response to socalfish) I had trouble with this and then relaied that you have to be implicit with the Event. EG.: import fl.video.FLVPlayback; import fl.video.VideoEvent; player.autoRewind = true; player.autoPlay = true; function Loop(event:fl.video.VideoEvent):void { player.play(); } player.addEventListener(fl.video.VideoEvent.AUTO_REWOUND, Loop); ----------------------------------------- You see I have added fl.video before VideoEvent and this fixed the problem. I hope this helps. 7. Re: error 1119 VideoEvent - flash cs5.5screeen Nov 20, 2011 12:15 AM (in response to Nafem) hi Nafem, wanted to thank u for this AUTO_REWOUND bit of code, it worked for me w/an FLVPlayback component when all else failed. It does NOT work w/streamed video however, and i am wondering if u know how to loop video (flv) when it is streamed, but more importantly in my case, it is NOT possible to add cue points to streamed video, and am wondering if you or anyone else here is aware of how to do that. I will post a thread on this specifically, but am thinking that the issue but have done so here to ask: is AS for streaming and FLVPlayback component radically different? Is it impossible to impliment action script that works w/FLVPlayback when a netConnection and netStream is used? thanks. 8. Re: error 1119 VideoEvent - flash cs5.5Nafem Nov 21, 2011 7:43 AM (in response to screeen) I don't know the answer off the top of my head, I will have to do some investigation and come back to you. 9. Re: error 1119 VideoEvent - flash cs5.5jesus132233 Nov 27, 2012 6:52 PM (in response to Lesto) Here Ive got a code that didnt present the error!!!! import fl.video.FLVPlayback; import fl.video.VideoEvent; Myvideo.autoPlay = true; Myvideo.autoRewind=true; Myvideo.source = "rollovers1.flv"; function Loop(event:fl.video.VideoEvent):void{ Myvideo.play(); } Myvideo.addEventListener(fl.video.VideoEvent.AUTO_REWOUND, Loop);
https://forums.adobe.com/thread/857036
CC-MAIN-2019-04
refinedweb
697
68.16
Popular JavaScript Framework Libraries: qooxdoo and SproutCore By , if at all! This week we continue our overview of the top dozen Frameworks, with qooxdoo and SproutCore. If you've just encountered this series, you may want to go back to the beginning, where we looked at the Prototype, script.aculo.us and MooTools Frameworks. In the second installment, we turned our attention to three strong contenders for the title of Framework supremacy: JQuery, the Yahoo! UI Library (YUI) and MochiKit. In part three, we continued our overview of the twelve most popular JavaScript Frameworks in use today with Dojo, Rialto and the Spry Frameworks. This week's Frameworks are relative newcomers on the scene, but have already created quite a sensation. qooxdoo - URL: - Docs: - Demos: - Community: The last Framework we looked at was Adobe Lab's Spry Framework. It relied on heavy use of HTML, CSS, with minimal JavaScript code. By designing their Framework that way, they targeted Web designers over Web developers. The makers of qooxdoo went the other way and built their Framework around object-oriented JavaScript, while minimizing HTML, CSS and the DOM. The qooxdoo library classes are fully based on namespaces and don't extend native JavaScript types, thus cutting down on global variables. It offers a full set of widgets that are close approximations to those found in desktop applications. qooxdoo implements advanced client-server communications via Ajax, using an event-based model to handle asynchronous calls. For creating mature Web applications, qooxdoo offers several solutions to choose from, including the qooxdoo Web Toolkit (QWT), the Rich Ajax Platform (RAP), and Pustefix. Widgets Although several of the other Frameworks that we've seen contain an extensive library of custom widgets, qooxdoo also includes several familiar HTML controls, including labels, images, buttons, text fields, popups, tooltips and something you might not have seen before, called an atom, which is a combination of an image with a label. The advantages to using their controls over the standard HTML ones are twofold: first, qooxdoo allows you to create and manage them exclusively in JavaScript; second, they have implemented all the cross-browser abstraction for you while providing a highly efficient foundation on which to build. For instance, labels can be configured to show an ellipsis (...) when there's not enough space to display the text or line wrap. qooxdoo Images are precached automatically and allow for PNG transparency. Our first example demonstrates how to create some Labels and TextFields, and a TextArea control and append them to the page. The qooxdoo namespace convention is to include the full package and class name, just like in the Java Language (e.g.: qx.ui.basic.Label): Element Positioning qooxdoo also borrows heavily from the Java language in its use of Layout Managers to to position elements in their parent container and on the page. Layouts include Canvas, Grid, HBox (Horizontal Box) and VBox (Vertical Box). Layouts can either be set in the container's constructor or via the setLayoutProperties() method, which all containers implement. The optional second parameter of the qx.ui.container's add() method also accepts a map containing layout properties to configure. Looking at our example above, although the code that sets the Layout isn't included, the inclusion of row and columns points to the Grid Layout. Here's an example using the Canvas Layout to position a widget relative to the right or bottom edge of the available space. The Canvas Layout also supports stretching between left and right or top and bottom: Controlling the Appearance of Page Elements Page elements' appearance can be configured using global templates called meta themes (also referred to as skins in some Frameworks), and those that affect individual elements. qooxdoo includes two themes: - Modern: a graphically rich theme, showcasing many of qooxdoo's UI capabilities - Classic: a more lightweight, MS Windows oriented theme Each meta theme is comprised of five key parts: - appearance - color - decoration - font - icon Custom themes can be created by extending existing ones or from scratch. The following code creates a custom theme and sets three color properties using a hex value, an rgb array and a named color:
http://www.webreference.com/programming/javascript/rg23/
crawl-002
refinedweb
693
50.87
Red Hat Bugzilla – Bug 137336 a2ps seems to have a font problem. Output lines are too long. Last modified: 2007-11-30 17:10:53 EST Description of problem: When I print using a2ps, the printed output looks as though it is not using the font that a2ps internally thinks it is using. The symptoms are lines running off the right side (no wrap, or wrap too late) and the font height a bit bigger than a nicely sized font for the same line vertical spacing. (i.e., looks like a default font is slipping into the process somewhere). I am using cups and a networked postscript printer (HP 2100M). Somehow, with release of FC3 imminent, this should work 'out of the box'. Version-Release number of selected component (if applicable): I am working with current fc3/devel yum updated files. Clean load a few weeks ago with fc3-3 (no change to a2ps config files or font files) [user1@hoho2 ~]$ a2ps --version GNU a2ps 4.13 Written by Akim Demaille, Miguel Santana. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. [user1@hoho2 ~]$ How reproducible: I think this same problem has existed for awhile (maybe months) Steps to Reproduce: 1. see commands below Actual results: The command below creates a single page with line numbers. Should be 10 pt font, but looking at the output, it looks bigger. The (1 line wrapped) is shown, but the first part of the line runs off the right edge and 'eadow after a shor' is totally missing on the printed page. [user1@hoho2 ~]$ a2ps -1 -f 10 --line-numbers=1 -d code.txt [code.txt (plain): 1 page on 1 sheet] request id is HP_Laser_ppd-75 (1 file(s)) [Total: 1 page on 1 sheet] sent to the default printer [1 line wrapped] [user1@hoho2 ~]$ cat code.txt #include <stuff> /* This should be a long line */ printf("%s","A quick brown fox jumped over the big green box in the meadow after a short nap"); [user1@hoho2 ~]$ Expected results: I should be able to see all of the words on the printed page. Additional info: I can attach the generated postscript file if you wish. Confirmed with a2ps-4.13b-41. Same problem exists on Fedora Core 3 Clean installation from CDs, move of old /old/home/user1 to /home/user1 after user1 was created in new system. I think it is also related to Mozilla printing of plain text lines - too large and Mozilla does not have the correct metric to figure out where the text is on the printed page. Note that this problem does not exist on RedHat 9. Since my problem stemed from printing using a2ps and also shows up in Mozilla, I am focusing on CUPS as the root of the problem. Check out this extremely well written critique of CUPS - at least from the GUI and documentation thought-process point of view I suspect that debugging font metrics for the default monospace font are deep in the same mire. OK, fixed it. Gnome->System Settings->Printing->(select printer queue)->Action->Import PPD I navigated to the ppd file which came on the disk with my printer (HP 2100M). The application 'opened' it and did whatever with it. Gnome->System Settings->Printing->(select printer queue)->(button)Edit->(tab)Printer Driver This panel recommends using the pxlmono driver for my printer (HP 2100M). Since my printer IS a postscript printer, ignoring this advice and choosing the 'Postscript' printer does the trick. I also did a 'kill -HUP xxx' on the pid of every process with a 'cups' in the name. (it is like a wooden stake..) ---- Mow, both the 'code.txt' sample and pages in Mozilla with <pre> plain text print very nicely. Works for me, but there is still a problem in the 'plxmono' driver for real Postscript printers. Created attachment 109590 [details] Broken postscript output of a2ps The above attachment was created using a2ps as follows: a2ps foo.txt -o foo.ps This problem appears both with a2ps, enscript and firefox printing. I tried changing the printer driver to no avail. My default printer is a laserjet 1100, and I tried both hpijs and ljet4, with no discrenable difference. I'm seeing this problem on FC3. *** This bug has been marked as a duplicate of 140584 ***
https://bugzilla.redhat.com/show_bug.cgi?id=137336
CC-MAIN-2017-47
refinedweb
735
72.16
IRC log of rif on 2010-07-27 Timestamps are in UTC. 14:53:04 [RRSAgent] RRSAgent has joined #rif 14:53:04 [RRSAgent] logging to 14:53:17 [csma] rrsagent, make minutes 14:53:17 [RRSAgent] I have made the request to generate csma 14:53:25 [csma] rrsagent, make log public 14:53:46 [csma] Meeting: RIF telecon 27 July 2010 14:54:00 [csma] Chair: Christian de Sainte Marie 14:54:25 [csma] Agenda: 14:54:45 [csma] csma has changed the topic to: RIF telecon 27 July; agenda: (csma) 14:55:25 [csma] Regrets: DaveReynolds 14:55:34 [csma] zakim, clear agenda 14:55:34 [Zakim] agenda cleared 14:55:53 [csma] agendum+ Admin 14:56:16 [csma] agendum+ liaisons 14:56:24 [csma] agendum+ Actions review 14:56:52 [csma] agendum+ Feedback on SPARQL ER 14:57:06 [csma] agendum+ XML data 14:57:13 [csma] agendum+ Primer 14:57:23 [csma] agendum+ RIF in RDF 14:57:36 [csma] agendum+ Test cases 14:57:53 [csma] agendum+ AOB (next meeting: 10 August) 15:00:03 [Zakim] SW_RIF()11:00AM has now started 15:00:10 [Zakim] +Sandro 15:00:16 [Harold] Harold has joined #rif 15:01:07 [lmorgens] lmorgens has joined #rif 15:01:37 [Zakim] +Leora_Morgenstern 15:01:53 [Zakim] + +33.1.49.08.aaaa 15:02:16 [csma] zakim, aaaa is me 15:02:16 [Zakim] +csma; got it 15:02:17 [ChrisW_] ChrisW_ has joined #rif 15:02:34 [Zakim] +[IBM] 15:02:43 [ChrisW_] yo zakim, ibm is temporarily me 15:02:58 [ChrisW_] zakim, ibm is temporarily me 15:02:58 [Zakim] +ChrisW_; got it 15:03:04 [Zakim] +[IPcaller] 15:03:49 [Zakim] + +1.503.533.aabb 15:04:16 [AdrianP] AdrianP has joined #rif 15:04:29 [AdrianP] Zakim, who is on the phone? 15:04:29 [Zakim] On the phone I see Sandro, Leora_Morgenstern, csma, ChrisW_, [IPcaller], +1.503.533.aabb 15:04:40 [AdrianP] Zakim, [IPcaller] is me 15:04:40 [Zakim] +AdrianP; got it 15:04:40 [ChrisW] zakim, ChrisW_ is me 15:04:41 [Zakim] +ChrisW; got it 15:04:47 [AdrianP] Zakim, mute me 15:04:47 [Zakim] AdrianP should now be muted 15:05:07 [ChrisW] zakim, aabb is Gary 15:05:07 [Zakim] +Gary; got it 15:05:30 [Zakim] +[NRCC] 15:05:39 [Gary_Hallmark] Gary_Hallmark has joined #rif 15:05:50 [Harold] zakim, [NRCC] is me. 15:05:50 [Zakim] +Harold; got it 15:05:50 [AdrianP] Zakim, unmute me 15:05:52 [Zakim] AdrianP should no longer be muted 15:06:05 [csma] Scribenick: Gary 15:06:08 [ChrisW] Scribe: Gary 15:06:21 [csma] zakim, next item 15:06:21 [Zakim] agendum 1. "Admin" taken up [from csma] 15:06:29 [ChrisW] rrsagent, make logs public 15:06:40 [csma] 15:06:59 [csma] PROPOSED: approve the minutes of July 13 telecon 15:07:25 [csma] RESOLVED: approve the minutes of July 13 telecon 15:08:07 [MichaelKifer] MichaelKifer has joined #rif 15:08:50 [Zakim] + +1.631.833.aacc 15:08:55 [csma] zakim, next item 15:08:55 [Zakim] agendum 2. "liaisons" taken up [from csma] 15:09:13 [MichaelKifer] zakim, aacc is me 15:09:13 [Zakim] +MichaelKifer; got it 15:09:33 [csma] zakim, next item 15:09:33 [Zakim] agendum 2 was just opened, csma 15:09:44 [csma] zakim, close item 2 15:09:44 [Zakim] agendum 2, liaisons, closed 15:09:46 [Zakim] I see 7 items remaining on the agenda; the next one is 15:09:48 [Zakim] 3. Actions review [from csma] 15:09:57 [csma] zakim, next item 15:09:57 [Zakim] agendum 3. "Actions review" taken up [from csma] 15:10:13 [sandro] zakim, ping 15:10:13 [Zakim] I don't understand 'ping', sandro 15:10:57 [csma] zakim, who is on the phone? 15:10:57 [Zakim] On the phone I see Sandro, Leora_Morgenstern, csma, ChrisW, AdrianP, Gary, Harold, MichaelKifer 15:11:50 [Gary] csma: removing string match from xml-data 15:13:49 [ChrisW] close action-1034 15:13:50 [trackbot] ACTION-1034 Contact Stella about test cases status closed 15:14:57 [csma] zakim, next item 15:14:57 [Zakim] agendum 4. "Feedback on SPARQL ER" taken up [from csma] 15:16:59 [Gary] sandro: a conversation with sparql makes more sense than a big review, because there are several issues 15:18:07 [Gary] ... ask Jos to send comments to sparql comments list 15:19:18 [Gary] csma: one issue is we think sparql should not restrict RIF 15:19:22 [csma] zakim, next item 15:19:22 [Zakim] agendum 5. "XML data" taken up [from csma] 15:20:12 [Gary] csma: incorporating Jos' and Michael's comments 15:20:39 [Gary] ... currently doc is in flux 15:21:47 [Gary] ... reduce size of xpath related material 15:21:49 [ChrisW] Harold, do you really want "skype highlighting" on your name in the Primer editors list? 15:22:46 [Gary] cmsa: use NCName to refer to many attributes and some elements that have no namespace 15:23:03 [Gary] ... no namespace => can't use rif:iri 15:24:18 [Gary] sandro: suggest using a dummy namespace 15:25:16 [Gary] ... or a local symbol 15:25:51 [sandro] I cant decide if using local is incredibly evil, or pretty clever. 15:28:15 [Gary] sandro: dummy namespace might be more straightforward 15:28:37 [Gary] ... but could offend some xml sensibilities 15:30:50 [Gary] csma: will go with dummy namespace for now 15:31:03 [csma] zakim, next item 15:31:03 [Zakim] agendum 6. "Primer" taken up [from csma] 15:31:33 [Gary] harold: making progress and have received some feedback 15:31:59 [Harold] 15:33:01 [Gary] csma: why if (a,b) rather than if a then b? 15:33:39 [sandro] 15:34:31 [Gary] leora: came from common logic, but is fine with if a then b 15:35:31 [Gary] harold: don't want to confuse with PRD 15:36:01 [AdrianP] but shouldn't we use a syntax which is understandable to the RIF community in the Primer, since the Primer is meant to give easy access to RIF? 15:36:02 [Gary] csma: it does not conflict (means the same thing) 15:38:35 [csma] q? 15:39:34 [Gary] chris: I uploaded several editorial changes to the primer on the wiki 15:41:48 [Gary] harold: we will change to If a Then b 15:43:01 [Gary] csma: target a review in 2 weeks 15:43:08 [ChrisW] zakim, who is here? 15:43:08 [Zakim] On the phone I see Sandro, Leora_Morgenstern, csma, ChrisW, AdrianP, Gary, Harold, MichaelKifer 15:43:10 [Zakim] On IRC I see MichaelKifer, Gary, AdrianP, ChrisW, lmorgens, Harold, RRSAgent, Zakim, csma, AxelPolleres, sandro, trackbot 15:45:23 [ChrisW] zakim, pick a victim 15:45:23 [Zakim] Not knowing who is chairing or who scribed recently, I propose Sandro 15:45:36 [ChrisW] zakim, pick a victim 15:45:36 [Zakim] Not knowing who is chairing or who scribed recently, I propose csma 15:45:43 [ChrisW] zakim, pick a victim 15:45:43 [Zakim] Not knowing who is chairing or who scribed recently, I propose Gary 15:45:47 [dave] dave has joined #rif 15:46:47 [DaveReynolds] DaveReynolds has joined #rif 15:47:02 [csma] Dave, don't leave! We have been waiting for you! 15:47:31 [csma] action: Sandro t oreview RIF Primer by August 27 15:47:31 [trackbot] Created ACTION-1035 - T oreview RIF Primer by August 27 [on Sandro Hawke - due 2010-08-03]. 15:47:31 [Zakim] +??P13 15:47:53 [csma] action: Gary to review RIF Primer by August 27 15:47:53 [trackbot] Created ACTION-1036 - Review RIF Primer by August 27 [on Gary Hallmark - due 2010-08-03]. 15:48:13 [csma] zakim, next item 15:48:13 [Zakim] agendum 7. "RIF in RDF" taken up [from csma] 15:49:49 [Gary] sandro: differs from Dave R 15:50:08 [Gary] ... key issue: is RDF a KR? 15:51:35 [Gary] dave: RIF is different from RDF. An encoding is closed world 15:58:13 [Gary] sandro: instead of optional elements, use empty lists 15:58:56 [Gary] dave: isn't this a corner case? 15:59:12 [sandro] dave: I expect extensions to add namespaces, not so much to fiddle with the core elements. 16:00:47 [Gary] csma: can a dialect mark a mandatory piece of core as optional? 16:00:53 [sandro] sandro: I've gotten used to this idea that rif syntactic elements don't get changed by extensions, even if how they are used (eg their cardinality). 16:02:31 [Gary] sandro: my mapping of xml to rdf requires that optional or repeated elements be lists 16:03:47 [Gary] chris: I favor following existing xml syntax (and not lists) 16:06:26 [Gary] csma: if you want to process a RIF XML document, you must understand RIF 16:07:24 [Gary] sandro: wants RDF graph (encoding a RIF document) to be "stable" under various RDF transformations 16:08:31 [Gary] ... including open-world processing 16:09:22 [sandro] sandro: It's important to me that people use RDF in an open-world KR sort of way. I don't want RIF-in-RDF to go the other way.... 16:10:32 [Gary] sandro: sparql 1.1 lets you query lists but order is not preserved 16:11:02 [sandro] dave: It's important to me be able to use SPARQL to search for bits of rules -- 1.1 will provide that, so I can live with this. 16:12:09 [sandro] In SPARQL 1.1 you CAN query for list members, but you can't get the elements back in order. 16:12:25 [sandro] (sort of DESCRIBE on the list/rule) 16:12:44 [sandro] dave: You won't write a parser in SPARQL, but it's good to be able to query for rule structures. 16:13:01 [sandro] dave: I'd like the requirement phrased differently, though. 16:13:27 [Gary] michael: neutral 16:14:37 [Gary] ... probably easier to do some transformations if lists are used 16:14:38 [sandro] michael: The rule encoded in RDF is no longer a rule, so I no longer find the KR argument compelling. But transformations are probably easier with lists. 16:15:08 [sandro] harold: OWL can express some rules, eg subsumption. 16:16:00 [Gary] chris: using lists doesn't correspond to our xml syntax in an obvious, neat way 16:16:05 [sandro] chris:What sways me against lists is the RDF and XML syntaxes not aligning as well. 16:17:07 [Gary] sandro: no parallel to OWL2 xml to rdf mapping 16:20:18 [Harold] The names used in the RDF syntax should be chosen as close to those of the XML syntax as possible. 16:20:56 [sandro] the four optional/repeated properties are: directive, sentence, declare, formula 16:20:59 [Gary] csma: prefer the mapping preserve the rif xml names, but not use lists 16:22:46 [Gary] sandro: give enough time, would implement with and without lists and see what works out 16:23:05 [Gary] ... but to choose now, would choose lists 16:23:24 [Gary] s/give/given 16:24:27 [sandro] PROPOSED: Do RIF-in-RDF with repeated properties (instead of the list encoding) 16:24:31 [sandro] -1 16:24:52 [ChrisW] +1 16:24:57 [DaveReynolds] +1 16:24:59 [Harold] +1 16:25:03 [csma] +1 16:25:08 [lmorgens] 0 16:25:10 [AdrianP] +1 16:25:20 [sandro] PROPOSED: Do RIF-in-RDF with the list encoding, instead of repeated properties. 16:25:23 [sandro] +1 16:25:26 [DaveReynolds] 0 16:25:32 [csma] 0 16:25:35 [ChrisW] 0 (prefer cleaner correspondance to XML syntax) 16:25:38 [Harold] 0 16:25:41 [AdrianP] 0 16:25:50 [lmorgens] 0 16:26:07 [sandro] RESOLVED: Do RIF-in-RDF with the list encoding, instead of repeated properties. 16:26:26 [csma] RESOLVED: Do RIF-in-RDF with the list encoding, instead of repeated properties. 16:27:20 [Zakim] -Harold 16:27:23 [Zakim] -MichaelKifer 16:27:24 [AdrianP] bye 16:27:28 [DaveReynolds] bye 16:27:32 [MichaelKifer] MichaelKifer has left #rif 16:27:35 [Zakim] -DaveReynolds 16:27:36 [Zakim] -Leora_Morgenstern 16:27:37 [csma] zakim, list attendees 16:27:38 [Zakim] -AdrianP 16:27:39 [Zakim] As of this point the attendees have been Sandro, Leora_Morgenstern, +33.1.49.08.aaaa, csma, +1.503.533.aabb, AdrianP, ChrisW, Gary, Harold, +1.631.833.aacc, MichaelKifer, 16:27:42 [Zakim] ... DaveReynolds 16:27:50 [csma] rrsagent, make minutes 16:27:50 [RRSAgent] I have made the request to generate csma 16:30:40 [Zakim] -Gary 16:32:21 [Zakim] -Sandro 16:32:22 [Zakim] -ChrisW 16:32:23 [Zakim] SW_RIF()11:00AM has ended 16:32:25 [Zakim] Attendees were Sandro, Leora_Morgenstern, +33.1.49.08.aaaa, csma, +1.503.533.aabb, AdrianP, ChrisW, Gary, Harold, +1.631.833.aacc, MichaelKifer, DaveReynolds 17:47:04 [AxelPolleres] AxelPolleres has joined #rif 17:47:52 [AxelPolleres] AxelPolleres has joined #rif
http://www.w3.org/2010/07/27-rif-irc
CC-MAIN-2017-30
refinedweb
2,228
62.21
The migration to WordPress has brought with it a number of useful new features built into the DSC Editor, making it easier than ever to create technical content, tables, and even mathematical equations directly into articles, dramatically reducing the difficulty of writing about code and making for far better-looking articles and output. This article explores a few of them, illustrating how specifically to use the new Gutenberg components to build out professional-quality content. Formatting Shortcuts Certain special characters, when used at the beginning of a paragraph, will automatically let you create specialized content quickly. For instance, if you type the hash character (#) the first character, then insert a space, the line will become a primary (H1) header. Two hashes will create a secondary (H2) header and so on down to H6. # This is an H1 header ## This is an H2 header ### This is an H3 header This is an H1 header This is an H2 header This is an H3 header By doing this, you can create headers automatically that use the current CSS formatting for the page. You can similarly use the * character as the first character in a paragraph to start an unordered list, and a 1 followed by a dot to create an ordered list. * This is the first item of an unordered list. * This is the second item of an unordered list - This is the first item of an unordered list. - This is the second item of an unordered list. 1. This is the first item of an ordered list 2. This is the second item of an ordered list - This is the first item of an ordered list - This is the second item of an ordered list Once you start an ordered list, each subsequent line will be the next number in the order. You can add a block quote by starting the paragraph with a right arrow bracket. > It was the best of times, it was the worst of times Charles Dickens` It was the best of times, it was the worst of times.Charles Dickens Creating Code Blocks To create an inline code sequence, use the backtick(`) character at the beginning and end of the sequence. This is an `inline block` of code. This is an inline block of code. You can also create a multiline code block by typing in three backticks and a carriage return (then doing the same at the end of this expression: ``` var expr = "This is a test."; expr.split(' ').join(', ') ``` var expr = "This is a test." expr.split(' ').join(', ') Short Codes and Tricks For frequent operations, you can also use the forward-slash character (/) at the beginning of a paragraph to bring up various options. This is often faster and easier than remembering specific key sequences. What options you see are largely predicated upon what kind of access you have to the system. For instance, from my account, when I start a paragraph with the forward slash, what shows up is a pop-up box listing about nearly ten possible states. Selecting one of these will change the block to reflect the associated state. The options usually reflect the most frequently accessed Gutenberg blocks. The forward slash / is an indicator for a short code. Such shortcodes make it possible to insert inline blocks that can be rendered as HTML, SVG or similar output. When the focus is inserted into such a block, an editor bar will then be displayed, allowing for customization of the particular block’s capabilities. Again, the specific details of this bar will vary depending upon the block in question, but the edit blocks make it possible to do fine-grain tuning of the resource in question. Additionally, on the right-hand side of the page, the available capabilities are displayable in a sidebar under the Block tab. This is useful for setting up code blocks to pretty print code output appropriate to the language itself. From within the editor, you can access a number of different features simply by beginning a paragraph line with the forward slash (/) character. When you do this, WordPress will display a popup menu with a number of the more frequently used Gutenberg blocks – special formatting blocks that let you edit content and even have it display while in the editor. Gutenberg Tables and Katex Additional Gutenberg blocks can be inserted by clicking the white on blue + at the upper-left part of the editor display. There will likely be anywhere from a dozen to several dozen components. One of the more useful of these, especially if you are used to work with the older Ning environment, is the Classic editor, which lets you embed a single pane editor within the page editor. Given that the Gutenberg components can occasionally be a bit unwieldy, this provides a good what of creating the majority of the content that you need, then inserting special components into the editor for the rest. Images and media can also be added through the component menu (+), and images can either be uploaded to the DSC’s repository or linked to via URLs, then edited to suit. Similarly, the default Table component is fairly sophisticated, though the lack of the ability to override the default TAB behavior to allow movement from one cell to the next can be annoying (you can use the arrow keys (with or without the ctrl/command key to initiate fast movement). Take advantage of the Block editor on the right-hand part of the page to deal with modifying table options. One of the more powerful tools in the Gutenberg toolbox is the KateX layout engine, which lets you write LateX code directly into articles and blog posts. For instance, here’s a weighted sum using the following LateX code, and rendered through KateX : \textbf{a}_j = \sum_{i=1}^n\omega_{ij}\textbf{u}^i \textbf{a}_j = \sum_{i=1}^n\omega_{ij}\textbf{u}^i There are other tools that are available to contributors through the Gutenberg plus selector. If you have any questions about how these should be used, please contact the editors at [email protected] for more information, and look out for more handy tips and tricks in creating your posts.
https://www.datasciencecentral.com/dsc-editing-tricks-and-tips/
CC-MAIN-2022-21
refinedweb
1,037
56.29
AWS Machine Learning Blog. With Gluon, you can build machine learning models using a simple Python API and a range of pre-built, optimized neural network components. This makes it easy to build neural networks using simple code without sacrificing training performance. Gluon makes building new computer vision models easy; just create your model in SageMaker, and with a single click deploy it to your DeepLens, where the model optimizer will automatically optimize it for the best performance on the device. In this post, we will walk you through developing a deep neural network model in Amazon SageMaker to detect the direction of the head and deploy it to AWS DeepLens. When there is a person in front of us, we humans can immediately recognize the direction in which the person is looking. For example, the person might be facing straight toward you, or the person might be looking somewhere else. The direction is defined as the head pose. We are going to develop a convolutional neural network mode (CNN) to estimate the head pose using images of human heads. The different head poses are classified as follows: down right, right, up right, down, middle, up, down left, left, and up left. Detecting the head pose could be used to understand who is paying attention in a classroom setting, viewer behavior in advertising, and even in driver assistance systems. Gluon, the imperative interface in Apache MXNet, offers four major advantages over the symbolic MXNet. First, Gluon offers a full set of plug-and-play neural network building blocks such as predefined layers, optimizers, and initializers. Second, it also allows us to bring the training algorithm and model closer together, which provides flexibility in the development process. Third, it enables developers to define their dynamic neural network models so that they can be built on the fly using Python’s native control flow. Finally, Gluon provides all the benefits without sacrificing the training speed that the underlying engine provides. Data: Prima Project head-pose image database First, let’s identify the head-pose dataset we are going to use for the project. For this blog post we will use the Prima Project head pose images. You will find the original raw data in the following link: Dataset: Citation: N. Gourier, D. Hall, J. L. Crowley Estimating Face Orientation from Robust Detection of Salient Facial Features Proceedings of Pointing 2004, ICPR, International Workshop on Visual Observation of Deictic Gestures, Cambridge, UK There are a total of 2,790 head pose images and their corresponding tilt and pan angle attributes in the dataset. The tilt is defined as the north-south vertical axis, and the pan is defined as the east-west horizontal axis. The dataset is composed of head-pose data for fifteen different individuals. Thus, there are 186 images for each subject (2,790/15 = 186). In this dataset, the head pose is categorized into 9 and 13 discrete tilt and pan angles, respectively (Tilt angles: -90°, -60°, -30°, -15°, 0°, +15°, +30°, +60°, and +90° from head-down posture to head-up posture. Pan angles: -90°, -75°, -60°, -45°, -30°, -15°, 0°, +15°, +30°, +45°, +60°, +75°, and +90° from the observer’s right to the left). When a subject is looking straight into a camera, both tilt and pan angles are 0°. The original image dimensions are 384 x 288 pixels. Preprocessing the image data Next, we preprocess the image data that will be used to train a neural network. We have a Python script (python2 preprocessingDataset_py2.py) for the preprocessing. Run the following command to prepare the input data to generate HeadPoseData_trn_test_x15_py2.pkl (6.7 GB). This command lets you generate input images with the dimensions of 84 x 84 pixels and their corresponding head-pose angles. During the preprocessing, applying the same scaling factor in both height and width of an input image is crucial for the head-pose estimator. If the scaling factors in two axes are different, the head-pose angle is altered. We are mainly targeting two different aspect ratios (1:1 and 16:9). (Spoiler alert! The aspect ratio of full frame size in an AWS DeepLens device is 16:9. Thus, if you want to use the entire frame data from AWS DeepLens for inference, the aspect ratio of 16:9 will be your choice. We used the model trained with the aspect ratio of 1:1 for our final product. Our final product only takes a part of frame data in a square shape for inference.) Inside the preprocessing script, the original head images were cropped and resized into a target image size while applying the same scaling factor in two orthogonal axes (84 x 84 pixels and 96 x 54 pixels for aspect ratios of 1:1 and 16:9, respectively). The following figure demonstrates the image preprocessing procedure in which the target aspect ratio is 16:9. First, a rectangular crop region with arbitrary length was applied to each image based on the following three criteria: (1) its aspect ratio is 16:9, (2) it must fully contain a face region inside, and (3) it must be contained within the image frame. The selected area is then resized into 96 x 54 pixels. This preprocessing procedure mimics the digital (as well as optical) zoom in a camera. This preprocessing was repeated 15 times for the data augmentation. Head-pose classification Next, we prepare the label data from head-pose angles. The head pose was classified into nine categories (the combinations of three tilt and three pan classes). The head pose contained within ± 19.5° in tilt and pan angles is labeled as a center position (Head pose Class of 4, Tilt Class of 1, and Pan Class of 1). The rationale behind the selection of threshold angles is that sin(19.5°) is equal to 0.33. Therefore, these two angles split a semicircle (the distance between sin(-90°) and sin(90°)) into three equal arc lengths. Train the ResNet-50 model using Gluon Creating the nine labels reduced the head-pose problem into a simple image classification task (that is, using an image as input, estimating one head pose out of nine). The model is fine-tuned from a ResNet-50 that we obtained from the MXNet model zoo. There are five main parts in the sample notebook: (1) data loading, (2) additional data augmentation, (3) fine-tuning ResNet-50, (4) validation, and (5) inference. Parts (1), (2), and (3) are especially important for training the model. Head-Pose Gluon Tutorial Notebook: ResNet-50 Model from model zoo We first download a pre-trained ResNet-50 model. Here is how you load the pre-trained model on Gluon. Obtain a pre-trained ResNet Model from model zoo The ImageNet pre-trained model has 1,000 categorical outputs. However in our case, we only need nine. Thus, we need to modify the number of output classes to match our labels. Modify the ResNet 50 model from model zoo Another ResNet-50 model called “net” is prepared. The “net” has nine class-outputs. Then, features from “pretrained_net” are passed onto the “net”. Note that the “net” is a model network in the serialized format. We are going to fine-tune the model. Train the model In this section we show you two helper functions for the training. Training helper functions The first helper method is for the accuracy evaluation during the training, and the other is a training loop. For the sake using this with AWS DeepLens, save the checkpoint model artifacts in the symbolic format (that is, .json and .params). Because “net” is in the serial format, we use the .export method to save a serial model in the symbolic model artifact. In addition, we want a softmax output layer at the end of our network. Thus, we used the Symbol API method to add a softmax output and .save method to overwrite the .json file. If you want to save the serialized model in the serial format, you can simply use the .save_param method. Here is an example of how you save the serialized model weights and pass the weights to another serialized model. Save the model in the serial (Gluon) format We now have all the tools necessary to train the model. Let’s start the fine-tuning. Fine-tune the model The hybridize method allows us to save the serialized model (“net”) in the symbolic format. Hopefully, the rest of the notebook is self-explanatory. After you successfully run the training, you will have .json and multiple model weights (.params) from multiple checkpoints. You have to hand-pick one .param that gives you the best validation accuracy. We trained the model on a p2.8xl ec2 instance running the AWS Deep Learning AMI Ubuntu version, and we achieved validation accuracy of ~80% with this dataset. Train the ResNet-50 model using Amazon SageMaker (Python SDK) with Gluon So far, we walked through the basics of how to train a CNN using Gluon in Python. The next step is to reproduce the same model training experience on the Amazon SageMaker Python SDK. Amazon SageMaker is a fully-managed service that enables developers and data scientists to quickly and easily build, train, and deploy machine learning models at any scale. To use our dataset and code, we’ll write a custom entry point Python script to run on Amazon SageMaker. S3 bucket Create an AmazonS3 bucket first if you don’t have one. In this example, we are going to name the S3 bucket “deeplens-sagemaker-0000” hosted in the N. Virginia (US East 1) AWS Region. (If you want to deploy your trained model artifacts straight into AWS DeepLens, the region must be N. Virginia (US East 1)). Inside the bucket, we have a folder named “headpose.” Inside the “headpose” folder, we have 4 sub-folders named “artifacts,” “customMXNetcodes,” “datasets,” and “testIMs.” You are going to host the head-pose dataset you created earlier ( HeadPoseData_trn_test_x15_py2.pkl) in the datasets folder. That is it for the preparation. Amazon SageMaker notebook Now, you launch Amazon SageMaker. After you open Amazon SageMaker notebook, upload our sample notebook and entry point Python script ( HeadPose_SageMaker_PySDK-Gluon.ipynb and EntryPt-headpose-Gluon.py, respectively). After you place the notebook and entry point script, there are only three steps for you to run the training. First, specify your S3 bucket name in the sample Amazon SageMaker notebook ( HeadPose_SageMaker_PySDK-Gluon.ipynb). In this part, you also specify other folders inside your S3 bucket such as the “headpose” folder as well as the “artifacts” and “customMXNetcodes” folders underneath it. Second, specify the training instance and other parameters in the MXNet object. In this example, we use a ml.p2.xlarge instance for the training. “train_max_run” represents the maximum training time that the training instance is running in units of seconds (432000 seconds = 5 days) in case that the training takes a long time. “train_volume_size” corresponds to the disk volume of the training instance in GB. You also see that the MXNet object, headpose_estimator takes the name of entry point script (i.e. EntryPt-headpose-Gluon.py) as well as folder locations such as “model_artifacts_location” and “custom_code_upload_location”. We name this job “deeplens-sagemaker-headpose”. The base_job_name will be the prefix of output folders we are going to create. For the model development for AWS DeepLens, it is a good practice to include both “deeplens” and “sagemaker” in the name of the Amazon S3 bucket as well as the name of the job. Finally, we run the training by calling the “.fit” method. The method “.fit” takes the location of input dataset in the Python dictionary form. This is how we run the training using Amazon SageMaker Python SDK. You can monitor the progress of the training on either the Amazon SageMaker or the Amazon CloudWatch consoles. Entry point Python script All details for the head-pose model training are described in the entry point Python script ( EntryPt-headpose-Gluon.py). You may want to closely look at the similarity between EntryPt-headpose-Gluon.py and HeadPose_ResNet50_Tutorial-Gluon.ipynb that we just discussed earlier. They are basically the same except for some instructions on directories to output and save model artifacts (such as model_dir and output_data_dir). You may also want to compare EntryPt-headpose-Gluon.py and EntryPt-headpose.py, which is the symbolic Apache MXNet version of the head-pose entry point script. The notable difference between two entry point Python scripts is that the Gluon script has two additional functions (save and model_fn). Because we want to develop the model for AWS DeepLens, we need to save the model in the symbolic format. However, the “net” in the function “train” is in the serial Gluon format. The function “save” accepts the return from function “train”, saves the format in any format that you want and places the model artifact in model.tar.gz. Without the “save”, Amazon SageMaker automatically saves the “net” in its default format. def model_fn(model_dir): The function “model_fn” is served for the same reason—the discrepancy between the formats of trained network and saved model artifact for the inference hosting. After you successfully run the training, you have model.tar.gz in output folder inside artifacts folder. Inside the model.tar.gz, you find a pair of model-symbol.json and model-0000.params that produced the best validation accuracy during the training. If you have your AWS DeepLens account, you can find the model artifacts you just developed on AWS DeepLens console. In the AWS DeepLens console, choose Models, select “Amazon SageMaker trained model” and scroll down the Job IDs. You can immediately deploy the model to your AWS DeepLens device. Conclusion In this blog post we developed a head-pose estimator CNN model using the Gluon interface in Apache MXNet using Amazon SageMaker and deployed on to the AWS DeepLens device. We also dove deep into the difference between symbolic and serial model formats and showed you how to handle them for your own application. The symbolic interface for the same application is also provided in the github repo ( HeadPose_ResNet50_Tutorial.ipynb, HeadPose_SageMaker_PySDK.ipynb, and EntryPt-headpose.py). The Amazon SageMaker Python SDK allows you to bring your custom Apache MXNet or Gluon script and dataset and makes it easy to train, deploy, and test Deep Learning models. About the Authors Tatsuya Arai PhD is a biomedical engineer turned deep learning oriented data scientist at Amazon ML Solutions Lab. He believes that the power of AI isn’t exclusively for computer scientists or mathematicians. Vikram Madan is a Senior Product Manager for AWS Deep Learning. He works on products that make deep learning engines easier to use with a specific focus on the open source Apache MXNet engine. In his spare time, he enjoys running long distances and watching documentaries. Eddie Calleja is a Software Development Engineer for AWS Deep Learning. He is one of the developers of the DeepLens device. As a former physicist he spends his spare time thinking about applying AI techniques to modern day physics problems. Brad Kenstler is a Data Scientist on the AWS Deep Learning Team. As part of the AWS ML Solutions Lab, he helps customers adopt ML & AI within their own organization through educational workshops and custom modeling. Outside of work, Brad enjoys listening to heavy metal and bourbon tasting. Sunil Mallya is a Senior Solutions Architect in the AWS Deep Learning team. He helps our customers build machine learning and deep learning solutions to advance their businesses. In his spare time, he enjoys cooking, sailing and building self driving RC autonomous cars. Jyothi Nookula is a Senior Product Manager for AWS DeepLens. She loves to build products that delight her customers. In her spare time, she loves to paint and host charity fund raisers for her art exhibitions.
https://aws.amazon.com/blogs/machine-learning/deploy-gluon-models-to-aws-deeplens-using-a-simple-python-api/
CC-MAIN-2021-49
refinedweb
2,646
56.05
LDFCN(3) Library Functions Manual LDFCN(3) NAME ldfcn - common object file access routines SYNOPSIS #include <<stdio.h>> #include <<filehdr.h>> #include <<ldfcn.h>> AVAILABILITY Available only on Sun 386i systems running a SunOS 4.0.x release or earlier. Not a SunOS 4.1 release feature. DESCRIPTION These routines are for reading COFF object files and archives contain- ing COFF object files., declared in the header file ldfcn.h. The primary purpose of this structure is to provide uniform access to both simple object files and to object files that are members of an archive file. The function ldopen(3X) allocates and initializes the LDFILE structure and returns a pointer to the structure to the calling program. The fields of the LDFILE structure may be accessed individually through macros defined in ldfcn.h and contain the following information: LDFILE *ldptr; TYPE(ldptr) The file magic number used to distinguish between ar- chive members and simple object files. IOPTR(ldptr) The file pointer returned by fopen and used by the stan- dard input/output functions. OFFSET(ldptr) The file address of the beginning of the object file; the offset is non-zero if the object file is a member of an archive file. HEADER(ldptr) The file header structure of the object file. The object file access functions themselves may be divided into four categories: (1) Functions that open or close an object file ldopen(3X) and ldaopen() (see ldopen(3X)) open a common object file ldclose(3X) and ldaclose() (see ldclose(3X)) close a common object file (2) Functions that read header or symbol table information ldahread(3X) read the archive header of a member of an archive file ldfhread(3X) read the file header of a common object file ldshread(3X) and ldnshread() (see ldshread(3X)) read a section header of a common object file ldtbread(3X) read a symbol table entry of a common object file ldgetname(3X) retrieve a symbol name from a symbol table entry or from the string table (3) Functions that position an object file at (seek to) the start of the section, relocation, or line number information for a particular section. ldohseek(3X) seek to the optional file header of a common object file ldsseek(3X) and ldnsseek() (see ldsseek(3X)) seek to a section of a common object file ldrseek(3X) and ldnrseek() (see ldrseek(3X)) seek to the relocation information for a section of a common object file ldlseek(3X) and ldnlseek() (see ldlseek(3X)) seek to the line number information for a section of a common object file ldtbseek(3X) seek to the symbol table of a common object file (4) The unction ldtbindex(3X), which returns the index of a par- ticular common object file symbol table entry. These functions are described in detail on their respective manual pages. All the functions except ldopen(3X), ldgetname(3X), ldtbindex(3X) return either SUCCESS or FAILURE, both constants defined in ldfcn.h. ldopen(3X) and ldaopen() (see ldopen(3X)) both return pointers to an LDFILE structure. Additional access to an object file is provided through a set of macros defined in ldfcn.h. These macros parallel the standard input/output file reading and manipulating functions, translating string table. See the manual entries for the corresponding standard input/output library functions for details on the use of the rest of the macros. The program must be loaded with the object file access routine library libld.a. SEE ALSO fseek(3S), ldahread(3X), ldclose(3X), ldgetname(3X), ldfhread(3X), ldl- read(3X), ldlseek(3X), ldohseek(3X), ldopen(3X), ldrseek(3X), ldlseek(3X), ldshread(3X), ldtbindex(3X), ldtbread(3X), ldtbseek(3X), stdio(3V), intro(5) WARNING The macro FSEEK defined in the header file ldfcn.h translates into a call to the standard input/output function fseek(3S). FSEEK should not be used to seek from the end of an archive file since the end of an ar- chive file may not be the same as the end of one of its object file 19 February 1988 LDFCN(3)
http://modman.unixdev.net/?sektion=3&page=ldfcn&manpath=SunOS-4.1.3
CC-MAIN-2017-30
refinedweb
676
57.81
Learning computer technology these days can seem overwhelming. It's not the technology itself that is the root of this evil; it's often the size of the book that we must drag home from the Super Crown bookstore. True system administration requires attention to detail, but in this age, I fear we are drowning in a little too much information. Do you really need a thousand-page book in order to become a Linux Administrator in 28 Days? Can anyone read a thousand-page Unix guide in 28 days? That's the real question. Perhaps all you really need is a little practical direction. I know from personal experience that Linux administrators come from all walks of life. A Linux admin can be a precocious teenager enthralled with the wonders of technology, or a secretary in a small office with newly expanded job duties, or someone just looking to improve themselves for a better job. Where to start? The truth of the matter is that professionals in this field today probably own the big Linux books, but it wasn't these books that helped them when they first started learning their craft. Today's successful administrators had someone called a mentor. Someone to SHOW them how to configure a Unix system. This is how many admins learned their trade. This guide should help you get started in the basics of small office system Linux administration. We'll go step by step: setting up the network interface connection, creating user accounts, and then some simple package installation. Once these are configured, you can then consult the really big books. Probably wasn't any longer than 18 months ago when the standard equipment for getting online was a 56K modem. How things have changed. DSL and the cable modem are rapidly becoming the standard means of Internet connection for the small office/home office environment. Both the DSL and cable modem service providers typically assign an IP address to clients in your network using Dynamic Host Configuration Protocol (DHCP). IP addresses for your network are most likely assigned by your DSL router or cable modem, which have a pre-assigned range of addresses for your equipment. You will need to configure your Linux system to request addresses from a DHCP server. I'll walk you through a DHCP configuration. In this example, I have an administrator, Dr. Morbius, who is setting up a Linux system to store a database on important research he is conducting. He has completed the installation of Linux onto his system and now he is configuring his network interface so he can use his Netscape browser. At the moment, the only account available to Dr. Morbius is the user root. Which is okay, because he will need to modify some privileged network files in the /etc directory. Dr. Morbius will need to create a configuration file for his Ethernet adapter. He changes his current directory to /etc/sysconfig/network-scripts and creates the file ifcfg-eth0. This file contains the following configurations for DHCP: DEVICE=eth0 IPADDR= NETMASK= ONBOOT=yes BOOTPROTO=dhcp BROADCAST= NETWORK= USERCTL=no Dr. Morbius closes this file after a careful inspection for typos. He then changes his current directory over to /etc/sysconfig and edits the file network. The following changes are made by Morbius for his DHCP connection: NETWORKING=yes FORWARD_IPV4=no HOSTNAME='altairIV.unitedplanets.com' DOMAINNAME=unitedplanets.com GATEWAY=0.0.0.0 GATEWAYDEV=eth0 Dr. Morbius is from the old school of Unix; he really likes using vi. However, he's aware that under the GNOME window environment, when logged in as user root, there is a graphical interface to accomplish the same thing under the caption "Another Level of Menus," followed out to "Administration." Now, Dr. Morbius is working on a workstation running LinuxPPC. He wants to use the pump utility to initialize his DHCP interface. The LinuxPPC installation does not install pump, so Dr. Morbius must install it from his LinuxPPC 2000 CD. This is easily accomplished when Morbius mounts his CD-ROM drive. mount /dev/cdrom /mnt/cdrom cd /mnt/cdrom/software This is a quick example of how the CD-ROM is mounted on your system so you may access it. Dr. Morbius keeps in the back of his mind that he should later add this device to the /etc/fstab configuration. To install the pump software, Dr. Morbius uses the Redhat Package Manager utility, called rpm. The install is simple. [root@altairIV software] rpm -i pump-0.7.2-2.ppc.rpm The pump utility is then installed onto Dr. Morbius' LinuxPPC workstation. He next brings up his network interface by typing the command pump -i eth0 Our good doctor waits a moment and then the interface initializes. Morbius can also view the specifics of his connection by typing the command pump -s. More information on pump can be found on the man pages, the online manual for most Unix operations, for pump. When your Linux system first boots, you'll have at least one user account, root. For initial setup, having the root super user account is okay. A safer approach is to create a user account and use this for most of your Linux usage needs. If you're learning Unix administration, creating user accounts is a basic and frequent task in system management. Most Unix operating systems provide a utility for adding users. As super user (root), you can use the tool adduser. You may want to examine the man pages on the exact syntax of this command. At your prompt, type man adduser and hit the return key. Take a moment to examine the syntax; it may look like garble at the moment, but we'll examine the arguments to this command. (The term arguments identifies the options we will use with this command.) Now the task at hand is to create a new user. The very first user account you should create is one for yourself. As I mentioned, using your system as user root is not advised. For this example, Dr. Morbius has chosen to use the tc shell for his activities and would like for his new account to reside in the /home directory. As a user, Dr. Morbius will also need a unique ID, uid, so he will use his employee ID, 2257. Now, having read the man pages, Dr. Morbius takes a bold step and creates a user account for himself. Using the utility adduser, he types the following: adduser morbius -d /home/morbius -u 2257 -s /bin/tcsh -c "Krell Research Admin" The account login name is morbius, the home directory (the -d option from the man page) is /home/morbius with user ID (the -u option is uid) 2257, and the login shell is the tc shell. Now, in simple terms, this is what this means: Whenever Dr. Morbius logs into his system, he will log in as user morbius, and his default directory will be /home/morbius. A unique ID (uid) is a 32-bit integer that is paired with a login name. The super user, root, is assigned the uid of 0. You will want to start assigning your users unique IDs starting at or above the integer 100. Most IS organizations pair the employee number with the user login, since the employee number is unique within the company. In our example, Dr. Morbius is employee 2257 and we used this for his uid. This unique pairing of login names and IDs is important especially in networked environments where privileges to different Linux machines are to be assigned. An example would be using Network File Services (NFS). The boot of the man pages for function adduser clearly identifies which files this utility modifies. Two files the utility changes are /etc/passwd and /etc/shadow. The passwd file is primarily the key file where we create the user account. The adduser command added the following line to create the morbius account: morbius:x:2257:2257:Krell Research Admin:/home/morbius:/bin/tcsh The other file modified is /etc/shadow which contains the encrypted password string. Currently, there is no password for the morbius account. We can create one in the following manner, passwd morbiusChanging password for user morbius New UNIX password: Retype new UNIX password: Passwd: all authentication tokens updated successfully. Shell resource files can get pretty complex, and knowledgeable users may customize their own files. An exhaustive listing of the capabilities of the .tcshrc file can be found on your system using the command man tcsh.: wheel::10:root, morbius Making this little modification will allow user morbius to quickly change himself to root in the following manner: [morbius@altair /home/morbius] suPassword: . [morbius@altairIV ~] ls j2sdk*j2sdk-1.3.0-FCS-linux-ppc.tar.bz2 The file has successfully downloaded; now Dr. Morbius changes to user root, using the handy su command he set up earlier. This file, according to the README.ppclinux document, most be moved to the /usr/local directory, owned by root. [morbius@altairIV ~] suPassword: [root@altairIV morbius] mv j2sdk-1.3.0-FCS-linux-ppc.tar.bz2 /usr/local[root@altairIV morbius] cd /usr/local[root@altairIV. [root@altairIV local]: [root@altairIV local]. import java.io.*; public class test { public static void main( String[] args ) { System.out.println("hello\n"); } } To compile this, he enters the following commands from his prompt: [morbius@altairIV ~] javac test.java[morbius@altairIV ~] java testhello.
http://www.onlamp.com/lpt/a/492
CC-MAIN-2016-50
refinedweb
1,573
57.47
mktemp() Make a unique temporary filename Synopsis: #include <stdlib.h> char* mktemp( char* template ); Since: BlackBerry 10.0.0 Arguments: - template - A template for the filename that you want to use. This template can be any file name with some number of Xs appended to it, for example /tmp/temp.XXXX. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The mktemp()temp() can return depends on the number of Xs provided; if you specify six Xs, mktemp() tests roughly 266 combinations. The mkstemp() function (unlike this function) creates the template file, mode 0600 (i.e. read-write for the owner), returning a file descriptor opened for reading and writing. This avoids the race between testing for a file's existence and opening it for use. Errors: - ENOTDIR - The pathname portion of the template isn't an existing directory. This function may also set errno to any value specified by stat(). Classification: Caveats: In general, avoid using mktemp(), because a hostile process can exploit a race condition in the time between the generation of a temporary filename by mktemp() and the invoker's use of the temporary name. Use mkstemp() instead. This function can create only 26 unique file names per thread for each unique template. Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/m/mktemp.html
CC-MAIN-2016-40
refinedweb
239
58.79
This question already has an answer here: - Is Java “pass-by-reference” or “pass-by-value”? 71 answers In Java, is it possible for a calling method to get the value of a local variable inside the called method without returning it? See below in C, where I can use pointers to change the value of the local variable of the fun function. #include <stdio.h> int main(void) { int* a; a = malloc(sizeof(int)); *a = 10; printf("before calling, value == %d\n",*a); fun(a); printf("after calling, value == %d",*a); return 0; } int fun(int* myInt) { *myInt = 100; } Can I do something similar in Java. I did try, but wasn't able to. public class InMemory { public static void main(String[] args) { int a = 10; System.out.println("before calling ..."+a); fun(a); System.out.println("after calling ..."+a); } static void fun(int newa) { newa = 100; } } int and Integer are not mutable. You could pass in a reference to a collection and modify the contents of it, or use a mutable implementation of an integer such as AtomicInteger if you're that keen on it. public class InMemory { public static void main(String[] args) { AtomicInteger a = new AtomicInteger(10); System.out.println("before calling ..." + a); fun(a); System.out.println("after calling ..." + a); } static void fun(AtomicInteger newa) { newa.set(100); } }
https://www.codesd.com/item/get-the-value-of-the-local-variable-from-the-method-called-no-return.html
CC-MAIN-2021-17
refinedweb
223
55.84
A design pattern is a general reusable solition to commonly occurring problem with a given context in software design. With Groovy is easier to implement design patterns than other languages such as C++ or Java. Using design patters we can share to the development teams a way to communicate solitions in the software design. Abstract factory Abstract out the creation of an object from its implementations. Let’s consider the following example: class Book { String title Integer pages } def create(clazz, properties){ def instance = clazz.newInstance() // 1 properties.each { name, value -> instance."$name" = value // 2 } instance // 3 } assert create(Book, [title: 'Who moved my cheese?']) instanceof Book - Create a new object based on it’s type - Iterates the properties and assign a value from the map to the instance field - Return the new instance created So now if we add a new class, let’s say CD that contains same title field but an Integer called volume, we can use the same factory to create our object. class Book { String title Integer pages } class CompactDisc { String title Integer volume } def create(clazz, properties){ def instance = clazz.newInstance() properties.each { name, value -> instance."$name" = value } instance } assert create(CompactDisc, [title: 'Tri-state', volume: 1]) instanceof CompactDisc Strategy Enables an algorithm behavior to be selected at runtime. def prices = [10, 20, 30, 40, 50] def computeTotal(prices) { def total = 0 for (price in prices){ total += price } total } assert 150 == computeTotal(prices) This code totalize all prices defined in the prices collection. But what if we want to get all prices under 35?, consider next code addition def prices = [10, 20, 30, 40, 50] def computeTotal(prices) { def total = 0 for (price in prices){ total += price } total } def computeTotalUnder35(prices) { def total = 0 for (price in prices){ if (price < 35) total += price } total } assert 150 == computeTotal(prices) assert 60 == computeTotalUnder35(prices) This code definitely works, but goes against all good developer manners since we are duplicating code. And what if we want totalize all prices over 35, we should do copy and paste again? Using strategy pattern to this case we can get the following piece of code. def prices = [10, 20, 30, 40, 50] def computeTotal(prices, closure) { def total = 0 for (price in prices){ if (closure(price)) total += price } total } assert 150 == computeTotal(prices, { true }) assert 60 == computeTotal(prices, { it < 35 }) assert 90 == computeTotal(prices, { it > 35 }) Selector decides whether we should sumarize all prices or not, and if not what condition applies to sumarize them. Iterator pattern Is so common pattern that we are using it all the time while programming in Groovy. def names = ["Joe", "Jane", "Jill"] names.each(){ println it } What if we want to print an index while iterate our collection?. We can solve this problem using this. def names = ["Joe", "Jane", "Jill"] names.eachWithIndex(){ name, i -> println "$i. $name" } And if we want to print number of charactes in each element in the collection. def names = ["Joe", "Jane", "Jill"] println names.collect { it.length() } The collect() method in Groovy can be used to iterate over collections and transform each element of the collection. If we want to get names from the collection with four letters length? def names = ["Joe", "Jane", "Jill"] println names.findAll { it.length() == 4 } All programmers have done this once in their life: Iterate a collection and print out all elements in the collection with a comma as separator. def names = ["Joe", "Jane", "Jill"] println names.join(', ') Delegation pattern Delegation is better than inheritance since minimize dependency. Let’s see how Groovy manage delegation. class Worker { def work(){ 'working...' } } class Expert { def work() { 'Expert working...' } def analyze() { 'analyzing...' } } class Manager { @Delegate Worker worker = new Worker() @Delegate Expert expert = new Expert() } def manager = new Manager() assert 'working...' == manager.work() assert 'analyzing...' == manager.analyze() What happening here is Manager in compiling time add all Worker methods in to the Manager class and all methods from the Expert class but only those methods that are not included so far. To download the project: git clone To run the project. gradle test Return to the main article
https://josdem.io/techtalk/groovy/design_patterns/
CC-MAIN-2022-33
refinedweb
680
55.54
Opened 8 years ago Closed 4 years ago #3496 closed (fixed) WSGI handler dies on a form containing only empty checkboxes Description WSGI handler hangs when submitting a form containing only empty checkboxes. Because checkboxes are unchecked, HTTP POST request has zero content-length in this case. This zero is passed forward to a socket read function which never returns. I have attached a patch which modifies WSGI to propeply deal with this case. Cheers, Mikko Ohtamaa Oulu, Finland Attachments (2) Change History (10) Changed 8 years ago by mikko@… Changed 8 years ago by cephelo@… Patch that applies cleanly against trunk comment:1 Changed 8 years ago by cephelo@… - Needs documentation unset - Needs tests unset - Patch needs improvement unset comment:2 Changed 8 years ago by SmileyChris comment:3 Changed 8 years ago by Michael Radziej <mir@…> comment:4 Changed 8 years ago by anonymous - Owner changed from nobody to anonymous - Status changed from new to assigned comment:5 Changed 8 years ago by anonymous - Owner changed from anonymous to nobody - Status changed from assigned to new comment:6 Changed 7 years ago by mtredinnick - Resolution set to fixed - Status changed from new to closed comment:7 Changed 4 years ago by jvdongen - Resolution fixed deleted - Status changed from closed to reopened I'm currently running into this issue again, using Django trunk, revision 15821. Replication is simple: submit an empty form (all checkboxes unchecked) and try to access request.POST in view. The wsgi handler dies as soon as you try to access request.POST. Putting a single hidden form input on the form solves the issue. The source code of the wsgi handler seems to be significantly modified since this patch was created and applied - so far I've been unable to pin down the exact location where the bug originates, as Django does not emit any debugging information in this case (I've tried adding extra debug logging at various places early in the request processing chain - but they don't output anything). My wsgi container (uwsgi) does output the following it its logging (with harakiri mode disabled - otherwise the django process is simply killed after 10 seconds), but I suspect that this is just the end game of a situation where Django's trying to read something that isn't there: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /XXXX/ !!! writev(): Broken pipe [wsgi_headers.c line 168] SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /XXXX/ !!! write(): Broken pipe [pyutils.c line 101] comment:8 Changed 4 years ago by anonymous - Resolution set to fixed - Status changed from reopened to closed After 3 years this is surely a somewhat different problem than the original so it deserves its own ticket. Also FWIW I cannot recreate any problem with the wsgi handler and a content length of 0 (using Apache/mod_wsgi, so the issue may be related to uwsgi specifically). Using this view: from django import forms from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt class YNForm(forms.Form): yes_or_no = forms.BooleanField(required=False) @csrf_exempt def testme(request): if request.method == 'POST': ynform = YNForm(request.POST) msg = 'Posted successfully, content length is %s, request.POST is %r' % \ (request.META['CONTENT_LENGTH'], request.POST) else: ynform = YNForm() msg = 'Blank form retrieved via %s' % request.method return render(request, 'ynform.html', {'msg': msg, 'form': ynform}) and this template: <html xmlns="" lang="en-us" xml: <head> <title>Yes or No?</title> </head> <body> <p>{{ msg }}</p> <form name="myform" method='post' action='.'> {{ form.as_p }} <p><a href="javascript: document.myform.submit();">Submit</a></p> </form> </body> </html> I when I click the link to post the form without having the checkbox checked the message I get back is: Posted successfully, content length is 0, request.POST is <QueryDict: {}> To investigate whatever issue you are seeing, please open a new ticket with more specifics (as above) of what exactly your view/submitting HTML looks like. Fixes empty checkbox bug in WSGI handler
https://code.djangoproject.com/ticket/3496
CC-MAIN-2015-14
refinedweb
677
51.89
Parent Directory | Revision Log More helpful exception message Added untested .phase() to Data. Making Lazy and the rest of escript use the same operator enumeration Complex changes Testing reveals holes in the complex code big enough to drive a truck through. This commit means you will however need a slightly smaller truck Eigenvectors for _some_ complex cases escript is cowardly refusing to compute eigenvalues for 3x3 complex matricies because the 3x3 alg has < in it. new configure check for working complex std::acos Relicense all the things! Add variable to control using replacement acos on broken OSX Renaming headers for (hopefully) easier understanding More cleanup Moving some includes around. The plan is to rename some includes to better reflect their purpose. Removing inheritance from std::binary_function (since that is deprecated). Replacing some doubles with real_t. a few more include rearrangements. Enabling more ops for complex Commenting out the templated C_TensorUnaryOperation. Want to remove the equivalent binary versions as well Enabling neg and exp for complex Major rework of our exceptions. We now have specific AssertException NotImplementedError ValueError which translate to the corresponding python exception type. I have gone through a few places and replaced things but not everywhere. To keep the mac happy Expanding some tabs. Replace more unaries The where? family of functions is now done via the enum. Fixed a few gcc 5 warnings. Fixing institution name to comply with policy fixes I forgot to commit Updating all the dates Recent release of g++ no longer accepts isnan outside of the std namespace. Added a general using namespace std _inside_ the function to catch both cases. Also, 5000th commit Ensure isnan calls the c++ version except on windows compilers I changed some files. Updated copyright notices, added GeoComp. include cmath in all cases rather than math.h - the mathinf for intel on windows is still there (in part because we have no way to test if it is still relevant) It begins Round 1 of copyright fixes First pass of updating copyright notices bug in eigenvector calculation fixed (see mantis=594).
https://svn.geocomp.uq.edu.au/escript/trunk/escriptcore/src/ArrayOps.h?view=log&amp;pathrev=6515
CC-MAIN-2019-18
refinedweb
343
57.16
What is the most concise and efficient way to find out if a JavaScript array contains an obj? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (a[i] === obj) { return true; } } return false; } Is there a better and more concise way to accomplish this? This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf. If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use Array.indexOf. Otherwise, I think you are going to end up with something similar to your original code.). Update: As @orip mentions in comments, the linked benchmark was done in 2008, so results may not be relevant for modern browsers. However, you probably need this to support non-modern browsers anyway and they probably haven't been updated since. Always test for yourself. As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while Here's a Javascript 1.6 compatible implementation of Array.indexOf: if (!Array.indexOf) { Array.indexOf = [].indexOf ? function (arr, obj, from) { return arr.indexOf(obj, from); }: function (arr, obj, from) { // (for IE6) var l = arr.length, i = from ? parseInt( (1*from) + (from<0 ? l:0), 10) : 0; i = i<0 ? 0 : i; for (; i<l; i++) { if (i in arr && arr[i] === obj) { return i; } } return -1; }; } Extending the JavaScript Array object is a really bad idea because you introduce new properties (your custom methods) into for-in loops which can break existing scripts. A few years ago the authors of the Prototype library had to re-engineer their library implementation to remove just this kind of thing. If you don't need to worry about compatibility with other JavaScript running on your page, go for it, otherwise, I'd recommend the more awkward, but safer free-standing function solution. Here's how Prototype does it: /** * Array#indexOf(item[, offset = 0]) -> Number * - item (?): A value that may or may not be in the array. * - offset (Number): The number of initial items to skip before beginning the * search. * * Returns the position of the first occurrence of `item` within the array — or * `-1` if `item` doesn't exist in the array. **/ function indexOf(item, i) { i || (i = 0); var length = this.length; if (i < 0) i = length + i; for (; i < length; i++) if (this[i] === item) return i; return -1; } Also see here for how they hook it up. Modern browsers have Array#indexOf, which does exactly that; this is in the new(ish) ECMAScript 5th edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page. jQuery has a utility function for this: $.inArray(value, array) It returns the index of a value in an array. It returns -1 if the array does not contain the value. jQuery has several useful utility functions. An excellent JavaScript utility library is underscore.js: _.contains(list, value), alias _.include(list, value)(underscore's contains/include uses indexOf internally if passed a JavaScript array). Some other frameworks: dojo.indexOf(array, value, [fromIndex, findLast])documentation. Dojo has a lot of utility functions, see. array.indexOf(value)documentation array.indexOf(value)documentation findValue(array, value)documentation array.indexOf(value)documentation Ext.Array.indexOf(array, value, [from])documentation Notice how some frameworks implement this as a function. While other frameworks add the function to the array prototype. In CoffeeScript, the in operator is the equivalent of contains: a = [1, 2, 3, 4] alert(2 in a) var mylist = [1, 2, 3]; assert(mylist.contains(1)); assert(mylist.indexOf(1) == 0); Thinking out of the box for a second, if you are in making this call many many times, it is more efficient to use an associative array to do lookups using a hash function. Just another option // usage: if ( ['a','b','c','d'].contains('b') ) { ... } Array.prototype.contains = function(value){ for (var key in this) if (this[key] === value) return true; return false; } If you are checking repeatedly for existence of an object in an array you should maybe look into contains(a, obj). Literally: (using Firefox v3.6, with for-in caveats as previously noted (HOWEVER the use below might endorse for-in for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length property is NOT enumerated in the for-in property list!).).) (Drag & drop the following complete URI's for immediate mode browser testing.) javascript: function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;} function check(ra){ return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('') } alert([ check([{}]), check([]), check([,2,3]), check(['']), '\t (a null string)', check([,,,]) ].join('\n')); which displays: There is an object in [[object Object]]. There is NO object in []. There is an object in [,2,3]. There is an object in []. (a null string) There is NO object in [,,]. Wrinkles: if looking for a "specific" object consider: javascript: alert({}!={}); alert({}!=={}); and thus: javascript: obj={prop:"value"}; ra1=[obj]; ra2=[{prop:"value"}]; alert(ra1[0]==obj); alert(ra2[0]==obj); Often ra2 is considered to "contain" obj as the literal entity {prop:"value"}. A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution: javascript: obj={prop:"value"}; ra2=[{prop:"value"}]; alert( ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ? 'found' : 'missing' ); See ref: Searching for objects in JavaScript arrays. Hmmm. what about Array.prototype.contains = function(x){ var retVal = -1; //x is a primitive type if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);} //x is a function else if(typeof x =="function") for(var ix in this){ if((this[ix]+"")==(x+"")) retVal = ix; } //x is an object... else { var sx=JSON.stringify(x); for(var ix in this){ if(typeof this[ix] =="object" && JSON.stringify(this[ix])==sx) retVal = ix; } } //Return False if -1 else number if numeric otherwise string return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal); } I know it's not the best way to go, but since there is no native IComparable way to interact between objects, I guess this is as close as you can get to compare two entities in an array. Also, extending Array object might not be a wise thing to do sometimes it's ok (if you are aware of it and the trade-off) b is the value, a is the array It returns true or false function(a,b){return!!~a.indexOf(b)} While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-IE browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined: Array.prototype.toTable = function() { var t = {}; this.forEach(function(x){t[x]=true}); return t; } Demo: var toRemove = [2,4].toTable(); [1,2,3,4,5].filter(function(x){return toRemove[x]===undefined}) (Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. Javascript has insufficient hooks to let you keep this state, unlike python for example.) function inArray(elem,array) { var len = array.length; for(var i = 0 ; i < len;i++) { if(array[i] == elem){return i;} } return -1; } Returns array index if found, or -1 if not found Similar thing: Finds the first element by a "search lambda": Array.prototype.find = function(search_lambda) { return this[this.map(search_lambda).indexOf(true)]; }; Usage: [1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 }) => 4 Same in coffeescript: Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)] As others have mentioned you can use Array.indexOf, but it isn't available in all browsers. Here's the code from to make it work the same in older browsers. indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original value. if (!Array.prototype.indexOf) { Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { "use strict";; } } I looked through submitted answers and got that they only apply if you search for the object via reference. A simple linear search with reference object comparison. But lets say you don't have the reference to an object, how will you find the correct object in the array? You will have to go linearly and deep compare with each object. Imagine if the list is too large, and the objects in it are very big containing big pieces of text. The performance drops drastically with the number and size of the elements in the array. You can stringify objects and put them in the native hash table, but then you will have data redundancy remembering these keys cause JavaScript keeps them for 'for i in obj', and you only want to check if the object exists or not, that is, you have the key. I thought about this for some time constructing a JSON Schema validator, and I devised a simple wrapper for the native hash table, similar to the sole hash table implementation, with some optimization exceptions which I left to the native hash table to deal with. It only needs performance benchmarking... All the details and code can be found on my blog: I will soon post benchmark results. The complete solution works like this: var a = {'a':1, 'b':{'c':[1,2,[3,45],4,5], 'd':{'q':1, 'b':{'q':1, 'b':8},'c':4}, 'u':'lol'}, 'e':2}; var b = {'a':1, 'b':{'c':[2,3,[1]], 'd':{'q':3,'b':{'b':3}}}, 'e':2}; var.";)); My little contribution: function isInArray(array, search) { return array.indexOf(search) >= 0; } //usage if(isInArray(my_array, "my_value")) { //... } var myArray = ['yellow', 'orange', 'red'] ; alert(!!~myArray.indexOf('red')); //true To know exactly what the tilde ~ do at this point refer to this question What does a tilde do when it precedes an expression? Ecmascript 6 has an elegant proposal on find. The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Here is the MDN documentation on that. The find functionality works like this. function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) return false; } return (element > 1); } console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found console.log( [4, 5, 8, 12].find(isPrime) ); // 5 You can use this in ES5 and below by defining the function. if (!Array.prototype.find) { Object.defineProperty(Array.prototype, 'find', { enumerable: false, configurable: true, writable: true, value: function(predicate) {++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } } return undefined; } }); } I use the following: Array.prototype.contains = function (v) { return this.indexOf(v) > -1; } var a = [ 'foo', 'bar' ]; a.contains('foo'); // true a.contains('fox'); // false You can use Array.prototype.some() var items = [ {a: '1'}, {a: '2'}, {a: '3'} ] items.some(function(item) { item.a === '3' }) // returns true items.some(function(item) { item.a === '4' }) // returns false One thing to note is that some() is not present in all js versions: (from the website) some was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard You can add it in case it's not there: if (!Array.prototype.some) { Array.prototype.some = true; } return false; }; } We use this snippet (works with objects, arrays, strings): /* * @function * @name Object.prototype.inArray * @description Extend Object prototype within inArray function * * @param {mix} needle - Search-able needle * @param {bool} searchInKey - Search needle in keys? * */ Object.defineProperty(Object.prototype, 'inArray',{ value: function(needle, searchInKey){ var object = this; if( Object.prototype.toString.call(needle) === '[object Object]' || Object.prototype.toString.call(needle) === '[object Array]'){ needle = JSON.stringify(needle); } return Object.keys(object).some(function(key){ var value = object[key]; if( Object.prototype.toString.call(value) === '[object Object]' || Object.prototype.toString.call(value) === '[object Array]'){ value = JSON.stringify(value); } if(searchInKey){ if(value === needle || key === needle){ return true; } }else{ if(value === needle){ return true; } } }); }, writable: true, configurable: true, enumerable: false }); Usage: var a = {one: "first", two: "second", foo: {three: "third"}}; a.inArray("first"); //true a.inArray("foo"); //false a.inArray("foo", true); //true - search by keys a.inArray({three: "third"}); //true var b = ["one", "two", "three", "four", {foo: 'val'}]; b.inArray("one"); //true b.inArray('foo'); //false b.inArray({foo: 'val'}) //true b.inArray("{foo: 'val'}") //false var c = "String"; c.inArray("S"); //true c.inArray("s"); //false c.inArray("2", true); //true c.inArray("20", true); //false function contains(a, obj) { return a.some(function(element){return element == obj;}) } Array.prototype.some() was added to the ECMA-262 standard in the 5th edition EcmaScript 7 introduces Array.prototype.includes. It can be used like this: [1, 2, 3].includes(2); // true [1, 2, 3].includes(4); // false It also accepts an optional second argument fromIndex: [1, 2, 3].includes(3, 3); // false [1, 2, 3].includes(3, -1); // true Unlike indexOf, which uses Strict Equality Comparison, includes compares using SameValueZero equality algorithm. That means that you to detect if an array includes a NaN: [1, 2, NaN].includes(NaN); // true It can be polyfilled to make it work on all browsers. one liner: function contains(arr, x) { return arr.filter(function(elem) { return elem == x }).length > 0; } A hopefully faster Bidirectional indexOf / lastIndexOf alternative While the new method includes is very nice, the support is basically zero for now. It's long time that i was thinking of way to replace the slow indexOf/lastIndexOf functions. A performant way has ben already found, looking at the top answers. From those i choosed the contains function posted by @Damir Zekić which should be the fastest one. But also states that the benchmarks are from 2008 and so outdated. I also prefer while over for but for not a specific reason i ended writing the function with a for loop.it could be also done with a while -- I was curious if the iteration was much slower if i check both sides of the array while doing it. Apparently no, and so this function is around 2x faster than the Top voted ones. Obiovsly it's also faster than the native one.This in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array. When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel trough big arrays and the result could be everywhere this could be a solid solution to make things faster. Bidirectional indexOf/lastIndexOf function bidirectionalIndexOf(a,b,c,d,e){ for(c=a.length,d=c*1;c--;){ if(a[c]==b)return c; //or this[c]===b if(a[e=d-1-c]==b)return e; //or a[e=d-1-c]===b } return -1 } //usage bidirectionalIndexOf(array,'value'); Performance test As test i created an array with 100k entries. Three queries : at the beginning, in the middle & at the end of the array. I hope you also find this intresting and test the performance. note: as you can see i slightly modified the contains function to reflect the indexOf & lastIndexOf output.(so basically true with the index and false with -1). That shouldn't harm it. The array prototype variante Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){ for(c=this.length,d=c*1;c--;){ if(this[c]==b)return c; //or this[c]===b if(this[e=d-1-c]==b)return e; //or this[e=d-1-c]===b } return -1 },writable:false,enumerable:false}); //usage array.bidirectionalIndexOf('value'); The function can also be easely modified to return true or false or even the object, string or whatever it is. if you have any questions just ask. EDIT And here is the while variante. function bidirectionalIndexOf(a,b,c,d){ c=a.length;d=c-1; while(c--){ if(b===a[c])return c; if(b===a[d-c])return d-c; } return c } //usage bidirectionalIndexOf(array,'value'); How is this possible? I think that the simple calculation to get the reflected index in an array is so simple that it's 2 times faster than doing an actual loop iteration. Here is a complex example doing 3 checks per iteration, but this is only possible with a longer calculation which causes the slow down of the code. This might work for you: $.inArray(obj, a) Use lodash's some function. It's concise, accurate and has great cross platform support. The accepted answer does not even meet the requirements. Requirements: Recommend most concise and efficient way to find out if a JavaScript array contains an object. Accepted Answer: $.inArray({'b': 2}, [{'a': 1}, {'b': 2}]) > -1 My recommendation: _.some([{'a': 1}, {'b': 2}], {'b': 2}) > true Notes: $.inArray works fine for determining whether a scalar value exists in an array of scalars... $.inArray(2, [1,2]) > 1 ... but the question clearly asks for an efficient way to determine if an object is contained in an array. In order to handle both scalars and objects, you could do this: (_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1) EDIT One can use Set () that has a method "has()": function contains(arr, obj) { var proxy = new Set(arr); if (proxy.has(obj)) return true; else return false; } var arr = ['Happy', 'New', 'Year']; console.log(contains(arr, 'Happy')); By no means the best, but just getting creative and adding to the repertoire do not use this Object.defineProperty(Array.prototype, 'exists', { value: function(element, index) { var index = index || 0 return index === this.length ? -1 : this[index] === element ? index : this.exists(element, ++index) } }) // outputs 1 console.log(['one', 'two'].exists('two')); // outputs -1 console.log(['one', 'two'].exists('three')); console.log(['one', 'two', 'three', 'four'].exists('four')); you can also use that trick : var arrayContains = function(object) { return (serverList.filter(function(currentObject) { if (currentObject === object) { return currentObject } else { return false; } }).length > 0) ? true : false } Solution that works in all modern browsers: const contains = (arr, obj) => { const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration return arr.some(item => JSON.stringify(item) === stringifiedObj); } Usage: contains([{a: 1}, {a: 2}], {a: 1}); // true IE6+ solution: function contains(arr, obj) { var stringifiedObj = JSON.stringify(obj) return arr.some(function (item) { return JSON.stringify(item) === stringifiedObj; }); } // .some polyfill, not needed for IE9+ if (!('some' in Array.prototype)) { Array.prototype.some = function (tester, that /*opt*/) { for (var i = 0, n = this.length; i < n; i++) { if (i in this && tester.call(that, this[i], i, this)) return true; } return false; }; } Usage: contains([{a: 1}, {a: 2}], {a: 1}); // true JSON.stringify? Array.indexOf and Array.includes (as well as most of the answers here) only compare by reference and not by value. [{a: 1}, {a: 2}].includes({a: 1}); // false, because {a: 1} is a new object Non-optimized ES6 one-liner: [{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1)); // true Note: Comparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one: Updated the contains function with a perf optimization. Thanks itinance for pointing it out. OK, you can just optimise your code to get the result, there are many ways to do this which are cleaner, but I just wanted to get your pattern and apply it to that, just simply do something like this: function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (JSON.stringify(a[i]) === JSON.stringify(obj)) { return true; } } return false; } Or this solution: Array.prototype.includes = function (object) { return !!+~this.indexOf(object); }; OK, you can just optimise your code to get the result! There are many ways to do this which are cleaner, but I just wanted to get your pattern and apply it to that using JSON.stringify, just simply do something like this: function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (JSON.stringify(a[i]) === JSON.stringify(obj)) { return true; } } return false; } Using idnexOf() it is a good solution, but you should hide embedded implementation indexOf() function which returns -1 with ~ operator: function include(arr,obj) { return !!(~arr.indexOf(obj)); } With ECMA 6 you can use Array.find(FunctionName) where FunctionName is a user defined function to search for the object in the array. Hope this helps! I was working on a project that I needed a functionality like python set which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone function set(arr) { var res = []; for (var i = 0; i < arr.length; i++) { if (res.indexOf(arr[i]) === -1) { res.push(arr[i]); } } return res; } Similar Questions
http://ebanshi.cc/questions/74/array-containsobj-in-javascript
CC-MAIN-2017-43
refinedweb
3,683
58.99
A namespace for functions that deal with things that one can do on sparsity patterns, such as renumbering rows and columns (or degrees of freedom if you want) according to the connectivity, or partitioning degrees of freedom. Use the METIS partitioner to generate a partitioning of the degrees of freedom represented by this sparsity pattern. In effect, we view this sparsity pattern as a graph of connections between various degrees of freedom, where each nonzero entry in the sparsity pattern corresponds to an edge between two nodes in the connection graph. The goal is then to decompose this graph into groups of nodes so that a minimal number of edges are cut by the boundaries between node groups. This partitioning is done by METIS. Note that METIS can only partition symmetric sparsity patterns, and that of course the sparsity pattern has to be square. We do not check for symmetry of the sparsity pattern, since this is an expensive operation, but rather leave this as the responsibility of caller of this function. After calling this function, the output array will have values between zero and n_partitions-1 for each node (i.e. row or column of the matrix). This function will generate an error if METIS is not installed unless n_partitions is one. I.e., you can write a program so that it runs in the single-processor single-partition case without METIS installed, and only requires METIS when multiple partitions are required. Note that the sparsity pattern itself is not changed by calling this function. However, you will likely use the information generated by calling this function to renumber degrees of freedom, after which you will of course have to regenerate the sparsity pattern. This function will rarely be called separately, since in finite element methods you will want to partition the mesh, not the matrix. This can be done by calling GridTools::partition_triangulation. Definition at line 48 of file sparsity_tools.cc. For a given sparsity pattern, compute a re-enumeration of row/column indices based on the algorithm by Cuthill-McKee. This algorithm is a graph renumbering algorithm in which we attempt to find a new numbering of all nodes of a graph based on their connectivity to other nodes (i.e. the edges that connect nodes). This connectivity is here represented by the sparsity pattern. In many cases within the library, the nodes represent degrees of freedom and edges are nonzero entries in a matrix, i.e. pairs of degrees of freedom that couple through the action of a bilinear form. The algorithms starts at a node, searches the other nodes for those which are coupled with the one we started with and numbers these in a certain way. It then finds the second level of nodes, namely those that couple with those of the previous level (which were those that coupled with the initial node) and numbers these. And so on. For the details of the algorithm, especially the numbering within each level, we refer the reader to the book of Schwarz (H. R. Schwarz: Methode der finiten Elemente). These algorithms have one major drawback: they require a good starting node, i.e. node that will have number zero in the output array. A starting node forming the initial level of nodes can thus be given by the user, e.g. by exploiting knowledge of the actual topology of the domain. It is also possible to give several starting indices, which may be used to simulate a simple upstream numbering (by giving the inflow nodes as starting values) or to make preconditioning faster (by letting the Dirichlet boundary indices be starting points). If no starting index is given, one is chosen automatically, namely one with the smallest coordination number (the coordination number is the number of other nodes this node couples with). This node is usually located on the boundary of the domain. There is, however, large ambiguity in this when using the hierarchical meshes used in this library, since in most cases the computational domain is not approximated by tilting and deforming elements and by plugging together variable numbers of elements at vertices, but rather by hierarchical refinement. There is therefore a large number of nodes with equal coordination numbers. The renumbering algorithms will therefore not give optimal results. If the graph has two or more unconnected components and if no starting indices are given, the algorithm will number each component consecutively. However, this requires the determination of a starting index for each component; as a consequence, the algorithm will produce an exception if starting indices are given, taking the latter as an indication that the caller of the function would like to override the part of the algorithm that chooses starting indices. Definition at line 197 of file sparsity_tools.cc. As above, but taking a SparsityPattern object instead. Definition at line 332 of file sparsity_tools.cc. For a given sparsity pattern, compute a re-enumeration of row/column indices in a hierarchical way, similar to what DoFRenumbering::hierarchical does for degrees of freedom on hierarchically refined meshes. This algorithm first selects a node with the minimum number of neighbors and puts that node and its direct neighbors into one chunk. Next, it selects one of the neighbors of the already selected nodes, adds the node and its direct neighbors that are not part of one of the previous chunks, into the next. After this sweep, neighboring nodes are grouped together. To ensure a similar grouping on a more global level, this grouping is called recursively on the groups so formed. The recursion stops when no further grouping is possible. Eventually, the ordering obtained by this method passes through the indices represented in the sparsity pattern in a z-like way. If the graph has two or more unconnected components, the algorithm will number each component consecutively, starting with the components with the lowest number of nodes. Definition at line 508 of file sparsity_tools.cc. Communicate rows in a dynamic sparsity pattern over MPI. Definition at line 522 of file sparsity_tools.cc. Similar to the function above, but for BlockDynamicSparsityPattern instead. Definition at line 655 of file sparsity_tools.cc.
http://www.dealii.org/developer/doxygen/deal.II/namespaceSparsityTools.html
CC-MAIN-2017-13
refinedweb
1,024
53
LIN help but Implementing an enumerator: - Reset – initialises the enumeration so that it starts over again - Current – returns the current item - MoveNext – updates the index to the next itemcol(int s) { rnd = new Random(); Size = s; } Now we have to implement the methods of the IEnumerator interface. The reset method is simply: void IEnumerator.Reset() { this.loc = -1; } You don’t really need the “this” but it helps to emphasise defined Current in this way? More about this problem later.. The reason is that any class offering an enumerator has to implement the IEnumerable interface. This has just a single method GetEnumerator which returns the instance of the class that provides the methods of the IEnumerator. If you think about it for a moment it is obvious that IEnumerable has to be implemented by the data collection class that holds the items to be enumerated so we have to add it to the class definition: class TestCollection:IEnumerator,IEnumerable { The single method that we have to implement is trivial as the instance of the TestCollection class concerned provides its own enumerators, i.e. it is the enumerator to be returned: IEnumerator IEnumerable.GetEnumerator() { return this; } } Now we can write some code that makes use of our data collection with enumeration. The simplest thing to try out is a foreach loop: TestCollection col = new TestCollection(5); foreach (object o in col) { MessageBox.Show(o.ToString()); } Notice that the iterator o has to be defined as an object. We can use an int in the foreach loop as it supports implicit casting. For example: foreach (int o in col) { MessageBox.Show(o.ToString()); } …works perfectly unless you happen to return something that can’t be cast to an int at runtime with the result that an exception is raised. If you want to do better then you need to change the enumeration interfaces to their generic forms, which is what we have to do anyway to use LINQ. Separating the enumerator Before moving on it is worth commenting on why we usually implement the enumerator as a separate class. Consider what happens if we try to use the current enumerator in a nested foreach loop. The same enumerator would be returned by GetEnumerator and hence the nested loops would interfere with each other. If you want to write nested loops or allow multiple enumerations to happen concurrently you need to implement the enumerator as a separate class and you need to create an instance of that class each time an enumerator is called for by GetEnumerator. As nesting of queries is very common we need to do the job properly before moving on to consider LINQ. All we need to do is separate out the enumeration methods into a new class. This class has to keep track of where it is in the enumeration and it needs to keep track of which instance of the collection it is enumerating: class TestCollectionEnnumerator : IEnumerator { private TestCollection m_Instance; private int loc = -1; If you create the enumeration class as an inner class of the data collection, i.e. TestCollection, it will have access to all of the data collection’s variables and methods and this makes it easier for the two classes to work together. The only new method we need is a constructor that initialises the enumerator with the current instance of the data collection: public TestCollectionEnnumerator( TestCollection Instance) { m_Instance = Instance; } The other enumeration methods have to now use m_Instance instead of “this” to make sure they work with the correct instance of the data: void IEnumerator.Reset() { loc = -1; } object IEnumerator.Current { get { if (loc > -1) return m_Instance.rnd.Next(500); else return -1; } } bool IEnumerator.MoveNext() { loc++; if (loc < m_Instance.Size) return true; else return false; } We also need to change the data collection class so that its GetEnumerator actually creates a new instance of the enumerator: class TestCollection:IEnumerable { private Random rnd; private int Size; IEnumerator IEnumerable.GetEnumerator() { return new TestCollectionEnnumerator(this); } Notice how the use of “this” makes the final connection between the instance and any number of enumerators. Now our example code is slightly more complicated but you can use it within nested for each loops and, as we shall see, nested LINQ queries. Generic enumeration It is generally better to use a generic form of the interfaces so add to the start of the program: using System.Collections.Generic; The generic form of the IEnumerator interface inherits from the non-generic IEnumerator interface. Note that when an interface inherits from another interface, for example IA:IB then when you add IA to a class it’s exactly the same as writing :IA,IB and you have to implement the methods of IA and IB. The generic form of the IEnumerator interface defines a single generic version of Current – after all this is the only method that needs to use the data type. To complicate things a little it also inherits the Dispose method from IDisposable, but we can ignore this at the moment by adding a null implementation. The generic form of IEnumerable interface simply adds a generic form of GetEnumerator. So to make our class use the generic Interfaces all we have to do is change its definition to: class TestCollection:IEnumerable<int> …and add to it a second generic GetEnumerator method: IEnumerator<int> IEnumerable<int>.GetEnumerator() { return new TestCollectionEnnumerator(this); } The enumerator class also has to implement the generic interface and has to have two new methods added to it: class TestCollectionEnnumerator : IEnumerator<int> { // ...rest of class definition New methods: int IEnumerator<int>.Current { get { if (loc > -1) return m_Instance.rnd.Next(500); else return -1; } } void IDisposable.Dispose() { } Notice that you have to keep the existing non-generic implementations and that the new generic methods are almost identical apart from the use of the int data type. Now you can write: foreach (int o in col) { MessageBox.Show(o.ToString()); } …and if you try to cast to something that is unreasonable, e.g. string, then you will see a compile time rather than runtime error.
https://www.developerfusion.com/article/8250/linq-to-objects-for-the-net-developer/
CC-MAIN-2019-04
refinedweb
1,010
50.36
#include <ggi/gii.h> gii_input_t giiOpen(const char * input, ...); gii_input_t giiJoinInputs(gii_input_t inp, gii_input_t inp2); int giiSplitInputs(gii_input_t inp, gii_input_t *newhand, uint32_t origin, uint32_t flags); int giiClose(gii_input_t inp);iiJoinInputs joins two inputs into one. From a programmers' point of view, this closes both inp and inp2 and opens an new input that combines both inputs into one. That is, after giiJoinInputs has completed, there is no need to giiClose inp and inp2 any more. When cleaning up, you need to close the returned input instead. See the example for details. However the inputs are not actually closed or reopened internally. That is, you will not get any startup-events or similar the driver generates, though pending events of both old inputs are transferred to the newly created input. giiSplitInputs splits one of the inputs from a group of joined inputs and returns the handle. The parameter origin can be used to choose which input to detach (use GGI_EV_ORIGIN_NONE to match any input.) The detached handle is returned in newhand. Note, though, that if the detached input is the same one given in inp, then the handle returned in newhand will be that of the rest of the joined inputs instead. You can tell whether this happened by checking the return code. Events queued in the joined input for the newly split input are not transferred automatically. You must drain them out yourself. The parameter flags is reserved for future use and should be set to 0. giiClose releases and destroys an open input and its associated internal control structures. This will put back input streams to their default modes, etc. giiClose returns GGI_OK (== 0) on success, otherwise an gii-error(3) code. giiSplitInputs returns 0 for normal success, or 1 if the input which was split off was the same as the one passed in inp (in which case, newhand may contain a handle to a joined set of visuals.) Otherwise, it returns an gii-error(3) code. gii_input_t inp, inp2, inp3; /* Initialize the GII library. This must be called before any other * GII function. */ if (giiInit() != 0) exit(1); /* Open the nulldevice for testing ... */ if ((inp=giiOpen("input-null",NULL)) == NULL) { giiExit(); exit(1); } /* Open stdin for testing ... */ if ((inp2=giiOpen("input-stdin",NULL)) == NULL) { giiExit(); exit(1); } /* Open evdev for testing ... */ if ((inp3=giiOpen("input-linux-evdev",NULL)) == NULL) { giiExit(); exit(1); } /* Now join them. Note the usage of _i_n_p_=_giiJoin(inp,inp2); * This is the recommended way to do this. */ inp=giiJoinInputs(inp,inp2); /* Note that this mends inp2 into inp. That is you may not call giiClose(inp2) - this happens together with giiClose(inp) ! */ /* Join another */ inp=giiJoinInputs(inp,inp3); /* ... do the real work here ... */ /* Split one of them back out of the join. */ res = ggiSplitInputs(inp, &inp2, GII_EV_ORIGIN_NONE, 0); if (res == 1) { gii_input_t tmp; tmp = imp2; imp2 = imp1; imp1 = tmp; } else if (res < 0) fprintf(stderr, "Failed to split inputs\n"); /* Close the single input */ giiClose(inp2); /* Close the joined input */ giiClose(inp); /* Now close down LibGII. */ giiExit();
http://www.makelinux.net/man/3/G/giiOpen
CC-MAIN-2015-35
refinedweb
504
57.77
/* ********************************************************************** * Copyright (c) 2003-2004, International Business Machines * Corporation and others. All Rights Reserved. ********************************************************************** * Author: Alan Liu * Created: March 19 2003 * Since: ICU 2.6 ********************************************************************** */ #ifndef UCAT_H #define UCAT_H #include "unicode/utypes.h" #include "unicode/ures.h" /** * \file * \brief. */ U_CDECL_BEGIN /** * An ICU message catalog descriptor, analogous to nl_catd. * * @stable ICU 2.6 */ 00071 typedef UResourceBundle* u_nl_catd; /** * Open and return an ICU message catalog descriptor. The descriptor * may be passed to u_catgets() to retrieve localized strings. * * @param name string containing the full path pointing to the * directory where the resources reside followed by the package name * e.g. "/usr/resource/my_app/resources/guimessages" on a Unix system. * If NULL, ICU default data files will be used. * * Unlike POSIX, environment variables are not interpolated within the * name. * * @param locale the locale for which we want to open the resource. If * NULL, the default ICU locale will be used (see uloc_getDefault). If * strlen(locale) == 0, the root locale will be used. * * @param ec input/output error code. Upon output, * U_USING_FALLBACK_WARNING indicates that a fallback locale was * used. For example, 'de_CH' was requested, but nothing was found * there, so 'de' was used. U_USING_DEFAULT_WARNING indicates that the * default locale data or root locale data was used; neither the * requested locale nor any of its fallback locales were found. * * @return a message catalog descriptor that may be passed to * u_catgets(). If the ec parameter indicates success, then the caller * is responsible for calling u_catclose() to close the message * catalog. If the ec parameter indicates failure, then NULL will be * returned. * * @stable ICU 2.6 */ U_STABLE u_nl_catd U_EXPORT2 u_catopen(const char* name, const char* locale, UErrorCode* ec); /** * Close an ICU message catalog, given its descriptor. * * @param catd a message catalog descriptor to be closed. May be NULL, * in which case no action is taken. * * @stable ICU 2.6 */ U_STABLE void U_EXPORT2 u_catclose(u_nl_catd catd); /** * Retrieve a localized string from an ICU message catalog. * * @param catd a message catalog descriptor returned by u_catopen. * * @param set_num the message catalog set number. Sets need not be * numbered consecutively. * * @param msg_num the message catalog message number within the * set. Messages need not be numbered consecutively. * * @param s the default string. This is returned if the string * specified by the set_num and msg_num is not found. It must be * zero-terminated. * * @param len fill-in parameter to receive the length of the result. * May be NULL, in which case it is ignored. * * @param ec input/output error code. May be U_USING_FALLBACK_WARNING * or U_USING_DEFAULT_WARNING. U_MISSING_RESOURCE_ERROR indicates that * the set_num/msg_num tuple does not specify a valid message string * in this catalog. * * @return a pointer to a zero-terminated UChar array which lives in * an internal buffer area, typically a memory mapped/DLL file. The * caller must NOT delete this pointer. If the call is unsuccessful * for any reason, then s is returned. This includes the situation in * which ec indicates a failing error code upon entry to this * function. * * @stable ICU 2.6 */ U_STABLE const UChar* U_EXPORT2 u_catgets(u_nl_catd catd, int32_t set_num, int32_t msg_num, const UChar* s, int32_t* len, UErrorCode* ec); U_CDECL_END #endif /*UCAT_H*/ /*eof*/
http://icu.sourcearchive.com/documentation/4.4.2-1/ucat_8h-source.html
CC-MAIN-2018-09
refinedweb
511
52.97
In his book Clean Code, Robert C. Martin makes a strong case against comments: You don't need comments if you write clean code. Like any blanket statement, Martin is partially true. Although code clarity increases readability and decreases the need for comments, code has never been able to convey the whole context to the reader. Programming patterns are often cited as a way to convey this context on a codebase scale. Well named functions and variables also convey some form of context. But most of the time, the context (the "why") never gets written anywhere. In this article, I present a few examples meant to showcase how comments may be written to convey the context around code. Contents: Code example 1 I call "in-flight comments" comments that we write to ease the process of writing code. In-flight comments help us articulate what we are trying to achieve. In the following example taken from the Google's Technical Writing, the developer wrote a comment as they were writing an algorithm for randomly shuffling a slice of integers: func Shuffle(slice []int) { curIndex := len(slice) // If the current index is 0, return directly. if (curIndex == 0) { return } ... } This comment is a typical in-flight comment: it only focuses on what the code does. This comment does not give context as to why this if statement exists. We can refactor this comment by focusing on the "why": func Shuffle(slice []int) { curIndex := len(slice) // No need to shuffle an array with zero elements. if (curIndex == 0) { return } ... } The reader now understand why this if exists, and does not have to dig further. Starting with the "why" helps glanceability: the reader only needs to read the first few words to get the idea. Here is how I would diffenciate the "why" from the "what": *Sometimes, the "what" may be valuable for readability purposes. I see three reasons to comment on the "what": - When the code is not self-explanatory, a "what" comment may avoid the reader the struggle of googling; - When a block of code is lenghy, adding "what" comments may help create "sections", helping the reader quicly find the part they are interested in. Code example 2 Our next example comes from the cert-manager codebase: // If the certificate request has been denied, set the last failure time to // now, and set the Issuing status condition to False with reason. We only // perform this check if the request also doesn't have a Ready condition, // since some issuers may not honor a Denied condition, and will sign and // set the Ready condition to True anyway. We would still want to complete // issuance for requests where the issuer doesn't respect approval. } After looking at the if statement, the reader wonders: why do we need this if statement? Their first reaction will probably be to take a look at the comment right above. Unfortunately, the comment starts with even more confusing implementation details. The reader has to keep reading until the 6th line to find out why the code is doing what it is doing. Let us rate each individual information that the comment conveys: From the reader's perspective, the paragraphs (D) and (C) are the most useful. They give a high-level overview of why this if statement exists. We can merge the two paragraphs into one: (C, D) External issuers may ignore the approval API. An issuer ignores the approval API when it proceeds with the issuance even though the "Denied=True" condition is present on the CertificateRequest. To avoid breaking the issuers that are ignoring the approval API, we want to detect when CertificateRequests has ignored the Denied=True condition; when it is the case, we skip bubbling-up the (possible) Denied condition. Paragraphs (B) and (A) may also be useful: they give the context about paragraph (C). The sentence lacks precision though, and "this check" may confuse the reader. Let us rephrase it: (A, B) To know when the Denied=True condition was ignored by the issuer, we look at the CertificateRequest's Ready condition. If both the Ready and Denied // Some issuers won't honor the "Denied=True" condition, and we don't want // to break these issuers. To avoid breaking these issuers, we skip bubbling // up the "Denied=True" condition from the certificate request object to the // certificate object when the issuer ignores the "Denied" state. // // To know whether or not an issuer ignores the "Denied" state, we pay // attention to the "Ready" condition on the certificate request. If a // certificate request is "Denied=True" and that the issuer still proceeds // to adding the "Ready" condition (to either true or false), then we // consider that this issuer has ignored the "Denied" state. } Code example 3 Another example inspired by the cert-manager codebase: errs := validateIngressTLSBlock(tls) // if this tls entry is invalid, record an error event on Ingress object and continue to the next tls entry if len(errs) > 0 { rec.Eventf(ingress, "Warning", "BadConfig", fmt.Sprintf("TLS entry %d is invalid: %s", i, errs)) continue } Once again, the in-flight comment can be rewritten to focus on the "why": // Let the user know that an TLS entry has been skipped due to being invalid. errs := validateIngressTLSBlock(tls) if len(errs) > 0 { rec.Eventf(ingress, "Warning", "BadConfig", fmt.Sprintf("TLS entry %d is invalid: %s", i, errs)) continue } Code example 4 The next example is inspired by an other place in cert-manager. This is another example of in-flight comment focusing on the "what". The context around this block of code is not obvious, which means this comment should refactored to focus on the "why". // check if a Certificate for this secret name exists, and if it // does then skip this secret name. expectedCrt := expectedCrt(ingress) existingCrt, _ := client.Certificates(namespace).Get(ingress.secretName) if existingCrt != nil { if !certMatchesUpdate(existingCrt, crt) { continue } toBeUpdated = append(toBeUpdated, updateToMatchExpected(expectedCrt)) } else { toBeCreated = append(toBeCreated, crt) } In this case, the code itself would benefit from a bit of refactoring. Regarding the comment, we start with the "why": // The secretName has an associated Certificate that has the same name. We want // to make sure that this Certificate exists and that it matches the expected // Certificate spec. existingCrt, _ := client.Certificates(namespace).Get(secretName) expectedCrt := expectedCrt() if existingCrt == nil { toBeCreated = append(toBeCreated, expectedCrt) continue } if certMatchesExpected(existingCrt, expectedCrt) { continue } toBeUpdated = append(toBeUpdated, updateToMatchExpected(expectedCrt)) Note that we removed the else statement for the purpose of readability. The happy path is now clearly "updating the certificate". Shaping comments To help with readability, I suggest hard-wrapping comments at 80 characters. Above 80 characters, the comments will become hard to read in PR suggestion comments. Take this example comment: //. Each sentence is started on a new line. This sort of style is fine in a Markdown document where these soft breaks are rendered as a single paragraph. The problem with the "random" length of each line is that the reader has to do more work while parsing the text. It is also less aesthetic than a well-wrapped 80 characters comment. Rewrapping the above comment at 80 chars looks like this: //. You can obtain the re-wrapping by using the If you still want to do separate paragraphs, I'd recommend separating each paragraph with two new line breaks: // To reduce the memory footprint of the controller-manager, we do not // cache Secrets. We only cache the metadata of Secrets which is enough to // allow the EnqueueRequestsFromMapFunc to lookup the associated Issuer or // ClusterIssuer. // // We use this option along with ClientDisableCache in NewManager to // configure the client to not cache Secrets when the token manager Gets // and Lists them. Conclusion As a developer, I want to write code that is readable and maintainable, and keeping track of the "why" (i.e., the context) in a codebase is essential for readability and maintainability. I found that putting myself in the place of the future reader helps me write comments that focus on the "why". HAProxy, Git or the Linux kernel are great examples of projects where there is a great focus on well-documented code: ebtree/ebtree.h(HAProxy) unpack-trees.c(Git) kernel/sched/core.c(Linux kernel). Updates: - 24 Feb 2022: add the section "Shaping comments". Discussion (0)
https://dev.to/maelvls/you-should-write-comments-36fd
CC-MAIN-2022-27
refinedweb
1,378
53.1
mongo57a at comcast.net wrote: >Somewhat". > Your interpretation of "global" appears flawed. You should re-read section 4.1 in the language manual about code blocks ... and namespaces. The "global" statement declares that variables which otherwise would be interpreted to be local are actually defined in an outer scope. The key rule in Python is that names generally are "local" to whatever scope in which they are assigned a value. This is what you want most of the time but occasionally leads to some subtle surprises. # "globals" count1 = count2 = 0 def func1( n ): count1 = 0 # creates a new "local" count, distinct from global one count2 += n # error: access local count2 before it is defined ... def func2( n ): global count1, count2 # causes next two statements to refer to above globals count1 = 0 count2 += n class myobject: def func3( self, n ): global count2 count1 = 0 # local count2 += n # global count2, argument n self.count1 # a distinct instance variable In the newer versions of Python, "nested scopes" are implemented. This means that variables which are NOT assigned-to in a local scope are looked for in successively outer scopes. def func3( n ): global count2 # necessary to make assigned-to local count2 global count2 += count1 # otherwise undefined count1 is found in global scope Note that local scopes do NOT work in older versions of Python, in which case you also would have to expressly declare count1 as global in the above example. Note that "global" is relative and generally means the outer most scope of a module. Nevertheless, global names in imported modules generally are qualified by the module name. E.g.,: import string string.join( alist ) Clear as mud? Once you understand how they work, you should reconsider your need for globals. In most cases, defining a class with one or more local names is a better solution. E.g., instead of: count = 0 def fn(): global count ... count += n you should define a class: class Counter: def __init__( self, init=0): self.count = init def inc( self, delta=1 ): self.count += delta counter = Counter() def fn(): ... counter.inc( n ) Since the counter name is NOT assigned-to, under nested scope rules you don't have to declare it global. In this stilted example, the overhead of the class seems excessive but in practice, you'll find it to be a vastly superior approach over the standard "rape and pilage" global style. Regards --jb -- James J. Besemer 503-280-0838 voice 2727 NE Skidmore St. 503-280-0375 fax Portland, Oregon 97211-6557 mailto:jb at cascade-sys.com
https://mail.python.org/pipermail/python-list/2002-October/168009.html
CC-MAIN-2016-44
refinedweb
426
65.42
Dissecting Method Calls If you’ve been writing Ruby code for a while, you already have a visceral feel of how completely object-oriented Ruby is. In fact, most introductory Ruby books will tell you that writing Ruby programs is all about manipulating objects — using/creating objects, endowing them with abilities through method definitions, inheritance, and mix-ins, and asking them to perform actions through method calls. Given how prevalent method and method calls are in a Ruby program, every beginning Ruby programmer should get a good grasp of the details of method calls. overview of method call elements Let’s start with the building blocks. Method calls may contain any of the following elements: - receiver (defaults to self if not provided) - dot operator (required if receiver is provided) - method name (required) - argument list (defaults to ()) - code block (optional, no default) There are methods that can be invoked with just the name and there are those that would need more to even run. puts # returns nil [1,2,3].drop # ArgumentError There are even methods that can be called with two arguments, an argument and a block, or even just one argument, and they’d all run fine. receiver = "dissecting method calls" receiver.gsub("dissecting", "examining") receiver.gsub("dissecting", {"dissecting" => "examining"} receiver.gsub("dissecting") { |match| match + " and examining" } receiver.gsub("dissecting") #=> Enumerator object With the myriad of predefined methods that Ruby provides and the number of ways to call each method, how do we make sure that we are calling them the right way? If it’s a predefined method in Ruby, look at the Ruby documentation. Otherwise, look at the method definition. The image below is lifted from the official Ruby documentation on gsub. Notice that we invoked gsub in four ways just like the documentation shows. In fact, Ruby-Doc gives you more than just variations for calling methods. It goes into details and gives a few examples. When in doubt, it’s always a good idea to check the documentation. Every method belongs to an object and is always invoked on an object, which we call the receiver. A receiver can either be a literal object construct or a variable which represents the object. string_variable = "RUBY METHODS" "RUBY METHODS".downcase #=> "ruby methods" string_variable.downcase #=> "ruby methdos" The two calls to downcase are invoked on a string object — the first one having a literal object construct as a receiver and the other, a variable representing a string. In practice, the receiver is usually a variable standing in for the actual object. In the absence of an explicit receiver, however, the default value will be self. self is an object much like everything else in Ruby. It represents the “I” in the program, to which methods called without an explicit receiver is addressed. It is important to note that there is only one self at any point, but who that self is changes depending on where you are in the code. When an explicit receiver is provided, the dot operator (.) must tag along. In Ruby parlance, it’s called the message-sending operator where the method on the right of the dot is “sent” to the receiver on the left for execution. In the code example above, what we are effectively saying is, “Hey string object, here’s a message: sort.” You might ask, “How can we be sure that the receiver knows what to do with the message?” Glad that you asked! In fact, the code above raises an error — NoMethodError. It means that "ruby_methods" does not know what to do with the message. It’s the equivalent of me handing you this message. You’d be like… …unless you know Chinese. Every object knows how to respond to a certain set of methods — not all methods. If it doesn’t understand, it raises an exception just like what happened above. Then you might ask, “How do we know which set of methods or messages an object can respond to?” Given that there’s so much that goes into determining the answer to that question including a discussion on inheritance and method lookup paths, I’ll reformulate the question to, “How do we know that an object responds to a certain method?” Through the respond_to? method that Ruby provides. "ruby methods".respond_to(:sort) #=> false "ruby methods".respond_to(:upcase) #=> true my_array = [1, 2, 3, 4] my_array.respond_to?(:sort) #=> true my_array.respont_to?(:upcase) #=> false It returns true if the receiver on the left knows what to do with the method argument of respond_to?, and false otherwise. The argument of the method is a method name prepended with a colon (:). Methods are just like mathematical functions or, if you hate math, machines. They take in inputs, do something with that input, and then output the result of the previous step — much like below. In Ruby, however, methods aren’t only used to get outputs, better known as return values in Ruby. Other use cases are to mutate passed inputs, or change the object states. These inputs are the arguments. To invoke a method with arguments, you put them inside parentheses after the method name although parentheses are optional. [1, 2, 3, 4].take(2) #=> [1, 2] "ruby_methods".split(' ') #=> ["ruby", "methods"] "ruby_methods"[0, 4] #=> "ruby" Methods can take in zero, one, two, or any number of arguments. Much like method call elements where some are optional and some are required, method arguments can also be either. They can also be a string, array, hash, or even any object. Figuring this out is important as passing in one less argument or an argument of a different class may spell the difference between an error or the code running. How do you figure out which is which? You can either look at the method signature at Ruby documentation if it’s part of the standard library or at the method definition if it’s a method that you or someone else defined. Methods can also be called with a code block. The difference between a method that can or cannot accommodate a code block boils down to its ability to yield. Simply put, if there’s a yield statement inside, the method can take a block. The yield method, literally, yields control to the block passing in any argument that is provided. def ruby_methods yield("I'm in the block!") puts "I'm back in the method." end ruby_methods { |message| p message.size + 1 } #=> 18 #=> I'm back in the method." The code inside the block is then executed. It can do whatever it wants to the passed in argument given it’s valid in Ruby. It can even ignore the passed in argument like below. ruby_methods { |message| puts "Where's the message?" } Control, along with the return value of the block, is then handed back to the original method and execution of code resumes right after yield. So that’s a quick run through over the syntactic elements of a method call. I’ll delve much deeper on each of them next.
https://medium.com/@sheldonchi/dissecting-method-calls-part-1-9f42f3a92ce2
CC-MAIN-2018-51
refinedweb
1,169
65.83
This is the tenth in a series of blog posts I’m doing on the upcoming VS 2010 and .NET 4 release. In today’s blog post I’m going to cover a small but really nice improvement to code intellisense with VS 2010 – which is its ability to better filter type and member code completion. This enables you to more easily find and use APIs when writing code. To help illustrate this intellisense improvements coming with VS 2010, let’s start by doing a simple scenario in VS 2008 where we want to write some code to enable an editing scenario with a GridView control. We might start off by typing “GridView1.Edit” to bring up intellisense to see what Edit members are available on the control. Doing this with VS 2008 brings up the intellisense drop-down and filters the current location in the dropdown to the members that start with the word “Edit”: This is great if the method/property/event we want to work with starts with “Edit” – but doesn’t really help us if the “Edit” member we are looking for starts with something else (for example: the “RowEditing” event or the “SetEditRow()” helper method). We have to either manually scroll up and down looking for the other edit members, or pull up the object browser or help system to find them. Let’s now try out the same scenario with VS 2010. When we type “GridView1.Edit” within VS 2010 we’ll find that the EditIndex property is still highlighted by default. But the intellisense list has also been filtered so that it enables you to quickly locate all other members that have the word “Edit” anywhere in them: This allows us to quickly see all of the edit related methods/properties/events and more quickly find what we are looking for. Searching for Keywords This new intellisense filtering feature of VS 2010 is useful for searching for any member – regardless of what word it starts with. For example, if we want to enable paging on a datagrid and can’t remember how to-do it, we could just type “GridView1.Paging” and it would automatically filter out everything but members that have the word paging. Notice below how no members on the GridView class actually start with the word “Paging” – but I am still finding the two members that do have paging in them later in their names: Searching for Types This new intellisense filtering capability of VS 2010 is also useful for quickly finding classes and types. For example, when we type “List” to declare a variable, the editor will provide automatic filtering to show all types that have the word “List” somewhere in them (including IList<> and SortedList<> – which do not start with List): This makes it much easier to find type names you can’t entirely remember – without having to resort to searching through the object browser and/or using help documentation. Pascal Case Intellisense The .NET Framework naming guidelines specify that type and member names should be “Pascal Cased” by default. This means that each word in a type or member should start with a capitalized letter (for example: PageIndexChanged). VS 2010’s intellisense filtering support now enables you to take advantage of this to quickly find and filter methods based on their pascal naming pattern. For example, if we typed “GridView1.PIC” VS 2010 would filter to show us the members that have PIC in their name, as well as those members which have a pascal cased name where the word segments start with that letter sequence: Notice above how PIC caused both “PageIndexChanged” and “PageIndexChanging” to show up. This saves us a few keystrokes when resolving either member or type names. I think you’ll find that the new intellisense filtering approach in VS 2010 makes it easier to quickly find and use classes and members when writing code. You can take advantage of it with both VB and C#. Hope this helps, Scott P.S. In addition to blogging, I have recently been using Twitter to-do quick posts and share links. You can follow me on Twitter at: (@scottgu is my twitter name) Looks great, unfortunately intellisense is either too slow to work or is not working which is the same thing. This is really great! But I am unsure of how useful the Pascal Casing search is. I can see that it will be useful when browsing the source code (as covered in your last post), but do you think it will be used when we are writing code? I suppose you have a good reason to add the feature, so it would be interesting to hear why. :-) I see sign of ReSharper ;) Camel Humps name matching rules! Great news, Scott, thanks for keeping us in touch with new features! And what about C++ IntelliSense? Will VS2010 have something like VisualAssist built-in or things remains the same with Ctrl-Space? This is great, often clicking through the list to find something long forgotten takes so much more time than it should. These options are nice. Is there a way to enable / disable this feature? does the namespace have to be imported in order for "Searching for Types" to find the class? If so, I don't see enough signs of Resharper :) Hmm.. haven't I seen this somewhere else? Oh yeah, resharper? I have noted before that some "new" functionality in visual studio already exists in resharper. How much ideas do you "borrow"? Wonder what Visual Studio would look like if JetBrains had taken patent on all of their ideas? ^^ Hello Scott, Are there any improvements in intellisense for aspx page ( not code behind). Specially is there are more kind of code blocks allowed ? The flexibility to write server side code mixed with HTML was very limited in ASP.Net till now. Thanks It's great feature. Thanks I like this improvement :) Question: Where could I send in ideas, change requests for your products, like say Visual studio 2010? One of many request/idéas would be to change the "add reference"-wizard. - Use threading for this wizard Or at least default it to "browse" , instead of w8:ing forever for it to reflect/enumerate all dll's from GAC. As it functions now it locks down my IDE until it's finished enumerating :( Nice post and nice feature. I'm wondering: 1. Can we also enable VS2008 like IntelliSense if we prefer that? 2. What about human intelligence? If I type Edit, I logically can think about all CRUD options... Please let me know your thoughts about this. Thanks, Alex de Groot good ones nice improvement.. vs 2010 is rocked. But there's a problem fetching when using of asp:textbox Maxlength with texmode=multiline in vs2008 not working. Will you please give some comments on that? Camel hump matching intellisense rocks! Not related to intellisense, but can you do a "find type by camel humps"? "Pascal Case" is also in Visual Assist, I use it rather rarely, though. hey scott, that is very nice! can you please tell us more about intellisense for javascript, asp.net and web application projects? i.e. will intellisense work now if i reference styles.css with "~" (application path) or will there still be the curly green lines under my css class attributes in html? in short: is VS2010 now capable to resolve "~" (application path) by iis at design time? and this in/for: .aspx, .ascx and .master files? .js files (via ///<reference path="~/myVirtualDirInIISThatIsNotPartOfThisWAP/myScript.js"/>)? it is possible that we can ///<reference> a .asmx scriptservice in a separate javascript.js file via "~" to get intellisense there? BTW: is it possible that the script handler that produces the json (via myScriptService.asmx/js) will be also capable of including all properties of my custom objects (that i referenced via GenerateScriptTypeAttribute)? Many Thanks, Tobi I would love to see intellisense for derived types so we could do: ISomeType x = new ..... and here we could get all types that fullfill this contract. Nice Features. I follow your blog on an every day basis. I love it. I'm counting the days for PDC09. Can't wait for what's comming. @Rune Grimstad> For example in windows forms, try to declare a new DataGridViewCheckBoxColumn, there are an awful lot of types that relate to DataGridView so you really have to type the name up to "DataGridViewC" before relevant matches start to appear. So I think that I'll be more than happy to simply type DGVCBC. Wo0ow, that's really great, that's will make writing code more easy, and help us to find what we want in short time. Thanks :) Scott, Looks good. I've often got fed up with scrolling through the list to find what I want. Is there any way of filtering by Fields, Interfaces, Methods, etc? Max Oh no ! The days where I was using intellisense to scan for all of an object's properties and methods seems to be over :( This feature is not so good to me :/ Great work done by micorosoft and great explanation done by you Mr. Scott. really a cool stuff thanks to VS team Hi Scott, Please could you have a friendly word with your distant colleagues in the SQL Server team and ask them to bring the same to SQL Server Management Stdio? THanks Jamie Very nice post scott, Thani What about taking a cue from the Office folks and the story they’ve written around paste? I think it would be great if when intellisense was invoked, you could tap on CTRL and intellisense would immediately filter the list to in-scope instantiated types. I posted an example at my URL, but basically, when I'm assigning a value to an instance of my SomeType class, I would like to be able to hit CTRL and further filter that list in intellisense down to local, member and global instances of SomeType. Take this to the next level as well: if I’m assigning a value to a string and I’m looking for a property on a class instance, when I invoke intellisense I could tap CTRL and filter the list of type members down to just strings (much like you're doing with keywords). Thanks for another solid release. Cheers, -cj Will VS 2010 have an option for us to choose between VS2010 intellisense and VS2008? There was usefulness in being able to see the entire set of methods, properties etc. from a class instead of a subset like in VS2010. This updates to intellisense will be handy for sure, thanks, keep the good work going. How about C++ intellisense? Will the parsing be faster/more reliable than in VS2008? Is there a problem with the JavaScript intellisense as reported by RIck Strahl? west-wind.com/.../50857.aspx Rgds, Anthony :-) I can't seem to be able to change the font used for IntelliSense inside a view (aspx/ascx) in code view mode. In .cs files it uses the right font, only in aspx files it doesn't work. Thanks. Intellisense filtering is a very nice feature. I'm not sure yet if "Pascal Case Intellisense" would be useful though. But we'll see. These features look great! Rune: The pascal case search will probably be good for accessing members with long names. For example, with VS 2008 you have to do a lot of typing to get DependencyPropertyChangedEventArgs to be near the top of your intellisense results, but if you can just type the first letter of each word you will get there way faster. EXCELLENT! Sounds very helpful. What would really be helpful would be if you could specify the size and amount of information of the intelisense hover / popup window. Its always frustrating having three huge 21" flat panels with epic amounts of information at hand, but having to digest intelisense through the smallest window in VS.net Also, parameter / argument information could be displayed in a much nicer and more verbose manner, as eclipse does. I miss not being able to resize the intellisense popup window. I used to have it stretched to it's max vertically so that I could see as many options as possible. In 2010 there's no border on the popup to grab hold to. Until there's some word on how goes the fixing of intellisense-hang-and-not-working-and-crashing-VS problem, I'm not even close to being sold on this. Are the new Intellisense features going to be added to C++ as well? It always seems like they C++ Intellisense feature set lags behind by about a decade or so :( Hello Scott. I am a longtime Microsoft developer. I have recently joined a startup company that is using PHP and Apache for its primary web application development. I would like to convince them to switch to using .NET since I think it is a much better environment for the advanced software/website that we are developing. Are there any documents/studies that would help me with my argument? Thanks for your time. Jay MacDonald jay@newvisionit.com I wish I could try that, but VS2010 can't be installed. I've tried 6 times. It's definitely a problem with the web installer. So where's the ISO? My browser is already are great downloader, so Microsoft didn't have to reinvent the wheel there. "Pascal Case Intellisense", this feature is so good, I use this feature a lof when using resharper. Hi Scott, Looks great. It would be great if it could also support Pascal Case Navigation. (It's already done by DevExpress visual studio addin) Right now VS only supports navigation around a word using Ctrl+ArrowKey For example now the cursor is at | |DataBound when i press ctrl+right arrow, it goes to DataBound| It would be a great feature if VS could support Alt+ArrowKey |DataBound would go to Data|Bound when Alt+left arrow key is selected. Its very helpful when selecting using Shift+alt+arrow keys in order to rename The filtering and Pascal casing look great. One thing I'm not happy with is the loss of the ability to hold down the Ctrl key while the intellisense window is open in order to reduce the opacity of the window to take a peek at your code. I use this all the time and it will be a great loss if this feature has been dropped. Also I'd like to be able to resize the intellisense window like we could previously. For anyone who previously used this feature, I've just created a bug on Connect if you'd like to vote for it: connect.microsoft.com/.../ViewFeedback.aspx Hi, Can anyone tell me where can I download VS 2010 professional edition. Jaswant Singh Rana <a href="">Sequent Technologies</a> No!No!No!No!No!No!No!No!No!No!No!No!No!No! If I want to select the Method start with "g", so I type "g". But I can't confirm it's "g" or "j" or "i", so I want to find it start with "g". So I type "g" and scroll the bar up to down to find the right method what I need. But after you improved it, I type "g", I think I can't show the word "xml" in the intellisense window. I get a lot of word like "google"/"mpeg"/"ignore" and so on. I think It's necessary to add a button under the intellisense window, named like "replace tradition!" or "show all!", then redirect it to the current word what you have typed. It's necessary! Intellisense is definitely moving in the right direction, especially for developers who haven't yet opted to buy ReSharper after writing code for several years, I'd like to write pure code instead of drag controls to IDE, with intelligence, it does help me a lot The new intellisense IS pretty cool but there seems to be fairly high computational cost. Running VS2010 B2 on a fairly fast dual-core laptop with 2GB RAM, I find that between the intellisense and general line formatting/highlighting, the IDE is having a lot of trouble keeping up with mornal typing speeds. I'm having to slow down the pace a bit in order to be able to allow the intellisense a moment to respond most of the time. Hopefully this is just an issue in B2 and will be further optimized in RTM, or I'll have a room full of developers with suddenly under-powered hardware. Brilliant, saves lot of time scrolling up and down in intellisense window. Any hope of there being intellisense support inside HTML attributes? This feature is great. I noticed this while I was playing with the new parallel extensions. Now the next step is for the intellisense to mind-read the property name I can never remember the name of. It'd be nice if it could filter the list based on the return type (first using "this."). For example all booleans properties are shown. I agree that there needs to be a way to enable/disable this functionality as there are times where I will not want intellisense to operate that way. To Jamie Thomson above who wants something for SQL Server, try SQL Prompt. My co-worker and I have been using it for the past 2 years or so and it works pretty good. It will drill down into all your tables, stored procs, and so on and give you intellisense on all your columns and parameters, etc in addition to SQL syntax. You can also create customs snippets and refresh your cache as you make changes to your data structures. FANTASTIC! is C# intellisense also going to be as good as vb.net now as well? it's never seemed quite as helpful or cooperative to me for whatever reason. BTW: is there truth in that or is it my imagination (can't think of specific examples) also the lack of autoupdating the squiggles without building in a lot of c# situations sucks (i know they've made improvements recently - but still not as good as vb.net) I like the keyword filtering, that's a great addition when you are looking for a property/method in a model you are not too familiar with. That said, the Pascal searching doesn't seem like it is that useful but I guess I would have to try it before making such a bold statement :) This is nice. I do think it should either be configurable or change back to the old behavior if I press the Ctrl key or something. It sometimes is helpfull to see all members in the list. I also second the notion of Intellisense in SQL Server Managment Studio (PLEASE!! :). Also, are there any improvements to javascript intellisense in VS 2010 that are not in VS 2008? More specifically the error messages I get for my custom javascript objects do not report the actual line number. I would like to be able to find what JScript Intellisense finds and is having a problem with. Thanks. Ah, this is so welcome... The Pascal Casing is just plain ingenious and it will save a lot of typing. I've always wished that intellilsense would have a way of filtering on types that apply to the left side of the assignment operator, like the following: IList<string> foo = new (intellisense filtered on types derived from IList<T>) I imagine that could be pretty CPU intensive, however. Thanks, great features... I look forward to the release of VS2010 - it will bring us one tiny step closer to the functionality of Jetbrain's Java IDE, which has been streets ahead for years now. As much as I'm enjoying my foray into the .NET world, I do miss the IDE functionality that I've become used to. Nice! I look forward to the release of VS2010. Thanks for heads-up on new improvements in VS 2010 in IntelliSense. Where the ideas of using more generic infrastracture for IS databases, like SQL Server did go, so that IS can be implemented and enhanced by the language developers so that better languages parity can be provided inside IDE? Nice feature indeed!! It will save a lot of time though... I need to add my voice to the people asking about C++. Same question: will intellisense for C++ be improved in 2010? It's not particularly great in 2008... ms makes developers more lazy :P
http://weblogs.asp.net/scottgu/archive/2009/10/22/vs-2010-code-intellisense-improvements-vs-2010-and-net-4-0-series.aspx
CC-MAIN-2013-48
refinedweb
3,441
71.95
Subject: Re: [boost] [local] this_ or _this? From: Steven Watanabe (watanabesj_at_[hidden]) Date: 2011-04-03 20:33:00 AMDG On 04/03/2011 12:22 PM, Emil Dotchevski wrote: > On Sun, Apr 3, 2011 at 11:13 AM, Lorenzo Caminiti<lorcaminiti_at_[hidden]> wrote: >> Hello all, >> >> Boost.Local uses a special name `this_` to access the object `this` >> bound from the enclosing scope. Shall this name be `this_` or `_this` >> according to Boost practices? > > Names with leading underscore should be avoided, they may be used by > the compiler for its own needs. > Names beginning with an underscore and a /capital/ letter are reserved for any use. Names beginning with an underscore and a lower-case letter are only reserved in the global namespace. In Christ, Steven Watanabe 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/2011/04/179743.php
CC-MAIN-2021-39
refinedweb
149
76.42
Talk:Haskell/Continuation passing style From Wikibooks, the open-content textbooks collection Here's everything I've written for this module so far, before running out of stamina: Continuation passing style (CPS) in Haskell is, like monads, rather difficult to understand. What makes a CPS value a CPS value is the fact that it takes an extra parameter, called a continuation. The continuation represents the function being applied to the value: the CPS value simply has to apply the continuation to the value within it. A very simple example: cps3 cont = cont 3 The consequence of this taking a continuation is a biggie: the CPS value has access to the function being applied to it. This allows values to do weird things: for example, it's easy to make a value that ignores the continuation and returns a different value instead. This is similar to the Maybe monad, where Nothing has the effect of ignoring whatever functions are applied to its "contained value". The type of a CPS value is simple: (a -> r) -> r Here, a represents the CPS value's "inner type". (a -> r) is the function applied to the CPS value, and r is of course the return type of this function. Note that there is nothing preventing the CPS value from imposing restrictions on r as well as a; a function like const 'a' can be used as a CPS value: const 'a' :: (a -> Char) -> Char Since const 'a' ignores any function passed to it, it doesn't matter what this function takes. However, const 'a' will always return a Char, so this must be the function's return type, to "disguise" the fact that the Char is not being pulled from the continuation. This restriction is imposed by the fact that a CPS value has to return the same type as its continuation--even if the continuation is not used. CPS values aren't often used alone: continuation passing style programming often contains them in great quantities. To make things easier to understand, there's a type with a data constructor that works on CPS values: newtype Cont r a = Cont { runCont :: ((a -> r) -> r) } Here r represents the restrictions on return type imposed by the CPS value, and a represents the value contained within the CPS value. The data constructor Cont turns a CPS value into a Cont value, and runCont turns it back again. Adding Cont to Monad allows us to stitch together continuations: instance Monad (Cont r) where return a = Cont $ \k -> k a (Cont c) >>= f = Cont $ \k -> c (\a -> runCont (f a) k) First of all, notice that (Cont r), and not Cont, is being defined here as an instance of Monad. This is because it is what (Cont r) is "applied" to that defines what's "contained within" the CPS value. Now, it's not necessary to understand just what >>= does and how it does it. It just feeds a CPS value into a CPS function and returns a CPS value. In case you're getting into the "gimme some CODE": we're getting there. Now, we can define an exit function. It is the same as the usage of const above, except making a Cont value rather than simply a CPS value. exit x = Cont (const x) Also, we'll make a finish function that takes the value "inside" a Cont value and returns it: finish x = runCont x id This turns its Cont argument into a normal continuation, then applies it to id, ending the computation. Finally, we'll note that return () acts as a "nop" in any do-block. Here's a basic example of division: divide x y = finish (do if y == 0 then exit (error "Division by zero") else return () return (x / y)) This does seem very useless, but many imperative constructs can be simulated in the Cont monad. This leaves the open question: how do I simulate the inarguably imperative monad that is IO? Well, Cont is, in fact, the most general of the monads, in that any monadic value can be turned into a Cont monadic value and back again. Looking again at the type of >>=: (>>=) :: m a -> (a -> m b) -> m b Wait. Did I see a CPS value there? Yep: >>= can be thought of as taking a monadic value and making a CPS value out of it. Simply apply Cont to this value, and we have a fully functional value in the Cont monad! monadToCPS :: m a -> Cont (m b) a monadToCPS x = Cont (x >>=) And the inverse: cpsToMonad :: Cont (m a) a -> m a cpsToMonad x = runCont x return One nice thing about this is that it will work on any Cont value with the appropriate type: it doesn't have to be one generated by monadToCPS. This allows us to mix other monads with Cont quite easily, though it's against the rules to combine other monads with each other. (Note that cpsToMonad is also the intuitive definition of a finishMonad function, that returns a monadic value instead of "just any value".) Much stuff. Go insane with it. --Ihope127 18:27, 29 January 2006 (UTC) [edit] Haskell's self-defeating authors Why the fixation amongst haskellers on mathematics? I mean, you all couldn't think of a better example for CPS than the quadratic formula? There's simply no need to be adding to the complexity of this, it only serves to steepen the learning curve for us non-math-gurus... seriously... - I can only encourage you to strengthen your math skills, the quadratic formula is like 9th grade... and a good example, mainly because the "classic" example of error continuations is uncommon in Haskell, since we have Maybeand Either. - -- apfeλmus 09:32, 17 May 2008 (UTC) [edit] Error in "a note of typing" As it appears to me, almost all explanation in this chapter is wrong. Concerning type of k: k :: a -> Cont r b The b type isn't arbitrary because of we don't do anything with result of k. It's arbitrary because we don't do anything with continuation supplied to Cont r b. Explanation: The return type of k is a Cont Monad which has type signature ((a->r)->r). As it stands in definition of callCC: class (Monad m) => MonadCont m where callCC :: ((a -> m b) -> m a) -> m a instance MonadCont (Cont r) where callCC f = Cont $ \h -> runCont (f (\a -> Cont $ \_ -> h a)) h As we can see, our k is (\a -> Cont $ \_ -> h a) It ignores it's parameter which is of type (a->r) where type of expression is Cont r a As we can see, because input function is ignored, the "a" type is arbitrary, and thats the real reason for k signature. Also, the reason we must use "return" at the end of callCC instead of k lies elsewhere. As we know x<-m1 m2 really means m1 >>= (\x->m2) and type of this is m1 :: m a (\x->m2) :: (a -> m b) Substituting this for our example: x = Msg :: String m1 = callCC m2 = return (length Msg) If we use return at the end of callCC, it returns Cont Monad of type Cont r String and it matches type of Msg. If we use k instead of return, type of k is already binded to () by use in "when" so it has type Cont r () and this is mismatch with String in definition of callCC >>= (Msg -> return (length Msg)). - I don't quite understand. Strictly speaking, the explanation in the article is correct, if very unclear. The problem is that while the bin k :: a -> Cont r bis indeed arbitrary, you cannot have both b=Stringand b=()as you point out as well. - The advice of always ending a do-block in callCCwith returnis wrong. The proper solution is to give callCCa rank-3 type: callCC :: ((forall b. a -> Cont r b) -> Cont r a) -> Cont r a - -- apfeλmus 09:17, 11 September 2008 (UTC) - After reading explanation from article many more times and giving it Deep Thought, I must admit it is correct. Probably my tendency to be very precise and the fact that I was still learning all of that made me unable to understand the text appropriately. - However, I don't understand why advice about "return" is bad. The type You gave is the same as in actual definition, unless explicit "forall" changes something (what? :). - -- Spawarotti 13-IX-2008 - Ah, after some Deep Thought on my part, there are actually two issues here and the advice about returnis partly right and partly wrong. - To see why returnis no panacea against type errors with k, consider the following foo :: Cont r Int foo = callCC $ \k -> do x <- k 41 let z = (x + 2) :: Int when True $ k 42 return 43 - What type does khave? The first two lines in the do-block force it to be of type Int -> Cont r Intwhile the third line forces it to be of type Int -> Cont r (). In other words, the bfrom the type of callCCshould be both Intand ()which is clearly not possible. (Well, unless you use the type I gave with the explicit "forall". Look at its position, it's not just an explicit forall. The chapter Haskell/Polymorphism ought to explain this. Meanwhile, have a look at GHC's Users Guide, Arbitrary rank polymorphism and/or ask a haskell mailing list or #haskell. Basically, you can use several bnow.) The returndidn't help here. - On the other hand, I think the advice was meant to mean that you should not use kas the last statement, like in bar :: Cont r Int bar = callCC $ \k -> do let n = 5 when True $ k n k 25 - Many thanks for Your explanation. That makes everything clear for me :) - -- Spawarotti 19-IX-2008
http://en.wikibooks.org/wiki/Talk:Haskell/Continuation_passing_style
crawl-002
refinedweb
1,637
64.85
Created on 2008-10-01 15:37 by haypo, last changed 2009-01-18 20:18 by loewis. This issue is now closed. IDLE checksyntax() function doesn't support Unicode. Example with idle-3.0rc1-quits-when-run.py in an ASCII terminal: $ ./python Tools/scripts/idle Exception in Tkinter callback Traceback (most recent call last): File "/home/haypo/prog/py3k/Lib/tkinter/__init__.py", line 1405, in __call__ return self.func(*args) File "/home/haypo/prog/py3k/Lib/idlelib/ScriptBinding.py", line 124, in run_module_event code = self.checksyntax(filename) File "/home/haypo/prog/py3k/Lib/idlelib/ScriptBinding.py", line 86, in checksyntax source = f.read() File "/home/haypo/prog/py3k/Lib/io.py", line 1719, in read decoder.decode(self.buffer.read(), final=True)) File "/home/haypo/prog/py3k/Lib/io.py", line 1294, in decode output = self.decoder.decode(input, final=final) File "/home/haypo/prog/py3k/Lib/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 87: ordinal not in range(128) To open an ASCII terminal on Linux, you can for example use xterm with an empty environment (except DISPLAY and HOME variables): "env -i DISPLAY=$DISPLAY HOME=$HOME xterm". Hum, the problem is that IDLE asks io.open() to detect the charset whereas open() doesn't know the #coding: header. So if your locale is ASCII, CP1252 or anything different of UTF-8, read the file will fails. I wrote a patch to detect the encoding. Python code (detect_encoding() function) is based on PyTokenizer_FindEncoding() and get_coding_spec() (from Parser/tokenizer.c). There is no existing Python function to detect the encoding of a Python script? (a public function available in a Python script) Ah! tokenize has already a method detect_encoding(). My new patch uses it to avoid code duplication. Notice that there is also IOBinding.coding_spec. Not sure whether this or the one in tokenize is more correct. loewis wrote: > Notice that there is also IOBinding.coding_spec. > Not sure whether this or the one in tokenize is more correct. Oh! IOBinding reimplement many features now available in Python like universal new line or function to write unicode strings to a file. But I don't want to rewrite IDLE, I just want to fix the initial problem: IDLE is unable to open a non-ASCII file using "#coding:" header. So IDLE reimplemented coding detection twice: once in IOBinding and once in ScriptBinding. So I wrote a new version of my patch removing all the code to reuse tokenize.detect_encoding(). I changed IDLE behaviour: IOBinding._decode() used the locale encoding if it's unable to detect the encoding using UTF-8 BOM and/or if the #coding: header is missing. Since I also read "Finally, try the locale's encoding. This is deprecated", I prefer to remove it. If you want to keep the current behaviour, use: ------------------------- def detect_encoding(filename, default=None): with open(filename, 'rb') as f: encoding, line = tokenize.detect_encoding(f.readline) if (not line) and default: return default return encoding ... encoding = detect_encoding(filename, locale_encoding) ------------------------- Please review and test my patch (which becomes longer and longer) :-) > Oh! IOBinding reimplement many features now available in Python like > universal new line or function to write unicode strings to a file. It did not *re*implement. The implementation in IOBinding predates all other implementations out there. @loewis: Ok, I didn't know. I think that it's better to reuse existing code. I also compared the implementations of encoding detection, and the code looks the same in IDLE and tokenize, but I prefer tokenize. tokenize.detect_encoding() has longer documentation, return the line (decoded as Unicode) matching the encoding cookie, and look to be more robust. I saw an interesting test in IDLE code: it checks the charset. So I wrote a patch raising a SyntaxError for tokenize: issue4021. I can't reproduce the problem. It works fine for me, displaying the box drawing character. In case it matters, sys.getpreferredencoding returns 'ANSI_X3.4-1968'; this is on Linux, idle started from an xterm, r66761 @loewis: I guess that your locale is still UTF-8. On Linux (Ubuntu Gutsy) using "env -i DISPLAY=$DISPLAY HOME=$HOME xterm" to get a new empty environment, I get: $ locale LANG= LC_ALL= LC_CTYPE="POSIX" LC_NUMERIC="POSIX" LC_TIME="POSIX" LC_COLLATE="POSIX" ... $ python3.0 >>> from idlelib.IOBinding import encoding >>> encoding 'ansi_x3.4-1968' >>> import locale >>> locale.getdefaultlocale() (None, None) >>> locale.nl_langinfo(locale.CODESET) 'ANSI_X3.4-1968' In this environment, IDLE is unable to detect idle-3.0rc1-quits-when-run.py encoding. IDLE uses open(filename, 'r'): it doesn't specify the charset. In this case, TextIOWrapper uses locale.getpreferredencoding() as encoding (or ASCII on failure). To sum IDLE: if your locale is UTF-8, you will be able to open an UTF-8 file. So for example, if your locale is UTF-8, you won't be able to open an ISO-8859-1 file. Let's try iso.py: IDLE displays the error "Failed to decode" and quit whereas I specified the encoding :-/ > @loewis: I guess that your locale is still UTF-8. To refute this claim, I reported that locale.getpreferredencoding reports 'ANSI_X3.4-1968'. I was following your instructions exactly (on Debian 4.0), and still, it opens successfully (when loaded through File/Open). Should I do something else with it to trigger the error, other than opening it? When opening iso.py, I get a pop window titled "Decoding error", with a message "Failed to Decode". This seems to be correct also. So I still can't reproduce the problem. I don't understand why you say that IDLE uses open(filename, 'r'). In IOBinding.IOBinding.loadfile, I see # open the file in binary mode so that we can handle # end-of-line convention ourselves. f = open(filename,'rb') :-/ This patch has two problems: 1. saving files fails, since there is still a call left to the function coding_spec, but that function is removed. 2. if saving would work: it doesn't preserve the line endings of the original file when writing it back. If you open files with DOS line endings on Unix, upon saving, they should still have DOS line endings. This is still a problem on my WinXP 3.0rc3 with # -*- coding: utf-8 -*- in a file but not with the same pasted directly into the shell Window. Here is a new patch that fixes this issue, and the duplicate issues (#4410, and #4623). It doesn't try to eliminate code duplication, but fixes coding_spec by decoding always to Latin-1 first until the coding is known. It fixes check_syntax by opening the source file in binary. It should have fixed tabnanny the same way, except that tabnanny cannot properly process byte tokens. I vote for fixing this too. This might be simplified/another example of above mentioned issues: # -*- coding: utf-8 -*- print ("ěščřžýáíé") in IDLE prints this: >>> ěščřžýáĂĂ© When running this script under python command line from another editor, I get the output readable as expected. Committed as r68730 and r68731.
http://bugs.python.org/issue4008
CC-MAIN-2015-32
refinedweb
1,183
60.41
RegistrationState Since: BlackBerry 10.0.0 #include <bb/platform/bbm/RegistrationState> To link against this class, add the following line to your .pro file: LIBS += -lbbplatformbbm Represents the RegistrationState of an application on the BBM Social Platform. RegistrationState is updated by the BBM Social Platform. Overview Public Types Index Public Types The list of possible registration states. BlackBerry 10.0.0 - Allowed 0 Your app has successfully registered and has full access to the BBM Social Platform. - Unknown 1 The BBM Social Platform has not yet retrieved the access code for your app.Since: BlackBerry 10.0.0 - Unregistered 2 Your app is not registered with the BBM Social Platform.Call requestRegisterApplication() to start the registration process.Since: BlackBerry 10.0.0 - Pending 3 Your app initiated the registration process and it is currently in progress.Since: BlackBerry 10.0.0 - BlockedByUser 4 Your app was blocked by the user and does not have access to the BBM Social Platform APIs.The user can unblock the app by using the global settings application.Since: BlackBerry 10.0.0 - BlockedByRIM 5 Your app was blocked by RIM and does not have access to the BBM Social Platform APIs.The app has most likely violated the terms of use.Since: BlackBerry 10.0.0 - NoDataConnection 6 A data connection could not be established to complete registration.The user needs to enable data services and/or access sufficient data coverage.Since: BlackBerry 10.0.0 - UnexpectedError 7 Your app could not register due to an unexpected error.Since: BlackBerry 10.0.0 - InvalidUuid 8 Your app could not register because an invalid UUID was used in the registration process.Since: BlackBerry 10.0.0 - TemporaryError 9 Your app could not register because of a temporary error.Since: BlackBerry 10.0.0 - MaxDownloadsReached 10 Your app has reached the maximum number of users allowed.Since: BlackBerry 10.0.0 - Expired 11 Your app's access to the BBM Social Platform has expired and no longer has access to the BBM Social Platform APIs.This limit is not applied to apps that are downloaded from BlackBerry World. You can submit your app to BlackBerry World to ensure that it does not reach this limit.Since: BlackBerry 10.0.0 - CancelledByUser 12 The registration process was canceled by the user.Since: BlackBerry 10.0.0 - MaxAppsReached 13 Your app cannot register on this device because the maximum number of allowed apps has been reached.Since: BlackBerry 10.0.0 - BbmDisabled 14 Your app cannot access the BBM Social Platform because BBM is disabled.The user needs to follow the instructions specified in the BBM app to re-enable BBM. Once BBM is re-enabled, your app will receive a new access status.Since: BlackBerry 10.0.0 - BlockedEnterprisePerimeter 15 Your app does not have access to the BBM Social Platform because it is installed in the Work perimeter.To connect to BBM you must install your app in the Personal perimeter.Since: BlackBerry 10.2 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/cascades/bb__platform__bbm__registrationstate.html
CC-MAIN-2015-48
refinedweb
515
61.93
Another link I found the other day to a blog posting by Vaibhav Choudhary on using the JavaFX 1.2 Charting APIs. He then followed up with a blog populating a chart from a web service call. The important pieces are the following code blocks. The first here is what generates the Pie Chart data slices after the web service call succeeded: function generateChartData(tg:TagInformation, done:Boolean):PieChart.Data[] { for (i in [0..<sizeof tg.tag]) { PieChart.Data { action: function() { showShopping = true; } label: tg.tag[i] value: tg.tagCount[i] } } } This function generateChartData simply returns a sequence of PieChart.Data instances. “for loop” expressions in JavaFX yield a sequence, one item for each iteration of the loop. So the generated sequence will be one PieChart.Data for each result in the tg.tag sequence. This next block of code uses the HttpRequest class to fetch and parse the RSS feed from Del.icio.us. The only thing here that I might have done differently, is to have used the RSS APIs introduced in JavaFX 1.2 rather than hand rolling my own parsing code and using HttpRequest. First the code from the blog doing it the “long” way: public class TagInformation { public var tag: String[]=[]; public var tagCount: Integer[]=[]; public var username: String = "javafx"; // for this sample it's javafx public-read var done = false; var url = bind "{username}?count=4"; var p: PullParser; var h: HttpRequest; init { h = HttpRequest { location: url onException: function(exception: Exception) { exception.printStackTrace(); } onInput: function(input) { p = PullParser { input: input onEvent: function(event) { if ((event.type == PullParser.END_ELEMENT)) { if (event.qname.name == "title" and event.level == 3) { insert event.text into tag; } if(event.qname.name == "description" and event.level == 3){ insert Integer.parseInt(event.text) into tagCount; } } } }; p.parse(); p.input.close(); } onDone: function() { Main.showtag = false; done = true; } }; h.start(); } } And now here is how I would have done it using the JavaFX 1.2 APIs. In JavaFX 1.2 we released some ATOM and RSS support. These classes are in the javafx.data.feed package. public class TagInformation { public var tag: String[]=[]; public var tagCount: Integer[]=[]; public var username: String = "javafx"; // for this sample it's javafx public-read var done = false; var url = bind "{username}?count=4"; init { RssTask { location: "" interval: 1h onItem: function(item) { insert item.title into tag; insert Integer.parseInt(item.description) into tagCount; } onDone: function() { done = true } }.start(); } } The only thing here that I found somewhat irritating and will get put on the bug list for the next release is that you must specify an interval for the RssTask, even if you won’t be polling. Expect this to change to some reasonable polling value as the default. Maybe 1 hour (as in this example) isn’t a bad default. 1 minute is a bit more extreme, but for the feed-junkies out there maybe that’s a better default. As you can see, the code is much simpler using the feed APIs. I guess that’s a good thing ;-). The RSS/ATOM feed APIs use the same basic programming model as HttpRequest — both extend from Task. Task’s have API for monitoring progress, canceling, starting, handling error condition, etc in a unified model. All asynchronous operations in JavaFX should extend from Task either directly or indirectly.
http://fxexperience.com/2009/06/vaibhav-charts-and-rss/
CC-MAIN-2018-30
refinedweb
551
60.31
I have an Arduino 2009 board setup with a simple temperature monitor:. I wanted to use Visual Basic to communicate with the board and build a graphics display page. Arduino provides interface code for various other languages. There is also a very professional interface to Visual Basic available using Fermata written by Andrew Craigie:. This is written so that a component can be added to the toolbox. This component can then be simply dragged onto any form to make it available to code within your project. Using this method hides the actual interface code from the Visual Basic programmer. There is an extra layer of code below your program. The Firmata library implements the Firmata protocol for communicating with software on the host computer. As such, the library must be included in the Arduino board firmware, using up scarce program storage:. As I did not need most of the methods available with this application and wanted to make the program as simple as possible, I decided to write my own code for the interface. All the functions are in classes as this brings discipline to the coding. The Arduino board samples the temperature every 10 seconds. After 6 such samples (1 minute), the board checks the serial input. If it is sent "SSSSSS", it will send the sample value on the serial output. If not, the sample will be stored on EEPROM. So, if the user's computer is not sending "SSSSSS", the samples will be stored on the EEPROM until it is full (1024 bytes). If the serial input is "U", all (if any) of the stored EEPROM samples will be sent on the serial output. So the user's computer will at the start send a "U" to check for and then upload stored samples. After that, it will look for a sample using "SSSSSS" every 1 minute. On closing, the user computer will save the samples in a user folder. These previously stored samples will be available to the user to view at any time the program is running. The Arduino uses a FTDI USB to serial port chip. This enables the board to appear as a serial port via a USB connection. When first connected, I direct Windows to the FTDI driver. After loading the driver, my computer allocated com8 for the Arduino. Communication then is just a matter of sending and receiving strings on com8. When the user form loads, I upload any stored samples available. As this runs before the form is activated, I let this code run on the form's thread. The serial input code is enclosed in nested Try Catch blocks. The outer block is for if com8 is being used by another program or the Arduino is not connected. The next block catches if a response is not available within 20 seconds. The inner block catches any loss of connection every 100 msec. Try Catch Try Dim com8 As IO.Ports.SerialPort = My.Computer.Ports.OpenSerialPort("com8", 9600) com8.ReadTimeout = 20000 'board will respond within 10 seconds com8.Write("U") 'arduino board command for upload on restart Try Dim addr_pointer As Integer = CInt(com8.ReadLine) ' get rid of cr lf If addr_pointer > 0 Then 'we have saved samples For i = 0 To (addr_pointer / 2 - 1) 'read all stored samples com8.ReadTimeout = 100 'if we dont get a new byte in 100 ms Try display_data(i) = _ software_dcoffset - CInt(com8.ReadLine) * software_scalefactor rx_number += 1 'updata the sample buffer pointer Catch ex As TimeoutException MsgBox("we have lost the circuit") End Try End If com8.Write("SSSSSS") 'arduino board command for upload single samples User_interface.Timer1.Enabled = True 'start the sampling proces com8.Dispose() Catch ex As TimeoutException MsgBox("we dont have a response") End Try Catch ex As Exception MsgBox("we cant open port to download") 'cant connect to port End Try The serial code is very similar to upload_stored, but as we now need to access the form during serial communication, this code is run on its own thread. This complicates the program as Windows controls are not thread safe. This means that we have to bend over backwards to use them from a thread we start. This involves using a delegate subroutine that will run on a thread that owns the underlying handle of the form. This is achieved using the Invoke (delegate) method:. upload_stored Invoke '''' _frm.Invoke(New messdelegate(AddressOf showmessage)) 'register sample '''' Delegate Sub messdelegate() 'a delegate will run on the main window thread Private Sub showmessage() 'this runs on the main window thread because control not thread safe 'register sample Upload_stored.rx_number = Upload_stored.rx_number + 1 'reset value***and save full sample If Upload_stored.rx_number = 1439 Then Upload_stored.rx_number = 0 If Display_files.show_current Then Dim d As New Display d.display_now = Upload_stored.display_data d.dt = Upload_stored.displaytime d.show_now() _frm.Label2.Text = "Current temperature = " & _ (Upload_stored.display_data(Upload_stored.rx_number - 1) * _ Upload_stored.software_nominal).ToString("n1") End If _frm.Timer1.Enabled = True 'OK lets check for another sample End Sub In a class, we can reference a label as form.label2, but we cannot do the same with form.invoke .It will compile OK, but give a runtime error of no handle available. We have to create an instance of the form in the class and then reference that in the code. form.label2 form.invoke Public Sub New(ByVal f As User_interface) 'constructor runs at start _frm = f 'need an instance of form to allow operation of Invoke Dim readthread As Threading.Thread = New Threading.Thread(AddressOf read) readthread.Start() 'see if have data to read using worker thread End Sub Private _frm As User_interface 'need instance of mainform to give invoke a handler We instantiate the class by: Dim c As New Read_current(Me) 'must pass form to constructor This uses simple graphics on a bitmap to display the temperature samples. Private part As New Bitmap(1570, 1070, Drawing.Imaging.PixelFormat.Format24bppRgb) Public display_now(1439) As Int16 'only 0 to 1023 possible '''' For i = 0 To 1438 If display_now(i + 1) = 0 Then Exit For 'only display the real samples g.DrawLine(Rpen, 62 + i, 1040 - display_now(i), 63 + i, 1040 - display_now(i + 1)) '''' User_interface.PictureBox1.Image = part This displays 24 (or less) hour samples that have been saved by the program. The date time for the samples are used as for the file names so that the time and date can be displayed on the graphics. Public Shared user_folder As String = _ My.Computer.FileSystem.SpecialDirectories.MyMusic & "\met_samples\" '''' 'get access to file Dim st As Stream = File.Open(files(displayed_time), _ FileMode.Open, FileAccess.Read) Dim sample_n = My.Computer.FileSystem.GetFileInfo(files(displayed_time)).Length / 2 - 1 Using br As New BinaryReader(st) For i = 0 To sample_n 'read the number of samples in tyhe stored file display_now(i) = br.ReadInt16 End Using '''' Dim sts As DateTime = rt.Replace(".", ":") 'fix up the stored time Dim dt = (sts.Subtract(starttime)).ToString("t") 'just need short time Dim yt = (sts.Subtract(starttime)).ToString("d MMM yyyy") Dim d As New Display d.display_now = display_now The C++ code is shown here with comments. The Arduino sketch is include in the zip file: #include <EEPROM.h> #include "WProgram.h" void setup(); void loop(); void adc(); int inByte =0; //received byte unsigned int minutesample = 0; //adc averaged over a minute byte numbersample = 0; //the number of samples so far -6 for 1 minute unsigned long previousMillis = 0; // will store last time we looked int addr = 0; //address of next data to be stored in the EEPROM void setup() { Serial.begin(9600); // initialize serial communication with computer pinMode(12, OUTPUT); // sets the digital pin as output pinMode(11, OUTPUT); // sets the digital pin as output analogReference(EXTERNAL); //can be 1.8 to 5.5v we use 3.3v } void loop() { if (millis() - previousMillis > 10000) //every 10 seconds { // remember the last time we sampled the pressure previousMillis = millis(); //flash the led digitalWrite(12, HIGH); digitalWrite(11, HIGH); //flash the led //is the computer comunicating if (Serial.available() > 0) // read the oldest byte in the serial buffer: { //if it is "U" we can upload saved samples to computer inByte = Serial.read(); if (inByte == 'U') { //send current address pointer to computer Serial.println(addr); if (addr > 0) //have we got stored values to upload { int i = 0; //counter for upload for (i; i < addr; i +=2) { //restore integer value minutesample = ((EEPROM.read(i + 1)) * 256) + EEPROM.read(i); //send stored sample to computer Serial.println(minutesample); }//end of upload stored values addr = 0; //we have now sent the lot minutesample = 0; //reset the sample numbersample = 0; //reset the counter } //end of have we got stored values }//end of upload any stored data if (inByte == 'S') { adc(); if (numbersample == 6 ) //we have 6 samples over 1 minute { Serial.println(minutesample/6); //send it to computer minutesample = 0; //reset the sample numbersample = 0; //reset the counter }//end of have 6 samples } //end of received "S" }//end of serial available //computer is not communicating else //no serial sent so the computer is not connected { //we need to store the samples in EEPROM untill reconnects if (addr < 1024) //328 has 1024 bytes ie 0 to 1023 { //only write if have spare space in EEPROM adc(); if (numbersample == 6 ) //we have 6 samples over 1 minute { minutesample /= 6; //get average of 6 samples EEPROM.write(addr, (minutesample%256)); //store least byte EEPROM.write(addr + 1, (minutesample/256)); //store most byte addr += 2; //next available storage for sample minutesample = 0; //reset the sample numbersample = 0; //reset the counter }//end of have 6 samples digitalWrite(11, LOW); //turn led off } //end of < 1024 then full so dont write }//end of serial not available }//end of wait to sample pressure digitalWrite(12, LOW); //turn led off }//end of loop void adc() { unsigned int sample = 0; //reset the sample value int i = 0; for(i; i<=64; i++) sample += analogRead(2); //get 64 samples added together 1024 x 64 max sample = sample / 64; //get the average of 64 samples minutesample +=sample; //add the 10 second sample numbersample +=1; //the next sample }//end of adc int main(void) { init(); setup(); for (;;) loop(); return 0; } The schematic is drawn using Eagle:. The files are in the zip file. The bread board picture is drawn using Peeble:. The files are in the zip file. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click arduino1.StartSysex() arduino1.mycommand1(20, 1) arduino1.EndSysex() Thread.Sleep(100) 'Delay less than a second arduino1.processInput() TextBox1.Text = arduino1.storedInputData(1) End Sub General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/42557/Arduino-with-Visual-Basic?msg=4466605
CC-MAIN-2017-43
refinedweb
1,807
55.34
49236/related-to-href Hey Himanshu, as far as I can understand, you want to click the 2nd href link or <a> tag of any website by using Selenium. So you can perform following steps to do that: List<WebElement> allLinks = driver.findElements(By.tagName("a")); Now to open the href link, use click() method: allLinks.get(1).click(); It can be done by using the ...READ MORE using OpenQA.Selenium.Interactions; Actions builder = new Actions(driver); ...READ MORE I solved this issue myself actually. I ...READ MORE The issue seems to be only with ...READ MORE This is a flaw with ChromeDriver. Tried ...READ MORE You can try using Javascript Executor to ...READ MORE The documentation of the library states that, ...READ MORE Try this code: ArrayList<String> tabs = new ...READ MORE Hi Ujjwal, you can use following code ...READ MORE Hello Nitin, as the Like button on ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/49236/related-to-href
CC-MAIN-2021-21
refinedweb
158
78.75
strings). The characters to use for ones and zeroes are obtained from the currently-imbued locale by calling std::use_facet<std::ctype<CharT>(os.getloc()).widen() with '1' and '0' as arguments. 2) Behaves as a FormattedInputFunction. After constructing and checking the sentry object, which may skip leading whitespace, extracts up to Ncharacters from is. [edit] Parameters [edit] Return value The character stream that was operated on, e.g. os or is. [edit] Example Run this code #include <bitset> #include <iostream> #include <sstream> int main() { std::string bit_string = "001101"; std::istringstream bit_stream(bit_string); std::bitset<3> b1; bit_stream >> b1; // reads "001", stream still holds "101" std::cout << b1 << '\n'; std::bitset<8> b2; bit_stream >> b2; // reads "101", populates the 8-bit set as "00000101" std::cout << b2 << '\n'; } Output: 001 00000101
http://en.cppreference.com/w/cpp/utility/bitset/operator_ltltgtgt2
CC-MAIN-2014-41
refinedweb
131
55.24
This edition of the SLB User Manual, last updated 26 April 2011, documents SLB Version 1.0. It is a common practice to set up several servers for handling the same task. In such configurations, it is important to distribute the load equally among the computers forming the set. While the term load may refer in this context to various things (e.g. CPU load, network traffic, etc.), the main principle of load balancing remains the same: determine which servers are less loaded and transfer to them part of the work from the most loaded ones. SLB (or Simple Load Balancer) is a tool designed for handling this task. servers in the order of increasing relative load. SLB does not attempt to actually correct SLB. Therefore, after obtaining the sorted list of servers, SLB filters it through a user-defined format template, and sends the result to a file, a named pipe or another program. All parameters used by SLB, including load estimation function, are supplied to it in a configuration file, which makes the package extremely flexible. When speaking about the package as a whole, we spell its name as SLB. When speaking about the program which constitutes the principal part of the package, we refer to it as slb. This book consists of the three main parts. The first part is a tutorial, which provides a gentle (as far as possible) introduction for those who are new to slb. Although it is meant to be self-contained, the reader is required to have some basic notions about SNMP and UNIX system administration. The tutorial should help the reader to familiarize himself with the package and to start using it. It does not, however, cover some of the less frequently used features of slb. The two chapters that follow complement the tutorial. The Invocation summarizes the command line syntax and options available to slb. The Configuration contains a detailed reference to the configuration file syntax and statements. These two chapters provide all the information necessary to understand and configure slb, for both beginners and for users familiar with the package. This chapter guides you through the most important features of slb and explains its configuration. Start here if you have never used slb before. It omits some complicated details and rarely used features, which will be discussed further, in SLB Configuration File. Options start with a dash. Most of them have two forms, called short and long forms. Both forms are absolutely identical in function; they are interchangeable. The short form is a traditional form for UNIX utilities. In this form, the option consists of a single dash, followed by a single letter, e.g. ‘-c’. Short options which require arguments take their arguments immediately following the option letter, optionally separated by white space. For example, you might write ‘-o name’, or ‘-oname’. Here, ‘-o’ is the option, and ‘name’ is its argument. Short options' letters may be clumped together, but you are not required to do this. When short options are clumped as a set, use one (single) dash for them all, e.g. ‘-ne’ is equivalent to ‘-n options consist of two dashes, followed by a multi-letter option name, which is usually selected to be a mnemonics for the operation it requests. Long option names can be abbreviated, provided that such an abbreviation is unique among the options understood by the program. Arguments to long options follow the option name being separated from it either by an equal sign, or by any amount of white space characters. For example, the option ‘--eval’ with the argument ‘test’ can be written either as ‘--eval=test’ or as ‘--eval test’. The configuration file defines most parameters needed for the normal operation of slb. The program will not start if its configuration file does not exist, cannot be read, or contains some errors. The configuration file is located in your system configuration directory (normally ‘/etc’) and is named ‘slb.conf’. You can place it elsewhere as well, but in this case you will need to explicitly inform slb about its actual location, using the ‘--config-file’ (‘-c’) command line option: Before actually starting the program, it is wise to check the configuration file for errors. To do so, use the ‘--lint’ (‘-t’) command line option: When started with this option, slb parses the configuration, reports any errors on the standard error and exits. If parsing succeeds, it exits with code 0. Otherwise, if any errors have been found, it exits with code 78 (configuration error). The ‘--lint’ option can, of course, be used together with ‘--config-file’, e.g.: If you are unsure about the correct configuration syntax, you can obtain a concise summary any time, by running: The summary is printed to the standard output and includes all configuration statements with short descriptions of their purpose and arguments. In this section we will provide a quick start introduction to the slb configuration. For a more detailed and formal discussion, refer to SLB Configuration File. The configuration file consists of statements. There are two kinds of statements, called simple and block statements. A simple statement consists of a keyword and value, or values, separated by any amount of whitespace and terminated with a semicolon, for example: A block statement is used for logical grouping of other statements. It consists of a keyword, optionally followed by a value, and a set of other statements, enclosed in a pair of curly brackets. For example: A semicolon may follow the closing ‘}’, although this is not required. Note that whitespace (i.e. space characters, tabs and newlines) has no special syntactical meaning, except that it serves to separate otherwise adjacent tokens. For example, the following form of the ‘syslog’ statement is entirely equivalent to the one shown above: Several types of comments are supported. A single-line comment starts with ‘#’ or ‘//’ and continues to the end of the line. A multi-line or C-style comment starts with the two characters ‘/*’ (slash, star) and continues until the first occurrence of ‘*/’ (star, slash). Whatever comment type are used, they are removed from the configuration prior to parsing it. After comment removal, the configuration is preprocessed using m4. This is a highly useful feature, which allows for considerable simplification of configuration files. It is described in Preprocessing with m4. The most important daemon parameters are the operation mode and wakeup interval. You are not required to explicitly configure them, but you may want to do so, if their default values don't suit you. There are two operation modes: ‘standalone’ and ‘cron’. In standalone mode, slb detaches itself from the controlling terminal and continues operation in the background, as a daemon. It will periodically wake up, poll the servers, compute load table and format it to the output file or pipe. This is the default operation mode. In cron mode, slb starts, polls the servers, computes and formats load table and exits when done. This mode is designed for use from crontabs, hence its name. It has some limitation, compared to the standalone mode. Most notably, the d() function (derivative) is not available in this mode. If you wish to explicitly set the operation mode, use the ‘standalone’ configuration statement. The statement: configures the standalone mode, whereas the statement: configures cron mode. The later can also be requested from the command line, using the ‘--cron’ option. When operating in standalone mode, the wakeup interval specifies the amount of time, in seconds, between successive polls. The default value is 5 minutes. To set another value, use the ‘wakeup’ statement. For example, the following configures slb to do a poll each minute: Normally, this does not require additional configuration, unless you want to load some custom MIBs. To load an additional MIB file, use the ‘add-mib’ statement. Its argument is the name of the file to load. Unless full pathname is specified, the file is searched in the SNMP search path. To modify the search path, use the ‘mib-directory’. Each ‘mib-directory’ adds a single directory to the end of the path: Server definitions are principal part of any slb configurations. They define remote servers for which slb is to compute the load table. A server definition is a block statement which begins as: The id argument specifies server ID, an arbitrary string of characters uniquely identifying this server. This ID will be used by log messages concerning this server. It can also be referred to in the output format definition (see section Output Configuration). As usual, the definition ends with a closing ‘}’. Statements inside the ‘server’ block supply configuration parameters for this server. Two parameters are mandatory for each server: its IP address and SNMP community: The ip argument can be either the IP address of the server in dotted-quad notation, or its host name. For example: The most important part of a server definition is its load estimation function. It is basically an arithmetic expression of arbitrary complexity, with SNMP variables serving as its terms (see section Expression). It is defined using the ‘expression’ statement. To begin with, suppose you want to use 1-minute load average as relative load. Let's name it ‘la1’. Then, the expression is very simple and can be defined as: Now, ‘la1’ is a variable name, which should be bound to the corresponding SNMP variable. This binding is declared with the ‘variable’ statement: The ‘variable’ statement has two arguments. The first one is the name of a variable used in the expression and the second one is the SNMP OID which is bound to this variable. This OID is added to the list of OIDs queried during each poll of this server. When a SNMP reply is received, all instances of that variable in the expression are replaced with the value of the corresponding SNMP variable. Once all variables have been thus resolved, the expression is evaluated and its result is taken as the relative load for the given server. Let's take a more complex example. Suppose you define the relative load to be a function of outgoing data transfer rate through the main network interface and the load average of the server. Data transfer rate is defined as first derivative of data transfer through the interface with respect to time. Let ‘out’ be the outgoing data transfer, ‘la1’ be the server's 1-minute load average, ‘k’ and ‘m’ be two server-dependent constants (weight coefficients). Given that, we define relative load as The ‘**’ operator raises its left operand to the power given by its second operand. The two constructs ‘d(…)’ and ‘sqrt(…)’ are function calls. The ‘d()’ function computes first derivative of its argument with respect to time. The ‘sqrt()’ function computes the square root of its argument. Now, let's define variable bindings: The constants ‘k’ and ‘m’ are defined using the following statements: The ‘constant’ statement is similar to ‘variable’, except that its second argument must be a floating-point number. Of course, in this particular example, the two constants could have been placed directly in the expression text, as in: However, defining them on a per-server basis is useful when the same expression is used for several different servers, as explained in the following section. To conclude, here is our sample server definition: In most cases, load estimation function is common for all servers (perhaps with server-dependent set of coefficients and/or variable bindings). To simplify configuration, such a common function can be defined once and then used by another ‘server’ definitions. It is defined as a named expression, i.e. an expression that can be referred to by its name. Named expressions are defined using the ‘expression’ statement outside of ‘server’ block. Such statements take two arguments: the name of the expression and its definition, e.g.: Named expressions can be invoked from another expressions using the ‘@’ operator, followed by expression's name. For example, the following statement in ‘server’ block: is in fact equivalent to the expression defined above. The ‘@’ construct can, of course, also be used as a term in arithmetic calculations, e.g.: A default expression is a named expression which is implicitly applied for ‘server’ statements that lack ‘expression’ statement. Default expression is defined using the ‘default-expression’ statement: To finish this section, here is an example configuration declaring two servers which use the same default expression, but supply different sets of coefficients: In the previous section we have seen how to define two servers which use the same expression to compute relative load. In real configurations, the number of servers is likely to be considerably greater than that, and adding each of them to the configuration soon becomes a tedious and error-prone task. This task is greatly simplified by the use of preprocessor. As mentioned earlier, the configuration file is preprocessed using m4, a traditional UNIX macro processor. It provides a powerful framework for implementing complex slb configurations. For example, note that in our sample configuration the ‘server’ statements differ by only three values: the server ID, its IP and community. Taking this into account, we may define the following m4 macro: The ‘defsrv’ macro takes two mandatory and one optional argument. Mandatory arguments are the server ID and its IP address. Optional argument is SNMP community; if it is absent, the default community ‘public’ is used. Notice, that we use m4_define, instead of the familiar define. It is because the default slb setup renames all m4 built-in macro names so they all start with the prefix ‘m4_’. This avoids possible name clashes and makes preprocessor statements clearly visible in the configuration. Using this new macro, the above configuration is reduced to the following two lines: Declaring a new server is now a matter of adding a single line of text. The default preprocessor setup defines a set of useful macros, among them m4_foreach (see (m4)Improved foreach section `foreach' in GNU M4 macro processor). This macro can be used to further simplify the configuration, as shown in the example below: The second argument to m4_foreach is a comma-separated list of values. The expansion is as follows: for each value from this list, the value is assigned to the first argument (‘args’). Then the third argument is expanded and the result is appended to the overall expansion. In this particular example, each line produces an expansion of the ‘defserv’ macro with the arguments taken from that line. Note, that each argument in the list must be quoted, because it contains commas. Note also the use of the optional third arguments to supply community names that differ from the default one. For a detailed information about slb preprocessor feature, see Preprocessor. When slb has finished building load table, it sends it to the output, line by line, using the output format string. This format string is similar to the format argument of printf(1): any characters, except ‘%’ are copied to the output verbatim; the ‘%’ introduces a conversion specifier. For example, ‘%i’ expands to the ID of the server this line refers to. The ‘%w’ specifier expands to the computed relative load for that server, etc. There is a number of such specifiers, they are all described in detail in Output Format String. The default output format is ‘%i %w\n’. This produces a table, each line of which shows a server ID and its relative load. This default is suitable for testing purposes, but for real configurations you will most probably need to create a custom output format. You do so using the ‘output-format’ statement: The output format string can be quite complex as shown in the following example: This format creates, for each line from the load table, a set of commands for nsupdate(1). The ‘<<’ block introduces a here-document, a construct similar to that of shell and several other programming languages. It is discussed in here-document. You may need to include server-dependent data in the corresponding output lines. For this purpose, slb provides server macros. Server macros are special text variables, defined in the ‘server’ block, which can be accessed from output format string. Macros are defined using the ‘macro’ statement, whose syntax is similar to that of ‘variable’ or ‘constant’. The first argument supplies the name of the macro, and the second one, its contents, or expansion, e.g.: Macros are accessed using the following conversion specifier: where name is the name of the macro. This specifier is replaced with the actual contents of the macro. The following example uses the ‘description’ macro to create a TXT record in the DNS: Sometimes you may need to produce some output immediately before the load table or after it. Two configuration statements are provided for that purpose: ‘begin-output-message’ and ‘end-output-message’. Both take a single string as argument. The string supplied with ‘begin-output-message’ is output before formatting the load table, and the one supplied with ‘end-output-message’ is output after formatting it. Continuing our ‘nsupdate’ example, the following statement will remove all existing A records from the DNS prior to creating new ones: You may want to output only a part of the load table. Two statements are provided for this purpose. The ‘head N’ statement outputs at most N entries from the top of the table. The ‘tail N’ statement outputs at most N entries from the bottom of the table. For example, to print only one entry corresponding to the least loaded server, use By default slb prints results to the standard output. To change this, use the ‘output-file’ statement. Its argument specifies the name of a file where slb output will be directed. If this name starts with a pipe character (‘|’), slb treats the remaining characters as the shell command. This command is executed (using /bin/sh -c), and the output is piped to its standard input. Thus, the following statement directs the formatted output to the standard input of nsupdate command. The slb configuration can be quite complex, therefore it is important to verify that it behaves as expected before actually implementing it in production. Three command line options are provided for that purpose. The ‘--dry-run’ (or ‘-n’) option instructs the program to start in foreground mode and print to the standard output what would have otherwise been printed to the output file. Additional debugging information is displayed on the standard error. The ‘--eval’ option initiates expression evaluation mode. In this mode slb evaluates the expression whose name is supplied as argument to the option. Actual values of the variables and constants used in the expression are supplied in the command line in form of variable assignments. The result is printed to the standard output. For example, if the configuration file contains then the command will print ‘.540625’. If the expression contains calls to ‘d()’ (derivative), you will need several evaluations to compute its value. The minimal number of evaluations equals the order of the highest derivative computed by the expression, plus 1. Thus, computing the following expression: requires at least two evaluations. To supply several values to a single variable, separate them with commas, e.g.: ‘out=16000,20000’. This will run first evaluation with ‘out=16000’ and the second one with ‘out=20000’. For example: Notice, that you don't need to supply the same number of values for each variable. If a variable is assigned a single value, this value will be used in all evaluations. A more elaborate test facility is enabled by the ‘--test’ option. This option instructs slb to read SNMP variables and their values from a file and act as if they were returned by SNMP. The output is directed to the standard output, unless the ‘--output-file’ option is also given. The input file name is taken from the first non-option argument. If it is ‘-’ (a dash) or if no arguments are given, the standard input will be read: The input file consists of sections separated by exactly one empty line. A section contains assignments to SNMP variables in the style of snmpset(2). Such assignments form several server groups, each group being preceded by a single word on a line, followed by a semicolon. This word indicates the ID of the server to which the data in the group belong. For example: This section supplies data for two servers, named ‘srv01’ and ‘srv02’. The format of slb invocation is: where options are command line options and args are non-optional arguments. Non-optional arguments are allowed only if either ‘--test’ or ‘--eval’ option is used in options. Use file instead of the default configuration file. Start in cron mode. Normally slb operates in daemon mode, in which it polls the monitored servers at fixed intervals and outputs the resulting load table. In contrast, when in cron mode, slb performs a single poll, outputs the table and exits. This mode is useful when starting slb from cron, hence its name. Notice that the function ‘d’ (derivative, see derivative) does not work in this mode. Run in foreground mode and print to the standard output what would have otherwise been printed to the output file. This option implies ‘--stderr --debug snmp.1 --debug output.1’. Use additional ‘--debug’ options to get even more info. The ‘pidfile’ configuration statement is ignored in dry run mode (see pidfile). Evaluate the named expression name, print its result and exit. Arguments for the expression can be supplied in the form of assignments in the command line, e.g.: See section eval, for a detailed discussion of the expression evaluation mode. Test mode. Instead of polling servers via SNMP, slb reads data from the file given as the first non-option argument on the command line (or from the standard input, if no arguments are given). The output is directed to the standard output, unless the ‘--output-file’ option is also given. See section Test Mode, for a detailed information about the test mode, including a description of the input format. Example usage: Show preprocessed configuration and exit. Parse configuration file, report any errors on the standard error and exit with code 0, if the syntax is OK, and with code 1 otherwise. Remain in the foreground. Useful for debugging purposes. See foreground statement. Direct output to file. This option overrides the ‘output-file’ setting in the configuration file. See output-file, for a discussion of file syntax. Log to the standard error. Log all diagnostics to syslog. Define the preprocessor symbol name as having value, or empty. See section Preprocessor. Add dir to include search path. See section #include. Disable preprocessor. see section Preprocessor. Use command instead of the default preprocessor. see section Preprocessor. Sets debugging level for the category cat. Category is a string that designates a part of the program from which the additional debugging information is requested. See below for a list of available categories. Level is a decimal number between 0 and 100 which indicates how much additional information is required. The level of 0 means ‘no information’ and effectively disables the category in question. The level of 100 means maximum amount of information available. If level is omitted, 100 is assumed. The following table lists categories available in version 1.0: Main program block. Expression evaluation. Expression grammar and parser. Expression lexical analyzer. SNMP request-reply loop. Output driver. Configuration file grammar. Configuration file lexer. Show configuration syntax summary. Print a concise usage summary and exit. Print a summary of command line syntax and exit. Print the program version and exit. Upon startup, slb reads its settings from the configuration file ‘slb.conf’. This file is normally located in $sysconfidr (i.e., in most cases ‘/usr/local/etc’, or ‘/etc’), but an alternative location can be specified using the ‘--config’ command line option (see section config-file). If any errors are encountered in the configuration file, the program reports them on its error output and exits with a non-zero status. To test the configuration file without starting the server use the ‘--lint’ (‘-t’) command line option. It instructs the program to check configuration file for syntax errors and other inconsistencies and to exit with status 0 if no errors were detected, and with status 1 otherwise. Before parsing, the configuration file is preprocessed using m4 (see section Preprocessor). To see the preprocessed configuration without actually parsing it, use the ‘-E’ command line option. To disable preprocessing, use the ‘--no-preprocessor’ option. The rest of this section describes the configuration file syntax in detail. You can receive a concise summary of all configuration directives any time by running slb --config-help.:. The version 1.0 of slb, understands the following pragmatic comments: . New directories can be appended in front of it using ‘-I’ (‘--include-directory’) command line option (see section include-directory). #include_once <file> #include_once file Same as #include, except that, if the file has already been included, it will not be included again. #line num #line num "file" This line causes slb : 5.1: Backslash escapes In addition, the sequence ‘\newline’ is removed from the string. This allows to split long strings over several physical lines, e$prefix/share/slb/version/include’ directory (where version means the version of SLB). The default ‘pp-setup’ file renames all m4 built-in macro names so they all start with the prefix ‘m4_’. This is similar to GNU m4 ‘--prefix-builtin’ options, but has an advantage that it works with non-GNU m4 implementations as well. Additional control over the preprocessor is provided via the following command line options: Define the preprocessor symbol name as having value, or empty. Add dir to the list of directories searched for preprocessor include files. Disable preprocessor. Use command instead of the default preprocessor. When running in standalone mode slb normally uses syslog to print diagnostic messages. By default, the program uses the ‘daemon’ facility. The syslog statement allows to change that: Configures the syslog facility to use. Allowed values are: ‘auth’, ‘authpriv’, ‘cron’, ‘daemon’, ‘ftp’, ‘local0’ through ‘local7’, and ‘mail’. This statement sets the syslog tag, a string identifying each message issued by the program. By default, it is the name of the program with the directory parts removed. In addition to priority segregation, provided by syslog, you can instruct slb to prefix each syslog message with its priority. To do so, set: The following statements configure slb activities in daemon mode. Enables or disables standalone daemon mode. The standalone mode is enabled by default. It is disabled either by setting in the configuration file, or by using the ‘--cron’ command line option (see option–cron). Do not detach from the controlling terminal. See option–foreground. Store master process PID in file. Default pidfile location is ‘/var/run/slb.pid’. Sets wake-up interval in seconds. SLB will recompute the server load table each number seconds. Suppress output during the first number wakeups. This statement is reserved mostly for debugging purposes. The following statement creates a named expression: Define the expression name to be expr. Named expressions can be used as load estimation functions in server statements (see section expression) and invoked from the output format string (see section Output Format String). Declares the default expression. The name refers to a named expression declared elsewhere in the configuration file. The default expression is used to compute relative load of servers whose ‘server’ declaration lacks explicit ‘expression’ definition (see server-expression). The expr in the ‘expression’ statement is an arithmetical expression, which evaluates to a floating point number. The expression consists of terms, function calls and operators. The terms are floating point numbers, variable and constant names. The names refer to constants or SNMP variables defined in the definition of the server, for which this expression is being evaluated. The following operations are allowed in expression: Addition Subtraction Multiplication Division Power A named expression reference is a reference to an expression defined by a ‘expression’ statement elsewhere in the configuration file. The reference has the following syntax: where name is the name of the expression as given by the first argument of its definition (see section Expression). The ternary conditional operator is used to select a value based on a condition. It has the following form: The ternary operator evaluates to expr1 if cond yields ‘true’ (i.e. returns a non-null value) and to expr2 otherwise. The condition cond is an expression which, apart from the arithmetic operators above, can use the following comparison and logical operations: True if a equals b True if the operands are not equal. True if a is less than b. True if a is less than or equal to b. True if a is greater than b. True if a is greater than or equal to b. True if expr is false. Logical and: true if both a and b are true, false otherwise. Logical or: true if at least one of a or b are true. Both logical ‘and’ and ‘or’ implement boolean shortcut evaluation: their second argument (b) is evaluated only when the first one is not sufficient to compute the result. The following table lists all operators in order of decreasing precedence: When operators of equal precedence are used together they are evaluated from left to right (i.e., they are left-associative), except for comparison operators, which are non-associative and for the power operator, which is right-associative (these are explicitly marked as such in the above table). This means, for example that you cannot write: Instead, you should write: Function calls have the following syntax: where name stands for the function name and arglist denotes the argument list: a comma-separated list of expressions which are evaluated and supply actual arguments for the function. The following functions are supported by SLB version 1.0: Returns the derivative of x, i.e. the speed of its change per second, measured between the two last wakeups of slb (see section wakeup). Notice, that this function is available only in standalone mode (see section standalone mode). Returns the maximum value of its arguments. Any number of arguments can be given. Returns the minimum value of its arguments. Returns the average value of its arguments. Returns the natural logarithm of x. Returns the decimal logarithm of x. Returns the value of e (the base of natural logarithms) raised to the power of x. Returns the value of x raised to the power of y. This function is provided for the sake of completeness, as it is entirely equivalent to ‘x ** y’. Returns the non-negative square root of x. Returns the absolute value of x. Returns the smallest integral value that is not less than x. Returns the largest integral value that is not greater than x. Rounds x to the nearest integer not larger in absolute value. Rounds x to the nearest integer, but round halfway cases away from zero: Adds dir to the list of directories searched for the MIB definition files. Reads MIB definitions from file. Creates a new entry in the database of monitored servers. The id parameter supplies the server identifier, an arbitrary string which will be used in log messages related to that server. Its value is also available in output format string as format specifier ‘%i’ (see section Output Format String). Other parameters of the server are defined in the substatements, as described below. If bool is ‘no’, this server is disabled, i.e. it is not polled nor taken account of in load calculations. Use this statement if you want to temporarily disable a server. Sets the IP address (or hostname) of this server. Sets the timeout for SNMP requests to that server. Sets the maximum number of retries for that server, after which a timeout is reported. Sets SNMP community. Defines load estimation function for this server. See section Expression, for a description of the syntax of string. If this statement is absent, the default expression will be used (see default-expression). If it is not declared as well, an error is reported. Defines a variable name to have the value returned by oid. The latter must return a numeric value. Any occurrence of name in the expression (as defined in the ‘expression’ statement) is replaced with this value. Defines a constant name to have the value returned by oid. Notice that expression variables and constants share the same namespace, therefore it is an error to have both a ‘variable’ and a ‘constant’ statement defining the same name. Defines a macro name to expand to expansion. Macros allow to customize output formats on a per-server basis. See macro. Ensures that the value of SNMP variable oid matches pattern. The type of match is given by the op argument: The value must match pattern exactly. The value must not match pattern. If the assertion fails, the server is excluded from the load table. Use this statement to ensure that a variable used in the computation refers to a correct entity. For example, if your expression refers to ‘IF-MIB::ifInOctets.3’ (number of input octets on network interface 3), it would be wise to ensure that the 3rd row refers to the interface in question (say ‘eth1’): Notice, that pattern must include the data type. The statement discussed in this section configure formatting of the server load table on output. Print at most number entries from the top of the table, i.e. the number of the less loaded server entries. Print at most number entries from the bottom of the table, i.e. the number of the most loaded server entries. Send output to the channel, identified by string. Unless string starts with a pipe sign, it is taken as a literal name of the file. If this file does not exist, it is created. If it exists, it is truncated. The file name can refer to a regular file, symbolic link or named pipe. If string starts with a ‘|’ (pipe), the rest of the string is taken as the name of an external program and its command line arguments. The program is started before slb enters its main loop and the formatted load table is piped on its standard input. Defines the text to be output before the actual load table contents. The string is taken literally. For example, if you want it to appear on a line by itself, put ‘\n’ at the end of it (see backslash-interpretation). Defines the text to be output after the actual load table contents. The string is taken literally. Defines format for outputting load table entries. See the subsection below (see section Output Format String), for a description of available format specifications. The format string is composed of zero or more directives: ordinary characters (not ‘%’), which are copied unchanged to the output; and conversion specifications, each of which is replaced with the result of a corresponding conversion. Each conversion specification is introduced by the character ‘%’, and ends with a conversion specifier. In between there may be (in this order) zero or more flags, an optional minimum field width and an optional precision. The value should be zero padded. This affects all floating-point conversions, i.e. ‘w’ and ‘{...}’, for which the resulting value is padded on the left with zeros rather than blanks. If the ‘0’ and ‘-’ flags both appear, the ‘0’ flag is ignored. If a precision is given with a floating-point conversion, the ‘0’ flag is ignored. For other conversions, the behavior is undefined. The converted value is to be left adjusted on the field boundary. (The default is right justification.) Normally, the converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A ‘-’ overrides a ‘0’ if both are given. A blank should be left before a positive number (or empty string) produced by conversion. An optional decimal digit string (with non-zero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the ‘-’ flag has been given). In no case does a nonexistent or small field width cause truncation of a field; if the result of a conversion is wider than the field width, the field is expanded to contain the conversion result. An optional precision, in the form of a period (‘.’) followed by an optional decimal digit string. If the precision is given as just ‘.’, or the precision is negative, the precision is taken to be zero. This gives the number of digits to appear after the radix character for floating-point conversions or the maximum number of characters to be printed from a string, for string conversions. A character or a sequence of characters that specifies the type of conversion to be applied. The conversion specifiers are replaced in the resulting output string as described in the table below: The server identifier. The server hostname, as set by the host configuration directive. Computed relative load. The value of the variable var. The result of evaluating expression expr-name in the context of the current server. Expansion of the macro. The percent character. When SLB terminates, it reports the result of its invocation in form of exit code. Exit code of 0 indicates normal termination. Non-zero exit codes indicate some kind of error. In this case the exact cause of failure will be reported on the currently selected logging channel. The exit codes are as follows: Normal termination. The program was invoked incorrectly. Input data were invalid or malformed. This error code is returned only when slb is used with ‘--test’ or ‘--eval’ options (see section Test Mode). Some error occurred. For example, the program was unable to open output file, etc. Internal software error. This usually means hitting a bug in the program, so please report it (see section How to Report a Bug). Program terminated due to errors in configuration file. The program handles a set of signals. To send a signal to slb use the following command: Replace ‘/var/run/slb.pid’ with the actual pathname of the PID-file, if it was set using the ‘pidfile’ configuration statement. The ‘SIGHUP’ signal instructs the running instance of the program to restart itself. It is possible only if slb was started using its full pathname. The signals ‘SIGTERM’, ‘SIGQUIT’, and ‘SIGINT’ cause immediate termination of the program. Please, report bugs and suggestions to gray+slb@gnu.org.ua. You hit a bug if at least one of the conditions below is met: slbterminates on signal 11 (SIGSEGV) or 6 (SIGABRT). slb. See. See. This document was generated by Sergey Poznyakoff on April, 26 2011.
http://puszcza.gnu.org.ua/software/slb/manual/slb.html
CC-MAIN-2018-26
refinedweb
6,448
57.06
You're probably feeling very tired at this point: this has been a long tutorial and you've had to learn a lot. Fortunately, this last chapter is a bonus – you don't need to read this to have a great CloudKit app, but I do add some neat CloudKit technologies here that make the whole experience better. So far, the app lets users record a whistle using AVAudioRecorder, send it off to CloudKit, download whistles others have posted, then write suggestions for what song they think it is. What we're going to add now is the ability for users to register themselves as experts for particular genres - they can say "I know all about jazz and blues music." When they do that, we'll automatically tell them when a new whistle has been posted in one of those categories, and they can jump right into the app to have a go at identifying it. We're going to do this with one of the most important technologies in iOS, called push notifications. These are alerts that are delivered straight to the lock screens of users whenever something interesting happens, and the app usually isn't running at the time. Push is so important to iOS that it comes built into CloudKit, and it's done so elegantly that this tutorial will be over in no time. In short: don't worry, the end is in sight! Create a new UITableViewController subclass called MyGenresViewController. Add a CloudKit import to it, then add this property: var myGenres: [String]! We'll use that to track the list of genres the user considers themselves an expert on. Before we starting adding code to this new view controller, we need to make two small changes in ViewController.swift. First, add this in viewDidLoad(): navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Genres", style: .plain, target: self, action: #selector(selectGenre)) Second, add the following method that allows users to choose genres: @objc func selectGenre() { let vc = MyGenresViewController() navigationController?.pushViewController(vc, animated: true) } Now, back to MyGenresViewController.swift. We can split this code into two parts: all the bits that handle users selecting their experts genres and saving that list, and the CloudKit part that tells iCloud we want to be notified when a new whistle has been published that might be of interest to this user. Letting the user choose which genres interest them is easy: we're going to use UserDefaults to save an array of their expert genres. If there isn't one already saved, we'll create an empty array. We're also going to use a right bar button item with the title "Save" that handles the CloudKit synchronization. More on that later; for now, here's the viewDidLoad() method that handles loading saved genres: override func viewDidLoad() { super.viewDidLoad() let defaults = UserDefaults.standard if let savedGenres = defaults.object(forKey: "myGenres") as? [String] { myGenres = savedGenres } else { myGenres = [String]() } title = "Notify me about…" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(saveTapped)) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } When it comes to how many sections and rows we have, we're going to specify 1 and the value of SelectGenreViewController.genres.count – that static property contains all the genres used in the app, so re-using it here is perfect: override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return SelectGenreViewController.genres.count } Now for the interesting part: we want users to be able to tap on rows that they like, and have iOS show a checkmark next to them. Once a genre is added to the myGenres array, we can check whether it's in there using the contains() of that array – if the array contains the genre, we put a check next to it. Here's the cellForRowAt method that does just that: override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let genre = SelectGenreViewController.genres[indexPath.row] cell.textLabel?.text = genre if myGenres.contains(genre) { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } The other part of this approach is catching didSelectRowAt so that we check and uncheck rows as they are tapped, adding and removing them from the myGenres array as necessary. Adding things to an array is as simple as calling the append() method on the array, but removing takes a little more hassle: we need to use firstIndex(of:) to find the location of an item in the array, and if that returns a value then we use remove(at:) to remove the item from the array at that index. As a finishing touch, we'll call deselectRow(at:) to deselect the selected row, so it highlights only briefly. That's all there is to it – here's the didSelectRowAt method: override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let cell = tableView.cellForRow(at: indexPath) { let selectedGenre = SelectGenreViewController.genres[indexPath.row] if cell.accessoryType == .none { cell.accessoryType = .checkmark myGenres.append(selectedGenre) } else { cell.accessoryType = .none if let index = myGenres.firstIndex(of: selectedGenre) { myGenres.remove(at: index) } } } tableView.deselectRow(at: indexPath, animated: false) } And now for the challenging part: when users click Save, we want to write their list of genres to UserDefaults, then send them all to iCloud. Then, when new whistles arrive that match a user's selected genres, we want to notify them with a push message. Thanks to what was I'm sure many months of effort from Apple engineers, registering for push messages is a breeze thanks to a class called CKQuerySubscription. This lets you configure a query to run on the iCloud servers, and as soon as that query matches something it will automatically trigger a push message. In our case, that query will be "when anyone publishes a whistle in a genre we care about." But first: we need to flush out any existing subscriptions so that we don't get duplicate errors. In the interests of keeping it brief, the easiest way to do this is by calling fetchAllSubscriptions() to fetch all CKQuerySubscriptions, then passing each of them into delete(withSubscriptionID:). As always, it's up to you to do useful error handling – I've done it enough for you already, so you're most of the way there. Note: the two parameters you get from fetchAllSubscriptions() are an optional array of subscriptions and an error if one occurred. You need to unwrap the optional array, because the user might not have any subscriptions. Here's an initial version of saveTapped(): @objc func saveTapped() { let defaults = UserDefaults.standard defaults.set(myGenres, forKey: "myGenres") let database = CKContainer.default().publicCloudDatabase database.fetchAllSubscriptions { [unowned self] subscriptions, error in if error == nil { if let subscriptions = subscriptions { for subscription in subscriptions { database.delete(withSubscriptionID: subscription.subscriptionID) { str, error in if error != nil { // do your error handling here! print(error!.localizedDescription) } } } // more code to come! } } else { // do your error handling here! print(error!.localizedDescription) } } } Again, please do put in some user-facing error messages telling users what's going on – they won't see the Xcode log messages, and it's important to keep them informed. There's just one more thing to do before this entire project is done, and that's registering subscriptions with iCloud and handling the result. You tell it what condition to match and what message to send, then call the save() method, and you're done – iCloud takes care of the rest. Normally you'd need to opt into push messages and create a push certificate, but again Xcode and iCloud have taken away all this work when you enabled CloudKit what feels like long ago. To make this work, we're going to loop through each string in the myGenres array, create a predicate that searches for it, then use that to create a CKQuerySubscription using the option .firesOnRecordCreation. That means we want this subscription to be informed when any record is created that matches our genre predicate. If you want to attach a visible message to a push notification, you need to create a CKSubscription.NotificationInfo object and set its alertBody property. If you want an invisible push (one that launches your app in the background silently) you should set shouldSendContentAvailable to be true instead. We're going to set a notification message that contains the genre that changed by using Swift's string interpolation. We're also going to use the value default for the soundName property, which will trigger the default iOS tri-tone sound when the message arrives. With that done, we can call save() to send it off to iCloud, then handle any error messages that come back. That's it – here's the code to put in place of the more code to come! comment: for genre in self.myGenres { let predicate = NSPredicate(format:"genre = %@", genre) let subscription = CKQuerySubscription(recordType: "Whistles", predicate: predicate, options: .firesOnRecordCreation) let notification = CKSubscription.NotificationInfo() notification.alertBody = "There's a new whistle in the \(genre) genre." notification.soundName = "default" subscription.notificationInfo = notification database.save(subscription) { result, error in if let error = error { print(error.localizedDescription) } } } If you run the app now you'll be able to save your genre preferences and send them off to iCloud, but you won't get any push messages through just yet. That's because although iCloud is now totally configured to send push messages when interesting things happened, the user hasn't opted in to receive them. As you might imagine, Apple doesn't want to send push messages to users who haven't explicitly opted in to receive them, so we need to ask for push message permission. Go to AppDelegate.swift and add an import for the UserNotifications framework: import UserNotifications Now put this code into the didFinishLaunchingWithOptions method, before the return true line: UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if let error = error { print("D'oh: \(error.localizedDescription)") } else { application.registerForRemoteNotifications() } } That requests permission to show alerts to the user, with a small error message being printed if something goes wrong. If there was no error, we call registerForRemoteNotifications(), which creates a unique device token that can be used to message this device. That device token is silently handed off to CloudKit, so we don’t need to do anything other than request it. For the sake of completeness, it’s worth adding that if a remote notification arrives while the app is already running, it will be silently ignored. If you want to force iOS to show the alert you must do three things: AppDelegateclass conform to UNUserNotificationCenterDelegate. willPresentmethod, calling its completion handler with how you want the alert shown. To satisfy step 2, add this line of code before return true inside the app delegate’s didFinishLaunchingWithOptions method: UNUserNotificationCenter.current().delegate = self For step 3, if you want the alert, sound, and badge of the notification to be shown even when the app is already running, you’d add this method to the app delegate: func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .sound, .badge]) } If you want only part of the notification to be used, just change the array being passed to completionHandler(). That's it. No, really – this epic project is now done. Go ahead and run the app on a real iOS device, register for certain genres, then quit the app – unplug your phone, lock it, and put it to one side. Now launch the app in the simulator and create a new whistle in one of the genre you just marked, and you'll get your.
https://www.hackingwithswift.com/read/33/8/delivering-notifications-with-cloudkit-push-messages-ckquerysubscription
CC-MAIN-2021-43
refinedweb
1,936
53.71
My!]]> After a bit of a dry spell on the Kickstarter video front, the second and third videos of the ten video series are up on YouTube. Saturday saw the release of Writing Idiomatic Python Video Two, in which a simple HTTP proxy is refactored according to the principles found in Writing Idiomatic Python. On Sunday, Writing Idiomatic Python Video Three (which continues the refactoring begun in the second video) was posted. Together, these two videos contain over two hours of content. I also made sure that the screen resolution/font size issues that a number of people had with the first video were handled properly. In addition, both videos have their own GitHub repos (links are on the respective YouTube pages) containing the original and final versions of the code. A number of people asked about this for video one as it's useful to compare the old and new versions directly. Given this surge of momentum, video four shouldn't be far off. The subject of the video has already been chosen, and it's something I'm excited about and I think you'll all enjoy: starting a program from scratch. There are a huge number of things to think about when starting from scratch as opposed to refactoring existing code. I have a feeling a lot of people will find video four useful. Just a reminder, as a result of the amount raised in the Kickstarter campaign, all of the ten videos are freely viewable at any time, distributed under the Creative Commons license. So feel free to share, embed, remix, or do whatever else people do with free videos.]]>!]]> NoS").: You might hear that a hundred times, but until you actually get into a code, compile, test cycle you have no idea how crazily fast compilation.]]>)? As I see it, I have three choices. The first is just to delete the old repo, rename the new repo, and call it a day. None of the old project will be preserved. On a positive note, however, the commit history will be clean and accurate, and reflect exactly what work was done on the project. Or I could "migrate" the old project to the new one, by simply adding the new files in the old repo and deleting any others that are no longer used (almost all of the old files). In this way, I keep the commit history and contributors of the original project, but at the cost of a weird history that doesn't make much sense. It would really be the history of two separate projects spliced together at a specific point. The third choice, of course, is to just keep the old project the way it is and not use the rewrite. Each day that goes by, though, this seems less and less viable a solution, as the new project is almost at feature parity with the old. That brings me to another question: How do I version the new project? The old project never hit 1.0 and thus it could be argued the API was always open to breaking changes, but this isn't a change to the API, it's an entirely new and different API. The current version of sandman is something like 0.9.8. If I replaced the old project with the new one, what would the version be? Keep in mind that for PyPI, the version would need to be higher than the version of the old project for PyPI to consider the new package the latest version. I'm really kind of stuck here, which is why I'm asking for help. My hope is someone much smarter than me sees another solution, or a better way to implement one of the ones I mentioned. So please, if you have any ideas, let me know! Feel free to either leave a comment here or in the thread on Chat For Smart People.]]>?.]]> The.]]> There have been a number of technology innovations in the field of software development over the last five or ten years. Cloud computing, Hadoop, and NoSQL are just a few technologies that have seen reasonably quick growth and adoption. But in terms of long-term effect on the software industry, these technologies are miles behind a relative newcomer. That technology is docker. Docker is an application build and deployment management system. It is based on the idea of homogeneous application containers. The shipping industry has long realized the benefit of such containers. Before an industry standard container existed, loading and unloading cargo ships was extremely time consuming. All of this was due to the nature of the shipping containers: they were all of different sizes and shapes, so they couldn't be stacked neatly or removed in an orderly fashion. Once a standard size and shape were agreed upon, it revolutionized the industry. New infrastructure could be built that dealt only with containers of a single size. Loading and unloading became orderly and automated. And shipping things got a lot faster. Docker consists of containers, based on preexisting technologies like lxc and union file systems. Certainly, launching Linux containers from the command line is nothing revolutionary. However, the containers themselves are only half the story. The other half is images. Images are indexed snapshots of the entire filesystem a container is meant to run. Every time a change to the filesystem is made, a new version of the image is automatically created and assigned a hash ID. In one stroke, a number of longstanding problems in managing software systems are solved by Docker: Docker solves all of these issues. I kid you not. Let me show you how. Let's see how Docker really works with an existing small (but not trivial) Flask application. It's called eavesdropper and I've written about it previously. Instead of using SQLite, though, we're going to use a big boy database and switch to PostgreSQL (through SQLAlchemy, of course). Let's actually get the database portion out of the way now, since it's mostly just boilerplate. We need to create a Dockerfile that installs PostgreSQL from scratch on a new Ubuntu image (the image we'll use as our base). Helpfully, this exists as one of Docker.com's tutorials. Follow the instructions in the article, except when it says to run sudo docker run --rm -P --name pg_test eg_postgresql, what we actually want to run is sudo docker run -d --name db eg_postgresql, which will start up a container using our image and call it db for short. Now that we've essentially taken care of all database deployment tasks, we turn to the eavesdropper application itself. Clone it from GitHub and take a look at the Dockerfile. All we're really doing is adding our application's code to the image, using requirements.txt to determine which packages to load, and running a script that pre-populates the database and starts the app. Run the following two commands to build and run the container, respectively: $ sudo docker build -t jeffknupp/eavesdropper:devel . And... $ sudo docker run -d -P --name eaves --link db:db jeffknupp/eavesdropper:devel The only trickery there is some of the flags in the run command: -d daemonizes the application, -P exposes ports for communication, and --link creates a communication link between our container and the db container we started earlier. What this does is essentially put an entry in the /etc/hosts file with a db entry and a local IP, allowing our container to connect to the database container, and that's it. If everything worked properly, you should be able to run $ sudo docker ps and get something like this: Here we can see that port 8080, which our application runs on, is being mapped to the local port 49154. You should now be able to open up a browser, point it to localhost:49154 (or the ip returned from boot2docker ip if you're on a Mac) and see the following: Let's take a step back for a moment and assess what we've done. We've created two containers runnable on any host machine capable of running Docker (which is basically any Linux machine). Each is built in a repeatable manner, with the filesystem ensuring no rogue changes make it into the image without us noticing. Most importantly, we've solved our dependency issues before we've deployed our application. Think about that: the image contains all dependent packages required to run our application. There is no Chef or Puppet step where we provision an entire machine for a single application because of dependency management issues. We just launch containers, and they already have everything they need to run. Two different containers with different versions of the same library? Who cares? We can't see inside the containers; we just run 'em. It's that black-box aspect of running containers with their dependencies already resolved that makes Docker so compelling. Gone are the days when each machine was given a name that matched the application it ran (and only ran one application). Instead, commodity hardware is finally a software commodity. Machines are just resources used to launch containers. This is big. No technology in recent memory has experienced the rate of adoption that Docker has. It's already supported on all of the major cloud platforms (AWS, Google Compute Engine, Rackspace, etc). This has broad implications for ease of deployment between vendors, as well as dynamic switching or load balancing between heterogeneous cloud providers. As long as you have your image, they'll all run your container in exactly the same way. If all of this doesn't sound as ground breaking as I make it out to be, it's due to my failures as a writer and is not a reflection of Docker's importance. I've spent the last few weeks thinking about what Docker makes possible and some of these ideas were truly mind-boggling. I urge you to take a few minutes after reading this post and reflect on exactly what this means for the software industry, as everyone from developers to managers to DevOps and SysOps will be affected. Let the revolution begin.]]>!]]> Most. That...]]> There are two recent trends I really hate: DevOps and the notion of the "full-stack" developer. The DevOps movement is so popular that I may as well say I hate the x86 architecture or monolithic kernels. But it's true: I can't stand it. The underlying cause of my pain? This fact: not every company is a start-up, though it appears that every company must act as though they were. "DevOps" is meant to denote a close collaboration and cross-pollination" .. Good developers are smart people. I know I'm going to get a ton of hate mail, but there is a hierarchy of usefulness of technology roles in an organization. Developer is at the top, followed by sysadmin and DBA. QA teams, "operations" people, release coordinators and the like are at the bottom of the totem pole. Why is it arranged like this? Because each role can do the job of all roles below it if necessary..]]> I...]]> When someone asks why the if __name__ == '__main__' idiom should be used, I say it's because it makes turning your "script" into a "library" a seamless act. Novices often write a series of one-off Python scripts that exist only as long as it takes to finish and run them. More seasoned developers have accumulated a set of libraries they've written over the years. Last night I needed to properly parse a fully-qualified domain into its constituent parts (top-level domain, second-level domain, sub-domains). I found one library that looked promising, but it used a hard-coded list to represent all of the possible TLDs. The problem is this list changes with some frequency, and I needed to get it right. So, fine, there's no third-party package that exactly fits my needs. Rather than just bolt on the domain parsing functionality to the application that required it, however, I turned it into a first-class citizen: a library (more accurately, a Python package). Heck, I even released it with unit tests and hooked it up to TravisCI. Why would I take the extra time required to make this a reusable library? Two main reasons: first, this is a straightforward problem that should be solved once and never thought of again. Any time you encounter situations like that, do the right thing and write a small library. Second, because it's a general enough task, I wanted to make it available to others so that they didn't need to keep solving a problem that's already been solved. As developers, we waste a ton of time on solved problems. Whether it's due to "Not Invented Here"-itis or general ignorance, I've seen entire systems duplicated by different teams in the same organization. I would argue that being able to sense when a problem likely has an open source solution is an integral part of being a "good" developer. So in the interest of saving everyone a bunch of time, I wrote the package, released it, and am happy to accept bug reports (and will fix them). What's more, the library becomes another tool in my tool belt rather than a few random functions in a script I'll never use again. As developers, we should be working together on the mundane stuff so that we can all go off and work on the cool stuff. Please, don't make other people solve your problem over and over again. Do it once, make a library, and release it to the world. You'll save all of us a lot of time.]]> Recently,!]]> Bre.]]> After.]]> On Friday, I launched a kickstarter campaign to turn my book, Writing Idiomatic Python, into a series of instructional videos. How would that work? I would find real-world code in need of some love and narrate the process of refactoring it using principles from the book. After launching the campaign, I threw up a quick blog post, sent out an email and a tweet, and went home. When I woke up the next morning, over $1000 had already been raised. As of this morning, over $2,400 has been raised of the $5,000 goal. With 27 days left, we're almost half way there. But there's another, perhaps more important, goal: if I raise $10,000, I'll make the videos free to view for everyone, forever. I'll release the videos under the Creative Commons license, allowing them to be used for just about anything. Heck, you could use them to run your own course if you wanted to. That's why the $10,000 goal is the one I really hope we hit. Make no mistake, I am amazed at the generosity of you guys and the entire Python community. $2,400 in a weekend is jaw-dropping. I want to keep the momentum up, though, to ensure we hit $10,000 so that these videos will be free to view. How awesome a resource would they be? If you've already contributed: Thanks a ton! You can still help by getting the word out to friends and colleagues. All of the funding is raised through word-of-mouth, so spreading the word is akin to backing the project. Ditto for those who would like to contribute but aren't in the financial situation to do so. You can still help by spreading the word! While I encourage everyone to get the word out, I want to briefly caution against spamming any communication channel. It's quite easy to find yourself flooding Twitter, Reddit, etc with messages for a cause you support. Ultimately, however, it does more harm than good as people turn resentful for being spammed. And if you ever feel like I'm spamming you, please let me know! I'd rather the campaign fail than lose whatever goodwill I've built up with all of you. Thanks again for being amazing, and thanks in advance for helping spread the word. When it comes to human nature, I tend to be optimistic almost to the point of naivete. Thanks for proving me right ;) Here's a link to the campaign:.]]> Let's turn the book "Writing Idiomatic Python" into a series of how-to videos! I loved writing "Writing Idiomatic Python." And I love giving talks at meet-ups and such on the topics covered in the book. The book has proven to be an effective way for novice and intermediate programmers to take their Python coding skills to the next level. I couldn't be happier... But I want even more developers to benefit from the book's ideas. That's why I want to turn "Writing Idiomatic Python" into a series of recorded screencasts. The format will be as follows: I'll take real-word code of questionable quality and refactor it into beautiful, Idiomatic Python. I'll narrate my thought process as I do so and will refer to specific idioms mentioned in the book. I'll also introduce new idioms not included in the book. You'll get to see exactly how to transform your code into idiomatic Python. There will be a minimum of 10 videos, each about 30 minutes in length. If I raise $10,000 or more, the videos will all be released under the Creative Commons license. If I raise $25,000 or more, I'll double the number of videos I create. That means 10+ hours of Idiomatic Python goodness, free for everyone! There are sweet incentives (free tutoring sessions, signed copies of the book, a day-long seminar for you and 25 friends, etc). Help me help other Python programmers! Back the project by clicking here!]]>!]]> A.]]> A.]]> When.]]> Recently,.]]> Web. If we were going to continue building on the example above as the basis for a web application, there are a number of problems we'd need to solve: POSTrequests in addition to simple GETrequests..]]> If you're like most novice Python programmers, you likely are able to envision entire applications in your head but, when it comes time to begin writing code and a blank editor window is staring you in the face, you feel lost and overwhelmed. In today's article, I'll discuss the method I use to get myself started when beginning a program from scratch. By the end of the article, you should have a good plan of attack for starting development for any application. Before a line of code is ever written, the first thing I do is create a virtual environment. What is a virtual environment? It's a Python installation completely segregated from the rest of the system (and the system's default Python installation). Why is this useful? Imagine you have two projects you work on locally. If both use the same library (like requests) but the first uses an older version (and can't upgrade due to other libraries depending on the old version of requests), how do you manage to use the newest version of requests in your new project? The answer is virtual environments. To get started, install virtualenvwrapper (a wrapper around the fantastic virtualenv package). Add a line to your .bashrc or equivalent file to source /usr/local/bin/virtualenvwrapper.sh and reload your profile by sourceing the file you just edited. You should now have a command, mkvirtualenv, available via tab-completion. If you're using Python 3.3+, virtual environments are supported by the language, so no package installation is required. mkvirtualenv <my_project> will create a new virtualenv named my_project, complete with pip and setuptools already installed (for Python 3, python -m venv <my_project> followed by source <my_project>/bin/activate will do the trick). Now that you've got your virtual environment set up, it's time to initialize your source control tool of choice. Assuming it's git (because, come on...), that means git init .. It's also helpful to add a .gitignore file right away to ignore compiled Python files and __pycache__ directories. To do so, create a file named .gitignore with the following contents: *.pyc __pycache__ Now is also a good time to add a README to the project. Even if you are the only person who will ever see the code, it's a good exercise to organize your thoughts. The README should describe what the project does, its requirements, and how to use it. I write READMEs in Markdown, both because GitHub auto-formats any file named README.md and because I write all documents in Markdown. Lastly, create your first commit containing the two files ( .gitignore, README.md) you just created. Do so via git add .gitignore README.md, then git commit -m "initial commit". I begin almost every application the same way: by creating a "skeleton" for the application consisting of functions and classes with docstrings but no implementation. I find that, when forced to write a docstring for a function I think I'm going to need, if I can't write a concise one I haven't thought enough about the problem. To serve as an example application, I'll use a script recently created by a tutoring client during one of our sessions. The goal of the script is to create a csv file containing the top grossing movies of last year (from IMDB) and the keywords on IMDB associated with them. This was a simple enough project that it could be completed in one session, but meaty enough to require some thought. First, create a main file to serve as the entry point to your application. I'll call mine imdb.py. Next, copy-and-paste the following code into your editor (and change the docstring as appropriate): """Script to gather IMDB keywords from 2013's top grossing movies.""" import sys def main(): """Main entry point for the script.""" pass if __name__ == '__main__': sys.exit(main()) While it may not look like much, this is a fully functional Python program. You can run it directly and get back the proper return code ( 0, though to be fair, running an empty file will also return the proper code). Next I'll create stubs for the functions and/or classes that I think I'll need: ""()) That seems reasonable. Notice that the functions both include parameters (i.e. get_keywords_for_movie, includes the parameter movie_url). This may seem odd when implementing stubs. Why include any parameters at this point? The reasoning is the same as for pre-writing the docstring: if I don't know what arguments the function will take, I haven't thought it through enough. At this point, I'd probably commit to git, as I've done a bit of work that I wouldn't like to lose. After that's done, it's on to the implementation. I always begin implementing main, as it's the "hub" connecting all other functions. Here's the implementation for main in imdb.py: import csv]) Despite the fact that get_top_grossing_movie_links and get_keywords_for_movie haven't been implemented yet, I know enough about them to make use of them. main does exactly what we discussed in the beginning: gets the top grossing movies and outputs a csv file of their keywords. Now all that remains is the implementation of the missing functions. Interestingly enough, even though we know get_keywords_for_movie will be called after get_top_grossing_movie_links, we can implement them in whatever order we like. This isn't the case if you simply started writing the script from scratch, adding things as you go. You would be forced to write the first function before you could move on to the second. The fact that we can implement (and test!) the functions in any order shows they are loosely coupled. Let's implement get_keywords_for_movie first:')] We're using both requests and BeautifulSoup, so we need to install them with pip. Now would be a good time to list the project's requirements via pip freeze requirements.txt and commit them. This way, we can always create a virtual environment and install exactly the packages and versions we need to run the application. The list comprehension that is returned may look odd, but it's simply doing an additional, nested iteration over the results of the first and using the elements from the nested iteration. With list comprehensions, you can chain as many for statements as you'd like. The last step is the implementation of get_top_grossing_movie_links: Reasonably straightforward. The if movie_title != 'X' was due to my()) The application, which began as a blank editor window, is now complete. Running it generates output.csv, containing exactly what we'd hoped for. With a script of this length, I wouldn't write tests as the output of the script is the test. However, it would certainly be possible (since our functions are loosely coupled) to test each function in isolation. Hopefully, you now have a plan of attack when faced with starting a Python project from scratch. While everyone has their own method of starting a project, mine is just as likely to work for you as any other, so give it a try. As always, if you have any questions, feel free to ask in the comments or email me at jeff@jeffknupp.com.]]> I've been taking stock of the digital services I use (and pay for) but am unhappy with. Digital goods sales (for my book) has already been taken care of by bull. Next on my list is tracking mentions of my site across the Internet. In this article, we'll build a simple (but fully functional) web application that searches for and displays mentions of a particular keyword (in my case, "jeffknupp.com"). I should mention that I use a service to do this already: mention. It's OK, but I'm reaching their quota for the free service, and I can't stand their mobile app, so I'd rather have something tailored for myself. And, as I've recently discovered with bull, writing a service like this from scratch can be done quite quickly. If you know of a better application for tracking mentions, by the way, please let me know! I'll focus initially on Twitter, as much/most of the commentary on my site likely occurs there (as opposed to blogs or newsgroups). I wanted to try out a new Python Twitter client anyway (birdy), so I decided to use birdy for my Twitter interactions. At the very least, I need to be able to persist mentions of my site in a database. Any problem with the word "database" in it can usually be answered with "SQLAlchemy," and this is no exception. Let's create some SQLAlchemy models for our database: "")} Nothing very surprising here. I create two models, one to represent a data source (like "Twitter"), and another to model the actual mention of the keyword I'm interested in. The only interesting thing is the to_json function. Since I know that I'll be creating a web application with a dynamic front-end, I imagine I'll be sending this data as JSON quite often. Hence the existence of to_json. After creating a models.py file, I usually follow up with a populate_db.py file to insert initial data into the database. Here are the contents of that file:: We need to iterate over each status object, which birdy returns as a JSONObject (basically a dictionary who's keys are available as attributed). We want the get_twitter_mentions function to be (logically) idempotent. That is, if we execute the function multiple times, our database does not contain duplicate results. To achieve this, we need to check for any Mention objects that have the same domain_id, which is the unique identifying ID in the source system (i.e. the unique ID Twitter assigned the tweet). Now it's time to implement the main application logic. Let's return to app.py, the file in which we created our skeleton. I know that the index function is just going to return a rendered template, since the querying for Mentions will happen on the client side. Thus, index is trivial: }) We simply use the <id> parameter passed in via the URL as the primary key in our database look up. Then we simply changed seen to True and save the object back to the database. We return a token response that's not of much interest (really, a HTTP 204 would have been more appropriate, but I was lazy). The rest is just mop up. Here's the implementation for ()) I've been looking for an excuse to learn Facebook's React.js framework, and this is the perfect opportunity. I won't go into detail about the implementation because a) I'm sure there's a better way to do it and b) I'm not an authority (by any means) on the subject. Regardless, using React, I was able to create a page that displays all mentions. Unread mentions are presented in a well. Once clicked, the asynchronously send a /read request to the database and change their appearance (by changing their CSS class). So basically there's a visual difference between read and unread items and it's updated dynamically. Here's the contents of index.html (which you may notice is very similar to the React tutorial code...): <.]]> As a developer, I sometimes forget the power I wield. It's easy to forget that, when something doesn't work the way I'd like, I have the power to change it. Yesterday, I was reminded of this fact as I finally got fed up with the way payments are processed for my book. After being unhappy with the three different digital-goods payment processors I've used since the book came out, I took two hours and wrote my own solution using Python and Flask. That's right. Two hours. It's now powering my book payment processing and the flow is so incredibly simple that you can buy the book and begin reading it in 20 seconds. Read on to find out how I created my own digital goods payment solution in an evening..]]>. Back None of these steps, except for perhaps the first, are covered in the official tutorial. They should be. If you're looking to start a new, production ready Django 1: (django_project) init This creates a git repository in the current directory. Lets stage all of our files to git to be committed. $ git add django_project Now we actually commit them to our new repo: $ git commit -m 'Initial commit of django_project' $ checkout -b <branchname> Which will both create a new branch named master mimics the "production" (or "version live on your site") master and can be used for recovery at any time. $!]]>.]]> One frequent source of confusion for novice developers is the subject of testing. They are vaguely aware that "unit testing" is something that's good and that they should do, but don't understand what the term actually means. If that sounds like you, fear not! In this article, I'll describe what unit testing is, why it's useful, and how to unit test Python code. Before discussing why testing is useful and how to do it, let's take a minute to define what unit testing actually is. "Testing", in general programming terms, is the practice of writing code (separate from your actual application code) that invokes the code it tests to help determine if there are any errors. It does not prove that code is correct (which is only possible under very restricted circumstances). It merely reports if the conditions the tester thought of are handled correctly. Note: when I use the term "testing", I'm always referring to "automated testing", where the tests are run by the machine. "Manual testing", where a human runs the program and interacts with it to find bugs, is a separate subject. What kinds of things can be caught in testing? Syntax errors are unintentional misuses of the language, like the extra . in my_list..append(foo). Logical errors are created when the algorithm (which can be thought of as "the way the problem is solved") is not correct. Perhaps the programmer forgot that Python is "zero-indexed" and tried to print the last character in a string by writing print(my_string[len(my_string)]) (which will cause an IndexError to be raised). Larger, more systemic errors can also be checked for. Perhaps the program always crashes when the user inputs a number greater than 100, or hangs if the web site it's retrieving is not available. All of these errors can be caught through careful testing of the code. Unit testing, specifically tests a single "unit" of code in isolation. A unit could be an entire module, a single class or function, or almost anything in between. What's important, however, is that the code is isolated from other code we're not testing (which itself could have errors and would thus confuse test results). Consider the following example: def is_prime(number): """Return True if *number* is prime.""" for element in range(number): if number % element == 0: return False return True def print_next_prime(number): """Print the closest prime number larger than *number*.""" index = number while True: index += 1 if is_prime(index): print(index) We have two functions, is_prime and print_next_prime. If we wanted to test print_next_prime, we would need to be sure that is_prime is correct, as print_next_prime makes use of it. In this case, the function print_next_prime is one unit, and is_prime is another. Since unit tests test only a single unit at a time, we would need to think carefully about how we could accurately test print_next_prime (more on how this is accomplished later). So what does test code look like? If the previous example is stored in a file named primes.py, we may write test code in a file named test_primes.py. Here are the minimal contents of test_primes.py, with an example test:. If we "run the tests" by running python test_primes.py, we'll see the output of the unittest framework printed on the console: $ The single "E" represents the results of our single test (if it was successful, a "." would have been printed). We can see that our test failed, the line that caused the failure, and any exceptions raised. Before we continue with the example, it's important to ask the question, "Why is testing a valuable use of my time?" It's a fair question, and it's the question those unfamiliar with testing code often ask. After all, testing takes time that could otherwise be spend writing code, and isn't that the most productive thing to be doing? There are a number of valid answers to this question. I'll list a few here: Testing assures correctness under a basic set of conditions. Syntax errors will almost certainly be caught by running tests, and the basic logic of a unit of code can be tested to ensure correctness under certain conditions. Again, it's not about proving the code is correct under any set of conditions. We're simply aiming for a reasonably complete set of possible conditions (i.e. you may write a test for what happens when you call my_addition_function(3, 'refrigerator), but you needn't test all possible strings for each argument). This is especially helpful when refactoring1 code. Without tests in place, you have no assurances that your code changes did not break things that were previously working fine. If you want to be able to change or rewrite your code and know you didn't break anything, proper unit testing is imperative. Writing tests forces you to think about the non-normal conditions your code may encounter. In the example above, my_addition_function adds two numbers. A simple test of basic correctness would call my_addition_function(2, 2) and assert that the result was 4. Further tests, however, might test that the function works correctly with floats by running my_addition_function(2.0, 2.0). Defensive coding principles suggest that your code should be able to gracefully fail on invalid input, so testing that an exception is properly raised when strings are passed as arguments to the function. The whole practice of unit testing is made much easier by code that is loosely coupled2. If your application code has direct database calls, for example, testing the logic of your application depends on having a valid database connection available and test data to be present in the database. Code that isolates external resources, on the other hand, can easily replace them during testing using mock objects. Applications designed with test-ability in mind usually end up being modular and loosely coupled out of necessity.:() unittest is part of the Python standard library and a good place to start our unit test walk-through. A unit test consists of one or more assertions (statements that assert that some property of the code being tested is true). Recall from your grade school days that the word "assert" literally means, "to state as fact." This is what assertions in unit tests do as well. self.assertTrue is rather self explanatory, it asserts that the argument passed to it evaluates to True. The unittest.TestCase class contains a number of assert methods, so be sure to check the list and pick the appropriate methods for your tests. Using assertTrue for every test should be considered an anti-pattern as it increases the cognitive burden on the reader of tests. Proper use of assert methods state explicitly exactly what is being asserted by the test (e.g. it is clear what assertIsInstance is saying about its argument just by glancing at the method name). Each test should test a single, specific property of the code and be named accordingly. To be found by the unittest test discovery mechanism (present in Python 2.7+ and 3.2+), test methods should be prepended by test_ (this is configurable, but the purpose is to differentiate test methods and non-test utility methods). If we had named the method test_is_five_prime is_five_prime instead, the output when running python test_primes.py would be the following: $ python test_primes.py ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Don't be fooled by the "OK" in the output above. "OK" is only reported because no tests actually ran! I think running zero tests should result in an error, but personal feelings aside, this is behavior you should be aware of, especially when programatically running and inspecting test results (e.g. with a continuous integration tool like TravisCI). Returning to the actual contents of test_primes.py, recall that the output of python test_primes.py is the following: $ This output shows us that our single test resulted in failure due not to an assertion failing but rather because an un-caught exception was raised. In fact, the unittest framework didn't get a chance to properly run our test because it raised an exception before returning. The issue here is clear: we are preforming the modulo operation over a range of numbers that includes zero, which results in a division by zero being performed. To fix this, we simply change the range to begin at 2 rather than 0, noting that modulo by 0 would be an error and modulo by 1 will always be True (and a prime number is one wholly divisible only by itself and 1, so we needn't check for 1). A failing test has resulted in a code change. Once we fix the error (changing the line in is_prime to for element in range(2, number):), we get the following output: $ python test_primes.py . ---------------------------------------------------------------------- Ran 1 test in 0.000s Now that the error is fixed, does that mean we should delete the test method test_is_five_prime (since clearly it will now always pass)? No. unit tests should rarely be deleted as passing tests are the end goal. We've tested that the syntax of is_prime is valid and, at least in one case, it returns the proper result. Our goal is to build a suite (a logical grouping of unit tests) of tests that all pass, though some may fail at first. test_is_five_prime worked for an "un-special" prime number. Let's make sure it works for non-primes as well. Add the following method to the PrimesTestCase class:. We've successfully tested two general cases. Let us now consider edge cases, or cases with unusual or unexpected input. When testing a function that whose range is all positive integers, examples of edge cases include 0, 1, a negative number, and a very large number. Let's test some of these now. Adding a test for zero is straightforward. We expect is_prime(0) to return False, since, by definition, prime numbers must be greater than one:)) Here we decide to check all numbers from -1 .. -9. Calling a test method in a loop is perfectly valid, as are multiple calls to assert methods in a single test. We could have rewritten this in the following (more verbose) fashion: def test_negative_number(self): """Is a negative number correctly determined not to be prime?""" self.assertFalse(is_prime(-1)) self.assertFalse(is_prime(-2)) self.assertFalse(is_prime(-3)) self.assertFalse(is_prime(-4)) self.assertFalse(is_prime(-5)) self.assertFalse(is_prime(-6)) self.assertFalse(is_prime(-7)) self.assertFalse(is_prime(-8)) self.assertFalse(is_prime(-9)) The two are essentially equivalent. Except when we run the loop version, we get a little less information than we'd like:) Hmm, we know the test failed, but on which negative number? Rather unhelpfully, the Python unittest framework does not print out the expected and actual values. We can side-step the issue in one of two ways: through the msg parameter or through the use of a third-party unit testing framework. Using the msg parameter to assertFalse is simply a matter of recognizing that we can use string formatting to solve our problem: def test_negative_number(self): """Is a negative number correctly determined not to be prime?""" for index in range(-1, -10, -1): self.assertFalse(is_prime(index), msg='{} should not be determined to be prime'.format(index)) which gives the following output:) We see that the failing negative number was the first tested: -1. To fix this, we could add yet another special check for negative numbers, but the purpose of writing unit tests is not to blindly add code to check for edge cases. When a test fails, take a step back and determine the best way to fix the issue. In this case, rather than adding an additional if:. In this article, you learned what unit tests are, why they're important, and how to write them. That said, be aware we've merely scratched the surface of the topic of testing methodologies. More advanced topics such as test case organization, continuous integration, and test case management are good subjects for readers interested in further studying testing in Python..]]> I.]]> After. Now for the meat of the article: the specific steps I took that inadvertently turned novices into rockstars. I'll list a number of areas I focused on and what I did in that space.. maketo%..).]]> I don't often toot my own horn, but I'm quite astonished to report that sandman is the #1 trending Python repo today on GitHub. It's also in the top ten for all trending repos today. ...and I'm pretty happy about that.]]>.]]> One. While cPython is the official, "reference" interpreter implementation for the Python language, there are a number of alternate interpreters written in languages other than C. The two most popular are Jython and IronPython. Why are they of interest? Neither has a GIL.. Prior to beginning tutoring sessions, I ask new students to fill out a brief self-assessment where they rate their understanding of various Python concepts. Some topics ("control flow with if/else" or "defining and using functions") are understood by a majority of students before ever beginning tutoring. There are a handful of topics, however, that almost all students report having no knowledge or very limited understanding of. Of these, " generators and the yield keyword" is one of the biggest culprits. I'm guessing this is the case for most novice Python programmers. Many report having difficulty understanding generators and the yield keyword even after making a concerted effort to teach themselves the topic. I want to change that. In this post, I'll explain what the yield keyword does, why it's useful, and how to use it. Note: In recent years, generators have grown more powerful as features have been added through PEPs. In my next post, I'll explore the true power of yield with respect to coroutines, cooperative multitasking and asynchronous I/O (especially their use in the "tulip" prototype implementation GvR has been working on). Before we get there, however, we need a solid understanding of how the yield keyword and generators work.. In Python, "functions" with these capabilities are called generators, and they're incredibly useful. generators (and the yield statement) were initially introduced to give programmers a more straightforward way to write code responsible for producing a series of values. Previously, creating something like a random number generator required a class or module that both generated values and kept track of state between calls. With the introduction of generators, this became much simpler. To better understand the problem generators solve, let's take a look at an example. Throughout the example, keep in mind the core problem being solved: generating a series of values. Note: Outside of Python, all but the simplest generators would be referred to as coroutines. I'll use the latter term later in the post. The important thing to remember is, in Python, everything described here as a coroutine is still a generator. Python formally defines the term generator; coroutine is used in discussion but has no formal definition in the language. Suppose our boss asks us to write a function that takes a list of ints and returns some Iterable containing the elements which are prime1 numbers. Remember, an Iterable is just an object capable of returning its members one at a time. "Simple," we say, and we write the following: def get_primes(input_list): result_list = list() for element in input_list: if is_prime(element): result_list.append() return result_list # or better yet... def get_primes(input_list): return (element for element in input_list if is_prime(element)) # not germane to the example, but here's a possible implementation of # is_prime... def is_prime(number): if number > 1: if number == 2: return True if number % 2 == 0: return False for current in range(3, int(math.sqrt(number) + 1), 2): if number % current == 0: return False return True return False Either get_primes implementation above fulfills the requirements, so we tell our boss we're done. She reports our function works and is exactly what she wanted. Well, not quite exactly. A few days later, our boss comes back and tells us she's run into a small problem: she wants to use our get_primes function on a very large list of numbers. In fact, the list is so large that merely creating it would consume all of the system's memory. To work around this, she wants to be able to call get_primes with a start value and get all the primes larger than start (perhaps she's solving Project Euler problem 10). Once we think about this new requirement, it becomes clear that it requires more than a simple change to get_primes. Clearly, we can't return a list of all the prime numbers from start to infinity (operating on infinite sequences, though, has a wide range of useful applications). The chances of solving this problem using a normal function seem bleak. Before we give up, let's determine the core obstacle preventing us from writing a function that satisfies our boss's new requirements. Thinking about it, we arrive at the following: functions only get one chance to return results, and thus must return all results at once. It seems pointless to make such an obvious statement; "functions just work that way," we think. The real value lies in asking, "but what if they didn't?" Imagine what we could do if get_primes could simply return the next value instead of all the values at once. It wouldn't need to create a list at all. No list, no memory issues. Since our boss told us she's just iterating over the results, she wouldn't know the difference. Unfortunately, this doesn't seem possible. Even if we had a magical function that allowed us to iterate from n to infinity, we'd get stuck after returning the first value: def get_primes(start): for element in magical_infinite_range(start): if is_prime(element): return element Imagine get_primes is called like so: def solve_number_10(): # She *is* working on Project Euler #10, I knew it! total = 2 for next_prime in get_primes(3): if next_prime < 2000000: total += next_prime else: print(total) return Clearly, in get_primes, we would immediately hit the case where number = 3 and return at line 4. Instead of return, we need a way to generate a value and, when asked for the next one, pick up where we left off. Functions, though, can't do this. When they return, they're done for good. Even if we could guarantee a function would be called again, we have no way of saying, "OK, now, instead of starting at the first line like we normally do, start up where we left off at line 4." Functions have a single entry point: the first line. This sort of problem is so common that a new construct was added to Python to solve it: the generator. A generator "generates" values. Creating generators was made as straightforward as possible through the concept of generator functions, introduced simultaneously. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function (even if it also contains a return statement). There's nothing else we need to do to create one. generator functions create generator iterators. That's the last time you'll see the term generator iterator, though, since they're almost always referred to as " generators". Just remember that a generator is a special type of iterator. To be considered an iterator, generators must define a few methods, one of which is To get the next value from a generator, we use the same built-in function as for iterators: This point bears repeating: to get the next value from a generator, we use the same built-in function as for iterators: ( next() takes care of calling the generator's __next__() method). Since a generator is a type of iterator, it can be used in a for loop. So whenever next() is called on a generator, the generator is responsible for passing back a value to whomever called next(). It does so by calling yield along with the value to be passed back (e.g. yield 7). The easiest way to remember what yield does is to think of it as return (plus a little magic) for generator functions.** Again, this bears repeating: yield is just return (plus a little magic) for generator functions. Here's a simple generator function: >>> def simple_generator_function(): >>> yield 1 >>> yield 2 >>> yield 3 And here are two simple ways to use it: >>> for value in simple_generator_function(): >>> print(value) 1 2 3 >>> our_generator = simple_generator_function() >>> next(our_generator) 1 >>> next(our_generator) 2 >>> next(our_generator) 3 What's the magic part? Glad you asked! When a generator function calls yield, the "state" of the generator function is frozen; the values of all variables are saved and the next line of code to be executed is recorded until next() is called again. Once it is, the generator function simply resumes where it left off. If next() is never called again, the state recorded during the yield call is (eventually) discarded. Let's rewrite get_primes as a generator function. Notice that we no longer need the magical_infinite_range function. Using a simple while loop, we can create our own infinite sequence: def get_primes(number): while True: if is_prime(number): yield number number += 1 If a generator function calls return or reaches the end its definition, a StopIteration exception is raised. This signals to whoever was calling that the generator is exhausted (this is normal iterator behavior). It is also the reason the while True: loop is present in get_primes. If it weren't, the first time next() was called we would check if the number is prime and possibly yield it. If next() were called again, we would uselessly add 1 to number and hit the end of the generator function (causing StopIteration to be raised). Once a generator has been exhausted, calling next() on it will result in an error, so you can only consume all the values of a generator once. The following will not work: >>> our_generator = simple_generator_function() >>> for value in our_generator: >>> print(value) >>> # our_generator has been exhausted... >>> print(next(our_generator)) Traceback (most recent call last): File "<ipython-input-13-7e48a609051a>", line 1, in <module> next(our_generator) StopIteration >>> # however, we can always create a new generator >>> # by calling the generator function again... >>> new_generator = simple_generator_function() >>> print(next(new_generator)) # perfectly valid 1 Thus, the while loop is there to make sure we never reach the end of get_primes. It allows us to generate a value for as long as next() is called on the generator. This is a common idiom when dealing with infinite series (and generators in general). Let's go back to the code that was calling get_primes: solve_number_10. def solve_number_10(): # She *is* working on Project Euler #10, I knew it! total = 2 for next_prime in get_primes(3): if next_prime < 2000000: total += next_prime else: print(total) return It's helpful to visualize how the first few elements are created when we call get_primes in solve_number_10's for loop. When the for loop requests the first value from get_primes, we enter get_primes as we would in a normal function. whileloop on line 3 ifcondition holds ( 3is prime) 3and control to solve_number_10. Then, back in solve_number_10: 3is passed back to the forloop forloop assigns next_primeto this value next_primeis added to total forloop requests the next element from get_primes This time, though, instead of entering get_primes back at the top, we resume at line 5, where we left off. def get_primes(number): while True: if is_prime(number): yield number number += 1 # <<<<<<<<<< Most importantly, number still has the same value it did when we called yield (i.e. 3). Remember, yield both passes a value to whoever called and saves the "state" of the generator function. Clearly, then, number is incremented to 4, we hit the top of the while loop, and keep incrementing number until we hit the next prime number ( 5). Again we yield the value of number to the for loop in solve_number_10. This cycle continues until the for loop stops (at the first prime greater than 2,000,000). In PEP 342, support was added for passing values into generators. PEP 342 gave generators the power to yield a value (as before), receive a value, or both yield a value and receive a (possibly different) value in a single statement. To illustrate how values are sent to a generator, let's return to our prime number example. This time, instead of simply printing every prime number greater than number, we'll find the smallest prime number greater than successive powers of a number (i.e. for 10, we want the smallest prime greater than 10, then 100, then 1000, etc.). We start in the same way as get_primes: def print_successive_primes(iterations, base=10): # like normal functions, a generator function # can be assigned to a variable prime_generator = get_primes(base) # missing code... for power in range(iterations): # missing code... def get_primes(number): while True: if is_prime(number): # ... what goes here? The next line of get_primes takes a bit of explanation. While yield number would yield the value of number, a statement of the form other = yield foo means, "yield foo and, when a value is sent to me, set other to that value." You can "send" values to a generator using the generator's send method. def get_primes(number): while True: if is_prime(number): number = yield number number += 1 In this way, we can set number to a different value each time the generator yields. We can now fill in the missing code in print_successive_primes: def print_successive_primes(iterations, base=10): prime_generator = get_primes(base) prime_generator.send(None) for power in range(iterations): print(prime_generator.send(base ** power)) Two things to note here: First, we're printing the result of generator.send, which is possible because send both sends a value to the generator and returns the value yielded by the generator (mirroring how yield works from within the generator function). Second, notice the prime_generator.send(None) line. When you're using send to "start" a generator (that is, execute the code from the first line of the generator function up to the first yield statement), you must send None. This makes sense, since by definition the generator hasn't gotten to the first yield statement yet, so if we sent a real value there would be nothing to "receive" it. Once the generator is started, we can send values as we do above. In the second half of this series, we'll discuss the various ways in which generators have been enhanced and the power they gained as a result. yield has become one of the most powerful keywords in Python. Now that we've built a solid understanding of how yield works, we have the knowledge necessary to understand some of the more "mind-bending" things that yield can be used for. Believe it or not, we've barely scratched the surface of the power of yield. For example, while send does work as described above, it's almost never used when generating simple sequences like our example. Below, I've pasted a small demonstration of one common way send is used. I'll not say any more about it as figuring out how and why it works will be a good warm-up for part two. import random def get_data(): """Return 3 random integers between 0 and 9""" return random.sample(range(10), 3) def consume(): """Displays a running average across lists of integers sent to it""" running_sum = 0 data_items_seen = 0 while True: data = yield data_items_seen += len(data) running_sum += sum(data) print('The running average is {}'.format(running_sum / float(data_items_seen))) def produce(consumer): """Produces a set of values and forwards them to the pre-defined consumer function""" while True: data = get_data() print('Produced {}'.format(data)) consumer.send(data) yield if __name__ == '__main__': consumer = consume() consumer.send(None) producer = produce(consumer) for _ in range(10): print('Producing...') next(producer) There are a few key ideas I hope you take away from this discussion: generatorsare used to generate a series of values yieldis like the returnof generator functions yielddoes is save the "state" of a generator function generatoris just a special type of iterator iterators, we can get the next value from a generatorusing forgets values by calling next()implicitly I hope this post was helpful. If you had never heard of generators, I hope you now understand what they are, why they're useful, and how to use them. If you were somewhat familiar with generators, I hope any confusion is now cleared up. As always, if any section is unclear (or, more importantly, contains errors), by all means let me know. You can leave a comment below, email me at jeff@jeffknupp.com, or hit me up on Twitter @jeffknupp.... When most people first hear that in Python, "everything is an object", it triggers flashbacks to languages like Java where everything the user writes is encapsulated in an object. Others assume this means that in the implementation of the Python interpreter, everything is implemented as objects. The first interpretation is wrong; the second is true but not particularly interesting (for our purposes). What the phrase actually refers to is the fact that all "things", be they values, classes, functions, object instances (obviously), and almost every other language construct is conceptually an object. What does it mean for everything to be an object? It means all of the "things" mentioned above have all the properties we usually associate with objects (in the object oriented sense); types have member functions, functions have attributes, modules can be passed as arguments, etc. And it has important implications with regards to how assignment in Python works. A feature of the Python interpreter that often confuses beginners is what happens when print() is called on a "variable" assigned to a user-defined object (I'll explain the quotes in a second). With built-in types, a proper value is usually printed, like when calling print() on strings and ints. For simple, user-defined classes, though, the interpreter spits out some odd looking string like: >>> class Foo(): pass >>> foo = Foo() >>> print(foo) <__main__.Foo object at 0xd3adb33f> print() is supposed to print the value of a "variable", right? So why is it printing that garbage? To answer that, we need to understand what foo actually represents in Python. Most other languages would call it a variable. Indeed, many Python articles would refer to foo as a variable, but really only as a shorthand notation. In languages like C, foo represents storage for "stuff". If we wrote int foo = 42; it would be correct to say that the integer variable foo contained the value 42. That is, variables are a sort of container for values. In Python, this isn't the case. When we say: >>> foo = Foo() it would be wrong to say that foo "contained" a Foo object. Rather, foo is a name with a binding to the object created by Foo(). The portion of the right hand side of the equals sign creates an object. Assigning foo to that object merely says "I want to be able to refer to this object as foo." Instead of variables (in the classic sense), Python has names and bindings. So when we printed foo earlier, what the interpreter was showing us was the address in memory where the object that foo is bound to is stored. This isn't as useless as it sounds. If you're in the interpreter and want to see if two names are bound to the same object, you can do a quick-and-dirty check by printing them and comparing the addresses. If they match, they're bound to the same object; if not, their bound to different objects. Of course, the idiomatic way to check if two names are bound to the same object is to use is If we continued our example and wrote >>> baz = foo we should read this as "Bind the name baz to the same object foo is bound to (whatever that may be)." It should be clear, then why the following happens >>> baz.some_attribute Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Foo' object has no attribute 'some_attribute' >>> foo.>> baz.some_attribute 'set from foo' Changing the object in some way using foo will also be reflected in baz: they are both bound to the same underlying object. names in Python are not unlike names in the real world. If my wife calls me "Jeff", my dad calls me "Jeffrey", and my boss calls me "Idiot", it doesn't fundamentally change me. If my boss decides to call me "Captain Programming," great, but it still hasn't changed anything about me. It does mean, however, that if my wife kills "Jeff" (and who could blame her), "Captain Programming" is also dead. Likewise, in Python binding a name to an object doesn't change it. Changing some property of the object, however, will be reflected in all other names bound to that object. Here, a questions arises: How do we know that the thing on the right hand side of the equals sign will always be an object we can bind a name to? What about >>> foo = 10 or >>> foo = "Hello World!" Now is when "everything is an object" pays off. Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python. Both 10 and Hello World are objects. Don't believe me? Check for yourself >>> foo = 10 >>> print(foo.__add__) <method-wrapper '__add__' of int object at 0x8502c0> If 10 was actually just the number '10', it probably wouldn't have an __add__ attribute (or any attributes at all). In fact, we can see all the attributes 10 has using the dir() function: >>> dir(10) ['___', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real'] With all those attributes and member functions, I think it's safe to say 10 is an object. Since everything in Python is essentially names bound to objects, we can do silly (but interesting) stuff like this: >>> import datetime >>> import imp >>> datetime.datetime.now() datetime.datetime(2013, 02, 14, 02, 53, 59, 608842) >>> class PartyTime(): ... def __call__(self, *args): ... imp.reload(datetime) ... value = datetime.datetime(*args) ... datetime.datetime = self ... return value ... ... def __getattr__(self, value): ... if value == 'now': ... return lambda: print('Party Time!') ... else: ... imp.reload(datetime) ... value = getattr(datetime.datetime, value) ... datetime.datetime = self ... return value >>> datetime.datetime = PartyTime() >>> datetime.datetime.now() Party Time! >>> today = datetime.datetime(2013, 2, 14) >>> print(today) 2013-02-14 00:00:00 >>> print(today.timestamp()) 1360818000.0 datetime.datetime is just a name (that happens to be bound to an object representing the datetime class). We can rebind it to whatever we please. In the example above, we bind the datetime attribute of the datetime module to our new class, PartyTime. Any call to the datetime.datetime constructor returns a valid datetime object. In fact, the class is indistinguishable from the real datetime.datetime class. Except, that is, for the fact that if you call datetime.datetime.now() it always prints out 'Party Time!'. Obviously this is a silly example, but hopefully it gives you some insight into what is possible when you fully understand and make use of Python's execution model. At this point, though, we've only changed bindings associated with a name. What about changing the object itself? It turns out Python has two flavors of objects: mutable and immutable. The value of mutable objects can be changed after they are created. The value of immutable objects cannot be. A list is a mutable object. You can create a list, append some values, and the list is updated in place. A string is immutable. Once you create a string, you can't change its value. I know what you're thinking: "Of course you can change the value of a string, I do it all the time in my code!" When you "change" a string, you're actually rebinding it to a newly created string object. The original object remains unchanged, even though its possible that nothing refers to it anymore. See for yourself: >>>>> a 'foo' >>> b = a >>> a += 'bar' >>> a 'foobar' >>> b 'foo' Even though we're using += and it seems that we're modifying the string, we really just get a new one containing the result of the change. This is why you may hear people say, "string concatenation is slow.". It's because concatenating strings must allocate memory for a new string and copy the contents, while appending to a list (in most cases) requires no allocation. Immutable objects are fundamentally expensive to "change", because doing so involves creating a copy. Changing mutable objects is cheap. When I said the value of immutable objects can't change after they're created, it wasn't the whole truth. A number of containers in Python, such as tuple, are immutable. The value of a tuple can't be changed after it is created. But the "value" of a tuple is conceptually just a sequence of names with unchangeable bindings to objects. The key thing to note is that the bindings are unchangeable, not the objects they are bound to. This means the following is perfectly legal: >>> class Foo(): ... def __init__(self): ... self.value = 0 ... def __str__(self): ... return str(self.value) ... def __repr__(self): ... return str(self.value) ... >>> f = Foo() >>> print(f) 0 >>> foo_tuple = (f, f) >>> print(foo_tuple) (0, 0) >>> foo_tuple[0] = 100 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment >>> f.value = 999 >>> print(f) 999 >>> print(foo_tuple) (999, 999) When we try to change an element of the tuple directly, we get a TypeError telling us that (once created), tuples can't be assigned to. But changing the underlying object has the effect of "changing" the value of the tuple. This is a subtle point, but nonetheless important: the "value" of an immutable object can't change, but it's constituent objects can. If variables are just names bound to objects, what happens when we pass them as arguments to a function? The truth is, we aren't really passing all that much. Take a look at this code: def add_to_tree(root, value_string): """Given a string of characters `value_string`, create or update a series of dictionaries where the value at each level is a dictionary of the characters that have been seen following the current character. Example: >>>>> tree = {} >>> add_to_tree(tree, my_string) >>> print(tree['a']['b']) {'c': {}} >>> add_to_tree(tree, 'abd') >>> print(tree['a']['b']) {'c': {}, 'd': {}} >>> print(tree['a']['d']) KeyError 'd' """ for character in value_string: root = root.setdefault(character, {}) We're essentially creating an auto-vivifying dictionary that operates like a trie. Notice that we change the root parameter in the for loop. And yet after the function call completes, tree is still the same dictionary with some updates. It is not the last value of root in the function call. So in one sense tree is being updated; in another sense it's not. To make sense of this, consider what the root parameter actually is: a new binding to the object refereed to by the name passed in as the root parameter. In the case of our example, root is a name initially bound to the same object as tree. It is not tree itself, which explains why changing root to a new dictionary in the function leaves tree unchanged. As you'll recall, assigning root to root.setdefault(character, {}) merely rebinds root to the object created by the root.setdefault(character, {}) statement. Here's another, more straightforward, example: def list_changer(input_list): input_list[0] = 10 input_list = range(1, 10) print(input_list) input_list[0] = 10 print(input_list) >>> test_list = [5, 5, 5] >>> list_changer(test_list) [1, 2, 3, 4, 5, 6, 7, 8, 9] [10, 2, 3, 4, 5, 6, 7, 8, 9] >>> print test_list [10, 5, 5] Our first statement does change the value of the underlying list (as we can see in the last line printed). However, once we rebind the name input_list by saying input_list = range(1, 10), we're now referring to a completely different object. We basically said "bind the name input_list to this new list." After that line, we have no way of referring to the original input_list parameter again. By now, you should have a clear understanding of how binding a name works. There's just one more item to take care of. The concepts of names, bindings, and objects should be quite familiar at this point. What we haven't covered, though, is how the interpreter "finds" a name. To see what I mean, consider the following: GLOBAL_CONSTANT = 42 def print_some_weird_calculation(value): number_of_digits = len(str(value)) def print_formatted_calculation(result): print('{value} * {constant} = {result}'.format(value=value, constant=GLOBAL_CONSTANT, result=result)) print('{} {}'.format('^' * number_of_digits, '++')) print('\nKey: ^ points to your number, + points to constant') print_formatted_calculation(value * GLOBAL_CONSTANT) >>> print_some_weird_calculation(123) 123 * 42 = 5166 ^^^ ++ Key: ^ points to your number, + points to constant This is a contrived example, but a couple of things should jump out at you. First, how does the print_formatted_calculation function have access to value and number_of_digits even though they were never passed as arguments? Second, how do both functions seem to have access to GLOBAL_CONSTANT? The answer is all about scope. In Python, when a name is bound to an object, that name is only usable within the name's scope. The scope of a name is determined by the block in which it was created. A block is just a "block" of Python code that is executed as a single unit. The three most common types of blocks are modules, class definitions, and the bodies of functions. So the scope of a name is the innermost block in which it's defined. Let's now return to the original question: how does the interpreter "find" what a name is bound to (or if it's even a valid name at all)? It begins by checking the scope of the innermost block. Then it checks the scope that contained the innermost block, then the scope that contained that, and so on. In the print_formatted_calculation function, we reference value. This is resolved by first checking the scope of the innermost block, which in this case is the body of the function itself. When it doesn't find value defined there, it checks the scope that print_formatted_calculation was defined in. In our case, that's the body of the print_some_weird_calculation function. Here it does find the name value, and so it uses that binding and stops looking. The same is true for GLOBAL_CONSTANT, it just needs to look an extra level higher: the module (or script) level. Anything defined at this level is considered a global name. These are accessible from anywhere. A few quick things to note. A name's scope extends to any blocks contained in the block where the name was defined, unless the name is rebound in one of those blocks. If print_formatted_calculation had the line value = 3, then the scope of the name value in print_some_weird_calculation would only be the body of that function. It's scope would not include print_formatted_calculation, since that block rebound the name. There are two keywords that can be used to tell the interpreter to reuse a preexisting binding. Every other time we bind a name, it binds that name to a new object, but only in the current scope. In the example above, if we rebound value in print_formatted_calculation, it would have no affect on the value in print_some_weird_calculation, which is print_formatted_calculation's enclosing scope. With the following two keywords, we can actually affect the bindings outside our local scope. global my_variable tells the interpreter to use the binding of the name my_variable in the top-most (or "global" scope). Putting global my_variable in a code block is a way of saying, "copy the binding of this global variable, or if you don't find it, create the name my_variable in the global scope." Similarly, the nonlocal my_variable statement instructs the interpreter to use the binding of the name my_variable defined in the nearest enclosing scope. This is a way to rebind a name not defined in either the local or global scope. Without nonlocal, we would only be able to alter bindings in the local scope or the global scope. Unlike global my_variable however, if we use nonlocal my_variable then my_variable must already exist; it won't be created if it's not found. To see this in action, let's write a quick example: GLOBAL_CONSTANT = 42 print(GLOBAL_CONSTANT) def outer_scope_function(): some_value = hex(0x0) print(some_value) def inner_scope_function(): nonlocal some_value some_value = hex(0xDEADBEEF) inner_scope_function() print(some_value) global GLOBAL_CONSTANT GLOBAL_CONSTANT = 31337 outer_scope_function() print(GLOBAL_CONSTANT) # Output: # 42 # 0x0 # 0xdeadbeef # 31337 By making use of global and nonlocal, we're able to use and change the existing binding of a name rather than merely assigning the name a new binding and losing the old one. If you've made it to the end of this post, congratulations! Hopefully Python's execution model is much more clear. In a (much shorter) follow-up post, I'll show some examples of how we can make use of the fact that everything is an object in interesting ways. Until next time... If you found this post useful, check out Writing Idiomatic Python. It's filled with common Python idioms and code samples showing the right and wrong way to use them.]]> Many: tryblock but never throwing an exception.]]> On January 24th, I officially "launched" my eBook Writing Idiomatic Python. I had no idea what to expect and even less of an idea about what I should do to promote it. So I did the easiest thing: posted to reddit (/r/python to be specific). Aside from a post to hacker news not about the book itself and a single tweet, posting on reddit was the only thing I did. And that was enough. The post got a few upboats and stayed on the front page of /r/python for 5 days (and was the top post for about 2 days). The traffic, from reddit alone mind you, sold a lot of books (the exact numbers are discussed later). Between the 24th and 29th, I received 10,002 page views during 6,052 visits from 4,848 visitors. As you can see below, the majority of these came during the first two days (1,570 visits on the 24th and 1,896 on the 25th). When I started, I only offered PDF versions of the book ($8.99) with payment via credit card. Much of the early feedback fell in to one of three categories: Needless to say I got right to work. By Friday morning I set up PayPal and Google Checkout as payment options. A few hours later, I offered a bundle of all versions and all formats of the book for $12.99 (roughly 50% more than the cost of the book in a single version/format.) Both of these helped, but one had a considerably larger impact. The 'bundle' option quickly became the most popular. I was now making 50% more per sale. I had effectively increased the price of the most commonly purchased item from $8.99 to $12.99. Apparently, either a lot of people wanted the contents of the bundle or, more likely, the bundle's price was very attractive compared to a single version. Total Sales: $2,526.65 As I specify on the landing page for the book, I'm happy to send out free copies of the book to those without the financial means to purchase it. To date I've given out roughly 30 free copies in various versions/formats. Everyone has been quite appreciative and I've noticed I get the most feedback from those who got it for free. I have no idea why that is, but I enjoy the feedback. Has this materially impacted sales? Possibly, but the effect is likely minuscule. I know the number of free versions I sent out, so that accounts for all possible lost sales (unless seeing that I offer a free version stops some people who would otherwise have purchased it. Not likely, but stranger things have happened). I also offer a 30 day money back guarantee. To date I've had (and successfully processed) 3 return requests. Doing so is quite painless through both of my payment gateways. Again, I know the exact impact this policy has on sales and am happy with it. I'd much rather return money to someone who didn't find the information helpful than have a bunch of random, tech-savvy people pissed at me. Let me get this out of the way: these numbers are far better than I expected or hoped for. Clearly, if I had more free time leading up to the release, I would have done more marketing. But, as with the book itself, all of this is done in my spare time (I have a full-time, non eBook writing job). Given the amount of effort I put into marketing, I'm frankly astounded at the results. Obviously, sales have been dropping off sharply as the traffic from reddit fades. That's fine. In fact, the whole point of this is to: a) help people learn Python and b) build a source of passive income. Aside from additions and updates to the book itself, my profit per month from this project will simply be a function of the effort I put into sales/marketing (modulo some small number of sales I would get by doing nothing). Passive income is a powerful idea and has been discussed ad nauseum, so I won't beat a dead horse. Until you actually see passive income flowing into your bank account, though, it's difficult to appreciate just how incredible a thing it is. One more thing: because of this project, I've gained a lot of email newsletter subscribers. Hopefully, these (wonderful!) people will at least take a glance the next time I release a project. That makes the whole "initial marketing" thing a lot easier...]]> It took far more effort and time than I ever anticipated, but the Writing Idiomatic Python eBook is finally available! It's in "beta" mode right now, meaning I'm still planning on adding more content over the next month, but if you get it today you'll automatically get all of the updates (and corrections) for free. I really believe that the book will be of use to both those new to Python and those looking to increase their Python mastery. Interestingly, the book has its own automated build and test process, and it's the most comprehensive I've ever used on a Python project. As the book is primarily comprised of code samples, regression testing is an absolute must. I'm using pytest to implement the tests themselves. I found it a bit more flexible than nose in terms of deciding which directories/files/functions should be searched for tests. I'm also using the coverage package to make sure all of the code samples are actually being tested properly. Since there are two different versions of the book (one for Python 2.7.3+ and one for Python 3.3+), tox is used to test each version of Python against the non-version specific tests plus those specific to version of Python being used. tox is incredibly flexible, which has been vital as my "project" is much different than most other Python projects. After the tests complete, a custom Python generate script traverses each directory and process the .py files it finds. Section headings are stored in __init__.py files, while individual idioms are normal Python files. For each idiom, the file's docstring represents the idiom's description and analysis ( written in Markdown). This is followed by two functions: test_harmful and test_idiomatic, which contain the actual sample code. The generate script extracts the code from the two functions just mentioned as code objects and does a bit of post-processing (stripping out doctest related docstrings and pytest assertions). The sample code often uses non-existent functions and classes for illustrative purposes, but these need to exist in order to test the samples. "Helper" code implements the non-existent classes and functions in such a way that the sample code both runs and gives sensible values. The helper code for each idiom resides in that idiom's file and is stripped out by the generate script. To make the above a bit more clear, here's the full text of a sample file for a single idiom (in this case named use_else_to_determine_when_break_not_hit.py): """ Use ``else`` to execute code after a ``for`` loop concludes One of the lesser known facts about Python's ``for`` loop is that it can include an ``else`` clause. The ``else`` clause is executed after the iterator is exhausted, unless the loop was ended prematurely due to a ``break`` statement. This allows you to check for a condition in a ``for`` loop, ``break`` if the condition holds for an element, ``else`` take some action if the condition did not hold for any of the elements being looped over. This obviates the need for conditional flags in a loop solely used to determine if some condition held. In the scenario below, we are running a report to check if any of the email addresses our users registered are malformed (users can register multiple addresses). The idiomatic version is more concise thanks to not having to deal with the `has_malformed_email_address` flag. What's more, *even if another programmer wasn't familiar with the `for ... else` idiom, our code is clear enough to teach them.* """ class User(): def __init__(self, name, email_list): self.name = name self.email = email_list def get_all_email_addresses(self): return self.email def __str__(self): return self.name def get_all_users(): return [User('Larry', ['larry@gmail.com']), User('Moe', ['moe@gmail.com', 'larry@badmail.net']), User('Curly', ['curly@gmail.com'])] def email_is_malformed(email_address): return 'badmail' in email_address def test_idiomatic(): """ >>> test_idiomatic() Checking Larry All email addresses are valid! Checking Moe Has a malformed email address! Checking Curly All email addresses are valid! """ for user in get_all_users(): print ('Checking {}'.format(user)) for email_address in user.get_all_email_addresses(): if email_is_malformed(email_address): print ('Has a malformed email address!') break else: print ('All email addresses are valid!') def test_harmful(): """ >>> test_harmful() Checking Larry All email addresses are valid! Checking Moe Has a malformed email address! Checking Curly All email addresses are valid! """ for user in get_all_users(): has_malformed_email_address = False print ('Checking {}'.format(user)) for email_address in user.get_all_email_addresses(): if email_is_malformed(email_address): has_malformed_email_address = True print ('Has a malformed email address!') break if not has_malformed_email_address: print ('All email addresses are valid!') You may notice in the description that some terms are surrounded by a single ` and others by two. This is used for the purposes of building the index at the end of the book. Anything with two `'s is both formatted as inline code and marked as an occurrence of that term for the index. A single \' is similarly formatted but not indexed (so useless phrases like has_malformed_email_address don't appear in the index). The generate script takes the appropriate action based on which style of backquote is used. So after all of these steps are completed, the generate script produces a single Markdown file that represents the complete text of the book, properly formatted. This is then run through pandoc with a custom latex template to produce a '.latex' file. This gets run through xelatex so that the index may be generated, makeindex is used to actually build the index, and xelatex is run again to produce the final PDF document. Of course, none of this infrastructure existed when I started. I had no idea how I was going to write the prose and test the code at the same time. I had no idea how PDF files could be created. I had never used latex in any form. All of the above just gradually grew out of necessity. Looking at it all now, I'm amazed I had the patience to set it all up since none of it is evident in the final product (the book). You can imagine, then, the pace at which the book has been written. I have a full time job, so work was done in hours stolen from evenings and weekends. My wife has been more supportive of this than I deserve, but is glad that it's quite close to ending. I have a new found respect for those that write technical books for a living. It is a mentally and emotionally draining process. In the end, though, all that matters is the following: I set out to write a book that newcomers to Python would find helpful, I worked on it whenever I could, and I actually finished it. The last part is the key. I have started and abandoned scores of projects, as I'm sure many of you have. This time, though, I persevered. This time I finished. Even if no one actually buys the book, I still got through the process of writing it. That's worth quite a lot to me.]]> I.]]> I. In the beginning of 2012, I developed a site called Linkrdr. It was designed to be "the next generation RSS reader." Instead of simply listing each item in your RSS feeds in chronological order, it would: scan their content, extract links it found, then intelligently rank all of the links from all new entries and display them accordingly. The idea was, if I subscribe to TNW and TechCrunch and they both have a write up of the same story, I'd rather see the link they're talking about than two entries from secondary sources. As you interacted with it, Linkrdr learned your preferences and factored them in to its rankings. The result: a personalized list of interesting links, with some traditional RSS reader functionality to boot. The system worked, but faced some scaling challenges. Users could import their feeds from other sources, and some had hundreds of feeds they followed. This meant the content retrieval and analysis process had a ton of work to do, even for a relatively small number of users. But the main issue was I was solving a problem that didn't exist for very many people. Those that understood it and had a large number of feeds found it really helpful. Most, however, didn't get it and weren't particularly unhappy with the way they consumed RSS feeds. It solved a problem they didn't have. So Linkrdr wilted due to lack of development. I could see the writing on the wall and, rather than pour even more effort into something not many people wanted, I shut it down. It wasn't a total loss, though. I learned a great deal about developing data and computation intensive web applications. More importantly, I learned how not to build a useful web application. Linkrdr was born from my frustration with finding good technical content to read. Each day, I read twenty or more articles, blog posts, white papers, etc. I can't help it, I genuinely love software development and technology. My current workflow is to find content using Zite, then save each interesting looking article to Pocket (aka ReadItLater) to read offline. I spend a tremendous amount of time in those two applications. But the setup is not ideal. For one, I need to use two different applications for one task, neither of which is optimized for what I do. Here are the pros and cons of each application as they apply directly to me: Zite So I decided that Linkrdr would solve my specific problem, and no more. At a minimum, I'll need a server process to collect content and a mobile app to view it. Here's the workflow I came up with: Server Process Mobile App That's it. The entire application. It's exactly what my ideal application would do, but no more. And it's implemented in the simplest way possible: Because of these self-imposed design constraints, the implementation is simple. The server side is already done and took about two days. The mobile portion is progressing nicely. I'm not setting a concrete date for it to be ready, but "soon" is a good approximation. So, if you have the exact same issue as me with finding and consuming technology focused content offline, check back here to see when Linkrdr goes live. If not, well, it's not your problem I'm solving. It's mine.]]> If None of these steps, except for perhaps the first, are covered in the official tutorial. They should be. If you're looking to start a new, production ready Django 1, and recommended, practice among Python and Django users. spoken to a number of Django developers over the past few months and the ones having the most difficulty are those that don't use a version control system. Many new the new startproject command was added alongside the existing startapp command. The answer lies in the difference between Django "projects" and Django "apps", which are clearly delineated in Django 1.4." support reader polls, the "polls" would be an Django app used by "Super Blogger". The idea is that your polls app should be able to be reused in any Django project requiring user but pays huge dividends later. init This creates a git repository in the current directory. Lets stage all of our files to git to be committed. $ git add django_project
http://www.jeffknupp.com/atom.xml
CC-MAIN-2015-18
refinedweb
15,509
63.19
On Tue, Aug 05, 2003 at 11:21:04PM -0400, MJM wrote: > On Monday 04 August 2003 21:40, Sebastian Kapfer wrote: > > > // change the way it is accessed to prove a point int * p_b = (int *) > > > p_a; > > > > Ouch. > > Try this in /usr/src/linux/kernel > > $ grep *\) *.c Well, C is not C++, so grepping C source will not really prove: > Try Meyers' More Effective C++. > Besides, reinterpret_cast is probably a template function doing this: > return ((T) x); // type conversion using cast No, it is an operator, and part of the language. There are four new casting operators in C++ that were added to be used in place of the C-style cast syntax. If you're writing it C++, you really should use the proper casting operators. But, if you only believe things written by "Bjarne", try > > That way, you're clearly stating the intent of the cast. It is up to your > > compiler what it makes of this statement; the C++ standard doesn't cover > > such abuse. > > Language experts sure get their shorts knotted up over simple questions. Because your question had to do with undefined and implementation-dependent behavior. > I've known some killer programmers and none of them have quoted a language > specification in conversation. That was way over the top. That stuff is for > compiler writers, not application programmers. Application programmers should be aware of what aspects of their language of choice are not portable or implementation-dependent. That includes portability between different compilers and even different versions of the same vendor's compiler. That code was not portable, and could break just by doing something as innocuous as upgrading the C++ library. -- Dave Carrigan Seattle, WA, USA dave@rudedog.org | | ICQ:161669680 UNIX-Apache-Perl-Linux-Firewalls-LDAP-C-C++-DNS-PalmOS-PostgreSQL-MySQL
https://lists.debian.org/debian-user/2003/08/msg00902.html
CC-MAIN-2016-36
refinedweb
298
56.25
Writing Custom Contexts for Djangodjango (72), python (59) In building this site I ran into a number of situations where I was using generic views, but I needed another piece of information that simply wasn't accessible. Sure, I could write a bunch of custom views, but thats how I handled my first large Django project, and I didn't have any intention of doing that again (so much time wasted through irrational fearing of generic views, bah). Fortunately there is a really fantastically easy way to solve this problem: writing your own contexts. What is a context? A context is just some information. They will usually be QuerySets, but they could be anything. They will be available from within your templates. Oh, and they are a breeze to make. When building my site I wanted to have a selection of random entries available on the navigation bar on each page, lets look at how we can do this with a context. Contexts are simply functions that take one argument, request, and return a dictionary of values. The one I wrote looks like this: from blog.models import Entry def blog(request): random = Entry.current.all().order_by('?')[:3] return { 'random_entries' : random, } And... thats it. Now you'll need to make a quick entry in your settings.py file. Lets say that the file containing your context is at myproject/blog/context.py, then we'll just add this snippet to our settings.py file: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug "django.core.context_processors.i18n", "django.core.context_processors.media", "myproject.blog.context.blog", ) Its that easy, and yet not particularly well documented. Ah well, go now and conquer.
https://lethain.com/writing-custom-contexts-django/
CC-MAIN-2021-39
refinedweb
280
58.08
Jacob Holm wrote: On 2011-06-15 02:28, Jan Kaliszewski wrote: -- should 'my_var' in kwargs be allowed? (it's a runtime question) There is no real conflict here, so at the first sight I'd say: yes. On second thought: no, such repetitions also should *not* be allowed. If a programmer, by mistake, would try to specify the argument value in a call, an explicit TypeError should be raised -- otherwise it'd become a trap (especially for beginners and absent-minded programmers). I disagree. One of the main selling points of this feature for me is that adding a few "hidden parameters" to a function does not change the signature of the function. If you raise a TypeError when the name of a hidden parameter is in kwargs this is a change in signature. This is another reason why function parameters should not be used for something that is not a function parameter! +1 on the ability to inject locals into a function namespace. -1 on having the syntax for that masquerade as function arguments.
https://mail.python.org/archives/list/python-ideas@python.org/message/CSWFHYEQJRV76MRZDIAHLVODKWMRASDP/
CC-MAIN-2022-27
refinedweb
176
60.85
Closed Bug 1090275 Opened 7 years ago Closed 6 years ago Web Services modules should maintain a whitelist of methods that are allowed instead of allowing access to any function imported into its namespace Categories (Bugzilla :: WebService, defect) Tracking () Bugzilla 4.0 People (Reporter: dkl, Assigned: dkl) References Details Attachments (4 files, 4 obsolete files) Broken out from bug 1085182 to be tracked a separate issue. In the XML and JSON APIs the dispatching system uses the module namespace to limit the available API methods. Bugzilla also uses exporter extensively, so this results in namespaces having many inappropriate methods available. Out of the methods available this way in 4.4.6, User.bz_locations and Bug.WS_DISPATCH, stand out as the ones that could be argued to return sensitive internal data. Two possible solutions: 1) Using a whitelist of allowed method names for the XML/JSON API namespaces We can add a ALLOWED_METHODS constant to each WS related module and only those methods will be allowed. If a method is used not in the list, an error is thrown. 2) Avoid importing any functions into these namespaces by adding the empty list to your "use" statements and qualify all function/method calls that go outside of the module with their full namespace. Instead of: use Bugzilla::Constants; bz_locations(); you write use Bugzilla::Constants (); Bugzilla::Constants::bz_locations() Personally I feel 1) is a better approach as it gives us full explicit control of the methods allowed. If we add another 'use module' in the future to our current WS modules to bring in new functionality, if the module being use'ed has methods that are automatically imported we may not catch it and have the same issue over again. Thoughts? dkl Summary: WebServices modules should maintain a whitelist of methods that are allowed instead of allowing access to any function imported into it's namespace → WebServices modules should maintain a whitelist of methods that are allowed instead of allowing access to any function imported into its namespace a whitelist seems to be the best approach, especially since adding new methods is a rare occurrence. note: we need to ensure that extensions which add webservice methods can also add whitelists and are protected by this feature. (In reply to Byron Jones ‹:glob› from comment #1) > a whitelist seems to be the best approach, especially since adding new > methods is a rare occurrence. > > note: we need to ensure that extensions which add webservice methods can > also add whitelists and are protected by this feature. glob mentioned in IRC that prefixing the methods in the WS modules with public_ (or something similar) and then have the backend replace the caller's method with the actual one internally may be better solution. We already disallow any calls to methods that start with underscore '_'. For example, a caller using Bug.get would get translated to Bug.public_get internally and then throw an error if the method does not exist. This is also better in that setting of ALLOWED_METHODS constants in each module is not extension friendly if an extension is trying to extend a current namespace such as adding Bug.some_ext_method. But just looking for a prefix is not as difficult. Whatever we go with will break existing extensions and will need to be updated to work with the new functionality. dkl (In reply to David Lawrence [:dkl] from comment #2) > For example, a caller using Bug.get would get translated to Bug.public_get > internally and then throw an error if the method does not exist. If WS module A uses another WS module B, and both modules have public_* methods, how do you prevent A.foo from calling B.public_foo despite A.public_foo doesn't exist? For imported functions, we could clear them with namespace::clean. But that is only part of the problem. A whitelist is clearly a better choice. I see three possible options, each with its own drawback: 1) Whitelist method registry, ideally as a class method on the relevant class. Class->ws_allowed_methods() returns a hashref of (MethodName => 1). Extensions that inject methods into other classes can either wrap the method or modify its return value (it should be in the contract of the method that the return value is a modifiable reference, e.g. not cloned). 2) Prefix method names, as mentioned in comment #2. The drawback of this is having to rename all the methods we currently provided. I'm not sure how this will effect our test that checks for documented methods, as well. But it is one of the easiest approaches. 3) Use subroutine attributes. This doesn't require any additional dependencies. So, to use Bug.get as an example: package Bug; ... sub get :Public { } Tagging methods with information is exactly what subroutine attributes are for. The downside of this is similar to renaming all the methods, but we don't have to worry about *accidental* public methods (if we don't use namespace::clean, and our chosen prefix (public_?) is imported into the package, it will be public.) The likelihood of an imported subroutine having an attribute is very, very low. Assignee: webservice → dkl Status: NEW → ASSIGNED Attachment #8522478 - Flags: review?(LpSolit) Is REST also affected by this problem? If not, why? (In reply to Frédéric Buclin from comment #6) > Is REST also affected by this problem? If not, why? No as the REST resources are basically very specific regular expressions that match to specific methods in the WebService modules. It should not be possible for someone to use a REST path to access any other subroutine that we have not specified. Otherwise they get an error message each time. dkl Severity: normal → major Flags: blocking5.0? Target Milestone: --- → Bugzilla 4.0 Flags: blocking5.0? → blocking5.0+ Comment on attachment 8522478 [details] [diff] [review] 1090275_1.patch Review of attachment 8522478 [details] [diff] [review]: ----------------------------------------------------------------- A few suggested changes. r- ::: Bugzilla/WebService/Server/JSONRPC.pm @@ +404,5 @@ > } > } > > + # Only allowed methods to be used from our whitelist > + if (!grep($_ eq $method, $pkg->PUBLIC_METHODS)) { any { } (from List::Util) would be better here, as it will stop (short-circuit) after the first match. ::: Bugzilla/WebService/Server/XMLRPC.pm @@ +97,5 @@ > my ($self, $classes, $action, $uri, $method) = @_; > my $class = $classes->{$uri}; > my $full_method = $uri . "." . $method; > + # Only allowed methods to be used from the module's whitelist > + eval("require $class") || die $@; I would recommend using this for a variety of reasons (speed, safety, etc) my $file = $class; $file =~ s{::}{/}g; $file .= ".pm"; require $file; (a better solution would Class::Load->load_class(), but I won't suggest that dependency right now.) @@ +98,5 @@ > my $class = $classes->{$uri}; > my $full_method = $uri . "." . $method; > + # Only allowed methods to be used from the module's whitelist > + eval("require $class") || die $@; > + if (!grep($_ eq $method, $class->PUBLIC_METHODS)) { s/grep/any/; (use List::Util qw( any )) Attachment #8522478 - Flags: review?(dylan) → review- Attachment #8522478 - Attachment is obsolete: true Attachment #8533297 - Flags: review?(dylan) Wouldn't it be more readable if methods were listed alphabetically? New patch with public methods alphabetically sorted. (yay vim :sort). dkl Attachment #8533297 - Attachment is obsolete: true Attachment #8533297 - Flags: review?(dylan) Attachment #8533853 - Flags: review?(dylan) Comment on attachment 8533853 [details] [diff] [review] 1090275_3.patch Review of attachment 8533853 [details] [diff] [review]: ----------------------------------------------------------------- r=dylan Attachment #8533853 - Flags: review?(dylan) → review+ Flags: approval? Flags: approval5.0? the example extension needs to be updated too; please do so on commit. (In reply to Byron Jones ‹:glob› from comment #13) > the example extension needs to be updated too; please do so on commit. What needs to be updated there? Also, it's not ok to do fixes on checkin for a security bug. Linux distros usually pick patches directly from here and do not look at what has been committed. And shouldn't we wait for 4.4 backports before approving this bug? Added PUBLIC_METHODS to the Example extension. Moving forward r+. Attachment #8533853 - Attachment is obsolete: true Attachment #8537457 - Flags: review+ Patch for 4.4 Attachment #8538225 - Flags: review?(dylan) Comment on attachment 8538225 [details] [diff] [review] 1090275_44_1.patch Review of attachment 8538225 [details] [diff] [review]: ----------------------------------------------------------------- r=dylan, please fix the indentation on Bugzilla::WebService::Server::XMLRPC::new() before commit. ::: Bugzilla/WebService/Server/XMLRPC.pm @@ +38,5 @@ > +sub new { > +my $class = shift; > +my $self = $class->SUPER::new(@_); > +$self->{debug_logger} = sub {}; > +return $self; nit: this isn't indented Attachment #8538225 - Flags: review?(dylan) → review+ Flags: approval4.4? That new() was actually not supposed to be there and was added simply to allow the webservice tests to work. Removed and moving r+ forward. Attachment #8538225 - Attachment is obsolete: true Attachment #8538741 - Flags: review+ Flags: needinfo?(dkl) Flags: approval4.4? Flags: approval4.4+ Flags: needinfo?(dkl) Realized we also need sep patches for 4.2 and 4.0 as the 4.4 will not apply. Here is 4.2. 4.0 coming right up. dkl Attachment #8540333 - Flags: review?(dylan) Comment on attachment 8540333 [details] [diff] [review] 1090275_42_1.patch Review of attachment 8540333 [details] [diff] [review]: ----------------------------------------------------------------- r=dylan Attachment #8540333 - Flags: review?(dylan) → review+ Comment on attachment 8540364 [details] [diff] [review] 1090275-40_1.patch Review of attachment 8540364 [details] [diff] [review]: ----------------------------------------------------------------- r=dylan Attachment #8540364 - Flags: review?(dylan) → review+ Flags: approval4.2? Flags: approval4.0? Flags: approval4.2? Flags: approval4.2+ Flags: approval4.0? Flags: approval4.0+ Version: unspecified → 2.23.3 To ssh://gitolite3@git.mozilla.org/bugzilla/bugzilla.git 4dabf1a..1612292 master -> master To ssh://gitolite3@git.mozilla.org/bugzilla/bugzilla.git 19117cc..211464d 5.0 -> 5.0 To ssh://gitolite3@git.mozilla.org/bugzilla/bugzilla.git f5b9cba..ce85e36 4.4 -> 4.4 To ssh://gitolite3@git.mozilla.org/bugzilla/bugzilla.git 7e1b7a5..17e8ba8 4.2 -> 4.2 To ssh://gitolite3@git.mozilla.org/bugzilla/bugzilla.git 5c7b317..828e407 4.0 -> 4.0 Status: ASSIGNED → RESOLVED Closed: 6 years ago Resolution: --- → FIXED Released Group: bugzilla-security this doesn't pass tests, and burned all the trees: # Failed test 'Bugzilla/WebService/Server/JSONRPC.pm has 1 error(s): # user error tag 'unknown_method' is used at line(s) (410) but not defined for language(s): any' # at t/012throwables.t line 202. # Looks like you failed 1 test of 217. Status: RESOLVED → REOPENED Resolution: FIXED → --- tracking in new bug 1124716 Status: REOPENED → RESOLVED Closed: 6 years ago → 6 years ago Resolution: --- → FIXED Comment on attachment 8540364 [details] [diff] [review] 1090275-40_1.patch >+++ b/Bugzilla/WebService/Product.pm >++use constant PUBLIC_METHODS => qw( >++ get >++ get_accessible_products >++ get_enterable_products >++ get_selectable_products >++); This code is wrong! ++ means that all these lines now start with a "+". runtests.pl caught it, but nobody paid attention to it. :( Flags: documentation?
https://bugzilla.mozilla.org/show_bug.cgi?id=1090275
CC-MAIN-2021-17
refinedweb
1,763
58.79
I just posted a new Code Secure article on MSDN about running as an admin, but executing browsers and email clients in lower privilege. Do you have any suggestions for limiting a user’s ability to double-click on existing URL shortcuts and thus launching IE with their full admin token (instead of the newly restricted one as described in this article)? Interesting article (although I’m surprised at the choice of "warez" as a folder name). As for the code flaw at the end, I assume the problem is that the loop will never terminate, so you’ll get an overflow error from "req++;", flipping the value to negative, and then the array access on the next line will be outside the bounds of the array, overwriting a random memory location. Speaking of which, any plans for the results of the "spot the deliberate mistake" entry from a week or so ago? DropMyRights is a great utility. I have my outlook shortcut pointing to, "C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE" /recycle It fails if I update that to, "C:DropMyRights.exe" "C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE" /recycle It fails if I update my shortcut to, "C:DropMyRights.exe" "C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE /recycle" It also fails if I update my shortcut to, "C:DropMyRights.exe" ""C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE" /recycle" Can you please suggest how do I use DropMyRights for application having switches (and having space in their parent folder name). I haven’t yet read the article (though after a quick glance, it looks quite interesting). However, I’d like to ask that you (please, please) get MS to make working in Windows as non-admin more usable. Some examples include 1) not being able to even open the Time/Date applet (so you can look at the calendar) if you’re not admin 2) it seems to be impossible to launch the network settings applet as an admin from a non-admin account (using "Run as…"). Apparently this has something to do with that applet being an explorer window instance. Anyway, thanks for the new aspect of this to look into. This is slightly related, well it is related to reading and security. I found out from MS Press that a couple security books were cancelled. One was Web Application Security Assessment by Microsoft’s Ace and Ea2 Teams () and Forensics by Troy Larson (Amazon link is gone). Those books looked like they could have been REALLY good, especially the web security one. What’s the deal with that? P.S. Aaron Margosis’ blog is great. I used it as a source for a presentation on running as a non-admin on Windows for my local ACM chapter. >>"C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE" /recycle what if you drop the /recycle option? I tried Outlook2003, and it works fine! >>"C:Program FilesMicrosoft OfficeOFFICE11OUTLOOK.EXE" /recycle what if you drop the /recycle option? I tried Outlook2003, and it works fine! There’s a link to a Interesting article over at Michael Howards Blog He makes some very valid points about why running Windows machines as an administrator is a very bad idea(tm) unless absolutely required. Also there’s information on a useful… Big ditto to mikeb’s comments. The Time/Date applet should be open-able but ‘read-only’. And ditto to the second too. Could you modify the application to remove the annoying console window being shown? Why not make it a windows application and hence no console output? All you need to do is to wrap it into a minmal Win32 application. Will this safeguard against malware accessing your computer via \127.0.0.1c$, changing or adding some files and then changing the registry via remote api to autostart this file or run it as a service? Shiv: Set the shortcut associated with DropyMyRights to run as minimized, and the "annoying console window" is gone, and the target application still starts normally. Michael: Thanks for this great utility! Thanks for the DropMyRights utility. Two points: 1) I use the WatchIE utility from MSDN (April 2002) to intercept popups. It launches IE, then sits in the background. It appears that I can chain a call from DropMyRights, via WatchIE, to launch IE with reduced rights and popup blocking. Could you confirm that this will work as desired? 2) For peace of mind, what is the easiest way to verify the privileges, SIDs etc. in force for a running process? Thanks, Martin I’d like to make a few adjustments to the source, especially for arguments; but it’s incomplete. Is it possible to get the WinSafer part? Here’s the version of the program which doesn’t create a new console, which allows additional parameters to be passed and which has very small binary (1296 bytes with VC6). Is it safe to inherit the existing console? ———— JanDropRights.cpp ————— #define UNICODE #include <windows.h> #include <WinSafer.h> #include <winnt.h> // JanDropRights Copyright J. Stamenovic 2004 // inspired by Michael Howard’s DropMyRights // // Features: no console, small exe, // command line can contain arguments to the program, // hard coded level id to "normal user" // // To build use (in one line): // cl janDropRights.cpp kernel32.lib user32.lib // advapi32.lib /link /ALIGN:16 /nodefaultlib // /ENTRY:wWinMainCRTStartup /SUBSYSTEM:WINDOWS >l TCHAR* skipCmdLine( TCHAR* p ) { if ( *p == ‘"’ ) { p++; while ( *p != ‘"’ && *p != 0 ) p++; if ( *p == ‘"’ ) p++; } else { while ( *p > ‘ ‘ ) p++; } while ( *p != 0 && *p <= ‘ ‘ ) p++; return p; } int WINAPI MyWinMain( HINSTANCE hInstance, instance HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { DWORD hSaferLevel = SAFER_LEVELID_NORMALUSER; SAFER_LEVEL_HANDLE hAuthzLevel = NULL; if ( !SaferCreateLevel( SAFER_SCOPEID_USER, hSaferLevel, 0, &hAuthzLevel, NULL) ) { return GetLastError(); } HANDLE hToken = NULL; if ( !SaferComputeTokenFromLevel( hAuthzLevel, NULL, &hToken, 0, NULL ) ) { DWORD fStatus = GetLastError(); SaferCloseLevel( hAuthzLevel ); return fStatus; } TCHAR* cmdLine = skipCmdLine( lpCmdLine ); STARTUPINFO si = { sizeof( STARTUPINFO ) }; DWORD fStatus = 0; PROCESS_INFORMATION pi; if ( !CreateProcessAsUser( hToken, NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ) ) { fStatus = GetLastError(); } CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); SaferCloseLevel( hAuthzLevel ); return fStatus; } void wWinMainCRTStartup( void ) { MyWinMain( GetModuleHandleW( NULL ), NULL, GetCommandLineW(), 0 ); } Michael: The link to more information about "Software Restriction Policy" () ends up at a "Page not found" page. I wanted to find more information about the "Retricting SIDs". That’s a new term for me. An MSDN search only comes up with a description of an event log entry. Searching for "Software Restriction Policy" gets me infomration about configuring group policy and COM+. There are no hits for SAFER_LEVELID_CONSTRAINED (or the other levels) outside of your article. Can you get MSDN to publich this info? Thanks. Very interesting. I’ve not been able to start any application (except for cmd.exe) using "Constrained" or "Untrusted" user. When I try it, I see the application quickly flash by in the task manager (followed by dwwin.exe, DrWatson). Is it possible to run a Win32 GUI application "Constrained" or "Untrusted"? Here is something that I believe should be interesing: Last week I’ve posted a tool on my blog that develops idea of DropMyRights several steps further: tool registers itself as Windows shell and after being started by Windows logon, the tool drops rights for real Windows shell – explorer.exe. After that, any program that is started from Windows Explorer, Windows Start menu or desktop shortcut – will be running with reduced rights (non-admin). Additionally the tool adds tray icon that allows starting programs with non-reduced rights (as admin) or even more reduced rights (Constrained or Untrusted). I’ve posted the tool in my blog (both source code and binary). Here is the link: Jacques Calicis has already translated my tool to french and posted french description on his site DMR … a nice tool. But I use Win2000. Does anyone know such an easy to use tool for Win2000? DMR … a nice tool. But I use Win2000. Does anyone know such an easy to use tool for Windows 2000? I’v made a little shellextension based on DropMyRights idea. You can download it from It’s free of course and I hope it does not hurt any copyright. Thank ypou for the idea!!! PingBack from PingBack from PingBack from PingBack from PingBack from However cash till payday loan advance cash chicago settlement PingBack from PingBack from PingBack from
https://blogs.msdn.microsoft.com/michael_howard/2004/11/18/new-code-secure-column-browsing-the-web-and-reading-e-mail-safely-as-an-administrator/
CC-MAIN-2018-43
refinedweb
1,363
65.52
Good programming practice with regard to conditional return statements I would like to know which of the following is the best programming practice: // Below is the contents of a dummy method which is passed a boolean "condition" as a parameter. int valueA = 3; int valueB = 5 if (condition == true) { return valueA } else { return valueB } Alternatively, I could write the same code like this: int valueA = 3; int valueB = 5 if (condition == true) { return valueA } return valueB In both cases, B is returned only if the condition is false, so the "else" is not required, but is it better to include it anyway? source to share The code is clearer to read "at a glance" with an else statement to make it better. Alternatively, some (but not all) of the coding guidelines say that you should only return once at the end of the method. In this case, you have to "return" a value, set it appropriately in the if (which in this case needs something else), and then return that value at the end of the method. source to share Take the following example to see how using else will help you understand the code better if (inputVar == thingOne) { doFirstThing(); } else if (inputVar == secondThing) { doSecondThing(); } else { doThirdThing(); } I could write it the same way. if (inputVar == thingOne) { doFirstThing(); return; } if (inputVar == thingTwo) { doSecondThing(); return; } doThingThree(); return; Now ask yourself which code looks clearer and where do you understand the most. Indeed, it’s clear to the end what the code is doing (not necessarily which bit of code is the shortest or least indented). source to share I would like to put there also for readability. However, you can also write a shorthand if / else statement: return condition ? valueA : valueB; Again, this is your own preference for how you write it. source to share The operator else provides more clarity on the flow of conditions, you can accept the first snippet and no one will blame you, but it would be better to expand your database of operations on conditional blocks. I would even suggest using the aux value int to store the returned result, and then using a single return statement, and this will surely provide more clarity if you care about developers landing and looking at your sources: public int test(boolean condition) { int valueA = 3; int valueB = 5; int result; if (condition == true) { result = valueA; } else { result = valueB; } return result; } Alternatively, I would recommend the ternary expression mentioned by @stealthjong in his answer , as it is more readable when the condition is short and no nested instructions are wired into the second and third parameters. source to share See how it works the same, but there is only one difference, your line code will be smaller in the second. If you take my advice, I personally follow the second when it comes to such state (s). or you can use this one. return condition ? valueA : valueB; source to share I prefer to use an if-else statement, returning a value in each block when the method line number is less than 10. However, if there are 30 or more lines, it is unlikely to read if-else statements, so using just the return value instead of using the else value might be better. source to share I would suggest using an if-else block (first approach) because it improves readability. However, for performance consideration, I have chosen two of your approaches in the program. The code looks like this. public class test { public static void main(String args[]) { int count1=0,count2=0; for(int i=0;i<50000;i++) { long timeStart=System.nanoTime(); method1(false); long timeEnd=System.nanoTime(); long result1=timeEnd-timeStart; System.out.println("\n\nTime taken for method 1 is :"+result1); long Start=System.nanoTime(); method2(false); long End=System.nanoTime(); long result2=End-Start; System.out.println("Time taken for method 2 is :"+result2); if(result1>result2) { //increment count2 when result2 execution speed is high (i.e) less time count2++; } if(result1<result2) { //increment count1 when result1 execution speed is high count1++; } } System.out.println("\n\ncount1 value at the end is\t"+count1); System.out.println("count2 value at the end is\t"+count2); } public static int method1(boolean condition) { int valueA = 3; int valueB = 5; if (condition == true) { return valueA; } else { return valueB; } } public static int method2(boolean condition) { int valueA = 3; int valueB = 5; if (condition == true) { return valueA; } return valueB; } } Output: Testcase 1: count1 at the end is 10707 count2 at the end is 10977 Testcase 2: count1 at the end - 10310 count2 at the end - 10225 Testcase 3: Count1 at the end is 9590 count2 at the end is 10445 Testcase 4: count1 at the end is 10687 count2 at the end is 10435 Testcase 5: Count1 at the end - 10670 count2 at the end - 10223 Testcase 6: Count1 at the end - 10594 count2 at the end - 10810 Overall cumulative result of all 6 test cases is count1 =62558 count2=63115 therefore there is not much difference in performance on both approaches. Therefore, it is better to use an if else block as it gives equal performance (in terms of time) and improves readability. source to share
https://daily-blog.netlify.app/questions/2164839/index.html
CC-MAIN-2021-21
refinedweb
870
54.86
I’ve been writing an FMod type library for VB users, and it works great so far… if I finish it, will you be interested in distributing it with FMod? It doesn’t have any bugs so far, except having to load fmod manually with loadlibrary to prevent VB from unloading FMod while it’s running. Anyway, doing it that way has the advantage of keeping it from crashing when you hit ‘Stop’. - Janus asked 16 years ago - You must login to post comments Why not ? It interest me but one thing : types libraries are not only for vb users, it s a COM object so any 32 bit language can use it. Thanx for your work My email : XxKarLKoXxX@aol.com If it includes all functions, constants and enums of the fmod.bas module currently bundled with fmod, I think it would be interesting. I’d even suggest to add it to the fmod package then, so users have the choice between a module and a type-library. btw. Do you know any site or something to learn more about type-libraries? I’m interested in creating type-libraries myself, but I haven’t found out how yet. As far as I know, a type-library is very similar to a visual basic module that declares functions, or to a c header file. I think I read somewhere the advantage of a type-library file is that not the whole library is compiled in your program, but only the functions that are actually used in your program. This means Visual Basic users would benefit from it. From the MSDN : “A type library is best thought of as a binary version of an Interface Definition Language (IDL) file. It contains a binary description of the interfaces exposed by a component, defining the methods along with their parameters and return types. Many environments support type libraries: Visual Basic, Visual J++, and Microsoft Visual C++® all understand type libraries; so do Delphi, Microsoft Visual FoxPro®, and Microsoft Transaction Server. Rumor has it that the next version of Microsoft (Visual) Macro Assembler will support COM via type libraries.” Here is a simple example (from the MSDN too): import “unknwn.idl”; [ object, uuid(10000001-0000-0000-0000-000000000001), oleautomation ] interface ISum : Iunknown { HRESULT Sum(int x, int y, [out, retval] int* retval); } [ uuid(10000003-0000-0000-0000-000000000001), helpstring(“Inside DCOM Component Type Library”), version(1.0) ] library Component { importlib(“stdole32.tlb”); interface ISum; [ uuid(10000002-0000-0000-0000-000000000001) ] coclass InsideDCOM { interface ISum; } }; As Adion say it, it s very userfull because only the fonctions used are compile to the program. (not only VB users)
http://www.fmod.org/questions/question/forum-919/
CC-MAIN-2017-22
refinedweb
442
61.97
This short tutorial will introduce you to the basics of testing your python code using nosetests. It is meant as an introduction only. I'll assume you know about unit testing, how to lay out your tests etc etc. Here I'm really just introducing you to some useful tools to make your TDD process more fun For the purposes of this tutorial we'll be testing the following code: foo.py class Foo: def bar(self): return "bar" test_code.py import unittest .. class FooTestCase(unittest.TestCase): def test_bar(self): """Bar method returns "bar" """ assert Foo().bar() == "bar", "Should return bar" Setting up As per usual, create a virtualenv and install what you need on there: virtualenv-3.4 /path/to/env source /path/to/env/bin/activate We'll then install some dependencies: You can install all of those into your venv with pip. Get better output with pinocchio The main thing I use pinocchio for is the spec output that it can render. For example: nosetests --with-spec --with-color Gives us: Foo test case - Bar method returns "bar" ---------------------------------------------------------------------- Ran 1 test in 0.004s OK Notice how it uses our docstring for foo() in the spec description. Autorun the tests with Sniffer Sniffer allows us to run our tests automatically every time we make a change. Usage is simple. You can just type sniffer. However, we want to also pass in some arguments to our nosetests. You can do this by prefixing the command with -x. For example: sniffer -x--with-spec -x--spec-color Now, whenever we make changes to our code, sniffer will re-run the tests. \o/
https://blog.toast38coza.me/fun-times-testing-python-with-nose-sniffer-and-some-other-good-stuff/
CC-MAIN-2020-50
refinedweb
273
74.49
index > Windows Forms Designer > is there any way to force a control to receive focus? is there any way to force a control to receive focus? i have a custom control inherited from panel and i need to be able to handle Enter/Leave events for it..any idears? MigrationUser 1 Friday, February 21, 2003 9:15 AM I've never tried anything like this before and don't even know if it's possible, but i don't have time to try it right now and i thought i'd throw it out just in case it might actually work. the Panel class doesn't seem to have a TabStop Property, so I was thinking, again, don't laugh if this isn't possibly, because it definitely might not be, but Panel inherits from the ScrollableControl which does have a TabStop property, maybe something like MyBase.MyBase.TabStop = True I'm guess that won't work, which means I'm guess that it's not possible, but I'm sure there's somebody out there that knows more than me that could tell you how to do it. MigrationUser 1 Friday, February 21, 2003 3:09 PM I'm confused. The Panel control supplies Enter and Leave events--what are you looking for that isn't there? MigrationUser 1 Monday, February 24, 2003 11:42 AM might wanna look into it. Panel doesn't fire Enter or Leave...at least not for me. MigrationUser 1 Monday, February 24, 2003 4:59 PM Yah, that's why I mentioned the TabStop Property and noticed that the Panel doesn't have one. I'm not sure if the Panel can actually get focus itself. I believe only it's children can. But hey, I'm quite often wrong! ;) MigrationUser 1 Monday, February 24, 2003 5:11 PM Randy, can you be a little more crisp in defining your scenario? What exactly are you trying to do? Set focus to a control inside a Panel? Get a notification when a control inside a Panel recieves focus? thanks -mike MigrationUser 1 Monday, February 24, 2003 5:45 PM While Randy comes up with his post, I just thought of some neato focusing eye candy, that that would be great for...what's the event to use (or however we would need to do it) to be notified when any control inside a Panel gets focus or is that something you'd have to setup yourself by adding an event handler for each control as it's added to the panel? MigrationUser 1 Monday, February 24, 2003 5:48 PM well, let's say i have a custom control derived from Panel that works just like the collapsing panels in winXP explorer..and let's say i have two of them on a form, when i switch from one to another i need to be able to handle the Leave() [for example] event and see if anything inside the control has changed, and if it has, write out changes to a file or database or whatever..the real scenario is the same idea, but with about 10 or 15 of these controls, and I'd write a generic handler that tested the sender...this make sense? MigrationUser 1 Monday, February 24, 2003 5:55 PM I tried the following and saw consistent behavior. I have a Form with two Panels and two TextBoxes on each Panel. In the Panel's leave events I have: private void panel1_Leave(object sender, System.EventArgs e) { Debug.WriteLine("Panel1 Leave"); } private void panel2_Leave(object sender, System.EventArgs e) { Debug.WriteLine("Panel2 Leave"); } When run, and I tab through the 4 TextBoxes, I get the following output: Panel1 Leave Panel2 Leave Panel1 Leave Panel2 Leave Panel1 Leave ..... Is this not the behavior you are looking for? Are you seeing a bug in this area? If you can supply a simple repro, I'll look into it. thanks - mike MigrationUser 1 Tuesday, February 25, 2003 2:01 AM this is sort of the behavior im looking for..and this is how im doing it right now..but if they click in any area IN the panel im looking for it to raise the leave and enter's instead of them having to tab to or click into another control that is IN the panel...that make sense? ie: if i had 3 panels with nothing in them, and they clicked back and forth between those panels i'd want the events raised. MigrationUser 1 Tuesday, February 25, 2003 6:13 AM Ah. The problem is that the Panel doesn't raise Enter/Leave events unless some control within the panel can get the focus, and there's somewhere else on the form to put the focus. The Panel control acts as an "aggregator" for Enter and Leave events of all the controls within it--the event bubbles up to the parent level, as if in DHTML. It's not clear to me how any other behavior would be of any use, but FWIW, that's how it works by default. MigrationUser 1 Tuesday, February 25, 2003 8:54 AM Randy, from your problem description a few posts up, you said that you were looking for notification in order to do some validation on things that may have changed inside the Panel. If this is the case, shouldn't you have at least one control in there that the user can interact with, and therefore, have focus? If you don't have a control that can take focus in there, what could change that you'd need to do work based on? thanks - mike FWIW - you might want to also look at the Validating / Validated events. But I think they are closely tied to Enter and Leave for when they are raised MigrationUser 1 Wednesday, February 26, 2003 5:05 PM I did hack up my own version of the Panel class that allows it to get focus when there are no other controls in it. Maybe it is a start to what you want? Since Panel hides the Enter\Leave events from showing in the designer, they still are hidden so you will have to do your event hookup manually (or if you are using VB .NET, you can use the WithEvents and Handles keywords.) code: [ Designer("System.Windows.Forms.Design.PanelDesigner, System.Windows.Forms.Design.DLL" ) ] public class MyPanel : System.Windows.Forms.Panel { public MyPanel() { SetStyle(ControlStyles.Selectable, true); this.TabStop = true; } protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) { this.Focus(); base.OnMouseDown(e); } } thanks, Mark Rideout MigrationUser 1 Wednesday, February 26, 2003 5:22 PM thanks for the help mark, but here's a thought..is that going to force the control to focus and throw an Enter event everytime a user clicks? or just once? ...im not at home so i dont have vs.net to test that on.. Mike -- actually yes, originally when i posted that your solution would work..but heres another one (again im not near vs.net so i cant test this) but if you have two panels inside that panel, with controls on those panels and let's say a splitter in between them..would the Enter circulate all the way up to the top? but once i started thinking about it, in the XP style collapsing panel for example..the collapse/expand is drawn simply using DrawIcon() and checking the MouseDown to see if its "hot" ..there are situations where i might have an empty windowpane (eventually the class may support dragging and dropping items between panels, and they could possibly get all of the items off of a particular panel..) MigrationUser 1 Wednesday, February 26, 2003 8:54 PM First off, yes, nested controls should raise Enter and Leave events all the way up the parent hierarchy. If this isn't working for a given scenario, it is a bug. Secondly, in your drag scenario, you would want to hook the DragEnter event. Randy, at this point, there's just too much hype. You need to write this control and share it with the community. :) I promise we'll help you work through any eventing issues. - mike MigrationUser 1 Thursday, February 27, 2003 4:14 AM the control is actually already written..i've worked through most of the issues and i don't think there's any real problems i havent figured out. i'll have to wrap up the zip and post it up on the controls gallery... MigrationUser 1 Thursday, February 27, 2003 9:28 AM Just to note - the panel only fires the Enter the first time focus is either on the Panel, or on a control in the panel, and fires Leave when focus leaves the Panel (or any control contained in the Panel). So, you wouldn't get an Enter everytime a users clicks, unless after the click you set the focus back to something else. Basically it works like it normally would. Note also that my little test Panel code also supports tab-stop to the Panel whether it is empty or contains controls. This helps for keyboard accessibility. -Mark MigrationUser 1 Thursday, February 27, 2003 11:04 AM You can use google to search for other answers Custom Search More Threads Where does Windows.Forms implement the control property editor? Design mode repaint problem Databinding faults due to Generic class Changed event Help Need Power Point Rect Tracker Source Code in VC6 or VC7 Adding EDIT function to DATAGRID Rows VS 2008 error HRESULT 0x80042929 Designer: Value does not fall within expected range Creating Tree View in Datagrid in VB.Net 2005? Can't get inheritance or association to work in class designer (Visual Studio 2005 Standard Academic)
http://www.windowsdevelop.com/windows-forms-designer/is-there-any-way-to-force-a-control-to-receive-focus-14720.shtml
crawl-003
refinedweb
1,628
70.84
Collections have quite a few methods that construct new collections. Examples are map, filter or ++. We call such methods transformers because they take at least one collection as their receiver object and produce another collection as their result. There are two principal ways to implement transformers. One is strict, that is a new collection with all its elements is constructed as a result of the transformer. The other is non-strict or lazy, that is one constructs only a proxy for the result collection, and its elements get constructed only as one demands them. As an example of a non-strict transformer consider the following implementation of a lazy map operation: def lazyMap[T, U](coll: Iterable[T], f: T => U) = new Iterable[U] { def iterator = coll.iterator map f } Note that lazyMap constructs a new Iterable without stepping through all elements of the given collection coll. The given function f is instead applied to the elements of the new collection’s iterator as they are demanded. Scala collections are by default strict in all their transformers, except for Stream, which implements all its transformer methods lazily. However, there is a systematic way to turn every collection into a lazy one and vice versa, which is based on collection views. A view is a special kind of collection that represents some base collection, but implements all transformers lazily. To go from a collection to its view, you can use the view method on the collection. If xs is some collection, then xs.view is the same collection, but with all transformers implemented lazily. To get back from a view to a strict collection, you can use the force method. Let’s see an example. Say you have a vector of Ints over which you want to map two functions in succession: scala> val v = Vector(1 to 10: _*) v: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> v map (_ + 1) map (_ * 2) res5: scala.collection.immutable.Vector[Int] = Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22) In the last statement, the expression v map (_ + 1) constructs a new vector which is then transformed into a third vector by the second call to map (_ * 2). In many situations, constructing the intermediate result from the first call to map is a bit wasteful. In the example above, it would be faster to do a single map with the composition of the two functions (_ + 1) and (_ * 2). If you have the two functions available in the same place you can do this by hand. But quite often, successive transformations of a data structure are done in different program modules. Fusing those transformations would then undermine modularity. A more general way to avoid the intermediate results is by turning the vector first into a view, then applying all transformations to the view, and finally forcing the view to a vector: scala> (v.view map (_ + 1) map (_ * 2)).force res12: Seq[Int] = Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22) Let’s do this sequence of operations again, one by one: scala> val vv = v.view vv: scala.collection.SeqView[Int,Vector[Int]] = SeqView(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) The application v.view gives you a SeqView, i.e. a lazily evaluated Seq. The type SeqView has two type parameters. The first, Int, shows the type of the view’s elements. The second, Vector[Int] shows you the type constructor you get back when forcing the view. Applying the first map to the view gives: scala> vv map (_ + 1) res13: scala.collection.SeqView[Int,Seq[_]] = SeqViewM(...) The result of the map is a value that prints SeqViewM(...). This is in essence a wrapper that records the fact that a map with function (_ + 1) needs to be applied on the vector v. It does not apply that map until the view is forced, however. The “M” after SeqView is an indication that the view encapsulates a map operation. Other letters indicate other delayed operations. For instance “S” indicates a delayed slice operations, and “R” indicates a reverse. Let’s now apply the second map to the last result. scala> res13 map (_ * 2) res14: scala.collection.SeqView[Int,Seq[_]] = SeqViewMM(...) You now get a SeqView that contains two map operations, so it prints with a double “M”: SeqViewMM(...). Finally, forcing the last result gives: scala> res14.force res15: Seq[Int] = Vector(4, 6, 8, 10, 12, 14, 16, 18, 20, 22) Both stored functions get applied as part of the execution of the force operation and a new vector is constructed. some class requires quite a lot of code, so the Scala collection libraries provide views mostly only for general collection types, but not for specific implementations (An exception to this are arrays: Applying delayed operations on arrays will again give results with static type Array). There are two reasons why you might want to consider using views. The first is performance. You have seen that by switching a collection to a view the construction of intermediate results can be avoided. These savings can be quite important. As another example, consider the problem of finding the first palindrome in a list of words. A palindrome is a word which reads backwards the same as forwards. Here are the necessary definitions: def isPalindrome(x: String) = x == x.reverse def findPalidrome(s: Seq[String]) = s find isPalindrome Now, assume you have a very long sequence words and you want to find a palindrome in the first million words of that sequence. Can you re-use the definition of findPalidrome? Of course, you could write: findPalindrome(words take 1000000) This nicely separates the two aspects of taking the first million words of a sequence and finding a palindrome in it. But the downside is that it always constructs an intermediary sequence consisting of one million words, even if the first word of that sequence is already a palindrome. So potentially, 999’999 words are copied into the intermediary result without being inspected at all afterwards. Many programmers would give up here and write their own specialized version of finding palindromes in some given prefix of an argument sequence. But with views, you don’t have to. Simply write: findPalindrome(words.view take 1000000) This has the same nice separation of concerns, but instead of a sequence of a million elements it will only construct a single lightweight view object. This way, you do not need to choose between performance and modularity. The second use case applies to views over mutable sequences. Many transformer functions on such views provide a window into the original sequence that can then be used to update selectively some elements of that sequence. To see this in an example, let’s suppose you have an array arr: scala> val arr = (0 to 9).toArray arr: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) You can create a subwindow into that array by creating a slice of a view of arr: scala> val subarr = arr.view.slice(3, 6) subarr: scala.collection.mutable.IndexedSeqView[ Int,Array[Int]] = IndexedSeqViewS(...) This gives a view subarr which refers to the elements at positions 3 through 5 of the array arr. The view does not copy these elements, it just provides a reference to them. Now, assume you have a method that modifies some elements of a sequence. For instance, the following negate method would negate all elements of the sequence of integers it’s given: scala> def negate(xs: collection.mutable.Seq[Int]) = for (i <- 0 until xs.length) xs(i) = -xs(i) negate: (xs: scala.collection.mutable.Seq[Int])Unit Assume now you want to negate elements at positions 3 through five of the array arr. Can you use negate for this? Using a view, this is simple: scala> negate(subarr) scala> arr res4: Array[Int] = Array(0, 1, 2, -3, -4, -5, 6, 7, 8, 9) What happened here is that negate changed all elements of subarr, which was originally a slice of the array arr. Again, you see that views help in keeping things modular. The code above nicely separated the question of what index range to apply a method to from the question what method to apply. After having seen all these nifty uses of views you might wonder why have strict collections at all? One reason is that performance comparisons do not always favor lazy over strict collections. For smaller collection sizes the added overhead of forming and applying closures in views is often greater than the gain from avoiding the intermediary data structures. A probably more important reason is that evaluation in views can be very confusing if the delayed operations have side effects. Here’s an example which bit a few users of versions of Scala before 2.8. In these versions the Range type was lazy, so it behaved in effect like a view. People were trying to create a number of actors like this: val actors = for (i <- 1 to 10) yield actor { ... } They were surprised that none of the actors was executing afterwards, even though the actor method should create and start an actor from the code that’s enclosed in the braces following it. To explain why nothing happened, remember that the for expression above is equivalent to an application of map: val actors = (1 to 10) map (i => actor { ... }) Since previously the range produced by (1 to 10) behaved like a view, the result of the map was again a view. That is, no element was computed, and, consequently, no actor was created! Actors would have been created by forcing the range of the whole expression, but it’s far from obvious that this is what was required to make the actors do their work. To avoid surprises like this, the Scala 2.8 collections library has more regular rules. All collections except streams and views are strict. The only way to go from a strict to a lazy collection is via the view method. The only way to go back is via force. So the actors definition above would behave as expected in Scala 2.8 in that it would create and start 10 actors. To get back the surprising previous behavior, you’d have to add an explicit view method call: val actors = for (i <- (1 to 10).view) yield actor { ... } In summary, views are a powerful tool to reconcile concerns of efficiency with concerns of modularity. But in order not to be entangled in aspects of delayed evaluation, you should restrict views to two scenarios. Either you apply views in purely functional code where collection transformations do not have side effects. Or you apply them over mutable collections where all modifications are done explicitly. What’s best avoided is a mixture of views and operations that create new collections while also having side effects.blog comments powered by Disqus Contents
http://docs.scala-lang.org/overviews/collections/views.html
CC-MAIN-2017-04
refinedweb
1,844
63.7
Rails csv import with associations I am building a rails application that associates posts with many different categories. For example, I have a Post and need to be able to assign it to the categories Sports, News and Science through csv import via rake task. My question is how can I import an array of multiple category_ids into my Post model? I have it working where I can manually create a new Post and assign multiple categories to the post, but I am confused as to how to complete this through csv. I need help figuring out the best way to accomplish this. Here is what I have so far: Schema create_table "posts", force: :cascade do |t| t.string "name" t.text "description" end create_table "styles", force: :cascade do |t| t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "post_id" t.integer "category_id" end create_table "categories", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end Post.rb class Post < ApplicationRecord has_many :styles has_many :categories, through: :styles end Category.rb class Category < ApplicationRecord has_many :styles has_many :posts, through: :styles end Style.rb class Style < ApplicationRecord belongs_to :post belongs_to :category end Rake Task require 'csv' require 'open-uri' namespace :post_import do desc "Import posts daily" task posts: :environment do filename = File.join Rails.root, "posts.csv" counter = 0 CSV.foreach(filename) do |row| name, category, description = row post = Post.create(name: name, category_ids: category, description: description) counter += 1 if post.persisted? end puts "Imported #{counter} [posts]" end end Sup Ryan! 👍 for formatting the markdown perfectly. First off you'll need a join table to connect the two models. PostCategory can belongs_to :post and belongs_to :category and give you the ability for your post to has_many :categories, through: :post_categories. That will give you the ability to associate multiple categories to a post and reuse the categories on multiple posts. The next question, of course, is how does your CSV format the categories in it? You'll basically just want to split those up, and then do a Category.find() on them to grab the categories and you can say something like post.categories << Category.find_by(name: category_name) Thanks Chris, I have the join table created though my naming convention is not the most logical - I've called it styles rather than PostCategories. My csv formats the categories by ID. For example a row would look like "1,2,3" with 1, 2, 3 representing the category_ids of three unique categories. Can you give me an example of how to split them up and "do a Category.find() on them to grab the categories"? Here is what I have in my rake task: require 'csv' require 'open-uri' namespace :post_import do desc "Import posts daily" task posts: :environment do filename = File.join Rails.root, "posts.csv" counter = 0 CSV.foreach(filename) do |row| name, category, description = row post = Post.create(name: name, description: description) post.styles.build(category_id: category) counter += 1 if post.persisted? end puts "Imported #{counter} [posts]" end end This works, but only for the first category in the row. Categories 2 and 3 arent being assigned. Oh derp. I wasn't paying attention whatsoever. :) My bad! So if you've got the array of 1, 2, 3 and these match the ID column for your Category records, you can say category_ids = ids # if this is a comma separated string of ids, you'll need to split(",") it into an array instead categories = Category.where(id: category_ids) post.categories = categories This will automatically create the join records in the Styles table between the two and do it all in one batch because you'd be querying for the entire array of categories and then you can assign them using the association. Of course, this assumes the categories are already in the database as a caveat. Another thing to double check with this is to make sure that it's idemopotent, meaning if you import the same csv twice, it doesn't create duplicate categories per post. I'm not sure if assigning the categories like that will or not, but it's worth checking. I am able to split the ids into an array successfully - but somewhere in categories = Category.where(id: category_ids) post.categories = categories the output becomes quadruplicated and I dont understand why. I am using a csv with only one row of data for testing. Even when I remove multiple category ids and leave a single id, the output of post.categories is [1,1,1,1]. I dont think this is what you mean by idemoptent as this is a single csv imported once. here is the code that I am using for my rake due to my particular schema: a_categories = category_ids.split(",") categories = Style.where(category_id: a_categories) post.styles = categories Is there anything here that could cause the quadruplication? I'd toss a byebug in there and inspect each line to see what's causing it. Make sure a_categories is just an array of one item, then make sure categories is just an array of one Style, and so on. Also keep in mind that you changed to operate on the Join table where I was showing querying the Category table instead. The reason for that was the query can verify those Category records exist. Your code works differently than my example and needs to change a little if you do want to skip the verification that the Categories exist like mine did. It's okay to do that, but instead of doing a where query, you would want to just do something like this: a_categories.each do |category_id| post.styles.where(category_id: category_id).first_or_create end Note that this does not verify if a category ID is correct. If you put in say, category ID of 99999 and there was no Category record with that ID, you'll be inserting invalid data into the db. This might be fine, or it may be something you don't want, so I'd be careful with that. Thanks so much for the help Chris. I'm going to spend some time reviewing all of this but I was able to get it to work with the final code bit you shared. Here is my current (now working) rake file for those also looking for the solution : require 'csv' require 'open-uri' namespace :post_import do desc "Import posts daily" task posts: :environment do filename = File.join Rails.root, "posts.csv" counter = 0 CSV.foreach(filename) do |row| name, category_ids, description = row post = Post.new(name: name, description: description) if post == nil post.save #separate string of category ids into array a_categories = category_ids.split(",") a_categories.each do |category_id| post.styles.where(category_id: category_id).first_or_create end counter += 1 if post.persisted? end puts "Imported #{counter} [posts] end end
https://gorails.com/forum/rails-csv-import-with-associations
CC-MAIN-2020-34
refinedweb
1,138
58.08
How to email Plotly graphs in HTML reports with Python. In the Plotly Webapp you can share your graphs over email to your colleagues who are also Plotly members. If your making graphs periodically or automatically, e.g. in Python with a cron job, it can be helpful to also share the graphs that you're creating in an email to your team. This notebook is a primer on sending nice HTML emails with Plotly graphs in Python. We use: - Plotly for interactive, web native graphs - IPython Notebook to create this notebook, combining text, HTML, and Python code smtpliband # The public plotly graphs to include in the email. These can also be generated with `py.plot(figure, filename)` graphs = [ '', '', '', '' ] from IPython.display import display, HTML template = ('' '<a href="{graph_url}" target="_blank">' # Open the interactive graph when you click on the image '<img src="{graph_url}.png">' # Use the ".png" magic url so that the latest, most-up-to-date image is included '</a>' '{caption}' # Optional caption to include below the graph '<br>' # Line break '<a href="{graph_url}" style="color: rgb(190,190,190); text-decoration: none; font-weight: 200;" target="_blank">' 'Click to comment and see the interactive graph' # Direct readers to Plotly for commenting, interactive graph '</a>' '<br>' '<hr>' # horizontal line '') email_body = '' for graph in graphs: _ = template _ = _.format(graph_url=graph, caption='') email_body += _ display(HTML(email_body)) Looks pretty good! me = 'chris@plot.ly' recipient = 'chris@plot.ly' subject = 'Graph Report' email_server_host = 'smtp.gmail.com' port = 587 email_username = me email_password = 'xxxxx' Send the email import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import os msg = MIMEMultipart('alternative') msg['From'] = me msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(email_body, 'html')) server = smtplib.SMTP(email_server_host, port) server.ehlo() server.starttls() server.login(email_username, email_password) server.sendmail(me, recipient, msg.as_string()) server.close() Notes¶ Sharing Private Images¶ Plotly graphs are public by default. This means that they will appear on your profile, the plotly feed, google search results. To share private images in an email, make your graphs "secret". The graphs will be unlisted from your profile but will still be accessible by the email server via a direct link - no login authentication is required. Secret links have the form:<username>/<id>?share_key=<share_key>. Secret images have ".png" after "id" and before the "?". For example: This graph: Has the secret unlisted image url: The graph images¶ The HTML template that we used includes the images by their URL on the Plotly server. The viewers of the email must have permission on Plotly to view your graph. Graphs sent in emails by Plotly Enterprise users on private networks will not be able to be viewed outside of the network. The reader of your email will always see the latest verison of the graph! This is great - if you tweak your graph or add an annotation, you don't need to resend the email out. If your graph updates regularly, e.g. every hour, the reader will see the latest, most updated version of the chart. For some email clients, you can download the image and include it inline the email. This allows you to share the graph outside of your network with Plotly Enterprise, and keep the graph entirely private. Note that this is not widely supported. Here is the support from a few years ago: Here is how to embed images inline in HTML: import requests import base64 template = ('' '<img src="s">'{caption}' # Optional caption to include below the graph '<br>' '<hr>' '') email_body = '' for graph_url in graphs: response = requests.get(graph_url + '.png') # request Plotly for the image response.raise_for_status() image_bytes = response.content image = base64.b64encode(image_bytes) _ = template _ = _.format(image=image, caption='') email_body += _ display(HTML(email_body)) Alternatively, you can create the image on the fly, without a URL using py.image.get. (Learn more about py.image by calling help(py.image)) import plotly.plotly as py # A collection of Plotly graphs figures = [ {'data': [{'x': [1,2,3], 'y': [3,1,6]}], 'layout': {'title': 'the first graph'}}, {'data': [{'x': [1,2,3], 'y': [3,7,6], 'type': 'bar'}], 'layout': {'title': 'the second graph'}} ] # Generate their images using `py.image.get` images = [base64.b64encode(py.image.get(figure)) for figure in figures] email_body = '' for image in images: _ = template _ = _.format(image=image, caption='') email_body += _ display(HTML(email_body)) import plotly.plotly as py url = py.plot([{'x': [1,2,3], 'y': [3,1,6], 'type': 'bar'}], auto_open=False, filename='email-report-graph-1') print url
https://plot.ly/python/email-reports/
CC-MAIN-2017-43
refinedweb
756
59.09
Developing Root and Link Naming Standards Updated: March 28, 2003 Applies To: Windows Server 2003, Windows Server 2003 R2, Windows Server 2003 with SP1, Windows Server 2003 with SP2 When you roll out DFS, you have the opportunity to implement consistent namespace designs. Developing naming standards first — and ensuring that you adhere to the naming standards during implementation — makes it easier to use and manage any DFS namespace, both from a user perspective and an administrative perspective. Even if you do not expect to implement DFS until a later phase of your Windows Server 2003 deployment, it is important to begin thinking about namespace design early in the planning process. For an Excel spreadsheet to assist you in documenting your DFS namespace design decisions, see "DFS Configuration Worksheet" (Sdcfsv_1.xls) on the Windows Server 2003 Deployment Kit companion CD (or see "DFS Configuration Worksheet" on the Web at). Creating DFS Root Names A DFS root name, significant primarily to users, is the point beyond the server name or domain name that is at the top of the hierarchy of the logical namespace. Standardized and meaningful names at this level are very important, especially if you have more than one DFS namespace in a domain, because the DFS root name is where users enter the namespace. The contents of a DFS namespace must be as clear as possible to the users so that they do not follow the wrong path, possibly across expensive WAN connections, and have to backtrack. When creating the DFS root names for servers that will contain multiple roots, review the following restrictions: - Each root requires its own shared folder. - When you create a domain-based DFS root, the share name in the UNC path \\servername\sharename must be the same name as the DFS root name in \\domainname\rootname. For example, if you want to create a domain-based DFS root \\Reskit.com\Public on Server1, the UNC path to the shared folder must be \\Server1\Public. - A root cannot be nested within another root. For example, if C:\Root is a shared folder that uses the share name Public, and you use this shared folder as a stand-alone DFS root (\\servername\Public) or domain-based DFS root (\\domainname\Public), you cannot create another root in the folder C:\Root\Software. Similarly, if you create a root by using the root folder C:\, you cannot create another root at C:\Root. - On server clusters, do not create clustered DFS roots that have the same name as nonclustered DFS roots or shared folders. - Shared folders on domain controllers must not have the same name as any domain-based DFS roots in the domain. If they do, clients who try to access the shared folder on the domain controller are redirected to the domain-based DFS root. For example, if Reskit.com has a domain controller named DC1 that contains a shared folder named Tools (\\DC1\Tools), do not create a domain-based DFS namespace using a root named Tools (\\Reskit.com\Tools). Otherwise, when users attempt to access \\DC1\Tools, they are redirected to \\Reskit.com\Tools. Creating DFS Link Names A DFS link is a component in a DFS namespace that lies below the root and maps to one or more link targets. Because DFS link names are exposed to users, it is important to develop standardized, meaningful names for DFS links. Another important design goal is to develop a DFS namespace that provides intuitive navigation within the hierarchy that the namespace represents. Keep in mind that comments entered in the Distributed File System snap-in are not visible to users. For this reason, the namespace must be as clear as possible at all levels. Designing a clear naming scheme is even more important for a DFS namespace than for a physical namespace, because a user might jump to a shared folder on a different file server when he or she selects a link in the DFS namespace. As a result, a session has to be set up with that physical server (if one does not already exist), which might delay access. Therefore, you want to minimize the number of times that users traverse a wrong path. Clear and meaningful naming standards can help. Try to keep links at the same level in the DFS namespace consistent in context. For example, you probably would not want to have links named New York, Seattle, and Milan mixed with other links named Sales, Marketing, and Consulting. To help you create a consistent namespace, DFS supports adding one or more folder names to the link name so that you can create a meaningful hierarchy of link names. In the previous example, you could create links such as the following: - Branches\New York, Branches\Seattle, and Branches\Milan - Departments\Sales, Departments\Marketing, and Departments\Consulting When users browse this namespace, they will see a folder called Branches and another called Departments, which they can use to navigate to folders for branch offices (New York, Seattle, and Milan) and departments (Sales, Marketing, and Consulting). Note - If you want to encourage users to access the DFS namespace instead of going to individual servers, you can use a dollar sign ($) at the end of the shared folder name to hide it from casual browsers. The shared folder will still appear in the DFS namespace with the link name you specify. Doing so prevents users from accessing the shared folders by specifying individual server names. Instead, users must access the shared folders by using the namespace, which enables DFS to load share requests across multiple link targets and allows clients to be directed to another link target if the previously used target is unavailable.
https://technet.microsoft.com/en-us/library/cc776841(v=ws.10).aspx
CC-MAIN-2015-18
refinedweb
950
55.47
#include <wx/treebook.h> This class is an extension of the wxNotebook class that allows a tree structured set of pages to be shown in a control. A classic example is a netscape preferences dialog that shows a tree of preference sections on the left and select section page on the right. To use the class simply create it and populate with pages using InsertPage(), InsertSubPage(), AddPage(), AddSubPage(). If your tree is no more than 1 level in depth then you could simply use AddPage() and AddSubPage() to sequentially populate your tree by adding at every step a page or a subpage to the end of the tree. The following event handler macros redirect the events to member function handlers 'func' with prototypes like: Event macros for events emitted by this class: wxEVT_TREEBOOK_PAGE_CHANGEDevent. wxEVT_TREEBOOK_NODE_COLLAPSEDevent. wxEVT_TREEBOOK_NODE_EXPANDEDevent. Default constructor. Creates an empty wxTreebook. Destroys the wxTreebook object. Also deletes all the pages owned by the control (inserted previously into it). Adds a new page. The page is placed at the topmost level after all other pages. NULL could be specified for page to create an empty page. Reimplemented from wxBookCtrlBase. Adds a new child-page to the last top-level page. NULL could be specified for page to create an empty page. Shortcut for ExpandNode( pageId, false ). Creates a treebook control. See wxTreebook::wxTreebook() for the description of the parameters. Deletes the page at the specified position and all its children. Could trigger page selection change in a case when selected page is removed. In that case its parent is selected (or the next page if no parent). Reimplemented from wxBookCtrlBase. Expands (collapses) the pageId node. Returns the previous state. May generate page changing events (if selected page is under the collapsed branch, then its parent is autoselected). Returns the parent page of the given one or wxNOT_FOUND if this is a top-level page. Returns the currently selected page, or wxNOT_FOUND if none was selected. Implements wxBookCtrlBase. Inserts a new page just before the page indicated by pagePos. The new page is placed before pagePos page and on the same level. NULL could be specified for page to create an empty page. Implements wxBookCtrlBase. Inserts a sub page under the specified page. NULL could be specified for page to create an empty page. Returns true if the page represented by pageId is expanded.
https://docs.wxwidgets.org/trunk/classwx_treebook.html
CC-MAIN-2021-49
refinedweb
392
59.19
I am trying to use the Likes tutorial to create Favs for locations, which are nested under stores. Here is the relevant route section resources :stores do resources :locations do resource :favorite, module: :locations end end It should be noted I am using Friendly ID and that works for my stores and locations currently. Favoriting works however un-fav throws the following error. SQLite3::SQLException: no such column: favorites.: DELETE FROM "favorites" WHERE "favorites"."" = ? app/models/location.rb has_many :favorites has_many :users, :through => :favorites, :source => :user app/models/user.rb has_many :favorites has_many :locations, :through => :favorites, :source => :location I would real appreciate any help you could provide. Hmm, it looks like you've somehow got a bad query. When it says WHERE "favorites"."" there should be something inside those last two empty quotes. What does your action looks like? Here is favorites#destroy def destroy @location.favorites.where(user_id: current_user.id).destroy_all respond_to do |format| format.html {redirect_to store_location_path(@store, @location)} format.js end end That looks correct to me. You may want to run this in your Rails console to verify it is working outside of your action. I can't think of what would cause it to generate the WHERE without a column name there, but it has to be something revolving around your database, associations, or query. Another thing, have you verified that @location.favorites works correctly? When you hit the create, it makes the record correctly including the user_id? Chris, thanks for the quick replies! I open rails console and verified a favorite. Checked my user id, checked the location id, verified that location.first.favorites works showing the first user having a favorite of the first location. The interesting part is that I cannot delete a favorite in the console. I figured maybe I set up wrong originally so I Would delete all favorites and start fresh. Inside console: Favorites.all lists my favorites, but Favorites.destroy_all throws the exact same error as the site SQLite3::SQLException: no such column: favorites.: DELETE FROM "favorites" WHERE "favorites"."" = ? Would you mind double checking my relationships included in the initial post, this relationship setup is something I have never used before, specifically the "source" portions. Google searches turned up a lot of solutions resulting in correcting relationship setup. Also here is my *schema.rb. Figured this may be beneficial as the last error would make me think its some sort of database issue. This seems very straight forward to me though. create_table "favorites", id: false, force: true do |t| t.integer "user_id" t.integer "location_id" end add_index "favorites", ["location_id"], name: "index_favorites_on_location_id" add_index "favorites", ["user_id"], name: "index_favorites_on_user_id" Also final thought: Where should the favorite model be located? This route setup where using favorites as a module is also new for me. Currently, this file is located in app/models/favorites should this be inside a locations folder? Thanks I really appreciate your help especially considering its a weekend. Always happy to help! :) Plus, weekends are when I record screencasts anyways. When you use a route module, it just means to put the controller in a folder of that name. If you say module: :locations then it will look in app/controllers/locations for the favorites_controller.rb file. It doesn't affect your models at all. The thing here I noticed is that you have create_table without an ID column. That could be affecting the query. It shouldn't matter, but Rails usually wants a primary key to look up the records quickly. Try generating the table again with the ID column and see what happens. Another possibility is you might try generating the model named singularly instead as "Favorite" instead of "Favorites". That is also something that Rails often wants a certain way and deviating can cause it to do some unexpected things once in a while. Regenerating the table with ID fixed this issue. THANKS! I could have sworn I read somewhere that was the best way to create join tables, clearly it causes issue though. Also for clarity, my model is favorite, the "s" was a typo. Thanks again!!! Really appreciate it. I really enjoy your tutorials, please keep them coming! Haha! Glad it's working for you. I think you're right about the join table not needing a primary key, but I think when you do that in Rails, it assumes you don't create a model for it. Since we're interacting with that join table a bit differently than normal, it seems like it probably is a good case to have it. In general, a ID column doesn't really add any noticeable overhead to your database, so you don't have to worry about that in the future. Join 24,647+ developers who get early access to new screencasts, articles, guides, updates, and more.
https://gorails.com/forum/likes-routing-error
CC-MAIN-2019-43
refinedweb
802
58.99
The documentation you are viewing is for Dapr v1.4 which is an older version of Dapr. For up-to-date documentation, see the latest version. Cron binding spec Component format To setup cron binding create a component of type bindings.cron. See this guide on how to create and apply a binding configuration. apiVersion: dapr.io/v1alpha1 kind: Component metadata: name: <NAME> namespace: <NAMESPACE> spec: type: bindings.cron version: v1 metadata: - name: schedule value: "@every 15m" # valid cron schedule Spec metadata fields Schedule Format The Dapr cron binding supports following formats: For example: 30 * * * * *- every 30 seconds 0 15 * * * *- every 15 minutes 0 30 3-6,20-23 * * *- every hour on the half hour in the range 3-6am, 8-11pm CRON_TZ=America/New_York 0 30 04 * * *- every day at 4:30am New York time You can learn more about cron and the supported formats here For ease of use, the Dapr cron binding also supports few shortcuts: @every 15swhere sis seconds, mminutes, and hhours @dailyor @hourlywhich runs at that period from the time the binding is initialized. Binding support This component supports both input and output binding interfaces. This component supports output binding with the following operations: delete.
https://v1-4.docs.dapr.io/reference/components-reference/supported-bindings/cron/
CC-MAIN-2021-49
refinedweb
200
50.57
tw.recaptcha is an extension to tw.forms TextField with a formencode validator. It keeps a form from being processed until there is proof that the form is being used by a human by forcing the human to analyze an image and type in the words that are shown. It also has an audio clip you can listen to instead. tw.recaptcha is good because like ReCaptcha the words you analyze are words that are scanned from old books that are being digitized. The books are free and anyone can download and read them. What happens is when the book is scanned it is broken up by word and those words are what is used in ReCaptcha. Since a scanner is not perfect and sometimes interprets the words incorrectly, the human answers the ReCaptcha sends back help to make the digital copies as accurate as possible and thus a pleasant experience for everyone. easy_install tw.recaptcha If you have problems there is a way to manually get ReCaptcha working: often recaptcha-client does not install properly: Download and install recaptcha-client on its own first. If you want to try it all in one command using easy_install then you could try this (just doing _easy_install_ _’recaptcha-client’_ sometimes gives a broken egg): easy_install recaptcha-client If you get a broken egg download manually and install using the available setup.py: curl -O tar -xvf recaptcha-client-1.0.1.tar.gz cd recaptcha-client-1.0.1 python setup.py install Now try easy_installing tw.recaptcha again First things first. Goto the ReCaptcha website and register your domain. It is free. Once that is done we can move onto the actual coding aspect. The first step is to make sure you have all of the imports that you need. If you are already using forms and/or validation you may already have some of these: from tw.forms import TableForm from tw.recaptcha import ReCaptchaWidget from tw.recaptcha.validator import ReCaptchaValidator from tw.api import WidgetsList from formencode import Schema, NoDefault from formencode.validators import NotEmpty Create a new Form to hold your recaptcha: class MyForm(TableForm): class fields(WidgetsList): recaptcha_response_field = ReCaptchaWidget(public_key='<your_public_key>') Of course, we are going to need a validator, and since there are extra fields appended with the recaptcha widget, we are going to need a filtering schema to address the extra fields. Alright, now with that done you need to setup your filtering schema class: class FilteringSchema(Schema): filter_extra_fields = False allow_extra_fields = True ignore_key_missing = False Add the recaptcha validator to the list of chained validators for your form: validator = FilteringSchema(chained_validators=(ReCaptchaValidator(private_key='<your_private_key', remote_ip='<your_domains_ip_address'),)) The next step is to create an instance of the form to pass into your page: captchaForm = MyForm(validator=validator) That takes care of the creation process. It should now load and work on your page. Make sure the function that it goes to when you hit submit is expecting the two variables. If you are using **kw then you are fine. If you are specifying each one individually, then you will want to add the two variables into your definition. If you don’t, it will error saying it got values it wasn’t expecting. Your code might look something like this: class MyController(BaseController): @expose("genshi:my.page.with.form.def") def showForm(self, **kw): pylons.c.form = captchaForm return dict(values=kw) @validate(captchaForm, error_handler=showForm) def storeFormData(self, myvar, myvar2, recaptcha_response_field=None, recaptcha_challenge_field=None): """My form storage code here""" return dict() Once you are done you will end up with a captcha on your page that looks like
http://www.turbogears.org/2.1/docs/main/ToscaWidgets/Cookbook/ReCaptcha.html
CC-MAIN-2016-40
refinedweb
604
55.24
Hi Matt, Looks like your browser doesn't recognize the document as HTML. Try to set the Content-Type header of the response : def hello(req, name=''): s = 'Hello, there!' if name: s = 'Hello, %s!' % name.capitalize() # Here it is req.content_type = 'text/html' tmpl = psp.PSP(req, filename='hello.tmpl') tmpl.run(vars = { 'greet': s }) return Regards, Nicolas 2005/11/22, Matt Shaw <matt.shaw at elanit.co.uk>: > > I have been playing with Python for making a web project, mainly to learn > the Python language and realised that the most painful part of it all was > not the Python at all but the CGI, so found MOD_PYTHON and am going to use > this as seems perfect. However when following the example below, it outputs > to the browser as plain text with all the tags shown and not as tho its > HTML, I'm using the Ubuntu 5.10. Oddly enough it does actually swap out the > variable, so it is kinda working :-) Any help would be appreciated. > > > > > > - > --------------------------------------------------------------------- >. > > _______________________________________________ > Mod_python mailing list > Mod_python at modpython.org > > > >
http://modpython.org/pipermail/mod_python/2005-November/019570.html
CC-MAIN-2018-39
refinedweb
177
73.88
Synopsis_11 - Modules Larry Wall <larry@wall.org> Maintainer: Larry Wall <larry@wall.org> Date: 27 Oct 2004 Last Modified: 26 Feb 2008 Number: 11 Version: 24 This synopsis discusses those portions of Apocalypse 12 that ought to have been in Apocalypse 11. As in Perl�5, a module is just a kind of package. Unlike in Perl�5, modules and classes are declared with separate keywords, but they're still just packages with extra behaviors. A module is declared with the module keyword. There are two basic declaration syntaxes: module Foo; # rest of scope is in module Foo ... module Bar {...} # block is in module Bar The first form is allowed only as the first statement in the file. A named module declaration can occur as part of an expression, just like named subroutine declarations. Since there are no barewords in Perl�6, module names must be predeclared, or use the sigil-like ::ModuleName syntax. The :: prefix does not imply top-levelness as it does in Perl�5. (Use ::* or GLOBAL:: for that.) A bare (unscoped) module declarator declares a nested our module name within the current package. However, at the start of the file, the current package is *, so the first such declaration in the file is automatically global. You can use our module to explicitly declare a module in the current package (or module, or class). To declare a lexically scoped module, use my module. Module names are always searched for from innermost scopes to outermost. As with an initial ::, the presence of a :: within the name does not imply globalness (unlike in Perl�5). The ::* namespace is not "main". The default namespace for the main program is ::*Main, which it switches to from * as soon as it sees the first declaration, if that declaration doesn't set the package name. (Putting module Main; at the top of your program is redundant, except insofar as it tells Perl that the code is Perl 6 code and not Perl�5 code. But it's better to say "use v6" for that.) But note that if you say use v6; module Foo {...} you've just created Main::Foo, not *Foo. Module traits are set using is: module Foo is bar {...} Exportation is now done by trait declaration on the exportable item: module Foo; # Tagset... sub foo is export(:DEFAULT) {...} # :DEFAULT, :ALL sub bar is export(:DEFAULT :others) {...} # :DEFAULT, :ALL, :others sub baz is export(:MANDATORY) {...} # (always exported) sub bop is export {...} # :ALL sub qux is export(:others) {...} # :ALL, :others Declarations marked as is export are bound into the EXPORT inner modules, with their tagsets as inner module names within it. For example, the sub bar above will bind as &Foo::EXPORT::DEFAULT::bar, &Foo::EXPORT::ALL::bar, and &Foo::EXPORT::others::bar. Tagset names consisting entirely of capitals are reserved for Perl. Inner modules automatically add their export list to modules in all their outer scopes: module Foo { sub foo is export {...} module Bar { sub bar is export {...} module Baz { sub baz is export {...} } } } The Foo module will export &foo, &bar and &baz by default; calling Foo::Bar.EXPORTALL will export &bar and &baz at runtime to the caller's package. Any proto declaration that is not declared "my" is exported by default. Any multi that depends on an exported proto is also automatically exported. When there is no proto for a multi, the autogenerated proto is assumed to be exportable. The default EXPORTALL handles symbol exports by removing recognized export items and tagsets from the argument list, then calls the EXPORT subroutine in that module (if there is one), passing in the remaining arguments. If the exporting module is actually a class, EXPORTALL will invoke its EXPORT method with the class itself as the invocant. Importing via use binds into the current lexical scope by default (rather than the current package, as in Perl�5). use Sense <common @horse>; You can be explicit about the desired namespace: use Sense :MY<common> :OUR<@horse> :GLOBAL<$warming>; That's pretty much equivalent to: use Sense; my &common ::= &Sense::common; our @horse ::= @Sense::horse; $*warming ::= $Sense::warming;, the module may also specify a different scoping default by use of :MY or :OUR tags as arguments to is export. (Of course, mixing incompatible scoping in different scopes is likely to lead to confusion.) Importing via require also installs names into the current lexical scope by default, but delays the actual binding till runtime: require Sense <common @horse>; require "/home/non/Sense.pm" <common @horse>; Only explicitly mentioned names may be so installed..) You may also import symbols from the various pseudo-packages listed in S02. They behave as if all their symbols are in the :ALL export list: use GLOBAL <$IN $OUT $ERR>; require CALLER <$x $y>; # Same as: # my ($IN, $OUT, $ERR) ::= ($*IN, $*OUT, $*ERR) # my ($x, $y) := ($CALLER::x, $CALLER::y) As pseudo-packages are always already preloaded, use and require will never attempt to load, for example, GLOBAL.pm from an external source. When at the top of a file you say something like module Cat; or class Dog; you're really only giving one part of the name of the module. The full name of the module or class includes other metadata, in particular, the version, and the author. Modules posted to CPAN or entered into any standard Perl�6 library are required to declare their full name so that installations can know where to keep them, such that multiple versions by different authors can coexist, all of them available to any installed version of Perl. (When we say "modules" here we don't mean only modules declared with the module declarator, but also classes, roles, grammars, etc.)�5 library policy is notably lacking here; it would induce massive breakage even to change Perl�5 to make strictness the default.) If a CPAN. The syntax of a versioned module or class declaration has multiple parts in which the non-identifier parts are specified in adverbial pair notation without intervening spaces. Internally these are stored in a canonical string form which you should ignore. You may write the various parts in any order, except that the bare identifer must come first. The required parts for library insertion are the short name of the class/module, its version number, and a URI identifying the author (or authorizing authority, so we call it "auth" to be intentionally ambiguous). For example: class Dog:ver<1.2.1>:auth<cpan:JRANDOM>; class Dog:ver<1.2.1>:auth<>; class Dog:ver<1.2.1>:auth<mailto:jrandom@some.com>; Since these are somewhat unweildy to look at, we allow a shorthand in which a bare subscripty adverb interprets its elements according to their form: class Dog:<1.2.1 cpan:JRANDOM> The pieces are interpreted as follows: [<ident> '::']* <ident>is treated as a package name v? [\d+ '.']* \d+is treated as a version number <alpha>+ \: \S+is treated as an author(ity) These declarations automatically alias the full name of the class (or module) to the short name. So for the rest of the lexical scope, Dog refers to the longer name. The real library name can be specified separately as another adverb, in which case the identifier indicates only the alias within the current lexical scope: class Pooch:name<Dog>:ver<1.2.1>:auth<cpan:JRANDOM> or class Pooch:<Dog 1.2.1 cpan:JRANDOM> for short. Here the real name of the module starts Dog, but we refer to it as Pooch for the rest of this file. Aliasing is handy if you need to interface to more than one module named Dog If there are extra classes or modules or packages declared within the same file, they implicitly have a long name including the file's version and author, but you needn't declare them again. Since these long names are the actual names of the classes as far as the library system is concerned, when you say: use Dog; you're really wildcarding the unspecified bits: use Dog:ver(Any):auth(Any); And when you say: use Dog:<1.2.1>; you're really asking for: use Dog:ver<1.2.1>:auth(Any); Saying 1.2.1 specifies an exact match on that part of the version number, not a minimum match. To match more than one version, put a range operator as a selector in parens: use Dog:ver(1.2.1..1.2.3); use Dog:ver(1.2.1..^1.3); use Dog:ver(1�6.. :-) To allow a version specification that works with both Perl�5 and Perl�6, we use variants of the "v6" pseudomodule. This form specifically allows use of a subsequent hyphenated identifier. Before the full specification of Perl�6.0.0 is released, you can use alpha to denote a program using syntax that is still subject to change: use v6-alpha; Later on use v6-std; will indicate standard version 6 of Perl. The use v6-alpha line also serves as the Perl�5 incantation to switch to Perl�6 parsing. In Perl�5 this actually ends up calling the v6.pm module with a -alpha argument, for insane-but-useful reasons. For wildcards any valid smartmatch selector works: use Dog:ver(1.2.1 | 1.3.4):auth(/:i jrandom/); use Dog:ver(Any):auth({ .substr(0,5) eq >:ver<1.12>:auth<cpan:DCONWAY>; use Whiteness:from<perl5 Acme::Bleach 1.12 cpan:DCONWAY>; # modules in your program require two different versions of the same module, Perl will simply load both versions at the same time. For modules that do not manage exclusive resources, the only penalty for this is memory, and the disk space in the library to hold both the old and new versions. For modules that do manage an exclusive resource, such as a database handle, there are two approaches short of requiring the user to upgrade. The first is simply to refactor the module into a stable supplier of the exclusive resource that doesn't change version often, and then the outer wrappers of that resource can both be loaded and use the same supplier of the resource. The other approach is for the module. To declare that a module emulates an older version, declare it like this: class Dog:<1.2.1 cpan:JRANDOM> emulates :<1.2.0>; Or to simply exclude use of the older module and (presumably) force the user to upgrade: class Dog:<1.2.1 cpan:JRANDOM> excludes :<1.2.0>; The name is parsed like a use wildcard, and you can have more than one, so you can say things like: class Dog:<1.2.1 cpan:JRANDOM> emulates Dog:auth(DCONWAY|JCONWAY|TCONWAY):ver<1.0+> excludes Fox:<3.14159> emulates Wolf:from<C# 0.8..^1.0>; To get Perl�6 parsing rather than the default Perl�5 parsing, we said you could force Perl�6 mode in your main program with: use v6-alpha; Actually, if you're running a parser that is aware of Perl�6, you can just start your main program with any of: use v6; module; class; Those all specify the latest Perl�6 semantics, and are equivalent to use Perl:ver(v6..*):auth(Any); To lock the semantics to 6.0.0, say one of: use Perl:ver<6.0.0>; use :<6.0.0>; use v6.0.0; In any of those cases, strictures and warnings are the default in your main program. But if you start your program with a bare version number or other literal: v6.0.0; v6; 6; "Coolness, dude!"; it runs Perl�6 in "lax" mode, without strictures or warnings, since obviously a bare literal in a void context ought to have produced a warning. (Invoking perl with -e6 has the same effect.) In the other direction, to inline Perl�5 code inside a Perl�6 program, put use v5 at the beginning of a lexical block. Such blocks can nest arbitrarily deeply to switch between Perl versions: use v6-std; # ...some Perl 6 code... { use v5; # ...some Perl 5 code... { use v6-std; # ...more Perl 6 code... } } It's not necessary to force Perl�6 if the interpreter or command specified already implies it, such as use of a " #!/usr/bin/perl6" shebang line. Nor is it necessary to force Perl�6 in any file that begins with the "class" or "module" module. module) code as you like; however, all imports of language tweaks from the official library must specify the exact interface version of the module. Such officially installed interface versions must be considered immutable on the language level, so that once any language-tweaking module module directly, or the tool can proceed in ignorance. As an intermediate position, if the tool does not actually care about running the code, the tool need not actually have the complete module in question; many language tweaks could be stored in a database of interface versions, so if the tool merely knows the nature of the language tweak on the basis of the interface version it may well be able to proceed with perfect knowledge. A module that uses a well-behaved macro or two could be fairly easily emulated based on the version info alone. But more realistically, in the absence of such a hypothetical database, most systems already come with a kind of database for modules that have already been installed. So perhaps the most common case is that you have downloaded an older version of the same module, in which case the tool can know from the interface version whether that older module represesents the language tweak sufficiently well that your tool can use the interface definition from that module without bothering to download the latest patch. Note that most class modules do no language tweaking, and in any case cannot perform language tweaks unless these are explicitly exported. Modules that export multis are technically language tweaks on the semantic level, but as long as those new definitions modify semantics within the existing grammar (by avoiding the definition of new macros or operators), they do not fall into the language tweak category. Modules that export new operators or macros are always considered language tweaks. (Unexported macros or operators intended only for internal use of the module itself do not count as language tweaks.) The requirement for immutable interfaces extends transitively to any modules imported by a language tweak module. There can be no indeterminacy in the language definition either directly or indirectly. It must be possible for any official module to be separately compiled without knowledge of the.
http://search.cpan.org/~lichtkind/Perl6-Doc/lib/Perl6/Doc/Design/S11.pod
CC-MAIN-2016-40
refinedweb
2,436
63.49
ATOL(3P) POSIX Programmer's Manual ATOL(3P) This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. atol, atoll — convert a string to a long integer #include <stdlib.h> long atol(const char *str); long long atoll(const char *nptr); The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard. The call atol(str) shall be equivalent to: strtol(str, (char **)NULL, 10) The call atoll(nptr) shall be equivalent to: strtoll(nptr, (char **)NULL, 10) except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined. These functions shall return the converted value if the value can be represented. No errors are defined. The following sections are informative. None. The atol() function is subsumed by strtol() but is retained because it is used extensively in existing code. If the number is not known to be in range, strtol() should be used because atol() is not required to perform any error checking. None. None. ATOL(3P) Pages that refer to this page: stdlib.h(0p)
http://man7.org/linux/man-pages/man3/atol.3p.html
CC-MAIN-2019-22
refinedweb
232
56.86
5.4.1. Built-in bridges Hibernate Search comes bundled with a set of built-in bridges between a Java property type and its full text representation. Null elements are not indexed (Lucene does not support null elements and it does not make much sense either) null elements are not indexed. Lucene does not support null elements and this does not make much sense either. String are indexed as is Numbers are converted in their String representation. Note that numbers cannot be compared by Lucene (ie used in ranged queries) out of the box: they have to be padded [1] DateRange Query, you should know that the dates have to be expressed in GMT time. Usually, storing the date up to the milisecond is not necessary. @DateBridge defines the appropriate resolution you are willing to store in the index ( ). The date pattern will then be truncated accordingly. @DateBridge(resolution=Resolution.DAY) @Entity @Indexed public class Meeting { @Field(index=Index.UN_TOKENIZED) @DateBridge(resolution=Resolution.MINUTE) private Date date; ... } A Date whose resolution is lower than MILLISECOND cannot be a @DocumentId
http://www.redhat.com/docs/manuals/jboss/jboss-eap-4.3/doc/hibernate/Annotations_Reference_Guide/PropertyField_Bridge-Built_in_bridges.html
crawl-001
refinedweb
179
56.15
errno - XSI error return value #include <errno.h> errno is used by many XSI functions to return error values. Many functions provide an error number in errno which has type int and is defined in <errno.h>. The value of errno will be defined only after a call to a function for which it is explicitly stated to be set and until it is changed by the next function call. The value of errno should only be examined when it is indicated to be valid by a function's return value. Programs should obtain the definition of errno by the inclusion of <errno.h>. The practice of defining errno in a program as extern int errno is obsolescent. No function in this specification sets errno to 0 to indicate an error. It is unspecified whether errno is a macro or an identifier declared with external linkage. If a macro definition is suppressed in order to access an actual object, or a program defines an identifier with the name errno, the behaviour. A program that uses errno for error checking should set it to 0 before a function call, then inspect it before a subsequent function call. None. <errno.h>, errors. Derived from Issue 1 of the SVID.
http://pubs.opengroup.org/onlinepubs/007908775/xsh/errno.html
CC-MAIN-2013-20
refinedweb
207
54.42
User Name: Published: 17 Jul 2009 By: Karl Seguin The power of threads lie in their ability to share information - but two threads accessing the same information at the same time can have devastating effects. Depending on what you're trying to accomplish with threads, you may have to worry about two or more threads trying to access the same memory. At first, that might seem like an edge-case, especially if you're looking at threads for simple or isolated situations - such as unblocking the UI or a specific long-running query. However, as you move more and more of your execution pipeline into a multi-threaded paradigm, a growing number of resources will need to be shared across multiple threads. We'll examine two mechanisms that can help solve this problem: mutual exclusion and atomic operations. How serious is it when two threads access the same resources? In some cases it'll be benign, in others completely catastrophic. It depends on what you are trying to do - and whether or not the objects and methods you are using are inherently thread-safe. First though, understand that when you call a method, say Add on an List, multiple operations are actually executed. First, Add itself is written in .NET and composed of a handful of lines of C# code. This code is then compiled into multiple lines of intermediate language and again into many lines of assembly. This abstraction makes programming much easier, but also much more deceptive. How does this relate to multi-threaded programming? At any point during the execution of Add, the executing thread can be interrupted and another thread given priority. This could leave the List is an unpredictable state. This is the line of code that actually adds the item to the list: Add List Add List Don't let the fact that all this happens on a single line fool you. The executing thread could be put to sleep after incrementing the size field. If another thread then accessed size, say by calling Count, you'd likely end up with a NullReferenceException in your code as you tried to access an item which didn't yet exist in the list. size size Count NullReferenceException Essentially, what we're talking about here is atomicity. An atomic operation is one that cannot be interrupted and will either succeed or fail. As you start to do more multi-threaded programming you'll quickly learn that the vast majority of methods in .NET aren't atomic. As such, you need to know what is and isn't thread-safe. Luckily, the MSDN consistently documents the thread-safety of each class and method. If we look at the documentation for the List<T> class, we'll find a section named "Thread Safety", which states: List<T>. The primary way to turn thread-unsafe code into thread-safe code is to lock access to shared variables as you use them. There are many ways to lock code, but they all do the same thing: give you control over how many threads execute a given piece of code. For what we'll look at, we'll always give one thread exclusive access, but know that, if you have to, you can give multiple threads access. The simplest example we can consider is a counter which tracks the number of hits to our website. Our implementation will simply rely on a static integer counter which we'll increment whenever our application's BeginRequest method fires (in global.asax.cs). Our first version is as simple as possible Despite the elegant simplicity, the above code won't cut it - multiple threads can execute BeginRequest at the same time, thus trying to increment _hitCount at the same time. Unfortunately, the pre-increment (++) operator isn't thread safe which means we'll get some unexpected results. What we need to do is synchronize access to our variable. This can be accomplished in many ways, the most common being with the use of Monitor.Enter and Monitor.Exist methods (found in the System.Threading namespace): BeginRequest hitCount Monitor.Enter Monitor.Exist System.Threading Before we examine the above code, let's leverage the C# lock statement which provides a more convenient syntax to the above code (much like the using statement does). The following code compiles into the above: lock using (VB.NET users should look at the SyncLock statement) SyncLock The above code create an exclusive lock on a static object (statics are shared across all threads). Locking is an atomic operation and only 1 thread can hold the lock. Since unlocking happens within a finally you don't need to worry about exceptions causing your locks to be held forever. If you want to learn more about why we lock on a static object, check out:. Without question, locking is something that you'll end up having to do a lot of when doing multi-threaded programming, which means you need to be skilled at avoiding some of the very real and very dangerous risks associated with it. First and foremost, remember that our goal with multithreaded programming is to improve performance and scalability; however, locking does the exact opposite - it serializes access to our code. Therefore, the most important thing you must do is carefully review the code being locked and, as much as possible, minimize it. For example, say we want to celebrate our 1000000 hit, we might be tempted to do something like: But we could tweak it slightly to reduce the time spent in our lock: This may seem like an overly simplistic example, but it shows how locally scoped members can be used to reduce lock durations. Oftentimes, you'll have to give a lot more thought to what has to and shouldn't be locked. The other danger to look out for when locking are deadlocks. If you have multiple locks on multiple objects, it's possible to completely freeze your code. For example, imagine something like: Things can get nasty if a thread acquires a lock on _lockB while another thread acquires a lock on _lockA. Each thread will be blocked, waiting forever for each other to release their respective locks. The only solution to such code is to rearrange the code to remove the possible deadlock. _lockB _lockA It is possible to write multi-threaded code without the use of locks. Such an approach generally revolve around the use of atomic operation. If an operation is guaranteed to execute atomically at the CPU level then we don't need to worry about locking exclusive access to our resources. For example, our hit counter could leverage .NET's Interlock class which is used specifically for atomic operations: We haven't talked much about it, but most of the multithreaded locking you'll end up doing will be around collection operations (adding items to queues, removing them, peeking, and getting counts). The simplest approach is to lock the SyncRoot property of the collection itself before any operations: SyncRoot (The .NET framework has some built-in collection which are thread-safe (using the above method)). Depending on what you are doing, the above code might not scale well and prove to be a serious bottleneck for your entire system. A solution might be to use lock-free collections. One of the better (and free) set of lock-free collections is from Julian Bucknall. His collections leverage the CPU's Compare and Swap instruction. If you are interested, I suggest you check out his blog for more details (as well as a link to download his code). It's worth pointing out that .NET 4.0 has a System.Collections.Concurrent namespace which will ease some of grunt work we must deal with (although reviews of the beta suggest that they use locks making them unsuitable for high throughput systems). System.Collections.Concurrent In this part we covered the foundations of multi-threading programming, namely locking and lock-free operations. We also looked at some of the common locking pitfalls, which can easily bring a system to its knees (either by serializing access or creating deadlocks). Be warned that multi-threading programming is an advanced topic highly dependent on exactly what it is you are doing, and even on what type of system you are doing it.
http://dotnetslackers.com/articles/net/Multithreading-Programming-Primer-Part2.aspx
crawl-003
refinedweb
1,388
61.36
JavaScript Style Guide and Coding Conventions we use camelCase for identifier names (variables and functions). All names start with a letter. At the bottom of this page, you will find a wider discussion about naming rules. lastName = "Doe"; price = 19.90; tax = 0.20; fullPrice = price + (price * tax); Spaces Around Operators Always put spaces around operators ( = + - * / ), and after commas: Examples: var values = ["Volvo", "Saab", "Fiat"]; Code Indentation Always use 4 spaces for indentation of code blocks: Functions: return (5 / 9) * (fahrenheit - 32); } Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently. Statement Rules General rules for simple statements: - Always end a simple statement with a semicolon. Examples: var person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; General rules for complex (compound) statements: - Put the opening bracket at the end of the first line. - Use one space before the opening bracket. - Put the closing bracket on a new line, without leading spaces. - Do not end a complex statement with a semicolon. Functions: return (5 / 9) * (fahrenheit - 32); } Loops: x += i; } Conditionals: greeting = "Good day"; } else { greeting = "Good evening"; } Object Rules General rules for object definitions: - Place the opening bracket on the same line as the object name. - Use colon plus one space between each property and its value. - Use quotes around string values, not around numeric values. - Do not add a comma after the last property-value pair. - Place the closing bracket on a new line, without leading spaces. - Always end an object definition with a semicolon. Example firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; Short objects can be written compressed, on one line, using spaces only between properties, like this: Line Length < 80 For readability, avoid lines longer than 80 characters. If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or a comma. Example "Hello Dolly."; Naming Conventions Always use the same naming convention for all your code. For example: - Variable and function names written as camelCase - Global variables written in UPPERCASE (We don't, but it's quite common) - Constants (like PI) written in UPPERCASE Should you use hyp-hens, camelCase, or under_scores in variable names? This is a question programmers often discuss. The answer depends on who you ask: Hyphens in HTML and CSS: HTML5 attributes can start with data- (data-quantity, data-price). CSS uses hyphens in property-names (font-size).: var obj = getElementById("demo") If possible, use the same naming convention (as JavaScript) in HTML. Visit the HTML Style Guide. File Extensions HTML files should have a .html extension (not .htm). CSS files should have a .css extension. JavaScript files should have a .js extension. can break your web site. To avoid these problems, always use lower case file names (if possible). Performance Coding conventions are not used by computers. Most rules have little impact on the execution of programs. Indentation and extra spaces are not significant in small scripts. For code in development, readability should be preferred. Larger production scripts should be minified.
https://www.w3schools.com/js/js_conventions.asp
CC-MAIN-2018-47
refinedweb
504
67.15
This action might not be possible to undo. Are you sure you want to continue? K. D. Irani Morris Silver Editors GREENWOOD PRESS Social Justice in the Ancient World Recent Titles in Global Perspectives in History and Politics United States Foreign Policy at the Crossroads George Schwab, editor The Press and the Rebirth of Iberian Democracy Kenneth Maxwell, editor Macro-Nationalisms: A History of the Pan-Movements Louis L. Snyder The Myth of Inevitable Progress Franco Ferrarotti Power and Policy in Transition: Essays Presented on the Tenth Anniversary of the National Committee on American Foreign Policy in Honor of its Founder, Hans J. Morgenthau Vojtech Mastny, editor Perforated Sovereignties and International Relations: Trans-Sovereign Contacts of Subnational Governments Ivo D. Duchacek, Daniel Latouche, and Garth Stevenson, editors The Pure Concept of Diplomacy Jose Calvet de Magalhaes ´ ˜ Carl Schmitt: Politics and Theory Paul Edward Gottfried Reluctant Ally: United States Policy Toward the Jews from Wilson to Roosevelt Frank W. Brecher East Central Europe after the Warsaw Pact: Security Dilemmas in the 1990s Andrew A. Michta The French Revolution and the Meaning of Citizenship Renee Waldinger, Philip Dawson, and Isser Woloch, editors ´ SOCIAL JUSTICE IN THE ANCIENT WORLD Edited by K. D. Irani and Morris Silver Contributions in Political Science, Number 354 Global Perspectives in History and Politics George Schwab, Series Editor GREENWOOD PRESS Westport, Connecticut • London Library of Congress Cataloging-in-Publication Data Conference on Social Justice in the Ancient World (1993 : City University of New York) Social justice in the ancient world / edited by K.D. Irani and Morris Silver. p. cm.—(Contributions in political science, ISSN 0147–1066 ; no. 354. Global perspectives in history and politics) ‘‘This volume resulted from a Conference on Social Justice in the Ancient World held at the City College of the City University of New York on March 10, 11, and 13. All the papers read at the conference are published here, with the exceptions . . . ’’ Includes bibliographical references and index. ISBN 0–313–29144–6 (alk. paper) 1. Social justice—History—Congresses. 2. Civilization, Ancient— Congresses. I. Title. II. Series: Contributions in political science ; no. 354. III. Series: Contributions in political science. Global perspectives in history and politics. JC578.C63 1993 303.3'72'0938—dc20 94–30932 British Library Cataloguing in Publication Data is available. Copyright 1995 by K. D. Irani and Morris Silver All rights reserved. No portion of this book may be reproduced, by any process or technique, without the express written consent of the publisher. Library of Congress Catalog Card Number: 94–30932 ISBN: 0–313–29144–6 ISSN: 0147–1066 First published in 1995 Greenwood Press, Contents Preface Part I: The Idea of Social Justice: Its Forms and Evolution 1. The Idea of Social Justice in the Ancient World K. D. Irani 2. Social Justice and the Subsistence Economy: From Aristotle to Seventeenth-Century Economics S. Todd Lowry 3. The Origins of a Concept of Social Justice Howard L. Adelson Part II: Articulation of the Idea of Social Justice in the Ancient World ¯ 4. KHREMATA: Acquisition and Possession in Archaic Greece Thomas J. Figueira 5. Images of Justice in Early Greek Poetry Gregory Nagy 61 41 25 9 3 vii vi Contents 6. Justice and the Metaphor of Medicine in Early Greek Thought Marshall S. Hurwitz 7. Social Justice in Ancient Iran Farhang Mehr 8. Social Justice in Ancient India: In Arthasastra ´¯ M. G. Prasad Part III: The Practice of Social Justice in the Ancient World 9. The Ideological Basis for Social Justice/Responsibility in Ancient Egypt Scott N. Morschauser 10. Social Justice in Early Islamic Society Fereydoun Hoveyda 11. The Idea of Social Justice in Ancient China Thomas H. C. Lee Part IV: Social Justice and Reform in the Ancient World 12. Social Justice in the Ancient Near East Raymond Westbrook 13. Social Reform in Ancient Mesopotamia Benjamin R. Foster 14. Prophets and Markets Revisited Morris Silver 15. Demands for Land Redistribution and Debt Reduction in the Roman Republic Richard E. Mitchell Selected Bibliography Index About the Editors and Contributors 199 215 217 221 179 165 149 125 115 101 91 75 69 Preface This volume resulted from a conference on Social Justice in the Ancient World held at the City College of the City University of New York on March 10, 11, and 13, 1993. All the papers read at the conference are published here, with the exceptions, regretfully, of H. Z. Szubin’s ‘‘ ‘Law and Order’ and ‘Law and Equity’ in the Ancient Near East and in the Bible,’’ R. Garner’s ‘‘Lawless Women in Classical Athens,’’ and Baruch A. Levine’s ‘‘The Social Parameter of Biblical Law: Kinship and Justice.’’ The concept of social justice is one of the more influential ideas in the annals of human social existence. It arose in social consciousness probably at the dawn of civilization and affected the formation and transformation of social structures and legal institutions throughout history. The effect of this idea on modern life has received detailed attention. But its influence in ancient and relatively early times is deserving of much more attention than it has so far received. It was the desire to redress the intellectual balance that inspired this conference and motivated the participants. The chapters explore several aspects of the subject—the notion of social justice in the early days of human history; the articulation of social justice in certain ancient civilizations; the social and legal practices implementing social justice in the ancient world; and the legal and socioeconomic consequences of the implementation of schemes of social justice. Both editors wish to thank Carolyn France and Bertha Zeigler-Pickens for their invaluable assistance. Thanks are also due to Deans Jeffrey Rosen (Social Science Division) and Martin Tamny (Humanities Division) and, most of all, to viii Preface Dean Paul Sherwin (Humanities Division). We also gratefully acknowledge the basic funding provided by the Simon H. Rifkind Center for the Humanities and the supplementary funding provided by the Morton Globus Fund, the Harry Schwager Fund, and the Gabriel Mason Fund. Part I The Idea of Social Justice: Its Forms and Evolution 1 The benefits first benefits or burdens rather than as the adjudication of conflicting. 4 The Idea of Social Justice We do not know what legal arguments were used to achieve this end. Roman law sometimes employed the category of constructive fraud, that is, even though there was no proof of an actual fraud perpetrated on the victim, the conditions of the contract were such that no reasonable person would have agreed to them unless he was subjected to some deception or duress. In ancient Iran a properly solemnized contract was considered inviolate; however, when terms of the contract led one party to profit greatly and the other to suffer a loss, the judge might require the party to share some of his profit with the other party in the cause of righteousness! Such a legal requirement of sharing was not imposed if both parties profited, even if the profits were very unequal. There were indeed several legal issues that were affected by these ideals, among them, especially, discharge of debts, payment of interest, and slavery. These issues could not be adjusted by judicial interpretation. Specific legal rules had to be introduced through royal edicts or special codes. And these rules were often inspired by religious concepts promulgated by prophets, priestly ministers, or socially minded preachers who discerned the directions coming from the divinity regarding the social conditions of the populace. We find it difficult to comprehend the logic of the new legal requirements because they do not fit into our standard mode of legal thought. But this is the way the idea of social justice probably comes into being, and the logic of its foundations is what we shall explore here. The postulate of social justice is that society is responsible for the undeserved suffering of its members. From this one may draw the conclusion that society as a whole should repair the deprivation and should construct social means to ensure that such harm is avoided. The logic of this is the following: Some action of X has an effect on the state of Y that constitutes harm or deprivation for Y; if Y’s injury can be seen to be undeserved, then X would ordinarily be held responsible and be required to repair the damage. But consider a second example: In the course of ordinary life in a society and for no fault of his own, Y finds himself in a state of deprivation or dire need. Certainly Y has suffered an undeserved burden, but there is no individual who caused it and could be considered responsible and be required to provide the means to repair the damage. This problem was faced by almost every ancient civilization. Since at that period in the history of human thinking the framework of understanding was religious, the question became one of the justice of God, namely, Why did God permit undeserved suffering? A very important practical implication of this question was that since God was just, He wished the social authority to rectify the unjust situation. Thus the demand for social justice as a demand for social, economic, and legal reform appeared originally as a religious demand. Thus, society was responsible through its social norms, its laws, and its economic practices to create situations where the underprivileged and powerless, would not end up in states of deprivation of their property and freedom. And indeed in many civilizations in the ancient world, particularly in the ancient Near East, there appeared special legal reforms such as debt forgiveness, limi- Social Justice in the Ancient World 5 tations on the period of slavery, and provisions against usury. These were brought about as specific directions from the divinity, or as a general conception of a just society divinely ordained imposing upon the ruling authority the task of maintaining a just society. In Babylonian and Egyptian writings we have mentions of actions responding to the needs of those suffering impoverishments or deprivation as pleasing to the divinities. Much more explicitly we find in the utterances of the Old Testament prophets declarations of the demands of the Lord for the protection of the impoverished and the suffering, frequently exemplified by the widow and the orphan. Specific legal protections were created as a result of these divine injunctions altering otherwise traditional legal and economic practices. The other way in which the demand of social justice is articulated is through the notion of natural law. Natural law was viewed as a divine creation immanent in human and social nature, or it was viewed as a metaphysical reality functioning as a normative force on existence. Often it was both. The underlying order of reality applicable not just to the physical world, but also as normatively directing the social world, is considered a divine creation. This notion, with varying emphasis appears in most civilizations, it is most dominant as asha in ancient Iran and as dharma in post-Vedic Hindu thought. In the ancient Iranian tradition, founded upon the philosophic theology of Zarathushtra, asha is the idealized Truth—in other words, it is the normative Truth, the way the world was meant to be, ought to be, and would have been had the evil spirit not infected existence. In the social world with which we are concerned here, the principle of asha presents an ideal of perfection and harmony in which no one stands to gain through the deprivation or suffering of another. Clearly, that is not the actual state of society; the ideal of asha requires that the organizing power of society bring about through law or social structure and practice, a socioeconomic state in which no one’s advantage is dependent upon the suffering of another. What precisely such arrangements would consist of was never formulated. It was left to the intellectual and moral ingenuity of the human mind and character, since, presumably, the specific rules and regulations would be adjusted to the changing circumstances of existence tending toward the progressive improvement of the social condition. In contrast, the Hindu concept of dharma was articulated in specific prescriptions for particular contexts and was presented in a variety of didactic and mythologic sacred and quasi-sacred works. The central philosophic idea underlying these prescriptions was the notion derived from Upanishadic thought that no action of an individual can be viewed and judged solely in terms of the interest of that individual alone. Every action reflects the impulses of a reality greater than the individuality of the agent, and also affects others thereby generating responsibility upon the agent. This thesis presupposes the ultimate interconnectedness of human beings finally rooted in the view that each individual is a manifestation of the Universal Self, and the Universal Self is identical with the Essence of Reality. We are thus embedded in a vast web of mutual responsibility 6 The Idea of Social Justice in which empathy and compassion call for the minimization of human suffering, but especially to see that we do not add to human suffering by living in accordance with the detailed injunctions of dharma. A different conception of the foundation of justice, metaphysical as well as social, appeared in the Roman world, under the educational influence of Stoic schools. Natural law as developed in Stoicism was an attempt to coordinate social structure to human nature, to make the social structure such that we eliminate or minimize all avoidable suffering and abrasion of human beings seeking to satisfy their needs in society. Such goals were achievable by establishing a legal system that was in accord with our rationally conceived notion of natural justice. Events of Roman history brought these notions to the fore in an interesting way. When Rome was crowded with aliens, mainly traders, major and minor, litigation naturally arose among them. The Roman courts rightly avoided adjudicating these disputes according to the old patrician jus civile that had emerged from archaic, religiously traditionalized practices of a few families but looked rather for the common practices of businessmen and traders from the world over gathered in Rome. The set of decisions and the law that emerged therefrom was considered to be the law commonly applicable to humanity in general and came to be called the jus gentium. However, the philosophic development of this process went further, particularly in the hands of Roman lawyers educated in Stoic schools. They applied legal principles that constituted requirements of natural justice that could be discerned by reason reflecting upon human beings engaged in social interaction. This legal system came to be called jus naturale. This system operated with the fundamental concept of rights. A judgment resulted from an adjudication of a dispute viewed as a conflict of rights. An injury was viewed not as suffering or deprivation but as damage to one’s interest constituting a violation of one’s right. In such a framework the undeserved suffering befalling an individual in the absence of the act of an agent violating the right of a sufferer became by that very fact an unprotected interest and thus beyond legal redress. In procedural law the doctrine of equality affirmed the right of every individual to seek justice before a judicial tribunal; and in substantive law the doctrine required that rights and responsibilities apply to the actions of each and all in the same way. It is obvious that these ideas promoted an aspect of social justice by erasing the differences between persons arising from the accident of birth or from disabilities inflicted upon one because of one’s means of livelihood. It is worth remembering that in the ancient world, in the Indo-European tradition there was a pronounced tendency to view the population as divided into classes—usually three, but sometimes four. One belonged to a class by birth. Membership in the class determined not only one’s social position in communal or ceremonial festivals, but in most aspects of daily living, such as, one’s profession or means of livelihood, one’s residence and general mode of life. From the point of view of our present discussion, it is important to note that class Social Justice in the Ancient World 7 membership affected not only liability and culpability, but also approachability to courts for judicial redress. An act coming before a court calling for judicial consideration would have its construal dependent upon the classes to which the litigants belonged. Such inequality in substantive law was rejected by the Stoic theory of natural justice. It was mainly this principle that led to the emergence of equity in Roman jurisprudence. Similarly, in procedural law, class-based inequality of access to courts was repudiated. These particular aspects of social justice are indeed appropriately called the doctrine of equality before the law. This principle entered legal practice gradually and very unevenly, first in Roman jurisprudence, and then through the widespread impact of Roman law on the civilized world. Its complete acceptance the world over is a matter of very recent legal history. Surveying the diverse demands that fall under the general notion of social justice, we notice that some of them are included in the category of intrinsic justice, generating rights not recognized till then in the traditional jurisprudence of ancient societies. The correlative obligations to these rights were usually placed upon society, but sometimes upon the individual who was believed to have been unfairly advantaged in the social interaction. Other notions of social justice belong to the category of comparative justice; they generate metalegal principles, called principles of natural law. They are viewed as rules necessitated by the demands for natural justice capable of being grasped by philosophically clear and socially informed human reason. We have also seen the diverse grounds upon which these ideas were based. They extend from the wish of God, to a divinely created ideal Law or Truth to be grasped by the spiritually illumined Good-Mind, a position midway between the divinely inspired voice of conscience and a straightforward rationalism, to finally a moral rationalism in which natural law is discerned as a moral truth. We now turn to examine the effect of the implementation of prescriptions of social justice on the legal and socioeconomic aspects of society. Economic institutions arise to satisfy the needs of human beings in society for the exchange of goods and services. The practices gradually crystallize into relatively stable patterns. These patterns come to be recognized as mercantile customs by courts when such disputes arise in litigation. The earliest markets were not created by the political institutions of societies. As civilizations advanced, rulers established market locations, valuable for traders as well as for the rulers who could tax them. They also provided techniques for standardizing weights, measures, and coinage. Most markets were also equipped with a religious or civil institution for authenticating or recording contracts. In the context of our discussion here, the demand for social justice appeared as prescriptions altering the pattern of economic activity of the market. Some of these alterations could be incorporated into new socioeconomic patterns of market activity; sometimes however the alterations made traditional practices dysfunctional. In any case, legal aspects of commercial activity require that they be clear and stable for commerce to flourish. When the stability of legal practices 8 The Idea of Social Justice is put in doubt and their predictability is reduced by the introduction of new rules of liability, or the extinction thereof, present business activity diminishes, as well as confidence in investments for the future. Regardless of the disruption in the socioeconomic operations of a society that the implementation of some measures of social justice may have caused, the values inherent in them have been appreciated and progressively implemented in all civilizations. But alongside there have always been reservations about applying the rules of social justice, the intrinsic rather than the comparative, because they entail the imposition of responsibility upon society as a whole or an individual to remedy the undeserved suffering of someone. And though one may feel that the remedying of the undeserved suffering was valuable, one must realize that it is achieved at the expense of society or an individual who has to provide the resources. This fundamental value conflict is still with us today. It is that in some, though not all, socioeconomic situations the demand for intrinsic social justice and the right to private property become incompatible, resulting in two polar sociopolitical preferences. And what preference for one side may term a worthy act of charity and good conscience, would be viewed from the other side as a confiscatory deprivation of one’s property. Such a conflict does not arise in the area of comparative social justice, which, though gradually implemented in the ancient world, has been accepted as an aspect of universal human rights today. 2 Social Justice and the Subsistence Economy: From Aristotle to SeventeenthCentury Economics S. TODD LOWRY Much of the literature from antiquity is concerned with the exploits of kings, chieftains, pharaohs, and emperors. Their power, however, was in part dependent upon the number and competence of their subjects. The establishment of stability and order in such authoritarian regimes was an absolute prerequisite to the irrigated agriculture and craftsmanship upon which they depended and can easily be confused with a system of justice. A modern concept of social justice, however, requires the implementation of some standard of ‘‘good’’ or ‘‘fair’’ rules of conduct toward the mass of the population. An important distinction in this formulation is frequently ignored. Security and stability in possessions and uniformly administered laws contribute to efficient planning and have the appearance of justice; but if such practices are based on the administrative purposes of authority systems, not on the assertable rights of the individual, we are then dealing primarily with order and not with justice in a modern sense. In the Old Testament account of Job and his patient submission to the vicissitudes imposed upon him by his God, we find an idealized image of the committed servant for whom duty to superiors is the standard for virtuous conduct. Even when well treated, there is no presumption of rights in such a social setting. By contrast, we find in the ancient Greek world a clear formulation of a socioeconomic principle of prerogative that seems to have fueled a tradition that has survived and influenced modern thought. This tradition does not begin with the rather terse description of a subsistence economy found in Book II of Plato’s Republic and characterized as ‘‘a city of pigs’’ (II, 372d). Plato’s society, with its natural division of labor, grew out of an administrative ordering of the variations in human capabilities. It was primarily a formulation of Plato’s vision 10 The Idea of Social Justice of a hierarchical society ruled by a philosopher-king emphasizing the Near Eastern pattern of ‘‘duty to superiors.’’ It is in Aristotle that we find a synthesis of Platonic and democratic concepts carefully elaborating a mixture of natural and social processes that have influenced political economy and ethics for the past twenty-three centuries. ARISTOTLE’S THEORY OF THE NATURAL RIGHTS OF THE OFFSPRING In the opening chapters of Book I of his Politics, Aristotle sets up a descriptive classification of socioeconomic processes. He outlines the fundamental interactions of agrarian family life as the source of basic needs. In the family, marriage, supervision of slaves or servants, and the raising of children provide the primary elements of survival, that is, sex, food, drink, shelter, and human continuity. He then recognizes that, in the village system, barter exchange provides for social interdependence, the benefits of specialization, and the division of labor. This hierarchy of increasing complexity in socioeconomic interaction is carried on into a discussion of monetary exchange and, ultimately, usury, which kept this literature in the forefront of ethical-economic-juridical discussion through the Middle Ages and into the seventeenth century. At the same time, in Book VII of the Politics, Aristotle presents an often ignored reverse hierarchy of values. The order of physical priorities for society is physical needs (goods of the body), amenities through barter and monetary exchange (external goods), and philosophical and political virtue associated with the culture of the city (psychic goods). These values are sequentially dependent upon one another, but their true virtue is in inverse order, with psychic or spiritual values of highest importance, and mere physical survival—though necessary—of least importance. While we can see the echoes of this formulation implemented in medieval asceticism and in the Mendicant Orders of the Middle Ages, our interest here is in the primary hierarchy of subsistence and social organization developed in Book I. Despite the urbanization and commercialism of Athens and Corinth, Aristotle drew on the naturalistic tradition of a basically agrarian economy relying primarily on its own production for subsistence. He took money into account as a tool of efficient mediation in exchange as did Plato in the Republic. From this standpoint, money had a primary use value for trade, just as other goods that were useful in themselves were in the alternative useful for trading for consumption goods. This was the basis of Aristotle’s concept of a ‘‘natural limit’’ on the subjective desire for goods—they were of diminishing utility as consumption goods and therefore subject to the natural limits of realistic human needs. Money, properly used as an extension of the barter process, was also subject to this natural limit since it functioned in the exchange process as ‘‘commodities for money and money for commodities’’ (Lowry 1974, 1987, 1988). The hazard to the system was when outside traders, ‘‘metics,’’ undertook to Social Justice and the Subsistence Economy 11 trade goods for money and carry off the money. These people were not participating in the closed circle of the natural economy and were interested in aggregating wealth in the form of money by charging high prices and carrying the monetary medium out of the community. Outside trade also permitted the acquisition of goods, unlimited by the natural utility of the local consumers. These goods could be acquired for resale abroad. Aristotle suggested that this process involved a reduction of the physical wealth of the country—a loss of potential surplus—which, by right, belonged to the offspring, the potential population growth of the community (Politics, Book I, 1258a35; see also 1320a-b). This point is not elaborated extensively, but it is reenforced by the logic of the analysis. The naturalistic illustration is even used of the commitment of an accumulated surplus to the young in the form of the yolk of an egg that supports the development of the embryo. In addition, the argument is supported by the historical context of the Greek economic tradition, in which the city-states were constantly struggling with population problems, perpetuating the practice of infanticide, and founding colonies with surplus citizenry. At the same time, their young men, exploiting their hoplite training, hired out as mercenaries throughout the eastern Mediterranean. The clarity with which this problem was understood is illustrated in Plutarch’s Lives in his account of Lycurgus’ economic program in ancient Sparta. An iron money, the obel, derived from the slender rods or spits used in cooking ‘‘suvlocki’’ or ‘‘shiskabob,’’ was treated to destroy its commodity value as iron. This functionally sealed the economy against foreign goods or services that demanded an exportable money in payment. It also stimulated domestic trade and production and the export of commodities in exchange for commodities since outside money was of no value in Sparta (Lowry, 1987: 227–28). While such references support the argument that fourth-century B.C. Greeks understood the concept of an economy as a potentially closed system, the important point is that they also were concerned about the possibility of a class or interest group being deprived of a right or natural claim through the vagaries of the economic process. In this context, we can comment on Aristotle’s often cited denunciation of usury. As he put it, barter or exchange involving money as an intermediary was kept in line with the natural needs and limits on trade because it was consumption oriented. The lending of money with the stipulation that a greater amount of money be paid back was an abuse because it exploited a consumer need and because lenders were not subject to a natural limit on their desire for the benefits of the exchange. Although there are many discussions in Xenophon and Aristotle that indicate a consciousness of productive activities, in this formal systematic sketch, Aristotle focused on the citizen as an agrarian consumer trading surpluses for needs and potentially being exploited by usurers in times of privation. Within this framework of denunciation of usurers and outside traders, we can understand the special concern for the growing population’s right to any potential surplus as the beginning of a principle of economic 12 The Idea of Social Justice rights—an entitlement—a claim on the surplus generated by the efficient interaction of the economy. This surplus should go to the support of the ‘‘offspring.’’ This special concern for the young is, of course, implicit in any life-form that survives, since the offspring require gratuitous care to reach an age of selfsufficiency. Although the protection and rearing of children can be individually rationalized on the basis of personal altruism or as a means of guaranteeing support in one’s old age, when the prerogatives of children become recognized as a general social value to the community, then a subtle shift has taken place and a principle of social justice to the deprived or poor is nascent. This principle may well have a broader and older base as an established presumption in the extended family. The view that the family line transcends the claims of any individual generation reenforces the same concept that the future generation has a right or claim on the family or public patrimony. In Plutarch’s brief tract, ‘‘To an Uneducated Ruler,’’ the idea is reiterated that there is an obligation to recognize the rights of the coming generation and make provision for them (Plutarch, sec. 3). ROMAN LAW: NATURAL NEEDS—MINORS AND ORPHANS It is of some interest that in the Institutes of Justinian, prepared as a basic first text for law students in A.D. 533, the opening definition of natural law corresponds to Aristotle’s initial formulation of the basic economic process. The text begins: ‘‘Natural law is that which nature instills in all animals. For this law is not peculiar to humankind but is shared by all animals. . . . From it derives that association of man and woman that we call marriage; so also the procreation and rearing of issue’’ (Thomas 1975: 4 [Institutes I, 1]). It was, however, the civil law or ius civile, of each state that provided the rules of conduct enforceable against the citizens of any given jurisdiction. The law of nations or ius gentium, provided the arrangements common to mankind, based upon ‘‘natural reason’’ (Institutes I, 2, 1) from which such arrangements as contract and sale were derived. For the Christian emperors, this ius gentium was presumed to reflect a divinely inspired ‘‘higher law.’’ ‘‘Natural laws which are followed by all nations alike, deriving from divine providence, remain always constant and immutable’’ (Institutes I, 2, 11). This distinction between civil law and the law of nations, sometimes characterized as natural law, follows Aristotle’s distinction in the Nicomachean Ethics V.7.1, and in the Rhetoric I.13.2. However, the Roman characterization of ius gentium is more aptly defined as those rules that human beings work out between themselves under the aegis of natural reason—a sort of universal common sense and practice. The initial concept of ‘‘laws of nature’’ is still focused on the basic physical needs and is not incorporated in the ius gentium or the ius civile. Within the context of the municipality or empire, the legal prerogatives of citizens were defined as deductions from their roles in the corporate state. There was, then, no real concept of a right against the state or against the ordered structure of society. Social Justice and the Subsistence Economy 13 Nevertheless, the state did have a tradition of responsibility for the basic needs of the populace expressed in the Roman ‘‘dole,’’ which provided food for the destitute urban population. The perception of itself as a corporate entity made up of its citizenry, patrician and plebeian, led the Roman municipality to assume the obligation to import grain as tribute or by purchase and to supply its population through the market or by the dole. This tradition followed patterns found in fourth-century B.C. Athens and was perpetuated in Muslim municipal practice and in the medieval commercial towns as ‘‘provisions policies.’’ With regard to children or minors, Roman law provided an exemption for them from the enforcement of contracts or sales. This was conceived as a protection against the possibility that they would be taken advantage of because of their youth and inexperience. The rule remains basically unchanged in modern English and American law in that such contracts made by minors are ‘‘voidable’’ at the behest of the minor but are otherwise enforceable. English law, however, with cases evolving from the late Middle Ages, was particularly concerned about ‘‘the necessaries of life’’ and enforced contracts and sales dealing with the basic natural needs for survival. This special exception protected minors, living on their own, from being denied access to the necessaries of life because of the reluctance of merchants or landlords to risk dealing with them. The special concern for children took an additional peculiar turn in Roman life. By the second century A.D., both private and public practice evolved, making special provisions for orphans. This is characterized as a policy of alimenta (Hands 1968: 108). Of more particular interest is the occurrence, during Hadrian’s reign, of the motto ‘‘libertas restuta accompanying distribution scenes on coins of his reign, almost identical with those of his predecessor, . . . [equating] freedom with ‘freedom from want’ ’’ (Hands 1968: 110). These coins were in the tradition of tokens issued to citizens with which to claim their allotments of grain in earlier times. THE MIDDLE AGES: CHARITY AND NATURAL LAW We are fortunate to have an extensive document dating from 1159, John of Salsbury’s Policraticus, as a reference base for appraising the transitions of the thirteenth century (Dickinson 1963). This extensive medieval treatise epitomized the sociopolitical thought up to that time replete with a heavy reliance on an organic metaphor. It was the culmination of the patristic tradition traceable through St. Augustine and back to Plato with its heavy emphasis on duty to authority while maintaining a sense of commonwealth and citizenship. The Roman law traditions were perpetuated, embedded in the canon law, and the notion of a ius gentium was continued as a Church principle derived from a ‘‘higher power.’’ Although Salsbury characterized the peasantry as the ‘‘feet’’ or underpinnings of the organic image of the society, this culmination of early medieval thought moved away from feudalism and provided a groundwork for 14 The Idea of Social Justice conceptions of kings and states and more centralized organization under the Church. As Dickinson pointed out in his preface, ‘‘The significance of the Policraticus is that it contains the inchoate and incipient forms of so large a number of the political doctrines which were to identify themselves with greater clarity in later centuries’’ (Dickinson 1963: xi-xii). At the same time, this comprehensiveness of the Policraticus makes it an excellent threshold for appraising a significant transition that seems to have occurred in popular as well as philosophical thought. We refer to the apparent upsurge in private and municipal commitment to the well-being of the poor coinciding with the introduction of Aristotelian thought under the aegis, initially, of St. Thomas Aquinas. Up to the Middle Ages, the members of the regular clergy had dedicated themselves to a relatively simple life, producing their own subsistence in their monasteries and focusing on spiritual and intellectual values. However, the Mendicant Orders seem to have drawn directly on Aristotle’s thesis of the ordinal sequence of priorities of needs for ‘‘goods of the body,’’ ‘‘external goods,’’ and ‘‘psychic goods’’ (philosophy and civic virtue). Aristotle had, of course valued these goods in the inverse order. What the Mendicant Orders did was compress the necessary precondition for attaining these higher values into the barest minimum standard of living (goods of the body), and they depended upon the surplus or largesse of the society for their provision. One can argue that the simile of ‘‘the lilies of the field’’ gave a New Testament endorsement of the bounty of nature to their practice, but they actively begged and drew from the society to support their psychic or spiritual objectives. During the same period, across Europe, there was a documentable innovation of privately and publicly financed charities-hospitals and alms houses as well as public distributions of food to the poor. This clearly registered change in public attitude was expressed by the building of scores of hospitals for the displaced, the lame, and the sick. It has been attributed to the increase in urbanization, the expansion of population up to the carrying capacity of the agricultural base, and severe periodic famines. There was a clear patristic tradition for personal alms giving. Generally unmentioned is the possibility of a Muslim theological influence—the personal obligation to give alms to the poor—which may well have spread across the Mediterranean or up the Iberian Peninsula along with preserved Greek literature, Arabic numbers for bookkeeping, and Muslim science. The development of an extensive conspicuous structural poverty in the late twelfth and the thirteenth centuries, resulting from bare subsistence incomes for the employed workman, had its corollary in widespread pauperism among widows, orphans, the very young, the very old, the sick, the lame, and the demented. It may well be that this poverty was made conspicuous by the development of commercial towns in which the poor aggregated or were concentrated in more observable numbers. The laity of the newly developed towns took up the burden of support and management of this growing class that the church tended to accept as part of the order of things (Lis and Soly 1979: 20–25). From the late twelfth century on, direct personal philanthropy, organized confraternities, and Social Justice and the Subsistence Economy 15 municipal councils presumed to be responsible for the plight of the poor. As an example of the aggressive assertiveness of such groups, in 1209 the residents of the small Flemish fishing village of Mardyck collected the tithes themselves that were due to the local monastery and distributed a third of them directly to the poor (Mollat 1986: 98). Not only were there many institutionalized distributions of bread or shoes to the poor, but in Germany and in parts of France institutions arose at the end of the twelfth century to permit paupers’ claims for damages to be heard by citizen councils suggesting a basic sense of violated rights among the poor (Mollat 1986: 100). There was even a dissident theological current surfacing in the form of preachers and sects calling for higher status for the humble, illustrated by William Longbeard, Waldo, the Goliards, Durand of Huesca, the ‘‘White Capes,’’ and the Humiliati (Mollat 1986: 102). The point is that there is ample evidence that the public recognition of poverty and pauperism had evolved into an institutionalized social commitment on the part of the laity and of public organizations, both private and municipal. The Church was no longer recognized as primarily responsible for this social issue. The development of the famous Beginages in what is now Belgium is a case in point. This association of laywomen from the wealthy classes provided shelters for the rural poor. Furthermore, the duty v. rights issue was becoming unclear in the popular mind. The general state of conspicuous poverty in the towns had led to a formal cognizance of the large sector of the population that was chronically suffering from a shortage of the basic ‘‘goods of the body.’’ Both the Roman municipal tradition and the Aristotelian tradition of natural prerogative were in place to support this borderline evolution of concern for the rights of the poor or, au contraire, the moral duty to the poor. Let us turn to Aquinas’ rendition of the Aristotelian concept at this point. Writing in the early thirteenth century from northern Italy where the most advanced and varied of charitable institutions had developed, St. Thomas Aquinas carefully combined the Roman law tradition of ‘‘natural right’’ with the canon law assimilation of it as ‘‘divine providence’’ and merged the Aristotelian tradition back into the mainstream of European thought. In his Summa Theologica, he clearly summarizes the philosopher’s (Aristotle’s) thesis on natural limit and need and cites Politics (Summa Theologica 22 [qu. 77, art. 4, concl.]). However, his generalization and application of this tradition to the conditions of his time read like a theoretical abstraction and endorsement of contemporary social thought. His position deserves quotation in full: What pertains to human law can in no way detract from what pertains to natural law or to divine law. (Dist. XLVII): ‘‘The bread which you 16 The Idea of Social Justice withhold belongs to the hungry; the clothing you shut away, to the naked; and the money you bury in the earth is the redemption and freedom of the penniless.’’ But because there are many in necessity, and they cannot all be helped from the same source, it is left to the initiative of individuals to make provision from their own wealth, for the assistance of those who are in need. If, however, there is such urgent and evident necessity that there is clearly an immediate need of necessary sustenance,—if, for example, a person is in immediate danger of physical privation, and there is no other way of satisfying his need,—then he may take what is necessary from another person’s goods, either openly or by stealth. Nor is this, strictly speaking, fraud or robbery. (Lowry 1988: 249 [Sum. Theo. 21, qu. 66, art. 7, concl.]) A systematic study of this issue in the commentaries and writings of other scholastic thinkers would be beyond the limits of this exploratory survey. It should be sufficient, however, to point out the obvious impact of such an unequivocal affirmation of the moral right of subsistence put forward by one of the giants of scholastic theology. PROVISIONS POLICIES IN THE MEDIEVAL TOWNS Pirenne generalizes the character of the medieval commercial town from northern Italy to the Low Countries, pointing out that their basic problem was a sustainable food supply. Even though their populations ran from only 20,000 to 50,000 inhabitants, by the thirteenth century an array of policies and regulations had arisen designed to stimulate effective markets. These included the traditional measures from publicity (the promotion of market information) to laws against forestalling and regrating (Pirenne 1936: 173–76). This high level of municipal intervention in the flow of basic food stuffs, even in normal times, was, of course, augmented during times of famine. In a sense, then, we can see a rational tradition of primary responsibility for subsistence institutionalized in the ‘‘towns.’’ The emerging commitment to the problems of pauperism may be seen as a natural corollary of this municipal tradition. We must also remember that the municipal organization was an extension of the Roman legal tradition and was influenced by the surviving commercial towns that had thrived on both the Muslim and Christian sides of the Mediterranean Basin during the so-called Dark Ages. What must be kept in mind is that, with 80 to 90 percent of the population living on the land in peasant agriculture at little more than a subsistence level and with inefficient and expensive transport facilities, the provisioning of even small commercial towns required constant attention. These high percentages of the population on the land were an expression of the extremely low yields when compared to modern agriculture and the sensitivity of the flow of salable surplus to weather conditions. This meant that extensive networks had to be developed to provide for the necessaries of life for the working poor, much less for the paupers of the larger towns. During the frequent famines, heroic efforts were Social Justice and the Subsistence Economy 17 put forth by officials and loyal merchants trading over great distances. As Miskimin recounts, the Italian cities moved toward a pattern of control over their immediate hinterlands, making themselves monopsony buyers of foodstuffs with officials in charge of keeping track of population variations and food needs. They were provided with funds for purchasing outside food to make up anticipated shortfalls. Northern cities relied on market regulations. Generally the northern towns tried to stimulate market processes, but in the great famine of 1315–1317, a Pan-European grain deficiency brought home the tenuous and shallow food base for the towns. Ypres, for example, in the Low Countries, lost 10 percent of its population to famine (Miskimin 1975: 77–81). The high incidence of crop failures and famines is credited by Fernand Braudel with constant disruptions of nascent capitalist development until the revolution in agricultural production in the seventeenth and eighteenth centuries (Braudel 1982–1984). The continued institutionalization of this problem is illustrated by the complex machinations in Toledo, Spain, at the end of the sixteenth century over famine and pauper relief (Martz 1983: 145–48). It is sufficient to recognize, for present discussion, that there is overwhelming documentation of an elaborate pattern of institutionalized commitments to a special responsibility for the subsistence needs of the masses of the population who were, incidentally, generally poor. Some of the more complex economic directions that this tradition took are of considerable theoretical interest. THE MONTES PIETATIS: CREDIT FOR THE POOR One of the most interesting developments in the concern for the well-being of the poor that arose in the Middle Ages was the commitment to provide lowcost credit. Along with the enhanced level of awareness of the problems of paupers in the thirteenth century emerged a concern for small loans for the working poor. Loans were generally available from Jewish money lenders and Lombards (Christian usurers) for the wealthy as well as heads of state. However, the Jewish pawnbroker seems to have emerged as a particularly desirable institution. In the fourteenth century, the authorities of Venice began negotiations with the Jewish community, as a condition of the establishment of their residency, that it should maintain pawnshops for the poor financed by a tax levied on the Jewish community itself (Calimani 1985: chap. 1). Other sources of credit for the poor evolved out of the ‘‘confraternities’’ or associations—nascent credit unions—and some hospitals or other charitable foundations undertook to give interest-free loans. Records from Cambridge, England, in the first half of the thirteenth century indicate regular dealings with Jewish money lenders. The local hospital establishment could, however, lend money against land as collateral. The hospital appeared to be a lender of last resort (Rubin 1987: 224). Documents indicate that such charitable institutions advanced small amounts to carry peasants to harvest time or to finance some emergency, frequently buying land rights rather than making loans. 18 The Idea of Social Justice There were other examples of foundations dedicated to interest-free loans to different classes: Notably, in 1361 the Bishop of London endowed a foundation with 1,000 silver marks to provide one-year interest-free loans. These loans were limited to 10, 20 or 50 marks, depending on the status of the borrower (Mollat 1986: 278). Mollat discusses several recorded instances in the same century in which projects for publicly supported credit for little or no interest were proposed or implemented on the continent. The recognition of credit to prevent a man, rich or poor, from losing his foothold in the economy in a crisis seems to have become widely accepted in the thirteenth century. Guilds and other associations in Europe provided similar support for their members. In the Low Countries, Lombards and an unidentified group called ‘‘Cahorsians’’ operated licensed pawnshops and ‘‘tables de pret’’ (loan tables) in the commercial towns ˆ with official endorsement (de Roover 1948: 99ff.). Some foundations relied on the doctrine of ‘‘lucrum cessans’’ to avoid the problem of usury. Thus, an interest-free loan could be made against collateral, but the borrower would make a 10 percent gift to cover the ‘‘money lost’’ by the lender for foregoing his own use of the money in making the loan. Generally, it was clear that little attention was paid to the ban on usury, and there was a widespread concern for the availability of short-term credit in a world with capricious swings of fortune based on agricultural production and subject to military and political instability. It was not until the mid-fifteenth century that the institution of the Monte di Pieta swept across Italy, Spain, and, a century later, the Low Countries. This ` public pawnshop tradition made the availability of low-interest or free credit a social obligation in support of the poor. It was often extended to the wealthier citizens as well when they were in difficult straits. Although there seems to have been a scattering of prototype public institutions in the Mediterranean commercial towns, the real impetus grew out of an intense campaign by Franciscan Friars of the Observant sect. Mollat’s explanation is most persuasive. According to him, a zealous campaign against Jewish usurers in the 1460s created so much consternation among the citizens and municipalities who recognized the important role played by the pawnshops that the Franciscans found themselves faced with a powerful ‘‘backlash’’ of hostile sentiment. They quickly adapted their evangelistic crusade to one of insisting upon the public provision of Monti di Pieta, public pawnshops to replace those operated by the Jews whom they strove ` to persecute. These institutions would lend money for a year at a 5 or 10 percent interest against double collateral. This program generated great popular support and, incidentally, curtailed the operations of some Jewish usurers. The myth that the Church opposed or suppressed lending at interest (usury strictly defined) is a casualty of this movement that was institutionalized in Italy and Spain in the late fifteenth and early sixteenth centuries (Pullan 1971: 450ff.). The institution spread into the Low Countries in the late sixteenth and early seventeenth centuries but was not accepted in France until the eighteenth century. Small communities, however, were still dependent on the Jewish pawnshops. In addition, many major cities continued to negotiate charters guaranteeing rights to Jewish Social Justice and the Subsistence Economy 19 bankers and pawnbrokers to supply the major credit needs of active commercial centers (Calimani 1985: chap. 2). Of particular interest to economists are the variations of the institution, the Monti Frumentari [Mountain (or Foundation) of Wheat] in southern Italy that advanced seed grain to peasants. These were clearly production-oriented credit organizations. In Castille, as early as 1431, the Arcas de Limosnas (Alms Chests) were established and expanded their activities to include those of the Monti Frumentari of Italy. Later, the Positos de Trigo began with a similar ‘‘commodity loan bank’’ (wheat) in Molina in 1478 (Mollat 1986: 279). This interest in public banking had only an echo in England where Gerard de Malynes expressed interest in the institution of ‘‘Mountains of Charity’’ and openly advocated that the English institute a state bank similar to the Banco di San Giorgio of Genoa. However, of more widespread importance was the popular policy that parallelled the Monti di Pieta. This was the extensive introduction of vellon, or ` ‘‘black money,’’ which provided circulating money for the majority of the population. VELLON, LA MONETA NERA, MONETIZING POVERTY One of the most intriguing and little-studied developments of the late Middle Ages was the ambivalent attitude toward copper money and the dual lines of theory to which it gave rise. Vellon was apparently a name given to silver money heavily debased with copper. At the same time, we find the extensive circulation of pure copper money (black money) that served the same purpose. This money contrasted with ‘‘white money’’ (silver) and ‘‘yellow money’’ (gold). There seems to have been a well-recognized need for large amounts of some coinage in small enough denominations to facilitate the increasingly active exchange economy that permitted the masses of the poor to benefit from division of labor and geographic specialization. At the same time, it was difficult for theoretical purists to cope with the circulation of a fiat coinage based on copper in a bimetallic system based on silver and gold that traded at their international bullion values. Pedro de Valencia, writing in the first decade of the seventeenth century in Spain, severely criticized the king for doubling the value of the recently introduced copper coinage vis-a-vis its bullion exchange value with gold and ` silver. This practice enriched the crown, but also led to a massive importation of copper and counterfeit coins. Nevertheless, de Valencia grudgingly conceded that enough of this money should be left in circulation to serve the needs of the poor (Grice-Hutchinson 1986: 63). At the same time, Fernand Braudel pointed out that Portugal was being flooded with this debased copper money, being adjacent to the inflation in Spain. Small money was, however, so much in demand that 12 reals worth of small change in copper sold for 13 reals. This money spilled over into the Indies as fast as it could flow into the country (Braudel 1972: 542). Italy seems to have been the home of black money where it circulated in the 20 The Idea of Social Justice Venician orbit. The operative distinction from money of account, however, seems to have been moneta piccola (billon or copper money and some small silver money used in local markets only) and moneta grossa (gold and silver coins of larger denomination used in international trade) (Lane and Mueller 1985: 11–12). The need for this small coinage to facilitate local trade in the commercially burgeoning north Italian cities of the fourteenth and fifteenth centuries is illustrated by Braudel’s discussion of the complex specificity of trade at some ports. The saffron exports from Aquila in the Abruzzi required the import of linen bags and larger leather covers, and this valuable export was only traded for copper bars to supply the local mint that struck two kinds of copper coins (Braudel 1972: 376). The theoretical appreciation of this protofiat money is well documented (Cipolla 1956: chap. III). It is clearly indicated in a comment by Herrera: ‘‘It is by the base metal currency that one can best judge the fertility and abundance of a country for it is with this money that all the necessaries of daily life are bought every day from the shopkeeper’’ (qtd. in Braudel 1972: 525). There is a similar observation from a late sixteenth-century traveler in Italy, Fynes Moryson, that drew attention to the significance of this monetary system in augmenting the standard of living of the poor by promoting internal trade: The Italians have small moneys of brasse, and for the least of them a man may buy bread, little papers of spice, or any such thing that is to be sold. These small moneys, the aboundance of people in a narrow land, and the common peoples poverty, but most of all their innated pride, such as they had rather starve for want, then beg, these things make them doe any service for a stranger for a small reward, and make the passages of Rivers, or Channells (as at Venice), and all necessaries, to be affoorded for a small piece of money. Neither is it a small commoditie of these little brasse moneys, that it makes the meaner sort more ready to give almes. This benefit the English may well know by the want of like moneys, whereby the hire of Porters, all rewards and each almes being given in silver money, and the small pieces thereof being rare, all expences are much increased. (Moryson 1908, 4: 95–96) GERARD DE MALYNES AND SEVENTEENTH-CENTURY ENGLAND We can trace this line of concern and emphasis on the relation between petty trade and the well-being of the lower classes to England in the work of Gerard de Malynes. While much of his writing in the early seventeenth century approached carping about the treatment of English merchants in the exchange markets in the Low Countries, he nevertheless demonstrated a sophisticated understanding of monetary and exchange problems. He also demonstrated a strong concern for the lot of the common Englishman and the importance of basic subsistence goods, goods ‘‘of the belly and the back,’’ and the importance of ‘‘putting men on work.’’ He specifically lauded a landlord who kept an Social Justice and the Subsistence Economy 21 unprofitable lead mine in operation because he was concerned for the welfare of the miners who would be otherwise unemployed (de Malynes 1622: 183). In his elaborations on the consequences of the disadvantageous exchange rates given the English pound sterling against Flemish and Dutch money, de Malynes pointed out the consequences of a drain of bullion out of England since the silver value of the coinage was in excess of its exchange value against continental silver. This meant that sterling was being exported and reminted at a profit. De Malynes understood that, under a quantity theory of money, this process would only result in a smaller amount of money being in circulation in England—which should increase its buying power and, consequently, enhance its value to foreign buyers in the long run. However, he was apparently thoroughly aware of the importance of internal domestic trade from his mercantile contacts and observations in Spain and the Low Countries. Limited amounts of money would result in the increased purchasing power of the existing coinage and lower prices and would limit its function in promoting petty trade, so vital to the viability of the domestic economy. To confirm his commitment in this direction, his final enterprise as an active participant in commercial affairs in England was a project to manufacture farthings, one-quarter of a penny, for private circulation. The purpose was to produce large amounts of petty money in the tradition of vellon (billon) or black money in the Mediterranean (Muchmore 1969). The demand for small change had led to various measures, including leather money and other chits or tokens to provide ‘‘change’’ appropriate for small transactions. What is even more interesting about de Malynes is that he drew on the basic Aristotelian formulation of a hierarchy of values to distinguish between barter as ‘‘the body of trade,’’ money as the ‘‘soul of trade,’’ and bills of exchange as the ‘‘spirit of trade’’ (de Malynes 1622). The interesting subtleties of this hierarchy go beyond the scope of this discussion. It is of interest to note that the basic association of the barter and petty-village economy with basic subsistence seems to have been kept alive by perpetuation of the Aristotelian analysis. De Malynes’ theoretical perceptions are part of this ongoing tradition of special concern for the subsistence level of the poor. It is reflected in John Locke’s assertion of the right of the poor to ‘‘share in nature’s feast’’ (Winfrey 1981). Smith developed a corollary of this analysis in his Theory of Moral Sentiments, to the effect that as a result of natural satiety the wealthy landlords have surpluses from their incomes which they invest in productive activity, thus advancing the public interest, ‘‘as if guided by an invisible hand . . . advance the interests of the society and afford means to the multiplication of the species’’ (Smith 1976: 219–20). CONCLUSION In retrospect, we have looked for the beginnings of a modern concept of social justice in the effort of Aristotle to define a naturally rationalized communitarian 22 The Idea of Social Justice economy. This contrasts with the previous concepts of authoritarian order tempered with some moral benevolence by an efficient and absolute ruler. Aristotle’s reasoned naturalism not only supported the idea that the offspring had a claim on any available social surplus, but his rational naturalism also reached into Roman law. Rational naturalism was thus extended to a concept of public legal protection for the young and the deprived. The somewhat desaltory evolution of various ideas on social justice suggests some patterns. There was a tradition of parental obligation to children, then community concern for the children, and, when grown, for the deprived. In Roman law, there were formal legal rights or legal obligations developed in favor of the young and, to some extent, the poor. In medieval times, there seems to have been a strong upsurge of a sense of individual moral duty to aid the poor while the emerging commercial towns expanded their commitment to a tradition of ‘‘entitlements’’ to ‘‘goods of the body,’’ in Aristotelian terms. As commercial economies advanced and grew more complicated, individual almsgiving ceased to be adequate, be it ever so laudable. Institutions such as orphanages and hospitals were established to carry the burden of care. With the emerging consciousness of the dynamic activity of the village and town economies of the Renaissance, concern for the interests and needs of the poor took on more subtle forms. Economic justice was linked to viable opportunity to participate in the benefits of vibrant and expanding economic activities. Spurred perhaps by the natural-rights tradition perpetuated in Roman law and the potential mischief implicit in restless urban mobs, both rulers and the privileged classes supported credit systems and advanced monetary policies that facilitated domestic economic activity. This long history of rationalized individual and institutional commitments can be correlated with a European tradition of social justice. It inverted the duty-rights orientation so that duty could flow from the rulers and the wealthy to the poor and deprived while rights could be rationalized and asserted by the dispossessed and unfortunate against the complacent and empowered. Braudel observes that ‘‘in the sixteenth century, after the true Renaissance, came the Renaissance of the poor, the humble, eager to write, to talk of themselves and of others’’ (Braudel 1972: 21). While Braudel considered this culmination of popular literacy a potentially misleading undercurrent when considering the forces that dominated the history of the period, we can appreciate the foundation to which this body of perverse literature contributed. The explosive political and economic philosophies of the seventeenth and eighteenth centuries that accompanied the growth of nation-states built on the traditions of legitimate demands and assertable rights to participation in the natural and rational processes of the economy, and, ultimately, the industrial revolution. REFERENCES Braudel, Fernand. (1972). The Mediterranean and the Mediterranean World in the Age of Philip II. Vol. 1. New York: Harper and Row. Social Justice and the Subsistence Economy 23 ———. (1982–1984). Civilization and Capitalism, 15th–18th Century, 3 vols. New York: Harper and Row. Calimani, Riccardo. (1987). The Ghetto of Venice. New York: M. Evans & Company, Inc. Cipolla, Carlo M. (1956). Money, Prices, and Civilization in the Mediterranean World: Fifth to Seventeenth Century. Princeton: Princeton University Press. de Malynes, Gerard. [1622]. (1981). Lex Mercatoria. Reprint, Abingdon, England: Professional Books Limited. de Roover, R. (1948). Money, Banking and Credit in Mediaeval Bruges. Cambridge, Mass.: The Mediaeval Academy of America. Dickinson, John, trans. (1963). The Statesman’s Book of John of Salisbury, being parts of the Policraticus. New York: Russell and Russell. Grice-Hutchinson, M. (1986). ‘‘El Discurso Acerca de la Moneda de Vellon, de Pedro de Valencia.’’ In Aportaciones del Pensamiento Economico Ibero-Americana, Siglos XVI–XX. Madrid: EdiciOnes Cultura Hispanica del Instituto de Cooperacion Ibero-Americana. Hands, A. R. (1968). Charities and Social Aid in Greece and Rome. Ithaca, N.Y.: Cornell University Press. Lane, F. C., and R. C. Mueller. (1985). Money and Banking in Medieval and Renaissance Venice. Vol. 1. Coins and Moneys of Account. Baltimore: Johns Hopkins University Press. Lis, C., and H. Soly. (1979). Poverty and Capitalism in Pre-Industrial Europe. Trans. from the Dutch. Atlantic Highlands, N.J.: Humanities Press Inc. Lowry, S.T. (1974). ‘‘The Archaeology of the Circulation Concept in Economic Theory.’’ In Journal of the History of Ideas, 35, 429–44. ———. (1987). The Archaeology of Economic Ideas: The Classical Greek Tradition. Durham, N.C.: Duke University Press. ———. (1988). ‘‘From Aristotle to Modigliani on Surplus and Intergenerational Transfers.’’ In Tore B. Holmesland and Knut J. Ims, eds., Bedrifts Økonomiens Helhet: Spenning mellom analyse og humaniora. Bergen, Norway: Alma Mater Forlag As, 246–53. Martz, L. (1983). Poverty and Welfare in Habsburg Spain: The Example of Toledo. New York: Cambridge University Press. Miskimin, H. A. (1975). The Economy of Early Renaissance Europe, 1300–1460. New York: Cambridge University Press. Mollat, Michel. (1986). The Poor in the Middle Ages. Trans. from the French by A. Goldhammer. New Haven: Yale University Press. Moryson, Fynes. (1908). An Itinerary Containing His Ten Years Travel through the Twelve Dominions of Germany, Bohmerland, Switzerland, Netherland, Denmark, Poland, Italy, Turkey, France, England, Scotland, and Ireland. 4 vols. New York: Macmillan. Muchmore, Lynn. (1969). ‘‘Gerard de Malynes and Mercantile Economics.’’ In History of Political Economy, 1, no. 2 (Fall), 336–58. Pirenne, Henri. (1986). Economic and Social History of Medieval Europe. Trans. from the French. London: Routledge & Kegan Paul Ltd. Pullan, B. (1971). Rich and Poor in Renaissance Venice: The Social Institutions of a Catholic State, to 1620. Cambridge, Mass.: Harvard University Press. Rubin, Miri. (1987). Charity and Community in Medieval Cambridge. New York: Cambridge University Press. 24 The Idea of Social Justice Smith, Adam. [1759]. (1976). The Theory of Moral Sentiments. 2 vols. Ed. A. L. Macfie and D. D. Raphael. Oxford: Clarendon Press, Glasgow Edition of the Works and Correspondence of Adam Smith, Vol. l. Thomas, J. A. C. (1975). The Institutes of Justinian. Trans. and commentary. Amsterdam: North-Holland Publishing Company. Winfrey, John C. (1981). ‘‘Charity Versus Justice in Locke’s Theory of Property.’’ Journal of the History of Ideas, 42, no. 3, 423–38. 3 The Origins of a Concept of Social Justice HOWARD L. ADELSON There is one example from the ancient world that contains the most complete paradigm of what is meant by social justice as distinct from righteousness or the call to upright living. In the Book of Nehemiah (Slotki 1951) the tale is told of how a protest arose among the poorer Jews who were dwelling in Jerusalem after the return from Babylon (Nehemiah 5.1–13; cf. Ackroyd 1970: 259).1 The problem arose because of the social and economic privation to which the poorest elements of the population were subjected. Nehemiah, the royal governor of Judah, was angry that such a protest was even necessary, and he promptly consulted the more affluent members of the community (called in the text ‘‘the nobles and the rulers).’’ Nehemiah rebuked them for the injustice and inequality that was rampant in the land. He also called a ‘‘great assembly’’ of the multitude of the Jews. To them he repeated the complaint and exhorted them to cease oppressing the poor and to restore the lands and produce as well as a part of the money that had been usuriously exacted. To the probable amazement of Nehemiah, the rich promptly agreed to restore all that had been exacted from the poor in its entirety. Immediately Nehemiah summoned the priests and exacted an oath from the rich and powerful that they would fulfill what had been promised. Symbolically, Nehemiah then shook out his cloak from his lap and called for the punishment by God of those who failed to keep their oath. He said, ‘‘So God shake out every man from his house, and from his labor, that performeth not this promise, even thus be he shaken out and emptied.’’ The people promptly assented by calling out ‘‘Amen,’’ and they praised the Lord. Nehemiah also records that, in fact, they carried out their promise completely. This story reveals the salient features of an act of social justice. In the first 26 The Idea of Social Justice place social justice is clearly a form of justice involving different classes of society and not between individuals. The doctrine of righteousness, as we shall see, regulated the relationship between individuals. In this case, it is also clear that the lower classes apparently had a recognized right of complaint (the Hebrew word is tza akah for a complaint).2 Clearly the lower classes did not have to seek permission to voice their complaint, nor did they have to resort to threats in the fashion that the plebeians of ancient Rome had to deal with the patricians during the early Republic when the Conflict of the Orders was taking place. It was apparently the natural right of these poor Jews to voice their complaint to the ruler—in this case Nehemiah, the governor. Their complaint, however, did not call upon the royal governor to give them justice; and, in fact, Nehemiah did not issue an edict satisfying the complaint of the poor. Instead, the upper classes voluntarily, and without any sanction, yielded justice and restored the possessions of the poor. The appeal of the poor had been made on the basis of the equality of those from different classes. They prefaced their complaint by saying, ‘‘Yet now our flesh is as the flesh of our brethren, our children as their children; and lo, we bring into bondage our sons and daughters to be servants, etc.’’ (Nehemiah 5.5). The complaint is obviously addressed not merely to the royal governor but to the general assembly that particularly includes the oppressing class as well as the oppressed. The oppressing class, recognizing the equality of all and the socioeconomic injustice, promises restitution and justice for the oppressed. This is then confirmed by oaths and carried out completely. This single incident differs from all others in the ancient and medieval worlds. While our knowledge about the reforms of Solon, Cleisthenes, Lycurgus, or the Conflict of the Orders in Rome, and the struggle of the Gracchi is extensive, there is not the slightest indication that the lower classes enjoyed a recognized right to demand social justice, and certainly, in almost all cases, the upper classes refused to concede voluntarily any rights to the oppressed. In the case of Lycurgus, as described in the Life of Lycurgus by Plutarch (Perris 1982), some 700 years or more later, it was only the Spartan upper class that had to be convinced to live in a society that granted equality among the Spartiates, and the Spartiates alone. Even during the social turmoil of the early Roman Republic, while the patricians were oppressing the plebeians and the plebeians were striving for social and political rights, there was no suggestion that the plebeians had a right to make demands, nor did the patricians yield spontaneously without a resort to threats by the lower classes. None of the descriptions by Herodotus, Thucydides, Aristotle, Polybius, Livy, or even Plutarch, to mention only a few of the ancient authors, yields the slightest indication that a concept of social justice existed. Similarly, it should be noted that in the Roman law, in the Institutes of Gaius as well as those of Justinian, there is not the slightest suggestion that social justice existed even as a purely jurisprudential concept. There are argumenta ex silentio that should not be made by a historian. We can, however, demonstrate that there were other intellectual and conceptual Origins of a Concept of Social Justice 27 frameworks that existed in the ancient and medieval worlds that invalidated the possibility of a concept of social justice among the ancient and medieval people except in the world described by Nehemiah in the post-Exilic period. If, for the moment, one goes back to the ancient Egyptian or Mesopotamian sources, the demand for individual righteousness, even in the absence of a divine sanction resting upon a systematic concept of reward and punishment, is clearly present. Similarly, the oldest parts of the Bible reveal a similar demand for individual righteousness. Very often this is connected with charity and kindness as in the case of widows and orphans, but sometimes it is the cause for a legal enactment. Such an incident occurs in the story of the daughters of Zelophahad who implored Moses for the right to an inheritance of land even though they were daughters and not sons. Moses solved this problem by consulting with the Deity, from whom he received the judgment to grant the demand of the daughters of Zelophahad (Numbers 27.1–5; Cohen 1956: 27). The concept of social justice clearly involves the idea of a relationship between the various classes of society. Righteousness and uprightness, however, are private and individual virtues. It is the individual who is exhorted to be kind and generous, and there is no evident right of the oppressed to complain. In ancient Mesopotamia the practice of referring to ‘‘righteousness’’ and ‘‘uprightness’’ is analogous to the use of those terms among the ancient Hebrews in the Bible. It would seem as though the virtues of righteousness and uprightness were shared by both deities and humans, primarily rulers among the Mesopotamian peoples. Analogously, among the Hebrews the Lord is spoken of in precisely those terms of righteousness and uprightness. It would seem as though among the Mesopotamian peoples what is implied in these terms is acting in accordance with the law. Hammurabi, on his great stele on which his code was written, refers to himself in the last paragraph as the ‘‘King of Righteousness’’3 (Pritchard 1955: 163–80, esp. 178; also see Driver and Miles 1952). The belief that a central function of kingship is the carrying out of justice, that is, fulfilling the law and enunciating the law, is a feature not merely of the earliest stages of monarchy but even of the monarchies of the Middle Ages. The idea of the king as a source of justice was very popular during the Middle Ages. Representations of this, as we know, exist in the medieval iconography of monarchy, and the giving of justice is one of the royal virtues throughout the Middle Ages. An excellent example exists in the Monte Cassino Gospels (A.D. 1022–1023) of the Emperor Henry II as a judge (Kantorowicz 1957: fig. 20). In ancient Egypt the word ma at, which is often simply translated as ‘‘righteousness,’’ obviously has a much broader meaning including ‘‘truth’’ and ‘‘justice.’’ It is obviously a cognate of the Semitic word ‘‘emet’’ meaning ‘‘truth.’’ It also seems as though it implies simply the correct order of the cosmos. In that sense it means ‘‘rightness’’ rather than ‘‘righteousness.’’ The most significant element in the concept of ma at appears to be not doing evil rather than doing good. In the Book of the Dead the suppliant in the ‘‘Broad-Hall’’ of the ‘‘Two Justices,’’ an obvious relic from the period before the unification of 28 The Idea of Social Justice Egypt, proclaims that he has not done evil or anything wrong (Pritchard 1955: 34–36; also see Renouf and Naville 1904: chap. 125, 212–44). It is interesting that the concept or memory of the two lands of Egypt is preserved in the Hebrew name for Egypt, Mizraim, which, like Sepharvaim, the two Sipparas, is a dual construction meaning ‘‘the two Egypts.’’ That, of course, parallels the framework of the ‘‘Two Justices’’ and the fact that the pharaoh wore one crown for Upper Egypt and another crown for Lower Egypt. Within Egypt there was obviously a call for righteousness and uprightness, but it did not involve a concept of social justice, meaning justice between different classes of society. Rather it was a call for individual uprightness and truthfulness. Obviously justice is the core concept, but it is justice for individuals even if one speaks of giving justice to widows. The royal official was expected to act as a court of equity and not to make distinctions in giving justice between the lowly and the powerful. Nowhere, however, is there a concept that all people are equal in moral terms and are entitled to social and economic rights to express that human equality. In other words, the Egyptian concept of uprightness and righteousness is highly individualized and is deeply intertwined with an attack upon judicial corruption and violation of the law. One must not insist too much upon this connection with justice, but perhaps, as was stated above, the locus classicus of the Egyptian conception of morality and justice is the so-called ‘‘Declaration of Sinlessness,’’ often called the ‘‘Negative Confession’’ in the Book of the Dead. The setting is a court, and the moral value of the declaration is virtually nil because it is embedded in a magical spell. The ancient Egyptian believed that the essence of anything, das Ding an sich in Kantian terms, resided in its name. That is by no means a uniquely Egyptian belief because it can be traced in many cultures. It is still a belief that is found in certain parts of Western society. There is a reminiscence of this concept in the Bible, as seen in Genesis 2.20 (Cohen 1956), where Adam names all of the animals and birds. In the Egyptian example in the Book of the Dead the scene takes place in the Broad Hall of the Two Justices where the judgment of the dead by Osiris is taking place. At that point the dead Egyptian is instructed how to prepare for casting the spell that will force the forty-two gods to accept his declaration of innocence. In his preparation the dead Egyptian announces to the gods that he can make them accept his declaration because he knows their names. The knowledge of the name gives one power even over the gods (Pritchard 1955: 163–80). In any event, the Declaration of Sinlessness and the entire Book of the Dead does not deal with the equality between the classes of society. It is the usual restatement of what is meant by righteousness. It merely treats the claims necessary for the Egyptian to be believed to be a righteous and upright individual. In that connection the constant refrain of Egyptian and Mesopotamian rulers and officials to having performed acts of charity, such as assisting widows and orphans, does not imply a conception of social justice. Even with the rise of the classical culture of Greece and Rome, with its Origins of a Concept of Social Justice 29 emphasis during the Roman period on jurisprudence, there was a failure to create a coherent concept of social justice. The Digest, a book devoted to jurisprudence, begins with a discussion of what is ius or ‘‘right,’’ and what is lex or ‘‘law’’4 (I.1.1 Krueger 1954: 29). In the Roman system of jurisprudence as set forth in the Digest, justice is described as the art of the good and the equitable, a definition originating from Celsus. In a slightly later passage, the word justice (iustitia) is defined as the perpetual will to give each his proper deserts (‘‘ius suum cuique tribuendi’’). It then says that the precepts of justice are to live honestly, to harm no one else, and to give each his proper due (I.1.10 Krueger 1954: 29). The ancient Greeks, of course, discussed justice in philosophical terms, but they did not feel that law was necessarily a product of justice. For the Greeks justice was not a legal concept. Justice is probably the accurate translation of δ κα οσ ´ νη, which, along with courage, self-control and wisdom, constituted those four cardinal virtues that were encompassed in the conception of moral ) goodness, αρετη (Barker 1951: 176). Since such goodness could exist both ´ within the individual soul as well as within a community of individuals, it was a social as well as an individual virtue. It was, however, not an expression of law but of morality. In Plato’s Republic justice is part of goodness. In the case of the individual it is the relationship of the elements of the soul (reason, spirit, and appetite). In like fashion, the goodness of society may, for all practical purposes, be identified with the relationship of its various constituent elements. ‘‘The State which has ταξ s κα´ κο σµοs among its members through the faith´ ´ ful abiding of each in his station, and is thereby just, is also good’’ (Barker 1951: 153, n.2). Clearly the Platonic philosophical concept of justice involved acceptance of the inequalities that exist among the classes of mankind rather than the right of the oppressed to demand corrective action and the duty of the powerful to grant corrective action. Such a conception, as we shall see, involved belief in the equality of mankind that was not present in the classical world but which has its roots in the Hebrew Bible.5 Professor Irani has certainly emphasized the most crucial point about Aristotle’s conception of justice, which is that ‘‘justice requires that equals be treated as equals and unequals as unequals’’ (Irani 1981: 35–41 and esp. 37; cf. Evans 1981: 45–46, 52). The problem is how to give each his due, that is, his just deserts, and at the same time to treat all equally. The necessity of treating all equally, however, only arises if one believes that all men, or at least that segment of mankind to which the principle of social justice is to be applied, are, in fact, equal in some sense (Sabine 1954: 25–27, 54–55; also see Barker 1951: 139, n.2 and 256, n.1). For philosophers, like Plato, lacking the concept of ius or that contained in the English word ‘‘right,’’ justice is not a legal concept. It is rather the harmonious union of individuals each contributing, according to his natural fitness and his training (Sabine 1954: 55). Greek preoccupation with moderation and balance in human relationships precluded the Greek from asking for social jus- 30 The Idea of Social Justice tice in which the individual and society would be asked to go far beyond the limits of moderation and balance. Social justice, as illustrated in the passage in Nehemiah, requires that certain classes of society give much more to other classes than that to which they are legally entitled. It is also not an act of charity or kindness, which might be satisfied by the giving of alms. Thus, social justice implies moral obligations that transcend the class structure and even the legal inequality of citizens. While the ancient Greeks recognized a divine law, ε µ s and a human law, ´ νοµοs, there is never a suggestion even in the concept of δ´κη or of ` δ κα οσ ´ νη, which is normally translated as righteousness, of a demand for social justice in early Greek authors such as Hesiod6 (Sinclair 1932: 1–34 [LL. 1–302]). Every psephisma (i.e., decree) or the Athenian state, as we know from ) 7 7 7 ´ the epigraphical evidence, begins with the phrase, ‘‘E δοξεν τη βο λη κα´ τω 7 δηµω’’ meaning ‘‘It seems right to the Council and to the people (of Athens,)’’ but there is not the slightest moral implication in that preface. Greek law and practice did not envision anything remotely resembling social justice. For the Roman, with a finer set of juridical ideas, there was a distinction that existed among the varieties of law such as the ius civile, the ius gentium, and the ius naturale. It is, however, with the ius civile, the law of the Roman people, that we are concerned and not with the presumed religious prescriptions and rights or other forms of law recognized by the Roman state. According to the two ancient textbooks of Roman law, the Institutes of Gaius and the Institutes of Justinian, laws are decrees of the Senate that have been confirmed by one of the assemblies of the Roman people. Therefore, we have the use of the expression senatus populusque Romanorum in the proclamation of such laws. The actions of the Senate alone were known simply as senatus consulta, and those of the concilium plebis, which were not confirmed by the Senate, were known as plebiscita. What is important is that the Romans recognized law as the product of human action. In the Institutes of Justinian we are told that the will of the princeps has the force of law because the people have voluntarily surrendered to him their power. That this was the fact is illustrated by the famous epigraphical text of the Lex de Imperio of Vespasian which was preserved in small part when Cola di Rienzi placed a bronze tablet containing the last part of that law in the Basilica of St. John Lateran7 (Dessau 1865; I, 67 [no. 244]; also see Newton 1901: 2–3). While Roman history was replete with the struggle of the Orders in the early days of the Republic, the demands of the plebeians were never accepted immediately as justified by the patricians. The Romans of the early Republic did not accept the equality of man, and even the grants that were made to the plebeians simply confirmed their legal and political rights. It is clear that the Romans accepted the basic principle that all men were free by the ius naturale, but they accepted without a murmur the provisions of the ius gentium that permitted slavery. Roman literature reveals beyond any question that the prerequisites for a belief in social justice as we have described them on the basis Origins of a Concept of Social Justice 31 of the paradigm found in Nehemiah were not to be found in ancient Roman thought. The Romans did not arrive at a concept of social justice. Men of the Middle Ages, with a fully developed hierarchical concept of society, were completely incapable of arriving at a concept of social justice. Much earlier than the justly famous Capitulary of Kiersy of the middle of the ninth century, the arrangement of society in a hierarchical system that was to make manorialism and feudalism completely comprehensible was well established in Western Europe. As James Westfall Thompson noted seventy years ago, the socalled tripartite division of society into workers, warriors, and priests was adumbrated in a letter of Pope Zacharius to Pepin le Bref and his prelates and nobles. Pope Zacharius only spoke of the warriors and priests, but he did describe their functions in the maintenance of society8 (Thompson 1923: 593, n.1). The concept of law among the Germans in the early Middle Ages was one that rested upon the belief that the law was the mos maiorum and not the product of legislation. Thus, law might be discovered in response to social and political needs, but it was not the product of legislation as in the classical world. It was the customs of one’s ancestors, as they were recalled by those who were supposed to know the law. Law was therefore not generated either by a living group of men or by God.9 While new ideas of representative government were developed during the course of the Middle Ages, those ideas did not lead to a concept of social justice. The concept of the communitas regni, the community of the realm, became a political reality in the later Middle Ages, but it had no influence upon the development of an idea of social justice. In a word, social justice was as foreign to the Middle Ages as it was to the classical world. The roots of the concept of social justice as expounded in the paradigm of Nehemiah are to be found in the experience within Jewish culture and tradition that was the formative element for Nehemiah and his compatriots. There was a hiatus of some 2,500 years before the concept was resurrected in meaningful terms in the nineteenth century. It is obvious that human suffering and social strife have been a product of civilization that can be traced back to the earliest days of history, but the last days of the Kingdom of Judah, the Babylonian sack of Jerusalem, and the turmoil of the restoration after the conquest of Cyrus the Persian yielded a particularly striking example of suffering and social strife. While the term social justice is obviously of very recent origin, probably from the early nineteenth century10 (Shields n.d.: 26ff.), the concept of a society based upon the equality of man and requiring humane treatment of the lower, poorer classes, as a right of those classes and as a duty of the more fortunate, appears to be a product of a particular set of circumstances during the ancient period. This conception of social justice as distinct from the mere call to individual, or even national, righteousness, or of an overwhelming belief in the harmony of the various classes, homonoia or concordia, which was celebrated as an ideal in the classical world of the Greeks and the Romans, is quite remarkable. It is distinct from the 32 The Idea of Social Justice use of the term social justice in the modern world. It is not surprising that many of the most violent and bigoted groups in the modern world have utilized the term social justice for their own nefarious purposes without the slightest degree of loyalty or commitment to the ideal that is supposedly enshrined within the term. The principal writers on the subject of social justice in the modern world have been derived from the Catholic community. A simple perusal of the bulk of the literature reveals that fact. In some measure this is undoubtedly a result of the restrictive definition applied by Catholic authors to the concept of social justice and the vain attempt to find that it was among the concerns of medieval man— and, particularly, of St. Thomas. That has become a source of mental gymnastics because of the attempt to identify social justice with the legal justice described by St. Thomas11 (Ferree 1948: 16–18, 63–77, 81–87, 149). It remains clear, however, that though St. Thomas has a great deal to say on the topic of legal justice and of the common good and general virtue, he was nevertheless a figure of the Middle Ages, and as such he believed in a well-ordered society in which there were contractual relationships established between the various orders of society. The ideal expounded in Nehemiah is simply not to be found in the works of St. Thomas or his philosophy. There is, of course, a great temptation to identify social justice with social democracy and to insist that if one exists, then the other must also be present, even if only in an ancillary fashion. It can, however, be easily demonstrated that the equality of man is not a necessary axiom of social democracy. The conception of a world order by a supposedly social contract that binds ruler and subjects with specific obligations and duties does not imply social justice. That individual classes sought liberty in a quite restrictive sense and were determined to secure justice for themselves does not imply that they had a developed conception of a series of obligations to grant an equal privilege to others or to succour those who were less fortunate. Even at the end of the Middle Ages, when peasants chanted, ‘‘When Adam delved and Eve span, who was then the gentle man?’’ it is obvious that they were seeking the removal of onerous burdens that had been placed upon them over the centuries and not that they were proclaiming a crude egalitarianism. Medieval man believed in an ordered society with welldefined classes, each of which was to perform a task for the common good. There was, however, to be harmony among the classes. He believed that there could be unjust oppression of one class by another, but that is a far cry from the demand that the more fortunate must assist the less fortunate because it is both an obligation and right to ask for such assistance. As was pointed out above, the concept of concordia ordinum or homonoia did not require the correlative belief in social justice. The evidence is quite clear, according to Professor Louis Finkelstein, that social strife was marked in Jerusalem and throughout Judah during the final years of the Davidic monarchy and after the return from the Babylonian Exile. Not only was there conflict between the upper-class urban society of Jerusalem Origins of a Concept of Social Justice 33 and the rustic peasant society of the countryside, but there was a struggle between the great landowners who could afford to take advantage of life in the city and the poorer peasants who experienced great difficulty in every phase of life (Finkelstein 1962, 1: 7–42, and passim). This conflict found expression in many ways and undoubtedly involved not only the urban poor and their neighbors—the nobles, priests, and great merchants—but also the provincial class of the am ha-aretz and the upper classes of Jerusalem. There seems to be little doubt that the suffering of the poor was intense during the final days of the Kingdom of Judah before the Babylonian conquest and even during the siege of Jerusalem by Nebuchadnezzar. One incident from the period of the siege reflects the antagonism between the classes as well as the call for righteousness that had been the prophetic message for hundreds of years before the siege. While the siege was at its height, apparently the upper classes, determined to gain God’s grace, liberated their bondsmen before the requisite six years had been fulfilled. Then, perhaps because Nebuchadnezzar for some reason withdrew for a little time or because the forces of the besieged enjoyed a momentary victory, they promptly reenslaved their compatriots12 (Finkelstein 1962, 1: 304– 5; see also Jeremiah 34.12–22; Friedman 1949). The Prophet Jeremiah fulminates against the wickedness of the princes and the injustice of their actions. He prophesies condign punishment because of their sinfulness. Ezekiel, who prophesied in Babylonia during the Babylonian Exile, is quite clear in his anticipation of a period of restoration in which social justice and perfect equality will be evident and in which the wickedness that afflicted society will be condemned13 (Finkelstein 1962, 1: 332–33). What is most striking, however, about this prophesy of Ezekiel is his insistence upon the equality of all mankind (Ezekiel 18.25; Fisch 1950). One must not treat one individual as having greater intrinsic value than another. The poor are not to be considered merely the objects for righteousness and the recipients of charity. They have a right to real justice because of the innate equality of mankind. Since they are equal to all others, they should receive a decent living and kind treatment. This is carrying the prophetic message to a logical conclusion. Ezekiel, however, does not speak of human punishment or legal sanction for those who violate this moral imperative. Rather it is the Lord who will exact justice for those who pursue a wicked course. The evidence of the intense suffering of the lower classes in the period immediately before the Babylonian siege and in the aftermath of the destruction of Jerusalem is overwhelming. The catastrophic nature of the destruction of Jerusalem and the disastrous ruin of much of the rest of the land as a result of the Babylonian invasion is just beginning to be understood14 (Ackroyd 1970: 6ff.; Wright 1960: 108–26). Assyrian and Babylonian armies had wreaked havoc in the western Fertile Crescent. The final siege of Jerusalem was certainly a catastrophe of overwhelming dimensions, and Professor Finkelstein is certainly correct in insisting upon its completeness and its influence upon the ideas that arose at the time. 34 The Idea of Social Justice There seems little reason to question that the upper classes of the post-Exilic period dreamed of a restoration of all of their privileges and a return to the conditions before the catastrophe. The provincial rustics and the urban poor, however, found solace in a new religious conception that was established by a new class of pietists who were the forerunners of the Pharisees. The urban poor, drawn from the returning exiles, also provided supporters for this new doctrine of social justice15 (Finkelstein 1962, 2: 455, 460–61). Its universality is clearly seen in the prophecy of Deutero-Isaiah, which obviously refers to the period after the conquest of Babylon by Persia and the Jewish restoration16 (Isaiah chaps. 40–66). The expectation of a just world was the promise of the future. Israel is described by the Prophet as ‘‘a covenant of the people, a light for the gentiles’’ (Isaiah 42.6; Slotki 1957). He pictures the call to social justice in place of the sterile ritualism when he pre reward.17 (Isaiah 58.6–8) It appears quite clearly that the paradigm of Nehemiah does not stand alone in solitary splendor. It is an incident demonstrating a monumental change in the ideas that were being promulgated in the period of the restoration under Ezra and Nehemiah. This concept of social justice went far beyond the call for individual righteousness that existed much earlier and that was directed at the conduct of individuals toward other individuals and not toward establishing the relationships of equals between classes of society. The development of ideas of human equality and the universality of doctrine combined with the suffering and social strife that accompanied events in the period surrounding the Babylonian Exile and the return made the creation of an ideal of social justice possible. This ideal, however, was to remain quiescent for two and a half millenia until the message was resurrected in modern form during the nineteenth century. In its new garb, however, it was often used by bigots. In addition, since our legal concept of rights only recognizes those rights that are enforceable, the idea of social justice was converted from a moral into a political and legal ideal in modern society. NOTES 1. Ackroyd missed the entire significance of this passage, as did the other commentators. Origins of a Concept of Social Justice 35 2. The word has many uses in the Bible indicating a protest or a complaint. It was used as a legal term at a later period. 3. The Code of Hammurabi was translated by Theophile J. Meek. 4. The passage is derived from Ulpian. Cf. Micah 6.9: ‘‘It has been told thee what is good and what the Lord requireth of thee. Only to do justice and to love mercy and to walk humbly with God.’’ Also see Carlyle n.d.; 1: 57–59. On the biblical sources for righteousness see Kennett, Adam, and Gwatkin 1910: passim. A much better discussion of the term in various cultural settings is to be found in Hastings, Selbie et al., 1908– 1927; 10: s.v. righteousness. 5. Cf. Plutarch, Lycurgus 7 (Perris 1982, 1: 226–28) where he discusses the redistribution of land at the urging of Lycurgus. See, however, the revolt of the aristocracy as a result of the dissatisfaction with the reforms of Lycurgus (234). Plutarch attributes to Lycurgus the equality of all Spartiates economically, but he points to the differences based on merit. Cf. Barker 1951: 320–21. 6. See Sinclair 1932: 1–34. There is a fine translation by Lattimore 1959: 19–55. 7. The fragment of the lex regia of Vespasian is the only one that has survived from ancient Rome. The practice, however, is well attested, and it was revived in the early modern period in Europe. See Iustinianus, Institutes, 2, 6 (Krueger 1954: 29): ‘‘Sed et quod principi placuit legis habet vigorem, cum lege rege, quae de imperio eius lata est, populus ei et in eum omne suum imperium et potestatem concessit.’’ 8. Codex Carolinus, No. 3 (MGH Epistolae karolini aevi, I, 480): ‘‘Principes et seculares homines atque bellatores convenit curam habere et sollicitudinem contra inimicorum astutiam et provintiae defensionem, praesulibus vero sacerdotibus adque Dei servis pertinet salutaribus consiliis et oracionibus vacare, ut, nobis orantibus et illis bellantibus, Deo presstante, provincia salva persistat, fiatque vobis in salutem laudem et mercedem perpetuam.’’ This passage was cited by Thompson. 9. Side by side with the secular law, of course, there was the canon law, or religious law. The Church, however, did not merely accept the hierarchical organization of society but strongly taught that doctrine. The Church preached individual salvation through faith and righteousness or uprightness. Piety and righteousness, however, are not the sources of the doctrine of social justice. Pleas for the care of the poor are couched by the Church in terms of charity and not social justice. In the period of the Gospels and of the early Church, one can trace the development of doctrines about the equality of mankind and the universality of doctrine. For example, Mark 7.25–30 has Jesus say to the SyroPhoenician woman with regard to spreading his doctrine to the Gentiles: ‘‘Let the children first be filled: for it is not meet to take the children’s bread and to cast it unto the dogs.’’ See, however, the later passage in John 4.6–47, where Jesus, in speaking to the Samaritan woman, is obviously taking a universalistic approach. John is, of course, replete with anti-Jewish passages that can hardly be seen as proof for the equality of all mankind. Cf. John 8.31–59. It is much clearer in the preachings of St. Paul and in a statement by St. Peter at the Council of Jerusalem. See Acts 15.1–11; 20, 21; Romans 2.10–29; 11.1–36; I Corinthians 1.22–25; 9.19–23. St. Paul has some things to say about the subjection of women that infuriates modern feminists who pay less attention to the passages in which he preaches human equality. One should take note of the fact that the newspaper published by Father Coughlin, an extreme bigot in the thirties, was called Social Justice. Clearly, it is not an act of social justice within the paradigm set forth by Nehemiah when modern states exact taxes from one or more classes of society to utilize 36 The Idea of Social Justice that wealth for the benefit of a lower class. The individuals paying the taxes are doing so under compulsion. 10. Cf. Ferree 1948: 83–84. He follows the opinion of most in dating the first use of the term to 1845 when it was used by Tapperelli. Shields takes the same position. Also see Catholic Encyclopedia, 8: 572, s.v. justice (by T. Slater) for a distinction between individual righteousness and social good works on the issue of social justice. Cf. McCarthy 1990: 60-69, 249–54, and 302–8, for an indecisive attempt to find these moral values in the writing of Marx. On the issue of whether or not Marx had a vision of social justice, McCarthy’s effort reminds one of Abelard’s Sic et Non, and it is equally unsatisfying in simply leaving the conclusion to the reader. It cannot, however be ignored that Marx preached a classless society, and as a result his work would not fit the paradigm of Nehemiah. The very idea of dialectical materialism argues against any belief in social justice in the terms of the paradigm from Nehemiah. 11. Ferree also discusses the relation between the ideas of Aristotle and those of St. Thomas on the issue of justice. It is interesting to record that the meaning of the term was stretched far enough to permit Pope Pius X in the twentieth century to extol St. Gregory the Great as a ‘‘public champion of social justice’’ because he resisted the unjust pretensions of the Byzantine emperors. See [Iucundum Sane] in Actae Sanctae Sedis 36 (1904): 514–15: ‘‘Vere Dei consul factus [inscr. sepulcr.] actuosae voluntatis fecunditatem ultra Urbis moenia porrexit, totamque in bonum consortii civilis impendit. Byzantinorum imperatorum iniustis postulationibus restitit fortiter exarcharum et imperialium administrorum fregit audaciam, sordidamque avaritiam coercuit, publicus iustitiae socialis adsertor.’’ 12. Jeremiah is the source for the story (Jeremiah 34.12–22). Cf. Micah 2.1–3 in Cohen 1957, for a somewhat earlier attack upon social injustice. Ezekiel 34.1–19 also appears to be a plea for social justice. 13. Ezekiel 3.17ff., is a simple call to righteousness. Ezekiel often preaches about the need for reformation. Ezekiel 34.1–19, however, is certainly a vision of social justice in which all are equal. 14. Recent excavations in the City of David confirm the completeness of the destruction and the probable suffering of the inhabitants during and after the Babylonian Exile. 15. Surprisingly, Finkelstein does not cite the example of social justice described in Nehemiah. 16. Universality and equality are the themes of this restoration, which is to be greater than all that preceded it. The attack upon idolatory is couched in terms of a past human failing. The comfort of the future lies in the achievement of a new perfection. Also see Finkelstein 1962, 2, 490ff. 17. Cf. Zechariah 8.16–17 in Cohen 1957, where doctrines that adumbrate the idea of social justice are adumbrated before the destruction of Jerusalem. REFERENCES Ackroyd, Peter R. (1970). Israel Under Babylon and Persia. Oxford: Oxford University Press. Actae Sanctae Sedis 36 (1904). [Iucundum Sane]. Barker, Sir Ernest. (1951). Greek Political Theory: Plato and His Predecessors. London: Methuen & Co. Origins of a Concept of Social Justice 37 Carlyle, R. W., and A. J. Carlyle. (N.d.). A History of Political Theory in the West, 3rd ed., 5 vols. Edinburgh: William Blackwell & Sons. Cohen, Rev. Dr. A. (ed.). (1956). The Soncino Chumash: The Five Books of Moses with Haphtaroth, Hebrew Text and English Translation with an Exposition Based on the Classical Jewish Commentaries. London: Soncino Press. Cohen, Dr. A. (ed.). (1957). The Twelve Prophets. Hebrew Text, English Translation and Commentary. London: The Soncino Press. Dessau, Hermann (ed.). (1865). Inscriptions latinae selectae. 8 vols. Berlin: Weidmann. Driver, G. R., and John C. Miles (eds.). (1952). The Babylonian Laws Edited with Translation and Commentary [Ancient Codes of the Near East]. Oxford: Clarendon Press. Evans, Charles. (1981). ‘‘Justice as Desert.’’ In Randolph Braham (ed.), Social Justice. Boston: Martinus Nijhof. Ferree, William. (1948). The Act of Social Justice. Catholic University of America Philosophical Studies, no. 22. Washington, D.C.: Catholic University of America Press. Finkelstein, Louis. (1962). The Pharisees: The Sociological Background of Their Faith, 3rd ed., 2 vols. Philadelphia: Jewish Publication Society of America. Fisch, Rabbi Dr. S. (ed.). (1950). Ezekiel, Hebrew Text and English Translation with an Introduction and Commentary. London: Soncino Press. Friedman, Rabbi Dr. H. (ed.). (1949). Jeremaiah. Hebrew Text & English Translation with an Introduction and Commentary. London: Soncino Press. Hastings, James, and John A. Selbie et al. (eds.). (1908–1927). Encyclopedia of Religion and Ethics. 13 vols. Edinburgh: T. & T. Clark. Herbermann, Charles G. et al. (eds.). (1907–1914). Catholic Encyclopedia: An International Work of Reference on the Constitution, Doctrine, Discipline and History of the Catholic Church. 16 vols. New York: Encyclopedia Press. Irani, K. D. (1981). ‘‘Values and Rights Underlying Social Justice.’’ In Randolph Braham (ed.), Social Justice. Boston: Martinus Nijhof. Kantorowicz, Ernst H. (1957). The King’s Two Bodies. A Study in Medieval Political Theology. Princeton: Princeton University Press. Kennett, R. H., Mrs. Adam, and M. M. Gwatkin. (1910). Early Ideals of Righteousness: Hebrew, Greek and Roman. Edinburgh: T. & T. Clark. Krueger, Paul (ed.). (1954). Institutiones [Corpus Iuris Civilis]. Berlin: Weidmann. Lattimore, Richard (trans.). (1959). Hesiod, Works and Days, Theogony, The Shield of Herakles. Ann Arbor: University of Michigan Press. McCarthy, George F. (1990). Marx and the Ancients: Classical Ethics, Social Justice and Nineteenth Century Political Economy. Savage, Md.: Rowman and Littlefield. Mommsen, Theodore (ed.). (1954). Digesta [Corpus Iuris Civilis]. Berlin: Weidmann. Monumenta Germaniae Historica (MGH). Epistolae karolini aevi, I [Codex Carolinus]. Newton, H. C. (1901). The Epigraphical Evidence for the Reigns of Vespasian and Titus. Cornell Studies in Classical Philology, no 16. New York: Macmillan. Perris, Bernadette (trans.). (1982). Plutarch’s Lives With an English Translation. Loeb Classical Library. Cambridge, Mass. and London: Harvard University Press and William Heinemann. Pritchard, James Bennett (ed.). (1955). Ancient Near Eastern Texts Relating to the Old Testament. Princeton: Princeton University Press. Renouf, Peter Le Page, and E. Naville. (1904). The Egyptian Book of the Dead. London: Society of Biblical Archaeology. 38 The Idea of Social Justice Sabine, George. (1954). A History of Political Theory. Rev. ed. New York: Henry Holt and Company. Shields, Leo W. (n.d.). The History and Meaning of the Term Social Justice. South Bend, Ind.: Notre Dame Press. Sinclair, T. A. (ed.). (1932). Hesiod’s Works and Days. London: Macmillan and Co., Ltd. Slotki, Rev. Dr. Israel W. (1957). Isaiah: Hebrew Text and English Translation with an Introduction and Commentary. London: The Soncino Press. Slotki, Rev. Dr. Judah J. (ed.). (1951). Daniel, Ezra and Nehemiah. Hebrew Text With An Introduction and Commentary by Dr. Judah J. Slotki. London: Soncino Press. Thompson, James Westfall. (1923). ‘‘The Development of the Idea of Social Democracy and Social Justice in the Middle Ages.’’ American Journal of Sociology, 28, 586– 605. Part II Articulation of the Idea of Social Justice in the Ancient World 4 ¯ KHREMATA: Acquisition and Possession in Archaic Greece THOMAS J. FIGUEIRA My purpose in this chapter is to explore archaic attitudes toward affluence and poverty and toward upward and downward social mobility, using a semantic approach in which the evidence for the deployment of a characteristic terminology will be evaluated. First, it is necessary to delimit the subject chronologically and from the standpoint of the socioeconomic orientation of the sources. By archaic Greece, I denote the period beginning between ca. 750 B.C., when most Greeks began to live in poleis or city-states, and ending in 480–479 B.C., when the invasion of Greece by the Persians was repelled. Therefore, my primary focus will not fall on hexametric poetry, which, either necessarily or conventionally, describes a Dark Age, pre-polis society. We may need to have Homer and (especially) Hesiod in the back of our minds in understanding our sources, but my preoccupation here will be with those poetic traditions that are pervaded by a consciousness of the form of the polis and of its systemization of articulated relations between social groups. It is also essential to emphasize that the ethos of subsistence farmers is not a central concern here. Low-grade, autarkic cultivation supported the vast majority throughout the period, dominating many economies. Yet, its characteristic semantics, at least as may be discerned from Hesiod’s Works and Days, do not differentiate individuals and groups analogously to the terminological systems exhibited below. Instead, we must grapple with one of the most prominent and stark of the archaic polarities, wealth and poverty. The actual distribution of assets and incomes in many poleis may have approximated a continuum, with both the level of discontinuity and the placement of sharper gradations differing from city to city. The wealth and poverty occupying our attention were marks 42 Articulation of Social Justice of critical distinction, not simply the ends of a continuum. This wealth stood as a major, conspicuous focus for social attention, carrying with it a claim to political leadership. I have searched archaic poetry for the appearances of terms associated with several clustered concepts. The poets who have been surveyed are listed under Abbreviations (see the Table of Abbreviations, p. 59). The editions after which they are cited may be found in the Thesaurus Linguae Graecae: Canon of Greek Authors and Works2 (Oxford, 1986). Semantic categories are listed under Vocabulary, in which relevant terms appear in transliteration with English translations. My point of departure was the body of poetry transmitted to us under the name of Theognis. The Theognidea, as the corpus is also called, were composed in elegiac couplets of hexameters and pentameters. Archaic elegy contained instructive and admonitory statements, often with a gnomic character. This aphoristic quality encouraged later abbreviation of the poems into epigrammatic shapes. In some communities, elegiac poetry was a primary vehicle for the transmission of elite values between generations. As can be seen from the ‘‘Table of Attestations,’’ Theognis contains the most elaborate extant repertoire of archaic statements on the material conditions of human existence. Not only does the nature of elegy offer clues toward understanding why this is so, but the history of the Theognidea indicates how it became an unusually influential exposition of views on economic status. Theognis was the poetic persona assumed by a number of Megarian poets active from the late seventh or early sixth century down to the early 470s. An initial context for the circulation of the poetry was the elite at Megara, a city lying directly west of Attica, and its colonies in Sicily, the Sea of Marmara, and the Black Sea. The vividness and polemical thrust exhibited in these poems is owed considerably to the sharp ideological division between Megarian aristocrats and demos ‘common people’. ¯ Theognidian elegy, as the generic vehicle for the dissemination of an elite, exclusivist ideology, was opposed by early Megarian comedy, encapsulating a populist ethos. Theognidean poetry was particularly favored by late fifth- and early fourthcentury Athenian opponents of imperial democracy. Their adoption of Megarian aristocratic poetry had perhaps the effect of selecting for preservation poems most evocative of tensions between groups. With changes in relative economic standing so obviously a source of friction during the Peloponnesian War, the surviving poems of Theognis may have been chosen to help dramatize Athenian ideological conflict. This very process of filtering makes the Theognidea valuable as evidence of archaic ideas on the acquisition and possession of property: that is, archaic ideas as received by late fifth- and early fourth-century Greeks. Yet, a cautious reading is also warranted: We not only have the ‘‘economics’’ of an aristocracy in confrontation and retrenchment, but also those attitudes as received by elite Athenians anxious about redistribution of wealth to other classes. Acquisition and Possession in Archaic Greece 43 The Theognidea establish the framework that is presented in the ‘‘Table of Attestations,’’ within which one can assimilate other poets of elegiacs or iambic meters, such as Solon. Their poetry reveals congruences with the normative system revealed in Theognis, although the actual number of citations is much more modest. In the table, these attestations are headed by the ‘‘at-sign’’ symbol (@). Another body of poetry with analogies to the same system of reference is lyric symposial poetry, exemplified by skolia ‘drinking songs’, because it shared a context with elegiac poetry in social occasions like symposia. These attestations are introduced with the word also in the table. In juxtaposition to Theognis, I have placed lyric poetry and, in particular, the epinician choral poetry celebrating the victories of aristocratic athletes in the panhellenic games. These citations are introduced by a ‘‘tilde’’ (˜) in the table. This decision is not immune from chronological criticism—Pindar is a near contemporary of Aeschylus. I should emphasize, however, that fifth-century choral lyric plays an analogous role in oligarchic polities and in their more stratified societies to that performed by drama in democratic Athens, where a greater interpermeability of groups existed. Hence, Pindar and Bacchylides stand in a more direct line of succession from archaic thought than do the fifth-century literary figures of imperial, democratic Athens. Indeed, at least insofar as their attitudes toward wealth and property are typical, the gnomic comments of late archaic and early classical lyric often extend a tradition of elite moralizing previously crystallized in archaic elegy. There are, however, some important differences in perspective, in terms both of genre and of conceptual progression. WEALTH Let us start with the nature of wealth itself. Here it is striking that we do not find extensive catalogues of its constituent elements. To be sure, we do find the passages noted under I.A.1, where material possessions are listed along with other goods. Yet, it must be recognized that such collocations are subtlely subversive of the idea that wealth is valuable in isolation from other goods, as they combine material possessions with moral qualities and other attainments. There turns out to be little difference between these lists, where the material goods are treated more or less positively, and those passages collected in I.A.2. Here material goods are rejected for superior possessions such as arete ‘virtue’ or ¯ ‘excellence’, health, good judgment, and courage. The latter passages vouch for the superiority of nonmaterial possessions, while the former speak to their value only when possessed along with nonmaterial goods. Verses 1253–54 of Theognis describe an olbios ‘prosperous’ man and are almost identical to Solon fr. 23: ‘‘Olbios is he to whom there are dear boys and whole-hooved horses | and hunting dogs and foreign guest-friends.’’ Fragment 7 of the Carmina Convivialia offers: ‘‘It is best for a mortal man to have health; | second, to be beautiful in his appearance; | third, to be rich (ploutein) undeceitfully; | and fourth, to be young among friends.’’ 44 Articulation of Social Justice The rejection of wealth in preference to other goods is a more common sentiment. Archilochus puts a rejection of the goods of polukhrusos ‘with much gold’ Gyges of Lydia into the mouth of Kharon the carpenter (fr. 19). The same opinion appears in a poem in the Greek Anthology, attributed to Anacreon (AG 11. 47). The Theognidea contain a series of passages rejecting wealth in favor of nonmaterial attainments, e.g., vs. 315–18: ‘‘Many bad men are indeed rich and good men poor; | but we will not exchange with them | our arete ‘excel¯ lence’ for their wealth, since the former always endures, | while different men have khremata ‘property’ at different times.’’ In a similar lyric reminiscence of ¯ the fifth century, Ariphron rejects wealth, children, and sexual gratification for health (fr. 1). Particularly noteworthy is a passage of Theognis (719–28; nearly equivalent to Solon fr. 24), that details material tokens of prosperity, only to reject them in favor of a minimalist lifestyle that supports an enjoyment of sexual intimacy. Strikingly, it is the inevitability of physical decay and death, for which riches avail one not, that is the justifying factor: ‘‘Equally wealthy (verb: plouteo) indeed is the one to whom there is much silver | and gold and ¯ fields with wheat-bearing soil | and horses and mules, and the one to whom there is what is needed | for his stomach, sides, and feet in order to enjoy sensuously | a boy or a woman, and whenever the due season of these things | arrives, fitting youth is also present. | These things are wealth for mortals. Accordingly, no man goes | to Hades in possession of all these superfluous khremata, | nor would he, giving ransom, escape death or grievous | diseases ¯ or the approaching evil of old age.’’ Yet, it should be appreciated that the constituent items of wealth are never rejected in favor of their absence or poverty, but always for nonmaterial goods. As for the provenience of wealth, many passages say the same thing: The gods grant wealth to men. Note lines 165–66 of Theognis: ‘‘No one of men is either olbios ‘prosperous’ or penikhros ‘poor’ | or good or bad without god.’’ Solon refers in fr. 13.9 to the ‘‘wealth which gods grant.’’ In Theognis 319– 22, we find the conditional clause, ‘‘if god grants life and ploutos ‘wealth’ to an evil man’’ (v. 321; cf. fr. 5). A long poem of Theognis addresses Zeus, portrayed as all powerful and knowing of the human heart, reproachfully because of the prosperity of the base and the desperate plight of the just (373– 92). Testimony on the divine origin of wealth from Bacchylides and Pindar shows the vitality of this theme within aristocratic consciousness. Bacchylides in his fifth epinician ode observes (vs. 50–55): ‘‘Olbios ‘fortunate’ is he to whom a god | has granted both a share of fair things | and with an enviable fortune | to conduct an aphneos ‘wealthy’ lifestyle; | for no one on earth | is fortunate in all things.’’ Pindar often reflects on the god-given nature of human success, transcending material good fortune to encompass athletic victory and social prominence. The program of the epinicia is served in two senses: First, the victor and his family are oriented toward moderation, and, second, envy is avoided in a counterbalancing of the act of assertion inherent in the commission and per- Acquisition and Possession in Archaic Greece 45 formance of the victory ode. An example from Nemean 9 illustrates (45–47): ‘‘Let him understand that he is winning marvelous olbos ‘prosperity’ at the hands of the gods; | for, if he acquires conspicuous glory along with many kteana ‘possessions’, | it is not possible for a mortal to touch with his feet still farther upon another peak.’’ Naturally, as a gift of the gods, wealth can be properly a subject for prayer (note I.B.1a). The attention toward material well-being is again sometimes balanced by a concern for the achievement of other goods, as in Theog. 885–86: ‘‘May peace and ploutos ‘wealth’ hold the city, in order that | with others I may revel: I am not enamored of evil war.’’ In iambic verses, Hipponax requests of Hermes sixty gold staters among other goods (fr. 32), and, in another fragment (38), seems to ask Zeus why he has not received gold and silver. Since the honorands of Pindaric poetry are necessarily wealthy, such prayers in the odes take the form of requests that the passage of time not impair the prosperity of the poet’s patrons. There is, however, another type of meditation, striking a fatalistic note about man’s station; Pythian 3.104–110: ‘‘ . . . at different time, there are different breaths | of high flying winds. The olbos ‘prosperity’ of men does not remain for long | safe, whenever falling heavily it follows. | Small in small circumstances, great in great, | will I be, and I shall always honor my attending fortune | with my wits, serving with any device at my disposal. | If god would offer me delightful ploutos ‘wealth’, | I have hope to find later lofty fame.’’ Given the Greek propensity for deifying abstractions, it is unsurprising that Ploutos ‘Wealth’ himself could be envisaged as a divinity. This god could be invoked in a rebuking tone like Theognis’ long complaint to Zeus (373–92). Compare Theognis 523–26: ‘‘Not in vain do mortals honor you so much, O Ploutos ‘Wealth’, | since you indeed tolerate baseness easily. | It is fitting that good men men have ploutos, and | penie ‘poverty’ be a misfortune for a bad ¯ man to bear.’’ The popularity of a belief in god-given wealth suggests that it served as a psychological mooring spot for archaic aristocracies buffeted by changing economic conditions. The relative insignificance of the related idea that wealth is a product of impersonal fate substantiates this point. Prosperity resulting from chance was less acceptable than from divine decree, however variable that was perceived to be. In fact, Fate as introduced in the Pindaric passages in I.B.1c seems to be another deified abstraction or, at least, to be envisioned as an agent of divine volition. Two contradictory ideas seem to flow from the theologically determined origin of individual wealth. One notion is that such wealth ought to be durable, since grounded in something more permanent than fragile, transitory human existence. Solon in fr. 13.9–10 states that: ‘‘the ploutos ‘wealth’ which gods give, remains for a man | steadfast from the lowest bottom to the summit.’’ Theognis 197–98 observes: ‘‘khrema ‘useful property’ which is from Zeus and ¯ in a man’s possession justly and | purely, always remains durable.’’ Pindar Nem. 8.17–18 has ‘‘olbos ‘prosperity’ planted with god’s help is more lasting.’’ 46 Articulation of Social Justice Where movement up and down the hierarchy of economic status was becoming more common, we also find a second notion much more commonly voiced, namely, that the material condition is highly variable. In elegy, that variability can be specifically traced to divine disposition. Theognis 155–58 advises: ‘‘Being angry with a man, never reproach him | with soul-devouring penie ‘poverty’ ¯ and destructive akhremosune ‘need’, | for Zeus balances the scale variously at ¯ ¯ different times, | at one time to ploutein ‘be rich’, at another to have nothing.’’ More commonly, however, invoking the changeability of material fortunes serves to distance affluence from the entire system of appraising individual worth. Wealth springs from an ever-changing cycle of vicissitudes. The predicament is vividly put by Theognis 557–60: ‘‘Be alert: truly danger stands on a razor’s edge. | At one time you will have much, at another rather few goods, | so that neither will (or: ought) you be exceedingly aphneos ‘rich’ in kteata ‘possessions’ | nor will you go into great akhremosune ‘need’.’’ In con¯ ¯ trast, riches in the possession of base men are assumed to derive from mere variability and not from divine dispensation. Accordingly, they are bound to be lost catastrophically (e.g., Theog. 197–208). Changing material fortune is treated differently in epinician lyric, and understandably so. Epinician poets commemorated the victories of their patrons. These wealthy individuals were preoccupied with the maintenance of their present prosperity and status that the choral performance in their honor symbolized. Impermanence is muted, being invoked best in gnomic reflections like fragments 24 and 54 of Bacchylides or Pythian 3.104–11 or 8.73–78. Regarding the fortunes of honorands, the mutability of prosperity appears only obliquely in the prayers noted above that their affluence abide. Elegiac poets, however, more often dramatized situations where persons who once claimed elite status by heredity were now impoverished. Among lyric genres, threnoi ‘dirges’, illus¯ trated by the fragments of Simonides cited in I.B.3, emphasize the fragility of wealth. They stand between elegy and epinician poetry, pointing up the generic boundaries. Observe fr. 16: ‘‘Being a man you may never say what happens tomorrow , | nor, seeing an olbios ‘prosperous’ man, how long he will be so; | for not so swift is even a long winged fly’s | movement.’’ A similar dichotomy exists on the valuation of prosperity in elegy and epinician choral lyric. In epinicia, the praise of prosperity takes several characteristic forms. Wealthy individuals, civic prosperity, or possession of valuable objects are standard subjects of praise. They act as tokens of the favored status of the honorands. Such references perform the necessary political function of directing public attention toward individuals whose participation in the economic elite established a presumptive claim to political leadership. Very often, praises of material prosperity are linked to the possession of various virtues. Elite status for the honorands of epinician poetry was a package deal. For example, I could find only one reference to envy that might be directed mainly toward wealth, but, in Pythian 11.29–30, Pindar might still be using olbos ‘prosperity’ in a more general sense. Acquisition and Possession in Archaic Greece 47 Contrast the elegiac treatment in I.C.1 of the honor paid to wealth. Theognis speaks of the preeminent standing of wealth, but his treatment is rather like that of the catalogues of goods reviewed earlier. The prestige of riches is a situation to be conceded only with regret. In verses 699–718, a particularly long, mythologically grounded exploration of the dominance of riches over moral and intellectual faculties concludes with the observation that ‘‘ploutos ‘wealth’ has the most power of all.’’ Verses 619–22 note that ‘‘everyone honors the plousios ‘rich’ man, but condemns the penikhros ‘poor man’, and the mind within all men is the same.’’ AFFLUENCE AND MORAL CHARACTER Archaic elegy sought to account for social change and, in particular, for the upward and downward mobility altering the composition of the elite. Hence, the identity of those affluent is one of its central preoccupations, along with issues such as the difficulty of transmitting values across generations and the fragility of social cohesion in the face of treachery. As the passages under II.A (and the aforesaid enumerations of life’s goods) indicate, wealth ought to be held by those with arete, justice, and wisdom. Elegy advises this in admonitions such ¯ as Theognis 523–26 (reproduced above) or in 753–56: ‘‘Having learnt these things, dear companion, gain khremata justly, | having a temperate spirit apart ¯ from wantonness, | while always mindful of these words. In the end | you will approve, being persuaded by temperate discourse.’’ Compare Solon fr. 13.7–8: ‘‘I desire to have khremata ‘property’, but I do not wish to acquire it unjustly.’’ ¯ Pindar provides parallels in praising honorands who combine wealth and virtue (note the starred entries in the table). Consider Olympian 2.53–56: ‘‘Ploutos ‘wealth’ adorned with virtues brings the proper | time for these things (i.e., victories), sustaining a profound, keen involvement; | (it is) a conspicuous star, genuine | light for man . . . ’’: or Ol. 5.23–24: ‘‘ . . . if someone tends an olbos ‘prosperity’ that is sound, being generous with his kteata ‘possessions’ and adding in fair fame, | let him not seek to become a god.’’ The chastening accent that is sometimes present concerns the danger of forgetting one’s mortal limits in a moment of exultation, as we have just seen in Ol. 5.23–24 (cf. [e.g.] Nem. 11.11–16; Is. 5.11–15). In both elegy and the gnomic reminiscences of epinicia, the propriety of the joint possession of wealth and arete was occasionally trans¯ muted into a rejection of riches in favor of moral attainments, although the belief that the just and good deserve to be prosperous is the more dominant idea. Naturally, Pindar and Bacchylides, whose epinician poetry is absorbed with praising the athletic victor, his family, and city, cannot give us the other element of the equation. Elegiac poets provide the correction, as we can perceive in II.B: Deserving individuals have poverty instead of riches. Some of these passages have already been cited above, like Theognis 373–92. In addition, note verses 383–85 of the Theognidea: ‘‘ . . . those from base | deeds are restraining their 48 Articulation of Social Justice hearts, nonetheless | have penie ‘poverty’ the mother of resourcelessness, al¯ though they cherish just things.’’ The necessary analogue is presented in II.C, that is, that base, foolish, or socially useless individuals can become wealthy. The two ideas are often juxtaposed. Solon fr. 15 states that ‘‘many bad men are rich, many good men penontai ‘are poor’’’; Theognis 149 has ‘‘god gives khremata ‘property’ even ¯ to a very bad man.’’ Verses 731–52 close with the observation that: ‘‘whenever an unjust and wanton man, avoiding the anger neither of any man | nor of any of the gods, | is hybristic, sated by ploutos ‘wealth’, while the just | are wasted, being worn by dreadful penie ‘poverty’.’’ The same formula appears in 683– ¯ 84: ‘‘many mindless people have ploutos ‘wealth’, but others seek fair things (kala) worn by grievous penie ‘poverty’.’’ Lines 1059–62 attach the motif to ¯ the Theognidean preoccupation with testing human character: ‘‘for some have badness, hiding it by ploutos, while others have arete, hiding it by destructive ¯ penie ‘poverty’.’’ Some passages lack explicit parallels, though the link is im¯ plicit in their combining the riches of the base/foolish with the superiority of virtue (e.g., 149–50; 465–66). Theognis 865–66 offers ‘‘god gives fair olbos ‘prosperity’ to useless men.’’ Solon gives a political shading in fr. 6.3–4: ‘‘for satiety breeds hybris, whenever much olbos ‘prosperity’ attends men, for whom the mind is not straight.’’ In this category, where the status of the epinician honorands is not threatened, Bacchylides can make gnomic pronouncements akin to those of Theognis: 1.160–63: ‘‘ploutos keeps company even with base men. It is eager to inflate a man’s ideas’’; 10.49–51: ‘‘I also know the great power of ploutos which makes a useless man useful.’’ The line between good (agathoi/esthloi) and bad (kakoi/ deiloi) is usually drawn quite sharply. In one passage, however, the kakos is explicitly imagined as becoming an esthlos with the help of the god Ploutos (1115–22). In the moral context of the elegiac poet, we can determine the identity of these kakoi ‘bad’ or deiloi ‘base’ men, whose acquisition of wealth is so objectionable. They are not primarily the miscreant peers of a well-born poet, but rather persons of lower status who have infiltrated the elite. Theognis treats such interlopers as wild men who have entered the polis and the ranks of the good (53–60), comparing them elsewhere to ship’s passengers who have overthrown the helmsman (667–82). Since, in the main, elegy takes a passive posture toward the improvement of one’s economic standing, the Theognidea can envisage no means for the incorporation of upwardly mobile people in an hereditary elite. Even Solon, who opened up Athenian officeholding by his census system, does not advocate such adjustments, at least not in his elegiac poetry. Ill-gotten wealth would seem impossible, if affluence is god given, but the vicissitudinous character of status is to be considered. Thus the moral loading of any specific level of affluence is dependent upon the inherited rank of its holder. Hence, a negative outcome is posited for the nouveaux riches: Temporary advantage yields to misfortune (Theog. 202–3). Characterized by hubris ‘arro- Acquisition and Possession in Archaic Greece 49 gance’, they indulge in koros ‘glutting’. This arrogance seems to subsume the very ambition underlying an improvement in their material condition. Pindar can warn both aphoristically and mythologically that it is necessary to suppress hybris and koros (Is. 3/4.2: ‘‘restrains destructive koros in his heart’’; Pyth. 4.150: ‘‘[Pelias] fattening ploutos’’). The necessary downfall of rich ‘‘bad men’’ can be worked in an entropic process, implementing a subversion of their noos ‘mind’ or exploiting an innate lack of intelligence or sanity. Solon fr. 6 combines the processes: ‘‘the demos ‘common people’ may follow their leaders ¯ best, | neither too much released nor constrained; | for koros ‘glut’ breeds hubris ‘arrogance’, whenever wealth attends | men whose noos ‘mind’ is not straight.’’ A similar citation is Theognis 683–86, as quoted above. Bacchylides introduces the idea in a mythological exemplum, when he describes the derangement of the daughters of Proitos who boasted that their father was wealthier than the goddess Hera (11.40–56; compare 15.57–63, ending in a similar exemplum on hybris). ACQUISITION AND ACQUISITIVENESS If wealth is devolving on unworthy individuals in archaic elegy, that is not surprising, inasmuch as we are warned against the dangers of acquiring property through evil means, and that wealth, once acquired, can be conducive of immorality or injustice. Consider the passages cited in III.A and B. In Theognis 86, ‘‘kerdos ‘profit’ induces a shameful act,’’ and v. 466 advises, ‘‘may kerdos that is shameful not master you.’’ A parallel aphorism in choral lyric is Pindar’s remark that ‘‘shame is stolen in secret by kerdos’’ (Nem. 9.33). This commentary appears pervaded by a class chauvinism, in which inherited wealth is valued as divinely sanctioned, while acquired wealth is suspect. Not only does the appetite for betterment induce immorality individually, but it is also contributory to antisocial behavior that damages the community. Solon speaks of ‘‘citizens motivated by khremata who are willing to destroy a great city, in ¯ their follies’’ (fr. 4.5–6), and boasts of his prudence in rejecting boundless ploutos and tyranny (fr. 33.5–6). Theognis relates acts of political corruption ‘‘for the sake of private kerdea ‘profits’ and power’’ (45–46). The idea culminates in the stark juxtaposition of private profit and public misfortune. Significantly, the elegiac evaluation of profit-seeking is seen where kerdos ‘advantage’ is juxtaposed with immorality (Arch. fr. 93a; Pin. Nem. 7.17–20; 9.31–34; Sim. fr. 36; Theog. 39–52; 83–86; 401–6; 823–24; 833–36; cf. Theog. 563–66, a rare positive passage). That wealth does not promote immoral behavior is owed to its accompaniment by arete ‘virtue’, dike ‘justice’, and sophia ‘wisdom’. That conclusion is implicit ¯ ¯ in the passages authorizing the possession of wealth only in conjunction with such moral qualities. The praise of liberality provides a parallel assurance that riches are rightly held and are likely to be, if not protected by the gods, at least not stimulatory of divine envy. This belief is present in Theognis 979–82, linked 50 Articulation of Social Justice with practical personal intervention on behalf of a philos ‘friend’ (in a factional context). The praise of generosity is even more prominent in epinician lyric, where such allusions balance the ostentation inherent in the revelry on behalf of the victor. Two passages of Pindar are helpful: Ol. 5.23–24: ‘‘if a person cultivates a healthy olbos ‘prosperity’, | being generous (verb: exarkeo) and ¯ adding in fair repute, let him not seek in vain to be a god’’; Nem. 1.31–33: ‘‘I do not delight to have great ploutos, hiding it away in the house, | but being generous (exarkeo) to friends both to enjoy my | possessions and gain good ¯ repute from them . . . .’’ The concept of generosity is balanced by the avoidance of hoarding not only here but in Isthmian 1.67–68 a negative injunction: ‘‘ . . . But if someone tends hidden ploutos within, | while he takes pleasure in oppressing others, | he does not consider that he is paying his soul over to Hades without repute.’’ Underpinning the interpretation of self-advancement as subversive is the argument that the desire for material goods is insatiable, unlike other human appetites. Material appetition can even overcome koros ‘satiety’. Solon fr. 13.71– 73 presents the phenomenon thus: ‘‘No manifest limit of ploutos ‘wealth’ exists for men; | whoever of us has now the greatest substance for life, | they are eager for two-fold that. Who will satiate everyone?’’ Theognis notes that ‘‘there is satiety of everything except ploutos’’ (596), and that ‘‘you cannot satiate your spirit with ploutos’’ (1158). An opportunistic person can set no check on his appetitiveness, inevitably causing others damage if he is not restrained externally. Thus, the pursuit of upward mobility can become a perversion of individual ambition. Pindar and Bacchylides reflect the same attitude, but perforce approach it negatively in pondering the human condition on behalf of honorands who would have appeared incredibly wealthy to the audience of a type of performance that itself risked appearing excessive or overbearing. Just as elegy lacks a nonpejorative rationale for enrichment of members of the demos, the processes by which aristocrats become impoverished are not ¯ much evidenced. Variability of fortune and divine intervention are, of course, two causes for the existence of a poor but virtuous aristocrat. As for mundane aetiology, some passages, speaking of property acquired immorally, focus on rapacious misappropriation. Solon fr. 4.12–13, notes stealing by persons ‘‘sparing nothing of sacred or public kteana ‘possessions’,’’ and Theog. 1149 has persons with their thoughts on ‘‘other persons’ kteana ‘possessions’.’’ In parallel phrasing, Bacchylides mentions hybris ‘‘which quickly provides another man’s wealth and power’’ (15.59–60). Moreover, Theognis notably claims to have lost his wealth through robbery or aggression in his lament that ‘‘ . . . vengeance has not appeared for us | over the men who have our khremata ‘property’, | having ¯ robbed it by violence . . . ’’ (345–47). He concludes by imagining himself a hellhound who will drink his enemies’ blood. Vs. 831–32 may be a concise echo of the same thought: ‘‘I lost my khremata ‘property’ by good faith; I saved ¯ it by faithlessness. | The thought of both is difficult.’’ Furthermore, the extended metaphor of the ship of state in vs. 667–82 is introduced by the proviso, Acquisition and Possession in Archaic Greece 51 ‘‘if I had the khremata, Simonides, that I once had, I would not be distressed ¯ in keeping company with the agathoi.’’ Unfortunately, it is hard to generalize from this perspective on impoverishment since such claims are difficult to parallel elsewhere. The absence of portrayals, however, of deserved or at least selfinduced impoverishment by aristocrats is quite striking. That cannot be unconnected with the feeling that hybris succeeds, objectionable though that conclusion may be, for some duration of time. The one exception, a fragment of the fifth-century elegist Euenus of Paros, offers ‘‘hybris which profiting not at all, still does wrong’’ (fr. 7). Yet, that thought seems to belong to a different tradition of commentary on the morality of acquisition and upward mobility. Exploiting one’s chances and ambition toward material betterment are not treated with universal contempt in extant poetry. A scatter of passages offers a more balanced picture, one which common sense advises must have reflected the actual behavior of many individuals and its reception by some segments of society. Greece in the seventh and sixth centuries was undergoing much economic expansion that cannot all have been marginalized in normative terms. The hostility of the Theognidea toward infiltrators into the ranks of elite betrays that increases in economic rank carried acceptance of claims to sociopolitical status. It is, however, striking that references to acquisition, portrayed positively, lack the coherence and systemization that the negative reflections seem to demonstrate. Phocylides fr. 7 is remarkable for its isolation from the rest of elegy on upward mobility: ‘‘Desiring ploutos, take on the cultivation of rich land: | for they say land is the horn of Amalthea.’’ Consider also how Bacchylides treats enrichment in fr. 20B.14–16 as typical of the grandiose dreams amid drinking without a hint that there would be any disapproval about ‘‘wheat-bearing ships carrying the greatest ploutos from Egypt on the brilliant sea.’’ The sentiment is a commonplace since it is repeated in Pindar fr. 124, where we are in our cups ‘‘all equally sailing on a sea of polukhrusos ‘very golden’ ploutos ‘wealth’ toward a fictitious cape; whoever is akhremon ‘needy’ then becomes aphneos ¯ ¯ ‘affluent’, and indeed even the plouteuntes ‘wealthy’ will exalt their minds, mastered by the arrows of the vine.’’ POVERTY In the archaic Greek ‘‘shame culture,’’ poverty was undoubtedly a profound misfortune (IV.A). It is standard to link poverty with old age, death, and disease as incontrovertible ills (Ba. 1.170–71; Theog. 173–74; 1129–32). The concept of penie ‘poverty’ is accompanied by a characteristic vocabulary. Mimnermus ¯ has ‘‘the household wasted (verb: trukho)" (fr. 2.11–12; cf. Theog. 752). Poverty ¯ (penie or or akhremosune) is teiromene ‘wasting’ (Theog. 182, 684, 752), thu¯ ¯ ¯ ¯ mophthoros ‘spirit-destroying’ (Theognis 155–58, 1129, fr. 4; cf. Hes. Works 717), and oulomene ‘destructive’ (156, 1062; cf. Works 717; Theogony 593). ¯ Poverty masters a man (root: dam[n]-), as in Alc. fr. 364 and Theognis 173– 52 Articulation of Social Justice 82. It is khalepe ‘grievous’ (Theog. 180, 182, 684, 752, fr. 4) and deile ‘evil’ ¯ ¯ (Theog. 351, 649). Thus, penie is associated with amekhanie ‘resourcelessness’ ¯ ¯ ¯ (Theog. 385, 619, 1114a-b; cf. Alc. fr. 364), as is khremosune ‘need’ in Theog¯ ¯ nis 392. Poverty is not prominent in surviving choral lyric, a hardly surprising condition, given its subject matter. One reference, however, in Bacchylides speaks of amakhanos penia ‘resourceless poverty’ (1.170–71), congruent with the elegiac semantic system. Since one can pray for wealth, the prayer for release from poverty also makes its grim appearance (IV.A.1). Verses 561–62 in Theognis denote a special route for fulfillment of the prayer for release from poverty, as the poet prays to acquire the khremata ‘property’ of his enemies for himself ¯ and his friends. To see poverty as a misfortune would appear to be simple common sense, but it is notable the degree to which compensating or ameliorating contentions are minimized in our sources. The idea that ‘‘you can’t take it with you’’ can act to lessen tensions over differences in economic status. Wealth can be rejected in face of mortality (see I.A.2a), but Solon fr. 24 and its equivalent Theog. 719– 28 do not seem too prominent when compared with the citations treating poverty as an unmitigated evil. The corresponding note in epinician lyric, again represented by one passage, Pin. Nem. 7.17–20, is muted: That rich man and poor man equally face death helps the point that the sophoi ‘wise’ are acute enough to foresee and to avoid harm from kerdos ‘gain’. Similarly, the cliche that hard ´ times test a person’s mettle appears in only a single elegiac passage, Theog. 393–400 (IV.A.2). ‘‘In penie, the base man and the much better man | shine ¯ forth, whenever khremosune ‘need’ takes hold; | for whose mind thinks just ¯ ¯ thoughts, has always | straight judgment grown fixed in his breast. | The mind of the other abides with neither evil nor goods, | but it is necessary that the good man endure and bear varying vicissitudes.’’ Even here, however, more common sentiments, such as the superiority of arete and justice to wealth and ¯ the mental confusion of the base or lower class, quickly occupy center stage. The characteristic metaphor for the testing of human character, that of the basanos ‘touchstone’, used for evaluating the gold content of metal, is never linked with the ‘‘testing’’ intrinsic to experiencing poverty. Since wealth was so intensely felt to be the birthright of the aristocrat, who was assumed to possess inherited personal worth, impoverishment manifestly threatened that noble’s identity, since it could deprive him of his capacity for honorable activity (IV.B). Theognis 267–70 explains that: ‘‘Indeed penie is well ¯ known, even though it should not be ours, | for neither does it come into the marketplace nor the law courts, | and everywhere has the lesser place, and everywhere is mocked, | and is everywhere equally hated, wherever it may be.’’ In vs. 173–83 (where poverty is seen to subdue a man), ‘‘every man subdued by penie is able neither to say nor do anything: his tongue is bound.’’ Theognis ¯ also notes that ‘‘everyone dishonors a penikhros ‘poor man’ ’’ (621–22). The poor man’s inability to participate in public affairs was symbolized by this voicelessness, an image reappearing in 669–70: ‘‘I am voiceless from khremo¯ sune ‘want’.’’ Thus, the taunt over impoverishment is an assault on an aristo¯ Acquisition and Possession in Archaic Greece 53 crat’s identity envisaged in several Theognidean passages (IV.B.1: e.g., 155–58 cited above; cf. Hes. Works 717–18). A salient facet of archaic economic awareness was that the main context in which gainful activity by an aristocrat could be openly lauded was an effort to escape poverty (IV.C). A series of passages authorize any endeavor to escape pauperhood. Note Theog. 179–80: ‘‘It is necessary equally on land and on the broad back | of the sea to seek release from penie ‘poverty’, Kyrnos’’ (cf. fr. ¯ 4). Thus upward social mobility can be approved when it involves recovery of previous status. Yet, such activity was still tainted by the general impropriety of acquisition. Theognis offers in vs. 831–32: ‘‘I lost my khremata ‘possessions’ ¯ through faithfulness, I saved them through faithlessness: | the knowledge of both is painful.’’ Solon fr. 13.41–42 offers ‘‘the works of penie do violence to ¯ him, and he decides to acquire (verb: ktaomai) much khremata ‘property’ in any ¯ way.’’ Theognis 383–92 amplifies ‘‘ . . . those, from evil | acts are restraining their hearts, nevertheless | receive penie, the mother of amekhanie, though cher¯ ¯ ¯ ishing justice; | (poverty) beguiles the heart of man into wantonness, | damaging judgment in his breast out of strong necessity. | Unwilling to endure suffering many humiliations, | yielding to khremosune ‘want’, that ¯ ¯ teaches many evils, | lies, and deceits, and destructive quarrels, | even a man who is unwilling, a man whom no evil befits: | for (poverty) engenders grievous amekhanie ‘resourcelessness’.’’ Wealth went with aristocratic birth, so that the ¯ ¯ injustice and immorality of aggrandizement could be justified only as a response to pauperization. WEALTH, POVERTY, AND SOCIAL CONDITIONS Wider ramifications can be drawn from the negative impact of acquisitiveness on society, with the Theognidea standing as a treasury of relevant commentary. Yet the influence of the same themes is illustrated by their appearance, once more rather elusively, in lyric. We have already seen how wealth often gravitates into the hands of the base, and that the pursuit of wealth is fraught with temptations for antisocial acts. The affective ties between members of society can also be viewed as dependent on economic status (V.B). I have already discussed how Theognis can explicate this condition in 699–718, where he balances gnomic statements with mythological counterexamples (note also 267–70, cited on the alienating effects of poverty). The impoverished noble is also alienated from his associations with other members of the elite and even from partisans of his faction. Therefore, enrichment and impoverishment tend to subvert the natural alignments in society (e.g., Ba. 10.49–51: ploutos ‘‘makes a useless man useful’’). In commentary that could be considered the essence of aristocratic reflection on social mobility, Alcaeus deliberately chooses as his mouthpiece a Spartan, presumably for the sake of his community’s reputation for austerity and for suppression of social differentiation (fr. 360): ‘‘for they say that Aristodemus 54 Articulation of Social Justice once spoke a not witless saying at Sparta: | khremata is the man, not one pen¯ ikhros ‘poor man’ is good or honored.’’ This fragment is found among the scholia (marginalia) to Pindar Isthmian 2.6–11. Pindar, who identifies the speaker as an Argive, says that the phrase khremata, khremata aner ‘property, ¯ ¯ ¯ property is the man’ was spoken when the speaker was ‘‘left without kteana ‘possessions’ and friends.’’ The Theognidea are eloquent on the subject of marriages, or rather misalliances, predicated on seeking a mate for the purpose of material advancement (see V.B.1). Noble men and women end up mating with those of lower classes, who are assumed to be vicious in character. The result is an adulteration of the genetic resources of the polis, since inherited excellence is diluted: Theog. 183– 92: ‘‘In rams and asses and horses we seek, Kyrnos, | the well-bred, and anyone wishes them to derive from good stock, | but a good man is not troubled to marry the bad daughter | of a bad father, if someone gives him much khremata ¯ ‘property’; | and a woman does not refuse to be the wife of a bad man | who is plousios ‘rich’, but she prefers an aphneos ‘rich’ man over a good one; | They honor khremata, and a good man marries of bad stock | and a bad man from ¯ good; ploutos has mixed the bloodlines. | So do not wonder, son of Polupaus, that the race of the citizens | is made obscure, for good things are mingled with bad.’’ Another reaction, albeit extreme, to the ‘‘corrosive’’ influence of wealth on society was to exalt an egotistical attitude toward consumption (V.B.2). Theognis can recommend to his fellow aristocrats that they consume their estates in their own lives, so that nothing is left to be inherited by their relatives, toward whom they are to feel no ties of affinity. In 903–32, he begins by stating that ‘‘whoever watches the spending of his estate regarding his khremata has the ¯ most praiseworthy arete among the knowing’’ (903–4). He turns to the difficulty ¯ of knowing whether to stint or to live more pleasantly, inasmuch as the length of life is unforeseeable (905–14). For the self-abnegating plousios a premature death brought his khremata to an heir he did not wish (915–19), but the man ¯ who consumed his khremata must play the beggar to his friends (verb: pto¯ ¯ kheuo). He concludes with verses 923–32. ‘‘So, Demokleis, it is best of all ¯ regarding khremata | to control expenditure and to pay attention. | Thus la¯ boring before you would not share your labor with another, | nor being a beggar (ptokheuo) would you live out slavery, | and, if you reach old age, all your ¯ ¯ khremata will not have run away. | In such a generation, it is best to have ¯ khremata: | if you are wealthy (plouteo), there are many friends, but if you are ¯ ¯ poor (penomai), | few, and (you are) no longer equally the same good man.’’ Yet it is equally important to note that extreme statements of the disruption inherent in social mobility are limited to elegy, and are especially prominent in the Theognidea. This is presumably because elegy is significantly diachronic in perspective. By convention, it is concerned with the intergenerational transmission of norms and the problems intrinsic to that process. Hence, the upward mobility of the supposedly base lower classes into the elite and the downward mobility of aristocrats appear especially foreboding. Epinician poetry is more Acquisition and Possession in Archaic Greece 55 synchronic in its outlook, with a stress on the virtuous deployment of wealth by nobles in the present. There are indications that high social standing is vulnerable, as well as dependent upon the divine will, but victory odes focus on the possibility that the wealth of their honorands will be utilized to underwrite their pursuit of virtue. That difference in perspective underlies the broader appreciation of the causation of affluence in epinician lyric, which transcends the almost claustrophobic system of Theognidean elegy, where it at times appears that nothing is left to be said once it is ‘‘established’’ that the genetic monopoly of the traditional elite on the highest level of moral attainment ought to be united with the permanent possession of a disproportionate share of communal assets. Pindar recognizes a variety of causalities for the wealth of a community (V.C). In olbios ‘wealthy’ Corinth, eunomia ‘good government’ is present, the foundation of cities along with ‘‘Dika ‘justice’ and Eirana ‘peace’, the stewards of ploutos for men, the golden children of well-counseling Themis ‘law’ ’’ (Ol. 13.3–8). Peace is itself several times credited as the cause of wealth: Ba. fr. 4.61–62: ‘‘peace engenders noble ploutos for mortals’’; Lyr. Adesp. fr. 103: ‘‘O sweet peace, granter of ploutos to mortals.’’ Concomitantly, stasis ‘civil strife’ was recognized as a cause for impoverishment: ‘‘plucking out spiteful stasis from his heart, the giver of penia, the loathesome nurse of youth’’ (fr. 109). Solon fr. 4 provides specifics on how the self-aggrandizing behavior of the elite was creating stasis, and, in fr. 5, we are told how Solon protected the property and political power of the aristocrats. CONCLUSION There is little reflection in the poets under discussion of the Hesiodic vision of work and affluence. Hesiod envisaged that status of the plousios ‘rich man’ prompts his neighbor to strive for aphenos ‘riches’ (Works 20–24). This good type of eris ‘strife’ is essentially competition, not only setting potter against potter and carpenter against carpenter, but even beggar against beggar (24–26). The adoption of a work ethic avoids the threat of hunger, making men wealthy in flocks and aphneios ‘affluent’ (299–312; cf. 498–501). In contrast to elegiac views, arete ‘virtue’ and kudos ‘glory’ are not separate attainments to be jux¯ taposed to ploutos, but accompany the ploutos achieved by work (313). Although shame here also attaches to the state of poverty—and tharsos ‘confidence’ to olbos—work is the antidote that can operate only when the mind has diverted itself from others’ kteana and khremata (315–20; cf. 637–38). It is ¯ through work, a commitment to just dealings (280–81), and a submission to the dictates of temporality (cf. 306–7; 455–57; 493–97; 630–40; 686; 826–27) that men of the age of iron may approach the bliss of the golden race of men (109– 20) who are, even in the underworld, the givers of wealth to men (125–26). Khremata and olbos are god given (and thus durable), but divine grant is pred¯ icated in Hesiod on just acquisition, attained through working (320–26; cf. 56 Articulation of Social Justice Theogony 420; 974). There are, to be sure, many allusions in Theognis to observing kairos ‘timeliness’ but they are not attached to the achievement of prosperity in the manner of the Hesiodic references. The ethos of the archaic aristocrat offers many dismaying signs of fixation on a ‘‘zero-sum’’ game. The elite, particularly as represented in elegy, saw moral qualities and socioeconomic status as thoroughly genetic. Nobles, placing so heavy a burden on themselves in maintaining unchanged the distribution of goods and status within their cities, were bound to be affected by alterations in the status quo worked both by initiative or carelessness and by the play of factors beyond personal control. The archaic period was a era marked by growing population and wealth and by a greater economic differentiation. We have encountered many denunciations of such changes; there were many condemnations of their beneficiaries and attempts to subvert their successes, at least psychologically. The entrepreneurs, traders, and workshop proprietors who helped to spur the growth of archaic cities are in a significant sense unsung heroes. They were not entirely unchampioned, but recovering their ideology entails investigating the later vestiges of archaic reciprocity, and that transcends the scope of this chapter. TABLE OF ATTESTATIONS I. Wealth A. Wealth and other goods: 1. Prized with other goods: @Solon fr. 23 ˜ Theog. 1253–54 (boys; horses; dogs; foreign friends); also Carm. Con. 7 ( 890; health, beauty, youth) ˜Ba. 20B.13–16; cf. Pin. Ol. 1.1–2; 3.42; fr. 221.3 2. Rejected for other goods: @Arch. fr. 19; Theog. 145–48 (dikaiosune ‘justice’); 315–18 (for arete and ¯ ¯ gnome ‘judgment’); 409–410 (aidos ‘shame’), cf. 1161–62 (for erotic as¯ ¯ sociation with aristocrats); 1063–68 (for sexual gratification); 1155–56 ( AG 10.113; for a simple life); also Lyr. Adesp. fr. 70 (988); cf. Theog. 77– 78; An. in AG 11.47 ¯ ˜Ari. fr. 1 (813; health); cf. Ba. 1.160 (arete ‘virtue’); Pin. Nem. 8.37–39 a. wealth to be rejected, because of human mortality: @Solon fr. 24˜ Theog. 719–28 ˜Pin. Nem. 7.17–20 B. The origin and durability of wealth: 1. Wealth as gift of the gods: @Sem. fr. 1.9–10; Sol. fr. 13.9–10, cf. 69–70; Theog. 133–42; 149–50; 155– 58; 165–66; 197–208; 227–32; 319–22; 373–92; 865–68; 1115–22; fr. 4; fr. 5; cf. 373–92; also Carm. Pop. 33 (879) ˜Sa./Alc. fr. S276; Ba. 5.50–55; 14B.1–6; fr. 65A.1–8; cf. 3.11–14∗; Pin. Pyth. 3.104–10; 8.73–78; 12.28–30; Nem. 8.17–18; 9.45–47∗; Is. 3/4.5–6; fr. 222; cf. Ib. fr. S166 a. hence prayed for: Acquisition and Possession in Archaic Greece 57 @Theog. 523–26; 885–86; 1115–16; 1119–22; also Carm. Con. 18 (901), 29b (912b); Lyr. Adesp. 20f.i (938); cf. Hippon. fr. 32; fr. 38; 129–30 ˜Pin. Ol. 6.97–100∗; Pyth. 1.46–50∗; Pyth. 3.104–10; Pyth. 10.17–21∗; cf. Nem. 8.37–39 b. wealth personified as deity: @Theog. 523–26; 1117–18; Hippon. fr. 36; also Carm. Con. 2 (885; son of Demeter); Tim. fr. 5 (731) ˜Lyr. Adesp. 45 (963) c. gift of fate: @Theog. 129–38 ˜Pin. Ol. 2.21–22 (cf. 36–37); Pyth. 2.56–57; 5.1–9; cf. Ba. 24.8–10?? 2. God-given wealth is durable: @Sol. fr. 13.9–10; Theog. 197–208 ˜Pin. Nem. 8.17–18; Is. 3/4.5–6; fr. 222; cf. fr. 134 a. wealth of the middle ranks is longer lasting: ˜Pin. Pyth. 11.52–53 3. Material condition variable: @Sol. fr. 15 (˜Theog. 315–18); Theog. 155–58; 167–68; 227–32; 315–18; 352–55; 557–60; 657–66; fr. 4 ˜Ba. fr. 24; fr. 54; Pin. Pyth. 3.104–10; Pyth. 8.73–78; Sim. fr. 16 (521); 17 (522) C. The appraisal of wealth 1. Wealth most or universally honored: @Theog. 183–90; 523–26; 619–22; 699–718 (more than moral or intellectual attainments); 1117–18 2. Praise/invocation of individual or civic wealth: ˜Ba. 3.11–14, 22∗; Pin. Ol. 1.8–11∗; 6.71–74∗; Ol. 7.1–4; Pyth. 1.46–50∗; 2.56–61∗; 6.47–49∗; Nem. 5.18–19∗; 7.58–60∗; 9.3–4∗; Is. 3/4.17a–b∗; fr. 119∗; cf. for civic wealth: Pin. Ol. 13.3–10; Nem. 1.14–15; fr. 122 a. Envy of wealth: Pin. Pyth. 11.29–30 II. Affluence and Moral Character A. Wealth proper with arete ‘virtue’ or dike ‘justice’: ¯ ¯ @Sol. fr. 13.7–8; Theog. 27–30; 523–26; 753–56; 1007–12; also Carm. Con. 7 (890) ˜Ba. 3.76–98∗; Pin. Ol. 2.8–11∗, 53–56; Ol. 5.23–24; 6.71–74∗; Pyth. 2.56– 61∗ (sophia); Pyth. 5.1–14∗; Nem. 7.58–60∗; 9.45–47∗; Nem. 11.11–16∗; Is. 3/4.1–3; 5.11–15; Sappho fr. 148; cf. Pin. Pyth. 3.104–10 1. Pursuit of arete superior to wealth: ¯ @Solon fr. 15˜Theog. 315–18; 465–66; also Lyr. Adesp. 43 (961); cf. Theog. 865–68 ˜Pin. Pyth. 8.88–92; Nem. 9.31–33; cf. fr. 52d.40–48; also An. fr. 39 (384; early poets nonmercenary) B. Just/virtuous men afflicted with poverty: @Sol. fr. 15 (˜Theog. 315–18); Theog. 145–48; 373–92; 683–86; 731–52; 1059–62; cf. 149–50; 465–66; 865–68; and Hippon. fr. 36 C. Base men acquire wealth: @Sol. fr. 4.12–15; 6 (˜Theog. 153–54), 15 (˜Theog. 315–18); Theog. 145–48; 58 Articulation of Social Justice 149–50; 183–90; 373–92; 683–86 (aidries ‘foolish’); 731–52; 865–68 (akhrestoisi ‘useless’); 1059–62; 1117–18 ¯ ˜Ba. 1.160–63; 10.49–51 1. Their wealth destroys them: @Theog. 197–208 ˜Sappho fr. 148 a. specifically by stimulating hubris/koros ‘arrogance/glut’: @Sol. fr. 6 (˜Theog. 153–54); fr. 13.71–73; Theog. 833–36; cf. 27–30; 197–208; 731–52; cf. Xen. fr. 3 ˜Ba. 15.57–63; Pin. Ol. 1.53–58; Pyth. 2.26–30; cf. Pin. Pyth. 4.148– 51; Is. 3/4.1–3 b. or by destroying their noos ‘mind’ or exploiting their lack of noos: @Sol. fr. 6 (˜Theog. 153–54); 227–32; 319–22; 683–86; fr. 5 ˜Ba. 1.160–63; 11.40–55; Pin. fr. 157; fr. 222?; cf. Pin. Pyth. 6.47–49 III. Acquisition and Acquisitiveness A. Pursuit of material advantage conducive of evil: @Theog. 83–86 (cf. 563–66); 197–208; 401–6; 465–66; cf. 607–10; Tim. fr. 5 (731) ˜Sim. fr. 36 (541); Pindar Pyth. 3.54–57; 4.139–41; Nem. 7.17–20; 9.31–33; fr. 123: cf. fr. 219 1. In particular appetition conducive of unjust/antisocial behavior: @Sol. fr. 4.6, 12; Theog. 39–52; cf. Sol. fr. 33, 34 ˜Pin. Is. 1.67–68 2. Private profit/public misfortune: @Theog. 39–52; 823–24; 833–36; cf. Arch. 93a 3. Contrast role of liberality: @Theog. 979–82 ˜Pin. Ol. 5.23–24; 10.88–90; Nem. 1.31–33; cf. Is. 1.67–68 B. Wealth achieved through evil: @Sol. fr. 4.5–6, 11–15; 33.5; Theog. 145–48; 197–208; 221–26; 831–32; 1135–50 (esp. 1149–50) ˜Ba. 15.57–60 1. (Poet’s) wealth lost through evil or robbery: @Theog. 341–50; 831–32; cf. Carm. Con. 26 (909); Sol. fr. 4.23; 34; Theog. 667–82; 955–56 ˜cf. Pin. Pyth. 8.13–14 2. hubris induces wrong-doing without hope of profit: Euenus fr. 7 C. Desire for property is insatiable: @Sol. fr. 13.71–73˜Theog. 227–32; 595–602; 1157–58 ˜cf. Ba. 1.160; Pin. Nem. 11.47–48 D. Acquisition portrayed positively: 1. Innocent dream of wealth: ˜Ba. fr. 20B.14–16; Pin. fr. 124 2. Agriculture is road to wealth: @Ph. fr. 7 IV. Poverty A. As evil or anxiety: @Mim. fr. 2.11–12; Sol. fr. 13.41–42; Theog. 155–58; 173–82 (like old age or disease); 351–54; 373–92; 523–26; 619–22; 649–52; 667–82; 683–86; Acquisition and Possession in Archaic Greece 59 750–52 (cf. 731–52); 1059–62; 1114a–b; 1115–16; 1129–32; fr. 4; Tyr. fr. 10.1–10; also Alc. fr. 364 ˜Ba. 1.170–71 1. Prayer for release from poverty: @Theog. 351–54; 1115–16; cf. 561–62 2. Poverty as a testing: @Theog. 393–98 B. Depriving of capacity for honorable activity: @Theog. 173–82; 267–70; 373–92; 621–22; 667–82, 931–32; cf. also Alc. fr. 360 1. Taunt about poverty: @Theog. 155–58; 1129–32; fr. 4; cf. 1209–16 C. Any activity acceptable for escape from poverty: @Sol. fr. 13.41–42; Theog. 173–82; 831–32; fr 4; cf. 383–92; cf. Sappho fr. 31.17? V. Wealth, Poverty, and Social Conditions A. Wealth is force for (negative) social change: @Theog. 183–92; 699–718 ˜Ba. 10.49–51 B. Social affinities dependent on wealth: @Theog. 183–92; 905–32; also Alc. fr. 360: cf. Theog. 267–70 ˜Pin. Is. 2.6–11 1. Wealth is dysgenic: @Theog. 183–92 2. Personal consumption best: @Theog. 271–76; 903–32 C. The causes of communal wealth and poverty: 1. Good constitutional order renders cities prosperous: ˜Ba. 14B.1–6 (Hestia); Pin. Ol. 13.3–10 2. Peace engenders wealth: ˜Ba. fr. 4.58–62; Lyr. Adesp. fr. 103; Pin. Ol. 13.3–10; fr. 109 3. Conquering land: ˜Pin. Paean 52b.59–63 4. Stasis ‘civil strife’ impoverishes a city: @Solon fr. 4; cf. fr. 5 ˜Pin. fr. 109 5. Slackness in combat: @Tyr. 12.6 ABBREVIATIONS: Alcaeus Alc.; Alcman; Archilochus Arch.; Ariphron Ari.; Bacchylides Ba.; Carmina Convivialia Carm. Con.; Carmina Popularia Carm. Pop.; Elegiaca Adespota El. Adesp.; Euenus; Hipponax; Ibycus Ib.; Lyrica Adespota Lyr. Adesp.; Mimnermus Mim.; Phocylides Ph.; Pindar Pin.; Sappho Sa.; Semonides Sol.; Theognis Theog.; Timocreon Tim.; TyrSem.; Simonides Sim.; Solon taeus Try.; Xenophanes Xen. 60 Articulation of Social Justice VOCABULARY 1. ploutos ‘wealth’; plouteo ‘to be wealthy’; plousios ‘wealthy’; bathuploutos ‘exceedˆ ´¯ ´ ´ ingly rich’; aphenos ‘riches’; aphneios or aphneos ‘rich’; olbos ‘wealth’ or ‘happi´ ´ ´ ´ ness’; olbios ‘wealthy’ or ‘happy’; panolbios ‘truly happy’ or ‘truly wealthy’ ´ ´ 2. penes ‘poor man’; penıa (penıe) ‘poverty’; penikhros ‘poor man’; penomai ‘to be ´ ¯ ´ ´¯ ´ ´ poor’; khremosune ‘need’; akhremon ‘needy’; akhremosune ‘neediness’; ptokhos ‘beg¯ ´ ¯ ¯ ¯ ¯ ´ ¯ ¯ ´ gar’; ptokheuo ‘to be a beggar’ ¯ ´¯ 3. paomai ‘acquire’; ktaomai ‘to get’; kteanon ‘piece of property’; ktear ‘piece of prop´ ´ ´ ´ erty’ 4. khrema ‘thing of use’; khremata ‘property’ ¯ ¯ ´ ¯ ¯ ´ 5. kerdos ‘profit’; philokerdes ‘desirous of gain’; kakokerdes ‘making base gain’; akerdeia ‘want of gain’; kerdaıno ‘derive a profit’; ophelos ‘advantage’ ´ ´ 6. arguros ‘silver’; argureos (adj.); khrusos ‘gold’; khrusıos (khruseos) ‘golden’; polu´ ´ ´ ´ ´ khrusos ‘rich in gold’; pankhrusos ‘entirely gold’ ´ ´ 5 Images of Justice in Early Greek Poetry GREGORY NAGY This work centers on the earliest Greek poetic visualizations of dike both in the ˆ short-range sense of ‘‘judgment’’ and in the long-range sense of ‘‘justice,’’ even ‘‘Justice,’’ which is also personified as a goddess. Two primary images come into play: (1) a just king in a well-tended and fertile garden or cultivated field, as described in Odyssey, xix 106–14, and (2) a crooked line that becomes straight in the fullness of time, a teleological concept that is elaborated most clearly in the Works and Days of Hesiod. In the primary texts that I quote, key words signaling these images will be underlined, not simply italicized, in order to highlight both the continuity and the coherence of the traditions that shaped the imagery. Let us proceed to the first image, that of a king in a garden or a cultivated field, as pictured by a disguised Odysseus who is at the moment speaking to his wife, Penelope: My lady, no one among mortals anywhere on this vast earth could utter words of reproach about you. For truly your renown [kleos] reaches the wide heavens as that of some blameless king, who, godlike, rules over men great in number and mighty, upholding the ways of good judgment [eudikiai], and the dark earth bears wheat and barley, while the trees are weighed down with fruit, the sheep produce young without fail, and the sea provides fish, all thanks to his good works, and the people achieve their goals because of him. Odyssey, xix 107–141 62 Articulation of Social Justice The plural noun eudikiai at line 111, which I have translated as ‘‘ways of good judgment,’’ is built on the noun dike in the sense of ‘‘judgment,’’ as convenˆ tionally rendered by kings. An idealized example is in Hesiod, Theogony 86, where the just king is described as deciding what is right or wrong by pronouncing dikai ‘‘judgments’’ that are ‘‘straight.’’ Surrounded by the well-tended and fertile garden or cultivated field, as envisioned by the Odyssey, is the King as the embodiment of Society itself.2 Metaphorically, he is both the cause and the effect of the ‘‘good tending.’’ The image of the king in this setting makes it implicit that, insomuch as the king pronounces good judgments, vegetation flourishes: To that extent, the king is the cause. Conversely, insomuch as vegetation flourishes, he has the authority to make judgments: To that extent, the king is the effect. The fertility and prosperity of the garden or cultivated field are the visible sign of the just king. Since Odysseus is counting on the recovery of his kingdom from the unjust suitors who are courting his wife, the fact that he invokes this image of a just king who is surrounded by flourishing vegetation—and the fact that he applies this image to his long-estranged wife—becomes a telling sign of the ultimate state of fertility and prosperity that will prevail by the time the narrative of the Odyssey draws to a close. This paradisiacal image in the Greek poetic tradition is readily comparable to images found in other poetic traditions that took shape from other Indo-European languages cognate with the Greek. I cite a striking example from the very end of the ‘‘Nala’’ story as retold in the larger narrative framework of the Indic national epic, the Mahabharata, which describes the ultimate state of fertility ˆ ˆ and prosperity enjoyed by the just king Nala after he finally recovers both his lost kingdom and his own long-estranged wife: King Nala joyously passed his days like the king of the Gods in the Nandana park. Having found renown among the kings in Jambudvıpa, the glorious monarch once more ˆ ˆ lived in the kingdom he had regained. And he offered up, according to the precepts, many sacrifices with plentiful stipends. . . . [At this point, the narrative switches back to the narrator, who is speaking to his audience.] Reflecting always on the impermanence of man’s riches, be serene at their coming and going, and do not worry. To him who narrates the great story of Nala and listens to it ceaselessly, misfortune will never befall. Riches will flow to him and he will become rich. After hearing this ancient and eternal great story one shall find sons, grandsons, cattle, and prominence among men, and without a doubt he will be happy in health and love. Mahabharata 3.783 ˆ ˆ In this passage taken from Indic traditions cognate with the Greek, it is clear that the moral correctness of the king’s justice, as validated by the fertility and prosperity signaled in the vision of the Nandana ‘‘park,’’ is coextensive with his ritual correctness. Moreover, it is the premise of this narrative that the fertility and prosperity earned by the king can extend even to those who atten- Images in Early Greek Poetry 63 tively listen to the narrative itself, as if the fertility and prosperity were immanent in the very words that tell about the king’s justice. The symbolism of the Nandana ‘‘park,’’ the ultimate point of reference for the well-tended and flourishing vegetal setting that marks the just king, is further elaborated in the following description: He [i.e., the hero Arjuna] looked upon the lovely city, which is frequented by Siddhas and Caranas, and adorned with sacred trees that flower in all seasons, while a fragrant ˆ . breeze, mixed with the perfumes of flowers and redolent trees, fanned him. And he saw the divine park Nandana, sought out by the hosts of Apsaras, with heavenly blossoming ˆ trees that seemed to beckon to him. This world of those of saintly deeds cannot be seen by one who has not done austerities or who has not maintained the fires, nor by those averse to war, those who fail to sacrifice, liars, persons devoid of the learning of the Veda, unbathed in sacred fords, outside ritual and gifts. Those base men who disrupt sacrifices and evil-doers who drink liquor, violate their teacher’s bed, or eat meat do not set eyes on it at all. Mahabharata 3.444 ˆ ˆ A comparable pattern of coextensiveness between moral and ritual correctness is evident in the Greek traditions. I cite first of all the Works and Days of Hesiod, where the moral correctness of dike in the ultimate sense of ‘‘justice’’ is proˆ grammatically reinforced by the ritual correctness of the just man. For example, immediately following up on a set of instructions praising justice and condemning the base man who behaves unjustly, the poem proceeds to urge the base man to embrace ritual correctness: But you should keep your deranged spirit completely away from these things, and, to the best of your ability, you must make sacrifice to the immortal gods, in a holy and pure fashion, and you must burn splendid thigh-portions. On other occasions, you must supplicate them [i.e., the gods] with libations and with burnt offerings, both when you go to bed and when the sacred light of dawn comes, so that they may have a propitious heart and spirit towards you. This way, you will be buying the arable land of others, not the other way around. Hesiod, Works and Days 335–41 Again we see the prospects of fertility and prosperity as the ultimate signal for those who turn to justice. The conventional Hesiodic injunction that one be memnemenos ‘‘mindful’’ to ˆ do what is prescribed applies to matters of either moral or ritual correctness, as in Works and Days 298 and 728 respectively. The same root ∗men(h2)-, as in Greek memnemenos ‘‘mindful,’’ can be found in the Indic name Manu, meaning ˆ ‘‘the mindful one’’: ‘‘This ancestor of the human race gets his name (which is 64 Articulation of Social Justice cognate with English man) by virtue of being ‘mindful’ at a sacrifice. Manu is the prototypical sacrificer, whose sheer virtuosity in what Sylvain Levi has called ´ ‘the delicate art of sacrifice’ confers upon him an incontestable authority in matters of ritual. Since ritual correctness is the foundation of Indic law, the entire Indic corpus of juridical/moral aphorisms is named after him.’’5 In line with such traditions, then, the very definition of a human being—Manu in Indic, or even man in a Germanic language like English—is predicated on the human capacity to be ‘‘mindful’’ of ritual and moral correctness. From the start, I have been using the word correct in referring to positive ritual and moral behavior that is envisioned in the symbol of the well-tended and flourishing garden or cultivated field. I did so because dike in the ultimate ˆ sense of ‘‘justice’’ is conventionally pictured as straight in archaic Greek poetry, and its opposite, hubris or ‘‘outrage,’’ as crooked. Let us, then, proceed immediately to the second of the two primary images to be examined in this work. This second image is that of a line that starts crooked but ends up straight in the fullness of time, as elaborated in the implied narrative that underlies the ostensibly nonnarrative surface organization of the Works and Days of Hesiod.6 Even at the very start of the Works and Days, the antithetical images of straightness and crookedness are correlated with dike and hubris: ˆ Muses of Pieria, you who make renown [kleos] with your songs, come and tell of Zeus, making a song about your father, on account of whom there are mortals both unworthy of talk and worthy, both worth speaking of and not—all on account of great Zeus. Easily he gives power, and just as easily he ruins the powerful. Easily he diminishes the distinguished, and magnifies the undistinguished. Easily he makes straight the crooked and withers the overweening —Zeus, the one who thunders on high, who lives in the highest abode. Heed me, seeing and hearing as you do, and with dike make straight the ˆ sanctions [themistes]. While you do that, I am ready to tell genuine things to Perses. Hesiod, Works and Days 1–10 As the king of the universe, Zeus is here being invoked as the absolute standard of justice. When an earthly king renders dike, it is a ‘‘judgment’’ in the short ˆ term, but when Zeus as absolute sovereign renders dike, it is simultaneously a ˆ ‘‘judgment’’ and ‘‘justice’’ in the long term. With his dike, as signaled at line ˆ 9 above, Zeus settles what is right and wrong, thereby effecting a straight line. As I have argued at length elsewhere about the Works and Days, the dike or ˆ ‘‘judgment’’ rendered by corrupt kings in their adjudication of the quarrel between the righteous Hesiod and his unrighteous brother Perses was in fact ‘‘crooked,’’ but this short-range ‘‘judgment’’ evolves into long-range ‘‘justice’’ in the fullness of time, dramatized by the actual passage of time in the progression of the poem while Hesiod is speaking to Perses—and while Zeus, as Images in Early Greek Poetry 65 invoked at the very beginning, is rendering justice by rendering judgment, making straight the themistes or ‘‘sanctions’’ (Nagy 1990b: 63–67). Personified as a goddess, Dike as ‘‘Justice’’ discredits unjust kings who make ˆ dikai ‘‘judgments’’ that are crooked: Then there is the virgin Dike, born of Zeus. ˆ She has great esteem and respect among the gods who abide in Olympus. Whenever someone does her harm, using crooked words, right away she takes her place at the side of Zeus son of Kronos, and she proclaims the intent of men that is without dike, so that the people have ˆ to pay retribution for the deeds of recklessness committed by their kings. These kings, having baneful thoughts in their intent, pronounce judgments [dikai] in a crooked way, making them veer and go astray. You kings! Guard against these things and make straight your words, you devourers of gifts! And put crooked judgments [dikai] out of your mind completely. Hesiod, Works and Days 256–64 What the poem of the Works and Days ultimately achieves is the invalidation of earthly kings and the simultaneous validation of Zeus as heavenly king and as absolute standard of justice (Nagy 1990b: 63–67). This validation is conferred by the poem itself, the words of which produce straight justice out of a crooked judgment in the fullness of time; though originally modeled on the justice of Zeus, the justice of kings is forfeited by the earthly kings in the poem and is actually transferred to Hesiodic poetry. The authoritative voice of the Works and Days claims for itself the immanence of dike as ‘‘justice,’’ envisioned simulˆ taneously in the two central images of the flourishing vegetation and the straight line (Nagy 1990b: 63–67). These images come together in an eschatological double vision of a City of Dike ‘‘Justice’’ and a City of Hubris ‘‘Outrage’’: ˆ As for those who render straight judgments [dikai] for guest-strangers and for local people alike, and who do not veer away from what is just [dikaion], for them, their city flourishes, and the inhabitants blossom. Peace, the nurturer of young men, ranges about the land, and never do they have wretched war manifested for them by Zeus who sees far and wide. Men who have straight justice [dike] are never visited by Hunger ˆ or by Derangement. Instead, at feasts, they reap the rewards of the works that they industriously cared about. For them the earth bears much life-sustenance. On the mountains, the oak tree bears acorns at the top and bees in the middle. Their wooly sheep are laden with fleeces. 66 Articulation of Social Justice Their wives bear children resembling their fathers. They flourish with all good things, without fail. And they do not have to find their way home on ships, but the grain-giving land bears fruit. But those who have evil hubris and wanton deeds on their minds for them the son of Kronos, wide-seeing Zeus, marks out justice [dike]. ˆ Many times it happens that an entire city suffers the consequences on account of just one evil man who transgresses and plans reckless deeds. For these men the son of Kronos brings down from the skies a great disaster, famine along with pestilence. And the people waste away. Their women do not give birth, and their households are depleted— all on account of the plans of Zeus the Olympian. There will be a time when Zeus will destroy their vast host of fighting men. Or he can exact retribution against them by destroying their city-walls or their ships sailing over the sea. Hesiod, Works and Days 225–47 Whereas dike as ‘‘justice’’ is envisioned as well-tended and flourishing vegˆ etation, signaling fertility and prosperity, we see that hubris signals sterility and dearth. But the barrenness of hubris can be caused by either of two negative extremes. Either there is not enough growth or there is too much growth. The latter case is made explicit in ancient Greek botanical lore: The term for excessive leaf or wood production—an ailment leading to akarpia or ‘‘failure to bear fruit’’—was hubris (e.g., Theophrastus Historia plantarum 2.7.6) (Michelini 1978). A remedy for this kind of hubris was pruning, a term for which was euthuno ‘‘straighten, make straight’’ (e.g., Theophrastus, Historia plantarum ˆ 2.7.7). These combined images of ‘‘straight’’ or ‘‘crooked’’ vegetal flourishing or barrenness are combined in the earliest examples of political poetry, composed for the historical settings of real cities as distinct from the eschatological settings of an ultimate City of Dike ‘‘Justice’’ and an ultimate City of Hubris ‘‘Outˆ rage.’’ When the elite of a city-state flourish excessively by behaving unjustly, they are warned by their poets, such as Theognis of Megara, that even a tyrant can become a ‘‘straightener’’ (euthunter) of their hubris:7 ˆ Kyrnos, this city is pregnant, and I fear that it will give birth to a man who will be a straightener [euthunter] of our base hubris. ˆ The citizens here are still moderate, but the leaders have veered so as to fall into debasement. Men who are noble, Kyrnos, have never yet ruined any city, but when the base decide to behave with hubris, and when they ruin the community and render judgments [dikai] in favor of things without justice [dike] ˆ for the sake of profits and for the sake of power, Images in Early Greek Poetry do not expect that city to be peaceful for long, not even if it is now in a state of much serenity, when the base decide on these things, namely, profits entailing public damage. From these things arise strife, internecine killings, and tyrants. May this city never decide to adopt these things! 67 Theognis 39–52 In this poetry, the social reformer is pictured as a tyrant. In the poetry of Solon, by contrast, the social reformer is the lawmaker himself, and it is this lawmaker of Athens who offers himself as a critic of the same kind of excessive flourishing, or hubris, on the part of the elite: But the intent of the leaders of the community [demos] is without dike. ˆ ˆ What awaits them is the suffering of many pains because of a great hubris. For they do not understand how to check insatiability [koros], nor can they make order [kosmos] for their existing merriment in the serenity of the banquet. They are wealthy, swayed by deeds without dike, ˆ and not caring at all about sacred or public property, they steal from one another by forcible seizure, and they do not heed the holy institutions of Dike. ˆ who silently observes the present and the past, and who will in the future come to exact complete retribution. Solon fr. 4.7–16 In the same poem of Solon, he personifies his own social reforms as Eunomia ‘‘good legislation,’’ a goddess whose effects are described as follows: Eunomia reveals everything in good order [kosmos] and arrangement. She shackles those who are without dike, ˆ She smoothes over what is rough, checks insatiability [koros], and blackens hubris. She withers the sprouting blossoms of Derangement. She makes straight [euthuno] the judgments [dikai] that are crooked, and as for ˆ overweening deeds, she tames them. Solon fr. 4.32–36 The old picture of the just king in his flourishing garden or cultivated field is a far cry from the Great Reformer’s new picture of a kingless state, but one thing remains a constant: Dike continues in her straight ways, and she continues ˆ to flourish. 68 Articulation of Social Justice NOTES 1. All the translations of quoted Greek texts are mine. 2. By slowly but surely rebuilding his identity after he arrives in Ithaca, Odysseus in the Odyssey is shown to be reconstructing his kingship and thereby reconstituting society (Nagy1990a: 425–26). 3. The Mahabharata, translated by J. A. B. van Buitenen (1975, 2: 363–64). ˆ ˆ 4. Ibid. (308–9). 5. G. Nagy (1990b: 70); quotation from Levi (1898: 85). ´ 6. Nagy (1990b: 63–70). For a different interpretation of justice in Hesiod, see Gagarin (1992). 7. For further analysis of the following passages from Theognis and Solon see Nagy (1985: especially 60–63); for more on Solon, see Anhalt (1993). REFERENCES Anhalt, E. (1993). Solon the Singer: Politics and Poetics. Lanham, Md.: Rowman and Littlefield. van Buitenen, J. A. B. (1975). The Mahabharata. Chicago: University of Chicago Press. ˆ ˆ Gagarin, M. (1992). ‘‘The Poetry of Justice: Hesiod and the Origins of Greek Law.’’ Ramus, 21, 61–78. Levi, S. (1898). La doctrine du sacrifice dans les Brahman as. Paris: Leroux. ´ ˆ . Michelini, A. (1978). ‘‘HYBRIS and Plants.’’ Harvard Studies in Classical Philology, 82, 35–44. Nagy, G. (1985). ‘‘Theognis and Megara: A Poet’s Vision of His City.’’ In T. J. Figueira and G. Nagy (eds.), Theognis of Megara: Poetry and the Polis. Baltimore: Johns Hopkins University Press, 22–81. Nagy, G. (1990a). Pindar’s Homer: The Lyric Possession of an Epic Past. Baltimore: Johns Hopkins University Press. Nagy, G. (1990b). Greek Mythology and Poetics. Ithaca, N.Y.: Cornell University Press. 6 Justice first understand what is meant by justice ‘‘writ large,’’ that is, before we can understand the abstract idea of justice, we must understand what justice means in society. In Books 2 and 3, Socrates explains how society arises, and he describes some of the component parts. In Book 4, he finally returns to the original quest of trying to define justice. Socrates makes a comparison with medicine; he says that ‘‘to, ‘‘ ‘‘theory 70 Articulation of Social Justice already appears in the Hippocratic Corpus, in the essay on Ancient Medicine, a work ascribed to Hippocrates’ son-in-law (Edelstein 1967). The motif of health as an equilibrium of forces and the implicit use of the metaphor of the state is found even earlier in a fragment of Alcmaeon of Croton, one of the immediate disciples of Pythagoras (according to Diogenes Laertius 8.5.83; see the discussion of the date in Guthrie 1962: 375ff.). It reads (Diehls and Kranz 1956: 24B4): The essence of health is isonomia (‘‘the equality of rights’’) of the forces (dynameis), wet-dry, cold-hot, bitter-sweet, etc.; but monarchia (the rule of one) causes disease, for the monarchia of one of the pair is deleterious. Disease occurs on account of an excess (hyperbole) of heat or cold, or on account of an abundance or deficiency of food; and in these things (it occurs): blood marrow or the brain. . . . Health is the symmetrical blending (symmetron krasin) of these qualities. In this fragment we find an extended comparison between health and the state, and both are seen as a product of the competition of forces. What exists in the state ideally is a balance of rival claims of classes, private interests, ethnic groupings, etc. They have, in the course of time, reached an accommodation, a balance that makes for stability—that is, isonomia represents an equal claim to their assigned proportion. Any distortion upsets this delicate balance and creates disease. Moreover, as Gregory Vlastos has demonstrated in a classical article on the subject1 (Vlastos 1953: 337–68) isonomia is a slogan of democracy; this social equilibrium is the ideal of a democratic state. It is all the more impressive that Alcmaeon, whose traditional date is at the end of the sixth century, a period still in the shadow of tyrannies in several Greek states, should equate illness with the political structure of a monarchy. Not only do we find this metaphor in medicine, but we find an analogous idea in the physical speculation of the pre-Socratics. Hesiod in the sixth century B.C. had already distinguished between two kinds of eris (strife); one, the bad kind that leads to war; the other, the good eris (rivalry) that leads to productive competition (Works and Days 11–26). Heraclitus, at the end of the sixth century B.C., taught ‘‘that everything came into being by way of strife’’ (Aristotle, Ethics 1155b4, fr. 8 DK). ‘‘War is the father and king of all things,’’ says Heraclitus (fr. 53). To quote Guthrie’s summary (Guthrie 1981, 1: 440) ‘‘everywhere there are forces pulling both ways at once. Apparent harmony, rest and peace is in the real constitution of things (physis) a precarious equilibrium between these forces.’’ Empedocles taught that the world was composed of four elements (earth, air, fire, and water). In addition to these elements there are two forces: love and hate that govern these elements. There is, as it were, alternations of tension and harmony just below the surface of things. These are some of the more obvious examples of this motif of the underlying tense equilibrium that exists in things. Nature, however, presents a picture of relative stability; the underlying tensions have reached some balance. Metaphor of Medicine in Early Greek Thought 71 Hippocratic medicine conceives of the function of the doctor as one who aids nature. Nature does the healing, that is, restores the balance when it is upset. There is, so to speak, a self-regulating mechanism in nature that dislikes (to use an anthropomorphic term) any disequilibrium. The biological notion of homeostasis, although the term is based on Greek roots, was a discovery and coinage of the nineteenth-century biologist Claude Bernard but might well apply to this pattern of thought; just as the physiological system of higher animals tends to maintain internal stability when threatened by a disruptive stimulus, so too for Hippocratic medicine ‘‘nature’’ brings about a new equilibrium when disease has disrupted it. Heraclitus expresses a similar idea for physical nature in the fragment 226 where he says: ‘‘The sun will not overstep its measures; otherwise the Erinyes, ministers of justice, will find him out.’’ Justice is envisioned as the regulating force that does not allow a disequilibrium to persist. The vocabulary of social justice repeats these motifs. The period of Greek literature that is replete with references to social injustices is the lyric age of Greece (seventh and sixth centuries B.C.). Not that other periods do not also refer to the wrongs which are rampant in society; but the centuries that produced Hesiod, Solon and Theognis are conspicuous in this concern for social issues. The products of the Attic-Boeotian-Megaran world of this period contrast sharply with the concerns of the earlier Ionian world and those of the later fifthcentury Attic world. Was it a difference in the intensity of the social issues or of the awareness of these concerns? Was it like the manifestation of social concerns and the passionate reaction to them found among the prophets of ancient Israel at exactly the same period? Was there an age of social concern that preceded the Jaspers’ Axial age? Be that as it may, one epic poet from the seventh century and two lyric poets from the sixth century, all living within a 75-mile radius, give us an insight into how this metaphor pervades the social picture. Excess is the cause of the injustice. As one quotation that is found both in Solon (5.9–10) and in Theognis (153–54) put it: ‘‘for koros (satiety) breeds hybris whenever much wealth / comes to the kind of man whose mind is not just right . . . .’’ Or again in Theognis (605–6): ‘‘many more men than hunger koros has ruined before now, / men who were anxious to have more than their share to possess.’’ Theognis addresses his boyfriend Kyrnos (39–48) and tells him that the city is pregnant and will give birth to a man who will check the hybris. ‘‘There never was a city that good men destroyed; but when it pleases base men to act with hybris and they corrupt the people and give verdicts in favor of the lawless for the sake of their own gain and power, then you may expect that city to be at peace for long, not even if it lies in the deepest calm (equilibrium) now.’’ The mention of corrupt judges brings to mind Hesiod who inveighs against them on the basis of his personal experience in a lawsuit with his brother Perses. He says to his brother (Works and Days 213–15): ‘‘Listen to justice, Perses, and do not practice hybris. Hybris is bad for a weak man, nor can the good man 72 Articulation of Social Justice bear it easily; he sinks beneath its weight.’’ Hybris is an illness that not only base men are susceptible to. Solon boasts that his great accomplishment was to create an equilibrium between warring parties (fr. 5, transl. R. Lattimore): I gave the people as much privilege as they have a right to; / I neither degraded them from rank nor gave them free hand; /and for those who already held the power and were envied for money / I worked it out that they should also have no cause for complaint. / I stood there holding my sturdy shield over both the parties; / I would not let either side win a victory that was wrong. . . . Solon was not just impartial, but he reestablished the equilibrium that constitutes a just state. Furthermore, in another poem Solon says that it is not supernatural forces that will destroy our state, but the natural forces of koros (greed) that leads to hybris (fr. 3, transl. R. Lattimore): This city of ours will never be destroyed by the planning of Zeus . . . / But the citizens themselves in their wildness are bent on destruction / of their great city, and money is the compulsive cause. The next stage / will be great suffering, recompense for their violent acts (hybris), / for they do not know enough to restrain their greed (koros) and apportion / orderly shares for all as if at a decorous feast . . . . Solon’s language, the decorous feast, where all is apportioned in an orderly fashion is a fine poetic metaphor of the stable equilibrium. Hybris (arrogance) distorts the balance; it is the product of excess (koros). Even the folk wisdom in proverbs warns us against disturbing the balance: MEDEN AGAN (nothing in excess), GNOTHI SEAUTON (know yourself—i.e., your limitations). An impersonal natural force requires us not to exceed the limits imposed on us by the gods. Herodotus in his History sees the defeat of Persia at the hands of the smaller Greece, not as a great nationalistic triumph or as evidence of the support of the gods, but as the impersonal natural force of nemesis that punishes national acts that go beyond the limit assigned to it, thus disrupting the precarious balance of nature. The virtue in the individual that corresponds to this equilibrium in the state is sophrosyne. ‘‘Sound judgment’’ is realizing one’s limitations and not attempting to transcend it. Here, too, the medical model is frequent. As Helen North (1966) points out in her book on this subject, Sophrosyne is a companion of other personified values honored in the Dorian ethos: Eusebeia (reverence, piety) and Eunomia (good order) in Theognis (1135–50), Hesychia (quiet, stability) in Epicharmus (101 Kaibel); and then she adds that ‘‘Hygeia, health of body, is naturally and inevitably coupled with sophrosyne, health of soul. It supplies one of the most common metaphors for virtue in general in Plato’s dialogues. . . ’’ (North 1966: 95). Socrates in the ‘‘Charmides’’ dialogue tries to cure the young man of a headache by discovering his sophrosyne, and then he leads him on a Metaphor of Medicine in Early Greek Thought 73 search for its meaning. This virtue, which is akin to the other virtue, dikaios, is also frequently spoken of in medical terms. Rather than call this a recurrent metaphor, we may look at it as a paradigm, one that pervades the intellectual life of a society at a given period, like the paradigm of the clock in eighteenth-century European thought, or like the paradigm of the living organism in nineteenth-century thought. According to this early Greek model there are competing forces in this universe that reach a state of equilibrium. Each man, thing, institution, and nation has its assigned portion (moira), and when it goes beyond the assigned portion, whether intentionally or not, it disrupts the stability. Natural forces reestablish an equilibrium. In medicine it is the dominance of one humor that causes disease; healing comes from nature with the doctor’s help. In physics this explains natural law; if it were other than how it should be nature would be disrupted and must restore the balance. In politics it is the competing claims that reach an accommodation in the well-ordered (eunomia) state; when the existing arrangement is upset there is stasis, civil unrest. Most generally in man’s affairs this stability is justice: injustice is a disequilibrium brought about by excess; just as in disease there are symptoms that persist until the balance is restored, so injustice may flourish until an equilibrium is achieved. NOTE 1. I am greatly indebted to this article and two others by the late Professor Vlastos i.e., Vlastos (1946) and Vlastos (1947). REFERENCES Classical Authors with translations are cited from the Loeb Library Editions (unless otherwise stated). Pre-Socratic philosophers are quoted from Diehls and Kranz (1956). Diehls, Hermann, and Walter Kranz. (1956). Die Fragmente der Vorsokratiker. 8th ed., 3 vols. Berlin: Weidmann. Edelstein, L. (1967). Ancient Medicine. Baltimore: Johns Hopkins University Press. Guthrie, W. K. C. (1962). History of Greek Philosophy. Vol. 1. Cambridge: Cambridge University Press. North, Helen. (1966). Sophrosyne. Ithaca, N.Y.: Cornell University Press. Vlastos, Gregory. (1946). ‘‘Solonian Justice.’’ Classical Philology, 65–86. Vlastos, Gregory. (1947). ‘‘Equality and Justice in the Early Greek Cosmogonies.’’ Classical Philology, 156–78. Vlastos, Gregory. (1953) ‘‘Isonomia.’’ American Journal of Philology, 337–68. 7 Social Justice in Ancient Iran FARHANG MEHR Social justice, with definable features, has an indeterminate domain. Its main features received recognition even in antiquity. In general terms, social justice is associated in substance with human rights, political liberalism, and economic equity, and in form with the authority of the law and the due legal process. This chapter is concerned with social justice in ancient Iran. Ancient Iran refers to pre-Islamic Iran and a phase of Iranian history that ended by Arab invasion in the seventh century. The key aspects of social justice were rooted in Zarathushtrian culture and Indo-Iranian tradition. Hence, Zarathushtrian literature, classical historical writings on Iran, and the stone inscriptions of ancient Iran provide the main sources for the present inquiry. The essential features of social justice may conveniently be discussed under four headings: political justice, administration of justice, economic equity, and human rights. POLITICAL JUSTICE In his first sermon, Ashu Zarathushtra proclaims: (Irani 1924) Hearken with your ears to these best counsels: Gaze at these beams of fire and contemplate with your best judgment; Let each man and woman choose his/her creed with that freedom of choice which each must have at great events; 76 Articulation of Social Justice O ye, awake to these my announcements. (Yasna 30–2) From the ‘‘Cyrus Cylinder,’’ recovered in 1879 from the site of the Temple of Marduk at Babylon, we learn that the founder of the Achaemenian dynasty considered himself, and wished to be considered by others, a ‘‘righteous ruler’’ and a ‘‘liberator’’ rather than a conqueror; he who wanted to restore proper government to Babylon (Stronach 1978: 291). Cyrus’ liberality and sense of political justice prompted him to restore all the gods of Sumer, Akkad, Guti, Susa and Ashur to their original places (Stronach 1978: 292). Several chapters in the Old Testament inform us that Cyrus (560-530 B.C.), who had conquered Babylon (539–537 B.C.) freed the Jews who had been held captive in Babylon and helped them to return to, and build a house of prayer, in Jerusalem., 6.3–5). Cyrus’ sanction of religious freedom for other peoples is recognized by the fact that he is called ‘‘my shepherd’’ (Isaiah 44.28), and is given the title of ‘‘anointed’’ (Isaiah 45.1) or Messiah in the Old Testament, and is ordered by Marduk, the great lord and protector of the Babylonians, who has seen Cyrus’ good deeds and upright behavior, to liberate the people of Babylon (Stronach 1978: 292). This tradition of liberality continued during the reign of Darius the Great, who conquered Egypt in 517 B.C. and there paid reverence to the Egyptian Deities. He erected a temple to the god Ammon and financed the search for a new Apis (the sacred bull) in place of the one that had died just before Darius’ conquest of Egypt (Polyaenus VII, 11, 7). This liberalism manifests itself in writings of the Sassanian Period (second to sixth centuries A.D.). The book of Mıno-I-Kharad (believed to have been written ˆ ˆ in the sixth century A.D.) mentions liberality as the first among thirty-three good causes of the good works of men (West 1871: 165). During the Sassanian Rule, however, traditions of liberality gradually faded away. The reason was twofold: (1) the merging of politics and religion in Iran and the use of religion as a political tool against the dissidents and (2) the emergence of the Eastern Roman Empire as the protector of Christianity in the third century A.D. Iran and Rome were the two largest, contemporaneous neighboring empires involved in continuous wars for territorial expansion and political hegemony. Social Justice in Ancient Iran 77 During the Sassanians, large numbers of Jews, Christians and Buddhists lived in Iran. ‘‘The adherents of foreign religions were able to live in peace, their organization and their religious laws were respected, so long as they did not set themselves against the authority of the state or conspire with its enemies. It was political reasons more than religious intolerance that brought about the first great persecution of Christians under Shapur II’’ (Christensen 1939: 122). Even toward innovators like Mani, intolerance started when Shapur I, against the wishes of the clergy, had shown sympathy toward the Manicheans. ‘‘Liberalism’’ constituted an integral component of social justice in ancient Iran. Rationality (Holy Wisdom or ‘‘Vohu Mana’’) is a thread that runs through the whole Gathas. ‘‘O, Mazda, from the beginning Thou didst create soul, body, mental power and knowledge; Thou didst bestow to mankind, the power to act, speak and guide (in order that) everyone should choose his or her own faith and path freely’’ (Yasna 31–11) (trans. Azargoshasb 1988). Freedom of man and freedom of choice lie at the foundation of Zarathushtrian tradition—a freedom which should be exercised through wisdom and rationality, and in accordance with the Truth (the law of Asha). In the Gathic tradition, every individual using his faculties of Holy Wisdom and Truth, is entitled to question the legitimacy of law, even God’s law, until one is satisfied with its legitimacy. Rationality negates dogma. Legitimacy of dogmas may be challenged, as can the legitimacy of any edict issued by the civil authorities. Liberality and rationality require ‘‘dialogue’’ and in the Gathas the dialogue between the all-powerful (omnipotent) Ahura Mazda, on the one side, and the soul of the Mother-Earth (Geush Urvan), the Holy Immortals (Amesha Spenta) of Wisdom (Vohu Mana) and Truth (Asha) on the other, is revealing. The scenario is set in Yasna 29 (trans. Taraporewalla 1951). The soul of Mother-Earth complains to Ahura Mazda: ‘‘Wherefore did you fashion me? I am oppressed by fury, rapine, outrage, plunder, and violence which are prevalent. Except in Thee I have no protector. I supplicate Thee to reveal to me a savior (on earth) who could repel the evil and to guide me through my difficulties.’’ Then Ahura Mazda initiates a series of consultations. First with Asha (Truth) whom He asks: ‘‘(In your opinion) who shall be the savior of the Mother-Earth and the people of the world—one who can keep at abeyance wrath and hatred, foster zeal, repel evil and protect the earth and righteous people.’’ Asha, the Holy Immortal, after some reflection, responds: ‘‘Such a leader should be just and compassionate, free from cruelty, and strongest of mortals who can support the righteous against the wicked. Ahura Mazda best knows what Daevas and their followers have done in the past and what they would do in the future (should their activities remain unchecked).’’ Then Asha, somewhat apologetically, admitted that he did not know such a person; and yet, together with the soul of Mother-Earth, Asha praised Ahura Mazda and appealed to Him, with uplifted hand, to name such a person. In a slightly admonishing tone, Ahura Mazda reminds Asha that he had been 78 Articulation of Social Justice assigned to regulate the progress of the world (and now he pleads ignorance). Next, Ahura Mazda turns to Vohu Mana, the highest Holy Immortal, and repeats his question. While Vohu Mana ponders over the matter, Ahura Mazda himself proclaims: ‘‘Such a person is well known to me. He is Zarathushtra, who has kept and carried out all our commands, and is eager to accept the mission and to preach the (hymns) of Mazda’s Eternal Law. Therefore, sweetness of speech shall be granted to him.’’ At this juncture, the soul of Mother-Earth asks if Zarathushtra has the (physical) strength required for the job. However, she quickly remembers that Ahura Mazda knows best and that the job must be done not by force, but by reason, righteousness, and persuasion, for which purpose Zarathushtra will be granted strength of reason and sweetness of speech. Thus she declares her support and promises to help Zarathushtra succeed in his mission. The dialogue reveals salient procedural rules in a just and democratic regime. The dialogue is between the rulers and the ruled. Consultation and a free, rational exchange of ideas are of essence in a just society. On ‘‘the customs which the Persians observe,’’ writes Herodotus ‘‘it is the general practice to deliberate upon affairs of weight when they are drunk (perhaps to eliminate inhibitions); and then on the morrow, when they are sober, the decision to which they came the night before is put before them again by the master of the house . . . ; and if it is then approved of, they can act on it; if not, they set it aside. Sometimes, however, they are sober at the first deliberation, but (then) reconsider the matter under the influence of wine’’ (Herodotus I, 133). Before his expedition against Athens, Xerxes summons an assembly of the noblest Persians, to learn their opinions and to lay before them his own designs. Having informed the assembly of his plans, Xerxes wants the nobles to speak and addresses them in the following words: ‘‘I lay the business before you, and give you full leave to speak your minds upon it openly’’ (Herodotus VII, 8). The form of government in ancient Iran was monarchical. Centuries of recorded history of ancient Iran had seen only four dynasties, except for a period of Hellenic rule. This indicates stability of the regimes based either on their legitimacy or on an efficient administration. The kings enjoyed extensive authority, exercised with tolerance and justice by some and arbitrarily and in an oppressive manner by others. But this authority granted to the kings by Ahura Mazda had to be used for the peace, progress, and happiness of man. According to the religious literature, King Yima, the son of Vavanghavant, after a long and splendid reign, lost his throne because he chose vanity and ignored the protection of Mother-Earth and the welfare of the people (Yasna 48–5) (Taraporewalla 1951). The Gathas instruct rulers and the ordinary people alike ‘‘to keep hatred far’’ from themselves (Yasna 48–7). In reference to the rulers blinded by pride and falsehood, Zarathushtra states: ‘‘Princes and Priests who like to yoke mankind to evil deeds, will destroy the true life’’ (Yasna 46–11). ‘‘The priests of falsehood never show regard for Ahura Mazda’s commands and laws to love and Social Justice in Ancient Iran 79 guard the Mother-Earth,’’ says Ashu Zarathushtra, who advises thus: ‘‘Let not bad rulers govern you’’ (Yasna 48–5). Undoubtedly, the religious teaching had a great influence on Achaemenians and Sassanians who considered their kingships entrusted to them by Ahura Mazda. ADMINISTRATION OF JUSTICE According to the Old Testament and Greek Classical writings, ‘‘Law’’ was supreme in ancient Iran. ‘‘Now, O King, establish the decree, and sign the writing, that it be not changed according to the law of the Medes and Persians, which altereth not’’ states the Old Testament. Then, ‘‘These men assembled, and said unto the King, know, O King, that the law of the Medes and Persians is that no decrees nor statute which the King established may be changed’’ (Esther 1.19). In ancient Iran, even as early as in the fifth century B.C., the laws were published so that everybody would know what the laws were and no law would have a retrospective effect. ‘‘And when the King’s decree shall be published throughout all the empire, everybody great and small will know and act upon it’’ (Esther 1.20). ‘‘If it please the King, let there go a royal commandment from him, and let it be written among the law of Persians and the Medes that it be not altered’’ (Esther 1.19) nor would anybody violate it through plea of ignorance. Strict rules governed the administration of justice. During the administration of the Achaemenians, the royal judges ‘‘held their offices for life, or until they were found guilty of some misconduct’’ (Herodotus III, 3). The judges tenure of office guaranteed their independence from the executive. In Iran, ‘‘Justice is administered, and (the laws) are interpreted, and all disputes (are) referred to the (judges)’’ (Herodotus III, 3). There is ample evidence that the administration of justice had reached juridical sophistication with vertically stratified courts—courts of first instance and appeal, services of defense lawyers, and well-defined procedural rules that guaranteed fair trials. Nonetheless, there are indications that under autocratic kings, the rules of law were sometimes ignored. Herodotus narrates a story about King Cambyses that implies in the normal time even the kings would follow the law of the land. However, in the case of a ruthless, mad, and despotic ruler, the royal judges would find a way to escape the ruler’s ravage without endorsing violation of law. Herodotus writes: ‘‘It was not the custom of the Persians, to marry their sisters—but Cambyses, wishing to marry his sister, called together the royal judges and asked them whether there was any law which allowed a brother, if he wished, to marry his sister. The judges gave him an answer which was at once true and safe. The answer given by the judges was that ‘They had not found any law allowing a brother to take his sister to wife, but they found a law, the king of the Persians might do whatever he pleased’ ’’ (Herodotus III, 80 Articulation of Social Justice 31). In other words they suggested that the king stands above the law. This, at least, during the administration of the Achaemenians was rare. In the abovementioned case, Cambyses followed the prevailing rule among Pharaohs, after the conquest of Egypt. ‘‘Darius, like Hammurabi, laid special weight on the rules for evidence . . . and insisted on the incorruptibility of the royal judges’’ (Olmstead 1948: 129). The official who administered the law (dat) was called Iahudanu and was charged with the task of insuring the exactness and accuracy of the applied law. The crimes against the state, the person of the king and his family, and often the king’s property, were very severe and usually punishable by death (Olmstead 1948: 130). Herodotus narrates the story of Pychius, whose eldest son’s life was forfeited for a presumed act of disloyalty toward the king. The king ordered the murder of Pychius’ son by cutting his body asunder and placing the two halves on the two sides of the exit to the great road so that the army might march out between them. Such was the severity or exemplary nature of the real or perceived crime against the king and state. A. T. Olmstead writes ‘‘To the end of his life, Darius continued to express his pride in his ordinance of Good Regulations.’’ His reputation as lawgiver whose laws had preserved the Persian Empire, was attested by Plato (Epistle vii, 332B). Darius’ laws were applied by the Seleucid rulers as authoritative law (Olmstead 1948: 130). Under the Sassanids the administration of justice reached a high degree of sophistication at the horizontal and vertical levels. At the horizontal level the courts were divided into Ecclesiastical and Temporal Courts (Bulsara 1937). The Ecclesiastical Courts (Dahyopatan) entertained the crimes against the church covering charges of heresy, apostacy, atheism and other like matters; Temporal courts (Dat-gehan) adjudicated crimes against the state and the civil litigations (Bulsara 1937: Ch. XL, 11). The king was nominally the highest judicial authority, though in reality the clergy had the upper hand in judicial matters (Bulsara 1937: Ch. XLII, 22, 47). The vertical stratification of the courts was in Courts of First Instance and Appeal, and the final decision lay with the king, who was functioning as the supreme court individually or in council. The accused persons were defended by the civil lawyers in the Temporal Courts and by the clergy in the Ecclesiastical Courts. The rules of procedure were well defined (Bulsara 1937: Ch. XXVII). In the ecclesiastical matters or litigations, the king could not intervene, for such matters fell under ‘‘the supreme authority’’ of the Grand Master of Divinity (Magopatan Magopat) (Bulsara 1937: Ch. XL, 10, 11). There are indications that matters of personal law (marriage, divorce, inheritance, adoption) and the proprietary rights of marriage, fell within the jurisdiction of the Ecclesiastical Courts (Bulsara 1937: Ch. XL, 6). The priests (Magis) under the mantle of religion exercised intensive power over the religious and civil lives of the people. Not only did the priests share Social Justice in Ancient Iran 81 sovereignty with the civil government, but they also possessed proprietary rights over temple endowments, lands, and the incomes accrued therefrom. They functioned as educators, judges, and priests. When an offense was classified as antireligion, the accused was doomed. In the civil courts, the administration of justice was humane. The erudite civil judges were well versed in law and had good reputations. Matikan-e-Hazar Datastan enlists specific rules with regard to the arrest of the perpetrators, determination of his/her correct identification, the nature and circumstances of the crime, evidence to be adduced, deposition, and expert’s opinion (Bulsara 1937: Ch. XL, 1, 2). As an illustration, the book mentions the case of a person being arrested and charged with theft. The arresting police had to act according to the orders of the judge and recognized procedure; the police must have identified the person, must have recognized the stolen article, and must have sufficient proof that the article was indeed stolen (and not to have come to the possession of the accused in some other way) (Bulsara 1937: Ch. XL, 13). ECONOMIC EQUITY Our knowledge about the state of the economy during the Median dynasty is scanty. In a tribal and extended family setup, economic needs and the welfare of the individuals, family, clan, and tribe are looked after by the elders. Herodotus informs us that ‘‘Deioces collected the Medes into a nation. . . . These are the tribes of which they consisted: the Busae, the Paretaceni, the Struchates, the Arizanti, the Budii and the Magi’’ (Herodotus I, 101). Except for Magi, no information is available on the other tribes. Magi were the religious sect that attended to the socioreligious affairs of the nation. They enjoyed a great power and exerted influence on the princes and rulers—and, as such, enjoyed privileges. The Gathas reproaches the Karapans (priests) and princes who dupe and exploit people and become burdensome (Taraporewalla 1951: 48–10). The princes and Karapans kept their sway over the people and carried out their own ill-intentioned plans. We do not know whether other tribes too performed specific functions to the exclusion of others in the nation. According to Herodotus ‘‘the Medes at that time dwelt in scattered villages, throughout the land’’ (Histories I, 91). When Deioces was elected king, he ordered a magnificent palace to be built, and dwelling houses were constructed outside the circuit of the palace walls. Thus, a large town emerged. The cost was paid by freemen as a voluntary contribution. We do not find any allusion to the use of coined money during the administration of the Medes. However, from Yashts (Avesta) and Ferdaussi’s ShahNameh we can conclude that gold, silver, and precious stones were used for ornaments, crowns, jewelry, settees, and other utensils. With regard to Achamenians, basic information may be gathered from Babylonian business documents, Egyptian papyri, the Bible, Greek sources, and Persian inscriptions (Olmstead 1930: 232–38). 82 Articulation of Social Justice Before the conquest of Elam and Babylonia by Cyrus and contact with older civilizations, the Persian societal structure was tribal, the nucleus of which was the family residing in a house (nmana). Several families formed a clan (tauma) ˆ ˆ living in a village (vis), and several clans formed a tribe (zantu) living in a town (shathra) or in an extended town (dainhu). The chiefs of clans and tribes were elected and enjoyed legitimacy of position. This societal structure is evidenced by Darius’ inscription at Nagsh-i-Rustam that reads: ‘‘I, Darius, the Great King, the son of Vishtasp (family), a Parsi (clan), of Aryan (tribe).’’ After contact with Assyrian and Babylonian tribes, the governmental administration of the Achaemenians became more centralized while the tribal structure continued, with loyalties to family, clan, and tribe. The king and central government were mainly responsible for the defense of the country during war between the tribes, and for maintenance of order while peace between the tribes reigned. The economy of the country was essentially agricultural. Farming in the plains by sedentary people with the use of highly skilled irrigation systems through Qanats, herd raising by nomads in the mountainous pastures, handcrafting, pottery making, and the constructing of clay houses, and primitive barter trade formed the main economic pursuits of the people. The emphasis on farming and agriculture in Zarathushtrian literature is striking: ‘‘(He) who intensively sows corn, (plants) fruit bearing trees; (He) who makes full use of water for cultivation; (He) who increases the amount of water on the earth . . . sows piety; (He) who does not (sow), does not eat and (He) who does not eat cannot work, and (He) who does not work (cannot become) holy’’ (Anklesaria 1949: 43). Through interaction with conquered nations, Iranians learned administrative bookkeeping from Babylonians and the cuneiform alphabet from the Elamites (Olmstead 1948: 68–86). One of the main economic developments of this period was the introduction of coin money. From the tablets in the revenue archives of Kudda Kaka and Huhan-haltash, the Elamite subjects of Persia, we learn that after the adoption of the monetary system, a class of private bankers emerged, who gave loans to individuals without mentioning the interest rate. However, the accruance of interest is evident from the fact that in one of the tablets it is mentioned that in case of failure to pay back the loan installments on time, the interest shall increase (Olmstead 1948: 69). Most probably the banking operations were done mainly by Elamite subjects of Persia. It seems that ‘‘the Elamite bankers were acquainted with the same tricks employed by their fellow bankers in Babylonia; on the inner tablet the six gold shekels are lent at the unusually favorable rate of one pound of silver, that is the ratio of ten to one; but on the envelope (the only part available for inspection unless it were broken in the presence of the judge), the loan is discounted one gold shekel, the more usual twelve-to-one ratio’’ (Olmstead 1948: 69). The Persians probably would not engage themselves in such dishonorable Social Justice in Ancient Iran 83 practices. Herodotus writes of the Persians of that period, ‘‘They hold it unlawful to talk of anything which it is unlawful to do. The most disgraceful thing in the world, they (Persians) think, is to tell a lie; the next worse, to own a debt; because among other reasons, the debtor is obliged to tell lies’’ (Herodotus I, 139). Honoring the promise was both a religious and a legal duty. In the Avesta, the chapter of Mehr Yasht is replete with statements confirming the sanctity of contracts. The Yazata (Angel) Mithra is the genius of the sanctity of contract and the foe of falsehood. He conducts the divine struggle against evil and chastises those in breach of promise (Mehr 1991: 35). In Vendidad the breaker of a promise is labeled ‘‘the thief of promise’’ (Anklesaria 1949: IV, I). The contract could have been made orally by word of mouth or in writing. The contracting parties could fix the damages for breach in advance, which would have been an animal (e.g., a sheep, horse, camel), or a slave, or a piece of real property (e.g., a house or a plot of land). The tablets in the archives of Kudda Kala inform us that the gifts offered to the king by the satrapies or subjects were both in money and in kind. Textile and garments, bows and arrows, spears and shields, are all mentioned among other items in the list of the king’s revenue (Olmstead 1948: 70). Again, the inscriptions on the tablet show that some merchants dealt in loan of seed, food, precious metals and stones. Sale or lease of a house or farm are mentioned as the subject matter of transactions and contracts. The proprietary right had acquired importance. Title deeds were used and animals were branded for ascertainment of ownership. According to Herodotus, Cyrus and Cambyses collected no tax and no formal tribute (Herodotus III 8, 9). Instead, the subject peoples would offer gifts. It was Darius who imposed a tax, fixed tributes, and dues. The economic regime was overhauled in 503 to 502 B.C. by Darius, the great lawgiver and administrator. Amongst his economic measures were a standardized system of weights and measures (in a new addition to the weights used by Babylonians, he introduced the new weight ‘‘karsha’’), a new monetary coinage, ‘‘Daric’’ standardization of the values of precious metals, and a new tax law. However, most traders continued the barter practice, and the monetary terminology was used in bookkeeping documents. Darius divided his territory into twenty provinces (or states) ‘‘of the kind which the Persians call satrapies.’’ He assigned a governor for each province and fixed the tributes that were to be paid to him by the several nations. The following is an account of these governments and of the yearly tribute that they paid to the king. ‘‘Such as brought their tribute in silver were ordered to pay according to the Babylonian talent; while the Euboic was the standard measure for such as brought gold.’’ Herodotus states: ‘‘Cyrus was gentle and poured them all manner of goods,—Cambyses was harsh and reckless,—Darius looked to making gain in everything’’ (Herodotus III, 89–91). In the Vendidad, different rewards in kind are set for physicians. The professional fee varied according to the social status of the patients. Those who had 84 Articulation of Social Justice a higher social status and income paid more. This reflects the concept of economic equity in those days (Anklesaria 1949: vii, 41–43). ‘‘A stray tablet from the treasury of Darius, vividly illustrates the drastic character of the revaluation and suggests the injustice which the tax payer occasionally might have suffered in the process,’’ writes Olmstead (1948: 189). The story runs like this. In the nineteenth and twentieth years of Darius’ reign, some coins with less than normal purity had been minted and placed in circulation. When the taxpayers used them in discharge of their tax obligations, the treasury would accept them at a discount and not at the face value. This was unjust and caused hardships to the taxpayers. Despite realization of the fact that inferior coinages were in circulation, the government had not collected and placed those coins out of circulation (Olmstead 1948: 190). The discount was sometimes up to one-eighth of the face value of the coins. During Darius’ reign, trade became more sophisticated, and government regulatory measures increased. The population became socially stratified; the tribes and clans were more integrated into the nation. National identity and loyalty were gradually replacing the tribal loyalty. Trade expanded, and the merchants and money lenders were the main profit makers. Some pursuits became family concerns, passing from father to son. The names that appear on the tablets reveal that many Jews and Babylonians were engaged in business and money lending (Olmstead 1948: 192). Very little is documented on the state of economy during the administration of the Parthians (250 B.C.–A.D. 226). However, the coins minted with the names of the Parthian kings on them and found in Asia Minor indicate a thriving trade at that time. Under the Parthians, the tribal system revived and the central government was weakened. Decentralization increased with the growth of feudalism. Unlike Achaemenian policy, with a permanent army under the superior command of the king, the Parthians forced their subjects to take arms when needed. They also used mercenaries. Most important decisions were adopted in the Council of the Chiefs of Tribes, big feudals, the tyul holders and notables and the influential members of the king’s family. The assignment of ludicrous positions to the officials and the election of the successor to the king were among the functions of the council. The high positions in the government were not hereditary. Rivalry and clashes between tribes were rampant. We know a great deal about the socioeconomic conditions during the administration of the Sassanians (A.D. 226–430). During the era the main sources of income were land tax (Xarag) and personal tax (Gazyat). As previously mentioned in Zarathushtrian literature and Persian tradition, agriculture is a divine and noble pursuit. With the extensive arid lands and shortage of rainfall in Iran, agriculture depended on an expensive and sophisticated system of irrigation through Qanat. The land tax was ‘‘from a sixth to a third according to the fertility of the soil,’’ and it was based on an assessment of the crops of each Social Justice in Ancient Iran 85 farm by the government officials (Christensen 1939: 109–37). Personal tax ‘‘was fixed at a yearly sum which was divided out among the taxpayers by the authority’’ (Christensen 1939: 109–37). A legacy from the Parthians, as well as the Sassanians, was that the farmers functioned as foot soldiers during the war. The town dwellers paid only the personal tax and were normally exempt from military service unless they were in the professional army or volunteered for the service. King Khosrow I (A.D. 531–579) revised the personal law exempting individuals younger than twenty and older than fifty from the personal tax. Also, members of the royal family, nobility, priesthood, and military became exempt from personal tax. Thus, the financial burden of the farmers was increased. The rate of personal tax varied between four to twelve Darham per person according to the income of the individual concerned. Once a person passed away, all of his or her tax in arrears would be written off. In addition to the two above-mentioned taxes, those who received the king’s audience during the national festivities presented gifts to him. The spoils of the war too went to the treasury. It was customary for the newly ascended king to relinquish all the uncollected and unpaid taxes. It was a gesture of grace to the subjects. The main expenditure of the government consisted of the wages of the civil servants, army, office expenses, the cost of the infrastructure (works such as construction of dams, roads and schools), welfare and upkeep of the poor, as well as the financing of war. During the Sassanian administration, the city of Ctesiphon, the capital of the empire, was a crossroads for international trade, a meeting place for caravans that ‘‘came from the west through Edessa and Nisibus, India by the Cabul Valley, China along the Tarim basin, and Turkestan through Rhagae’’ (Christensen 1939: 117). In Iran the Chinese brought carpets from Babylon, precious stones from Syria, and textiles from Syria and Egypt (Christensen 1939: 118). During the Achaemenian rule many skilled craftsmen from foreign lands worked on the construction of palaces, dams, roads, and were even engaged in trade. The study of records and the analysis of the inscriptions on tablets unearthed in the 1930s reveal the observance of economic justice toward foreign workers. The ‘‘Treasury Tablets’’ belonging to 492–460 B.C. give us impressive information about the egalitarian treatment of Iranians and foreigners who were engaged in the construction of Persepolis in Fars. The inscriptions on the tablets disclose that no slaves and no forced labor had been used in the building of the place. It seems that prisoners of war were not enslaved during the Achaemenian administration, though the situation changed during the Sassanian rule when the great dam at Shoshtar was built by Roman prisoners of war after the defeat of Valerian’s army by Shapur I. The following are excerpts from some tablets. The treasurer is informed that: three karsha, two and a half shekels of silver should be given to an Egyptian woodworker named Harandhama who is a wage earner at Persepolis. The sum is paid for services performed during five (5) months (eighth to the twelfth month of the thirty-second year of Darius’ reign); 86 Articulation of Social Justice by specific order of Darius, the sizable amount of 904 karsha of silver (perhaps equivalent to $9,000 in 1939) is here given to herdsmen of Parmizza; 165 karsha of silver are here awarded for the maintenance of the women of the horses; 530 karsha of silver are distributed in varying amounts to thirteen (13) specific individuals, the majority of whom are Persians; eight (8) karsha and ishekeb of silver are paid to workmen of Egypt and Syria. Sometimes the money is paid in silver coins or part of it in kind. The fact remains that they were paid for their services (Cameron 1948: 83–93). Economic equity was also achieved through charity; a time honored tradition observed by Parsis of India and Zartushtis of Iran that is still practiced today. In Zarathushtrian literature, Charity (Rata) is greatly praised. The last sentence of the Yatha Ahu Vairyo prayers says ‘‘that man who helps his fellow beings develops moral courage.’’ In ancient Iran during the year, six festivals of five days each (called Gahanbar) were observed. Even today the Zartushtis of Iran faithfully celebrate those feasts. The feasts are religio-social in nature and correspond to the time of sowing or harvesting crops, which were performed by mutual aid. ‘‘The festivals were of great significance to an agricultural community and if anyone avoided giving his share of a helping hand he was looked down upon’’ (Sethna 1978: 152). Another objective was to provide collective help for the poor and needy. The kings in the festivals of NoRooz and Mehrgan (the beginning of spring and autumn) gave public audience for several days, and help was given to the needy and poor. In religious literature, Rata (the Guardian of Charity) is the companion of Spenta Armaiti, the angel Guardian of Mother-Earth. In the Vendidad it is stated that when a coreligionist or friend goes to a person for financial assistance, he or she must be helped (Anklesaria 1949: 4, 44). A Zoroastrian prays that the spirit of Charity of the religious devotee may drive away the demon of stinginess. HUMAN RIGHTS ‘‘Human rights’’ is an illusive concept of modern coinage. It has its origin in the writings of social scientists of the eighteenth and nineteenth century who opposed the arbitrary rule of the kings and advocated freedom of conscience, thought, speech, assembly, and the dignity of man. The concept has been subjected to much scrutiny and has finally been incorporated into the United Nations Charter of Human Rights, to which all UN members have become signatories. In the meantime, the origin of human rights had been ascribed to national and religious laws in order to enhance the validity and legitimacy of the concept. Notwithstanding the undefinability of the domain of the subject matter, certain general principles lie at the core of the concept, which we glanced through in connection with social justice in ancient Iran. Slavery existed in the ancient world, and is acknowledged in most religions Social Justice in Ancient Iran 87 with disapproval. There is no word for ‘‘slavery’’ in Zarathushtrian holy scripture; nor does the existence of slavery appear in Iranian mythology and tradition. But cases are mentioned in the classical writings concerning enslaved, defeated nations. In the war against the Ionians, the Persians addressed them in these words: ‘‘If (you) submit, no harm shall happen to (you) on account of (your) rebellion. (Your) temples shall not be burnt, nor any of (your) private buildings. . . . But if (you) refuse to yield, and determine the chance of a battle, . . . when (you) are vanquished in the fight, (you) shall be enslaved; (your) boys shall be made eunuchs, and (your) maidens transported to Bactra’’ (Herodotus VI, 9). On this basis, ‘‘Bartholamae and West (have) concluded that slaves were imported from foreign countries or were captured’’ (Bulsara 1937: 72), and Bulsara infers that there was no indigenous slave in Iran. This practice must have continued even after the Achaemenians. In several places in the collection of the laws of the Sassanian period (Matikan-e-Hazar Datastan), allusions have been made to the law governing the ownership and treatment of slaves. Certain principles may be formulated from such laws relating to specific cases. The slaves were captured foreigners who were non-Zoroastrians. The ownership of the slave belonged to the man (Bulsara 1937: IV). The owner had to treat the slave humanely; violence and tyranny toward the slave was forbidden. In particular, the beating of a slave woman would be considered a crime (Bulsara 1937: IV). When a non-Zoroastrian slave, such as a Christian slave, embraced Zoroastrianism, he or she could pay his or her slave price and become free. When a Christian (non-Zoroastrian) slave converted into Zoroastrianism by marrying a Zoroastrian, the matrimonial partner had to pay the price of the slave to the owner and free the slave. Whoever sold a slave to a non-Zoroastrian committed a crime; both the vendor and the purchaser were subject to punishment. If a slave together with his or her foreign master embraced Zoroastrianism, he or she remained enslaved, when the master pledged the services of the slave to a third party, the master was entitled to receive the wage or reward that accrued to the slave (Bulsara 1937: XXI). If, however, the third party, in addition to the wage, paid some money as a gift to the slave, the latter was entitled to keep it (Bulsara 1937: XXXV) and use it in a later stage to purchase his or her freedom from the master (Bulsara 1937: XXI). To free a slave (irrespective of his or her faith) was a good deed. Besides the right to keep the gifts given to them, the slaves were entitled to at least three days of rest in a month (Bulsara 1937: IV). If the ownership of a slave lay with more than one person—say, three persons, or two persons with unequal rights— once the majority owner (or owners) freed the slave, the slave was completely free. The law protected the slave (Bulsara 1937: XXXII). Nobody ‘‘may inflict upon his own slaves a fatal punishment for a single crime. . . . Not even the king himself may slay anyone on account of one crime’’ (Olmstead 1948: 68–86). Equality of men and women, Iranian or non-Iranian, is apparent in the Gathas, 88 Articulation of Social Justice where Zarathushtra addresses man (Nar) and woman (Nairi) on the same footing. Zarathushtra also blesses Frayana, a Turanian along with his Iranian disciples. Egalitarianism is the bedrock of the ancient Iranian religion and the Achaemenian tradition. The mother and the wife of the king not only participated in the official ceremonies, but they also wore crowns and the mother took precedence over the king (Rapp 1878: 106). The women took part in public functions according to Plutarch. Persians condemned collective punishment and lynching. Comparing justice and retaliation in Greece and Persia, Herodotus writes, ‘‘The Persians consider that Greeks were to blame for ‘collective retaliation’ and the injuries on either side (caused by) common violence’’ (Herodotus I, 4). After the Spartans murdered the official emissaries of Persia sent to Sparta, some Spartans were sent to the Court of Persia, where receiving an audience with the king, they declared, ‘‘O, king, the Lacedaemonians have sent us hither, in the place of those heralds of yours who were slain in Sparta, to make atonement to you on their account’’; but Xerxes, the king of Persia, answered with true greatness of the soul that he ‘‘would not act like the Lacedaemonians, who by killing the heralds, have broken the laws which all men hold in common’’ (i.e., the international law). He continued, ‘‘As I have blamed such conduct in them, I would never be guilty of it myself’’ (Herodotus VII, 136). This shows the moral dimension of the ancient Persian law. In Sassanian Iran, the society rested on three pillars: the monarchy, the Zoroastrian clergy, and the aristocracy—all of whom collaborated with, or vied against, each other, depending on the strength or weakness of the central government. In that society several foreign religious communities existed: Jews, Christians, and Buddhists were the largest ones. Among these groups Christians were suppressed, not so much for their faith as for their political leanings. In the religious literature people were divided into clergy (Athrava), military (Rathaishta), farmers (Vastryufshyun), and craftsmen (Huviti). The division was horizontal, not vertical. No special privileges were assigned to these groups. During the Sassanian rule this horizontal grouping was modified and transformed into a vertical hierarchy with special rights and privileges. Transfer from one class to another was difficult, if not impossible. Consequently, Achaemenian social justice was replaced by social discrimination and inequality that contributed to the collapse of the Sassanian dynasty and the Arab conquest in Iran. The surveys of social justice reveal that its essential features were deeply rooted in ancient Iranian tradition and religious beliefs. These features were observed through political legitimacy, religious tolerance, economic equity, and application of a strictly implemented rule of law. Achaemenians (560–330 B.C.) expressed pride in their laws, incorruptability of their judges, fair economic practices, and equal treatment of Iranians and non-Iranians in matters of wage and financial benefits related to services rendered. During the Sassanians rule (A.D. 226–430), several features of social justice— Social Justice in Ancient Iran 89 particularly religious tolerance—were eroded because of internal (religion and aristocratic rule) and external (expansion of Christianity and a long-standing Irano-Roman war) forces. Nevertheless, the supremacy of law continued, though often interpreted by and enforced in favor of the ruling classes. REFERENCES Anklesaria, B. T. (1949). Pahlavi Vendidad. Bombay: K. R. Cama Oriental Institute. Azargoshasb, F. (1988). The Gathas. Vancouver: Kankash Mobedan Irani. Bulsara, S. J. (1937). Matikan-e-Hazar Datastan. Bombay: K. R. Cama Oriental Institute. Cameron, J. G. (1948). Persepolis Treasury Tablets. Chicago: University of Chicago Press. Christensen, A. (1939). Sassanid Persia in Cambridge Ancient History. Vol. 12. New York: Macmillan. Irani, D. J. (1924). The Divine Songs of Zarathushtra. London: George, Allen and Unwin. Mehr, F. (1991). The Zoroastrian Tradition. Rockport, Mass.: Element. Olmstead, A. T. (1930). ‘‘Materials for an Economic History of the Ancient New East.’’ Journal of Economic and Business History, 2, 232–38. Olmstead, A. T. (1948). History of the Persian Empire. Chicago: University of Chicago Press. Rapp, A. (1878). The Religion and Customs of the Persians and Other Iranians. Bombay: K. R. Cama Oriental Institute. Sethna, T. R. (1978). The Teachings of Zarathushtra. Karachi: n.p. Stronach, D. (1978). Pasargadae. Oxford: Clarendon. Taraporewalla, I. (1951). The Divine Songs of Zarathushtra. Bombay: D. B. Taraporevala Sons. West, E. L. (1871). Mainyo-i-Khard. London: Trubner. 8 Social Justice in Ancient India: In Arthasastra ´¯ M. G. PRASAD INTRODUCTION The discussion of dharma, the basic theme of the Vedas, has influenced difficult to define ‘‘san ´¯ known as Chanakya or Visnugupta. This has been a pivotal work in understanding ancient India’s systems of administration, law, and justice against the back- 92 Articulation of Social Justice ground of sanatana dharma. The Arthasastra has also been highly regarded by ´¯ several modern eminent scholars as a major source of reference belonging to ancient India. It is said that Kautilya used the Arthasastra as a manual in show´¯ ing how to balance the two sides of life: the mundane (materialistic) and the transcendental (spiritual) (Rangapriya 1983, 2: 205–11). The relevance of the Vedas to the human life is in terms of the fourfold objectives of life: dharma, artha, kama, and moksha. The objective of dharma is to become aware and to learn how to choose between right and wrong. Then comes artha, which has as its objective the acquisition of wealth and the proper use of it. Kama concerns natural and rightful desires’ and moksha concerns the state of spiritual contentment and realization of the self. The above order of fourfold objectives is important, and dharma and moksha mark the boundaries within which artha and kama have to be fulfilled. The objective of acquisition of wealth in reference to the society ruled by monarchy is dealt with in the Arthasastra (Kangle 1992, 2: 1–5). ´¯ ANCIENT INDIA: MAURYAN EMPIRE The advent of the Mauryan empire is a unique event in the history of ancient India. With the coming of Chandragupta Maurya around 382 B.C., the Mauryan empire receives more definite chronology (Mahajan 1960). Men like Megasthenes and Daimachus lived at the Mauryan capital, Pataliputra. The Indika of Megasthenes describes the wealth and prosperity of the state. The description of government is also provided in some detail. It is also mentioned that Chandragupta Maurya is one of the greatest personalities of ancient India (Gokhale 1956: 4). It is said that Chandragupta Maurya was brought to power by the scholar and philosopher Kautilya, who later became Chandragupta’s minister. In the pre– Mauryan Nanda period, the scholar Kautilya went to then-King Dhanananda for recognition of scholarship, but Kautilya was insulted instead. Kautilya, stung by the insult, took a vow to dethrone Dhanananda and left the capital. On his way back home, he found young Chandragupta playing in the woods. Kautilya took Chandragupta along with him and trained him in the arts of war and government. Later, Chandragupta formed an army and, with the help of Kautilya, won the throne of Magadha by killing Dhanananda (Gokhale 1956: 34–35). Chandragupta was the first historical emperor of India. A brilliant description of the life of Chandragupta is given by Megasthenes (Gokhale 1956: 35–36). The emperor spent most of his time supervising the administration of his vast territory. As supreme judge he heard cases in the imperial court during the whole day without interruption. The palace was open to all, and the king kept himself informed on all subjects of interest to his people. Elaborate precautions were taken to guard the emperor. The posting of female guards was a prominent Social Justice in Ancient India 93 feature of the court life. He rarely slept during the daytime, and according to some accounts, the emperor never slept in the same bedroom two consecutive nights. The public appearances of the emperor were occasions of great pomp and splendor. The administration of the capital city was entrusted to thirty dignitaries who served on six boards. Each board had a specific charge: Board I looked after industrial arts; Board II attended the needs of the foreigners; Board III recorded vital statistics; Board IV took charge of trade and commerce; Board V supervised the selling of manufactured articles (new and old, separately) by public notice; and Board VI collected titles on sale (and any fraud in payment of this tax was punishable by death). These were the separate functions by which the boards discharged their responsibilities. In their collective capacity they had charge of matters affecting general public interest, such as keeping public buildings in proper repair, regulating prices, taking care of markets, harbors, and temples. Generally, the people in this period of the Mauryan empire enjoyed a high reputation of honesty, and cases of thefts were exceedingly few. It is not surprising that homes were left unguarded and that litigation was seldom resorted to. In addition, an efficient police and penal system contributed to a comparative absence of theft (Gokhale 1956: 38). The administration of the vast imperial state encountered complex problems of polity. These problems were courageously faced and wisely solved by Chandragupta with the help of his friend, guide, and philosopher Kautilya, who served as constant counselor. Kautilya is reputed to be the author of the Arthasastra, ´¯ the celebrated work on polity. The Mauryan administration, under the able leadership of Chandragupta and Kautilya, maintained a delicate balance between a centralization of power and a decentralization of authority over the various levels of a state bureaucratic machine. The empire was divided into provinces of the royal family. The provinces were further divided into districts, and the smallest unit of administration was the immemorial Indian village in the charge of a village headman who collected revenue and maintained law and order on behalf of the king. In order to maintain close contact between the king and his officers, on the one hand, and the king and the people, on the other, extensive use of reporters, agents, and spies was made. These observers and information agents operated all over the empire, closely watching the officers and keeping the king well informed about the people. This efficient and fair administration that brought justice and happiness to people is widely attributed to Kautilya who has laid out the science of polity in his manual Arthasastra. We will now take a close look at this work. ´¯ ´¯ ARTHASASTRA: SCIENCE OF POLITY At the end of his monumental treatise Arthasastra, Kautilya reflects on the ´¯ science of polity and on his reason for writing the treatise: 94 Articulation of Social Justice Thus this science (of polity), expounded with devices of science, has been composed for the acquisition and protection of this world and the next (15.1.71). This science brings into being and preserves spiritual good, material well being and pleasures and destroys spiritual evil, material loss and hatred (15.1.72). This science has been composed by him [refers to Kautilya], who in resentment, quickly regenerated the science and the weapon and the earth that was under the control of Nanda Kings (15.1.73) (Kangle 1992, 2: 516). Kautilya’s work deals with such diverse subjects as accounts, coinage, commerce, forests, armies, and navies. Kautilya also discusses the rules of administration, selection of ministers, principles of taxation, economic development of the country, and the maintenance of discipline in the army. Though Kautilya devotes a section of his work to republic states, he prefers monarchial government. He suggests that the state is established by the weak as a protection against the strong. The king should be vigilant about the wellbeing of his subjects. ‘‘In the happiness of the subjects lies the happiness of the king; in their welfare, his own welfare; his own pleasure is not good, but the pleasure of his subjects is his good’’ (Radhakrishnan and Moore 1973: 243). A strikingly original feature of the state administration in Kautilya’s work is its policy of promotion of public health. This involved a ban on unwholesome food and drink, a strict control over physicians in the interest of patients, as well as state provision for medical treatment of victims of diseases and epidemics. Another notable characteristic of the administration is illustrated by the measures for protecting the public against the dealings of artisans and tradespeople (Chopra 1973, 2: 113). Arthasastra is a manual of guidelines and laws for enforcement for kings and ´¯ administrators. The treatise is remarkable for its elaborate and detailed consideration of the diverse aspects of statecraft. It contains fifteen adhikaranas (or ‘‘books’’). The first five deal with the internal administration (or tantra) of the state, the next eight deal with foreign relations (or avapa) with neighboring states, while the last two are miscellaneous in subject matter. The topics dealt with in the fifteen books are: 1 Training for administrators 2. Activities of heads of departments 3. Judges 4. Suppression of criminals 5. Secret conduct 6. Circle of kings 7. Six measures of foreign policy 8. Calamities of state 9. Activity of a king about to attack 10. War Social Justice in Ancient India 11. Policy toward obligarchies 12. The weaker king 13. Means of taking a fort 14. Secret practices 15. Method of scientific analysis (regarding politics) 95 Regarding social justice, there are several statements to guide the king or administrators. Some of the statements from book 3 are as follows: A matter of dispute has four feet: law, transaction, custom and the royal edict. (Among them) the later one supersedes the earlier one (3.1.39). Of them, law is based on truth, a transaction, however on witnesses, customs on the commonly held view of men, while the command of kings is the royal edict (3.1.40) (Kangle 1992, 2: 195). In the following statement, Kautilya says of social justice: ‘‘For it is punishment alone that guards this world and the other, when it is evenly met by the King to his son and his enemy, according to the offense’’ (3.1.42). The following statements indicate the specificity and detailed nature of some of the laws: ‘‘A (widow) remarrying shall forfeit what was given by her (late) husband’’ (3.2.26). ‘‘She shall use it if desirous of a pious life’’ (3.2.27). Kautilya emphasizes environmental justice so that every one in society can share and enjoy nature. ‘‘They shall be fined who hurt animals and cut the shoots of trees in city parks that bear fruits or yield shade’’ (3.19.26–28) (Kangle: 1992, 2: 249). Kautilya recognizes that judges have a social obligation to promote justice in society: The judges themselves shall look into the affairs of gods, brahmins, ascetics, women, minors, old persons, sick persons, who are helpless. When these do not approach [the court], and they [judges] shall not discuss the suits under the pretext of place, time or [adverse] possession (3.20.22) (Kangle 1992, 2: 253). It is clearly seen from the above statement that social justice was a justice for all members of the society. The concluding statement of book 3 reinforces this. ‘‘In this way judges should look into affairs, without resorting to deceit, being impartial to all beings worthy, of trust and beloved of the people’’ (3.20.24) (Kangle 1992, 2: 253). In the activity of trading by merchants, Kautilya emphasizes honesty and justice. He also recommends a heavy fine for artisans and artists who conspire together to bring about a deterioration in the quality of work. He also recommends a heavy fine for traders, who by conspiring together, hold back wares or sell them at a high price. 96 Articulation of Social Justice Kautilya also addresses remedial measures to be taken during natural calamities such as famine, fire, and flooding. Kautilya says: During a famine, the King should make a store of seeds and food stuffs and show favor (to the subjects), or (institute) the building of forts or water works with the grant of food, or share his provisions with subjects or entrust the country (to another King) (4.3.17). He (King) should seek shelter with allies or cause reduction or shifting of population (4.3.18). He should migrate with the people to another region where crops have grown, or settle along the sea, lakes or tanks (4.3.19). He should make sowings of grains, vegetables, roots and fruits along the water works or hunt deer, beasts, birds, wild animals and fish (4.3.20) (Kangle 1992, 2: 263–64). These statements reveal a highly pragmatic approach grounded in meeting the needs of the people. In order to maintain social justice, Kautilya arranged a system of informants to learn of the misdeeds of village officers and heads of departments. In the following statements Kautilya says clearly: The administrator should station in the country secret agents appearing as holy ascetics, wandering monks, cart drivers, wandering minstrels, jugglers, tramps, fortune-tellers, soothsayers, astrologers, physicians, lunatics, dumb persons, deaf persons, idiots, blind persons, traders, artisans, artists, actors, brothel keepers, vintners, dealers of groceries such as bread, meat, etc. (4.4.3). They (secret agents) should find out the integrity or otherwise of village officers and heads of departments (4.4.4). And whomsoever among these he (administrator) suspects of deriving a secret income he should cause to be spied upon by a secret agent (4.4.5) (Kangle 1992, 2: 265). With such a large and empowered bureaucracy, there was a danger of conflict between the people and the administration. The network of secret agents and informants was meant to guard against possible unrest due to conflicts. Only some of the statements that are relevant to social justice in state administration have been mentioned here. The Arthasastra, however deals in an elab´¯ orate way with all the intricate details of administration. The philosophy and practice of social justice with peoples’ welfare as a primary goal is also emphasized in other works of ancient India. To site an example, the book Tirukkural (The Voice of Nobility) written by the celebrated author Tiruvallavar around 300 B.C. in the Tamil language provides a section on the results of an unjust government as follows (Drew and Lazarus 1991: 112–13): 1. More cruel than the man who lives the life of [a] murderer is the king who gives himself to oppress and act unjustly (towards his subjects). 2. The request, (for money) of him (king) who holds the sceptre, is like the word of him who stands with a weapon (at your chest) and says ‘‘give.’’ Social Justice in Ancient India 97 3. The country of the king will daily fall to ruin, who does not daily examine into and punish (crimes). 4. The king, without reflecting (on its evil consequences), perverts justice, will lose at once both his wealth and his subjects. 5. Will not the tears, shed by a people who cannot endure the oppression which they suffer (from their king), become a file to waste away his wealth? 6. Righteous government gives permanence to the fame of kings; without that their fame will have no endurance. 7. As is the world without rain, so live a people whose king is without kindness. 8. Property gives more sorrow than poverty, to those who live under the sceptre of a king without justice. 9. If the king acts contrary to justice, rain will become unseasonable, and the heavens will withhold their showers. 10. If the guardian (of the country) neglects to guard it, the produce of the cows will fall, and the men of six duties will forget their sacred book. CONCLUDING REMARKS It is recorded in historical texts that the Mauryan empire ruled by Chandragupta and his minister Kautilya produced one of the more successful societies in ancient India and in the ancient world at large. Although Kautilya’s Arthas´ astra goes into minute details as a manual, the theme of the manual (or hand¯ book) is clearly toward social justice in the sense of the importance given to people and their welfare (De Bary 1958). It is noted that the happiness of the people is described as the happiness of the king. The king’s welfare lies in that of the people. The king receives the revenue from the people as his fee for the service of protection. This ideal monarchy is achieved through an education of the king that emphasizes selfcontrol as a prerequisite for successful government. The king is required to get help from state officials and ministers and to seek their advice. The king’s behavior toward his people, particularly the afflicted, is like a father toward his son. Punishment is an important aspect because in the absence of punishment the strong person devours the weak; but with the king’s protection and social justice, the weak person prevails over the strong. Public interest is of prime importance and is the basis on which all rules are formulated. Punishment when directed with compassion unites the people through virtue, wealth, and satisfaction. It is emphasized that the king must have a balanced view of various aspects of society in order to ensure social justice. The king should therefore attend personally to gods or to ones learned in the Vedas, to sacred places, minors, the aged, the afflicted, the helpless, and women. Salaries had to be according to learning and service. The welfare of the people claimed the first place in all considerations of policy, and the dominating aim of government was the main- 98 Articulation of Social Justice tenance of law and order, the punishment of the wicked, and the protection of the good. Thus Kautilya through his Arthasastra has provided an integrated basis and ´¯ working guidelines and a procedure for a society to prosper in both material as well as spiritual aspects. According to Kautilya, material and spiritual well-being are provided by the fourfold knowledge, namely, philosophy, the Vedas, economics, and the science of politics. Kautilya also advises that philosophy can be thought of as the lamp of all sciences, the means for all actions, and the support of all laws and duties. REFERENCES The author thanks Mr. S. Sudarasanam, the Consul for Education and Culture at the Consulate General of India for his helpful discussions. Thanks are also due to Mrs. Gupta, librarian at the consulate; Professor J. Scow of the Department of Humanities at Stevens Institute of Technology (N.J.), and Professor Irani of the Department of Philosophy at the City College of New York. Chopra, P. N. (1973). The Gazetteer of India. Vol. 2, History and Culture. New Delhi: Gazetteers Unit, Government of India. De Bary, W. T. (1958). Sources of Indian Tradition. Vol. 1. New York: Columbia University Press. Drew, W. H., and J. Lazarus (trans.). (1991). Thirukkural. New Delhi: Asian Educational Services. Gokhale, B. G. (1956). Ancient India: History and Culture. Bombay: Asia Publishing House. Kangle, R. P. (trans.) (1992). The Kautilya Arthasastra. 3 vols. New Delhi: Motilal ´¯ Banarsidass. Mahajan, V. D. (1960). Ancient India. New Delhi: S. Chand. Radhakrishnan, S., and C. A. Moore. (1973). A Source Book in Indian Philosophy. Princeton: Princeton University Press. Rangapriya, Swami. (1983). Significance of Kautilya Artha Sastra in Amarayani. Vol. 2. Mysore, India: Astanga Yoga Vijnana Mandiram. Rapson, E. J. (ed.). (1955). The Cambridge History of India. Vol. 1, Ancient India. New Delhi: S. Chand. Part III The Practice of Social Justice in the Ancient World 9 The Ideological Basis for Social Justice/Responsibility in Ancient Egypt SCOTT N. MORSCHAUSER I The Egyptian word most often translated into English as ‘‘justice’’ is the term ‘‘ma at.’’ It is used in connection with the promulgation and execution of laws; the suppression of criminal activity; and the correction of official abuses. Ma at, however, also had a far wider application than reference to legal practices alone; but denotes the basic ‘‘ordering’’ of Egyptian life (Helck 1980: 1110–19). Ma at defined the divine ordinances by which the universe was originally set into motion and properly maintained, manifested in the rhythms of the natural world: the rising and the setting of the sun, the annual inundation of the Nile, the recurring seasons of planting and harvest. In the immanent realm, ma at fixed the parameters of Egyptian society itself, setting out the limits for the proper and discretionary exercise of power by those who ruled toward those over whom they had authority. As attested by the literature that has survived from ancient Egypt, ma at encompassed specific ethical requirements, characterized as both the official and personal responsibilities of the socially advantaged toward their inferiors, as well as the obligations of subjects toward the state—which was embodied in the figure of the king. The image or metaphor most frequently encountered in ancient Egyptian texts 102 The Practice of Social Justice to illustrate this concept of ‘‘order’’ and ‘‘harmony’’ is that of the ‘‘scale.’’ Political and social equilibrium was achieved when the actions and comportment of an individual—the king and private citizen—balanced out with what ma at demanded of them respectively. While social roles and expectations may have varied according to position, the concept of ma at, nevertheless, provided a moral standard, by which every member of society, king and commoner, could be evaluated and judged. Therefore, it would be erroneous to equate ma at, ‘‘justice’’—or as it is also translated, ‘‘the Truth’’—in ancient Egypt simply with the personal wishes and ideology of the king and his ruling elites;1 for ma at was linked not only to protological concepts, but also to eschatology. Ma at was the ultimate determinant of an individual’s ability to achieve a meaningful existence beyond death. II The monarch, as recipient of the office of kingship, and earthly representative of the gods, was required to uphold the ‘‘order’’ bequeathed to Egypt at the creation of the world, in a manner that was requisite with ‘‘divine law’’—or, perhaps better, ‘‘divine intention.’’2 This expectation is clearly expressed in a wisdom text of the late First Intermediate Period—early Middle Kingdom, purported to be addressed to the Herakleopolitan ruler, Merikare (Helck 1977: 80, 83–87): Make secure your position in the Afterlife by being righteous, by enacting justice (ma at), upon which human hearts rely . . . The deity who governs well mankind, the cattle of god—he has made heaven and earth for the sake of humanity; subduing the Watery Chaos, and making the breath— intending that their nostrils should live. (Human beings) are his images which have come forth from his limbs. He rises in the sky for their sake; and makes for them plants and cattle, fowl and fish, to feed them . . . He makes daylight for their sake, sailing about (the heavens) to keep watch over them. (God) has erected his shrine about them, and when they weep, He hears them. From the start, he made rulers for them; (namely) leaders to raise up the back of the weak. Indeed, the office of the king was fairly well defined in terms of its function; being summarized in a Middle Kingdom solar hymn as ‘‘Judging humanity and propitiating the gods; setting order (ma at) in place of disorder. The king is to give offerings to the gods, and mortuary offerings to the spirits of the dead (i.e. those who have been afforded a ritual burial)’’ (Assmann 1970: 17–22) The royal instruction to Merikare quoted above, contains similar observations, although it is expanded to include the protection of the land against foreign enemies: ‘‘Guard your borders, and build up your fortresses, troops are useful Social Justice/Responsibility in Ancient Egypt 103 to their lord. Make your endowments abundant for God. . . . Make ample the daily offerings. . . . God recognizes the one who acts for him’’ (Helck 1977: 37– 40). These brief passages, enumerating a monarch’s responsibilities toward both the divine and his subjects may be taken as normative. Similar sentiments are ubiquitous in the records of royal acta throughout the long history of ancient Egypt. Thus, the primary duties the ruler was to carry out may be classified as first, the upkeep and maintenance of the temples and their staffs4; and second, the ruler’s proper exercise of the legislative, executive, and judicial powers inherent in his office. It was the responsibility of the king to promulgate ma at, through royal decrees and edicts, which created new laws, and reformed existing legal stipulations. ‘‘Justice’’ and ‘‘order’’ were enforced by the efficient working of the court system, accomplished by the ruler’s assigning competent officials to judicatory positions. Royal judges themselves were adjured by their lord to execute their tasks with integrity and moderation (Sethe 1961: 1090):5 Do not judge unfairly, God abhors partiality; This is an instruction, plan to act in accordance with it: ‘‘Regard one you know, like one you don’t know; one near you, like one far from you. . . . Do not pass over a petitioner, before you have considered his speech.’’ ‘‘When a petitioner is about to petition you, don’t dismiss what he says, as already spoken. You may overrule him, but only after you let him hear the reason for your doing so.’’ Lo, it is said, ‘‘A petitioner wants his plea considered, rather than have his case adjudged.’’ This royal oration, given at the installation of the king’s prime minister or ‘‘vizier,’’ further cites the historical case of a judge who was reviled for his harshness (Sethe 1961: 1089): ‘‘Avoid what was said of the minister, Khety: ‘He denied his own people for the sake of others, out of fear of being falsely called [‘‘partial’’]. If one of them appealed a verdict, that he had intended to carry out, he (nevertheless) persisted in denying their appeal.’ But such actions are in excess of ma at!’’ Finally, the monarch himself was responsible and liable for pronouncing sentences in capital cases. It is significant that kings are occasionally depicted as reluctant to execute criminals. Indeed, monarchs who were not troubled by this responsibility could be suspected of acting unjustly. For example, the so-called Papyrus Westcar, a literary composition dating to about 1600 B.C., contains a portrayal of the Old Kingdom monarch, Khufu— best known for his building of the great pyramid at Giza. In the text, the king is told of a man named Djedi who is reputed to have the ability to restore to 104 The Practice of Social Justice life a person who had been decapitated. Anxious for a demonstration of such miraculous power, Khufu summons the wonder-worker to court. At Djedi’s arrival, the monarch confronts him (Sethe 1928: 30–31): ‘‘Is the rumor true that you are able to re-attach a head that has been severed (from its body)?’’ ‘‘Yes, I am able, my sovereign, my lord,’’ Djedi answered. Then the king said, ‘‘Have a prisoner who is in jail brought to me, and execute his sentence!’’ But Djedi said, ‘‘No, my sovereign, my lord—not to a human being! Behold it is forbidden to do such a thing to the precious cattle (of god)!’’ Although the account is a fiction, the attitude and belief expressed by Djedi to the king should be regarded as a widely held tenet of ancient Egyptian morality. Human beings, even criminals, were ultimately considered to be under the watchful eye of the divine (cf. above) or, as the text says, ‘‘the precious cattle (of god),’’ and were not to be killed on whim. Royal power was limited by divine injunction. Indeed, by the end of the New Kingdom, capital sentences increasingly are ascribed, not to the pharaoh, but to the gods: an obvious attempt to absolve the king from responsibility in another’s death (Morschauser 1991: 209–10). This defensive attitude is best illustrated by the Judicial Papyrus of Turin, a document dating to the twelfth century B.C.E. (Kitchen 1983: 350–60). Containing the transcript of a trial for the assassins of the pharaoh, Ramesses III, the historical introduction to the text is cast in the form of a royal apology. Ramesses III proclaims from the Netherworld that he has had nothing to do with the outcome of the proceedings of the earthly court (Kitchen 1983: 351):6 As for all that has been done, it is they (e.g. the conspirators and assassins) who have done it. May (the responsibility for) all they done fall upon their (own) heads, while I am innocent and exempted forever; while I am among the great kings who are before Amun-Re , King of the Gods, and before Osiris, Ruler of Eternity. Such a declaration reveals anxiety about wrongful involvement in the death of potentially innocent parties. The setting for such a declaration, significantly, is depicted as the tribunal of the gods (Totengericht), where Ramesses III himself is to be examined at the Last Judgment.7 Third, the king was to maintain the funerary system: granting ritual burials to members of the royal administration and ensuring the protection of cemeteries, mortuary shrines, and foundation endowments and wills against tomb robbery, desecration, and embezzlement.8 Fourth, the king was obliged to protect the citizenry and country from both internal and external threats—or to remain vigilant against enemies ‘‘foreign and domestic.’’ Social Justice/Responsibility in Ancient Egypt 105 This would involve the suppression of banditry within the Nile Valley itself and controlling the movements of nomadic groups along border areas. Inherent in this was the king’s legal role as ‘‘commander in chief,’’ and his ability to declare and prosecute war. Royal campaigns had to be legally justified and could not be initiated without the authorization of the divine; the king presented his declaration of war before an oracle. Combat eventually came to be regarded as a judicial ordeal—a referendum on the fitness of the ruler to lead the country and on the rightness of his cause (Morschauser 1985: 149–50).9 Thus, the monarch’s fulfillment of these four primary duties—satisfying the divine patrons of the land, governing the Nile Valley in accordance with the law, maintaining the integrity of the funerary system, and defending the country from invasion or unrest—determined whether the king was a ‘‘beneficent ruler,’’10 upholding ‘‘ma at’’ on behalf of the gods, or whether he had acted in a manner unworthy of his office, thereby threatening the very fabric of society.11 III Ma at, was not restricted solely to the king’s administrative duties but was operative within the lives and conduct of the entire citizenry of Egypt. The subjects of the king—who were divided into the royal elites, called the p at, and the general populace, known as the rekhyt (possibly ‘‘those who were enrolled in the tax-lists’’)—were above all, obliged to be obedient to their ‘‘lord.’’ Clearly, allegiance to the king was subsumed under the rubric of ‘‘ma at’’; and ‘‘obedience’’ was broadly interpreted to include paying taxes and laboring on behalf of the crown; the conscientious execution of appointed office; along with the public pledging of fealty—thereby promising by oath not to rebel against the sovereign.12 Such duties, described as ‘‘loving the king with one’s heart’’ (Sethe 1961: 260), along with the benefits for acting so, formed the basis of what might be termed a ‘‘social-contract’’ between the Egyptian monarch and all his subjects; and ma at was interpreted according to this de facto agreement. However, ma at entailed further responsibilities beyond blind ‘‘loyalty’’ to the king, though not surprisingly, it was this latter aspect that was emphasized in royal propaganda. Officials were expected to act in accordance with standards that were not simply of royal, but of divine origin; a distinction that is important, though often unappreciated. Obligations to a transcendant principle of ‘‘justice’’ were specifically expressed in Egyptian texts as demands for personal tolerance, forbearance, and mercy toward the disadvantaged. These ‘‘ethical’’ requirements of ma at are cast in both positive and negative forms. As affirmations, they express what one ‘‘ought to do’’ or what has been upheld and praised by the gods, and are transmitted from one generation to 106 The Practice of Social Justice another (i.e., ‘‘wisdom’’). They are also delineated negatively as excesses or improprieties from which one should refrain and that were universally condemned. The positive elaboration of ma at first appears in the Old Kingdom, in the socalled autobiographical tomb inscription (Edel 1944: 1–90). In these mortuary texts, the deceased enumerates his rectitude and fairness in dealing with his contemporaries and his competence in executing his office. The following is a typical example of the genre: I I I I I I I I I I I I have carried out justice for my lord; have satisfied him with what he loves. spoke truly; I did what was right; spoke fairly, and reported accurately. held onto what was opportune, so as to stand well with people. adjudicated between two, so as to content them both, rescued the weak from one stronger than he, as much as was in my power. gave bread to the hungry, clothing to the naked, water to the thirsty. brought the deceased who could not afford transportation to the cemetery; buried him who had no son. furnished transportation for him who lacked it. respected my father, and pleased my mother, rearing up their children. (Sethe 1935: 198–200) This basic list—upholding fairness in office, concern for those in need, familial devotion, and care for the deceased—is further expanded as time goes by to include such statements as, ‘‘I was one who was father to the orphan, and who gave aid to the widow’’ (Sethe 1928: 79); ‘‘I was friend to the lowly; welldisposed to the one who had nothing. I helped the hungry who had no goods, and was generous to those in misery’’ (Sethe 1928: 80–81); ‘‘Whoever was lost, I put back on the road; I rescued the one who was robbed’’ (Sethe 1928: 7). The negative corollary consists of pronouncements that an individual had refrained from engaging in criminal acts, from committing sacrilege, or from oppressing social inferiors. The most celebrated example of this type appears in the 125th chapter of the Book of the Dead, where the deceased declares his innocence before the Eschatological Court, for example, at the ‘‘Last Judgment.’’ It is striking that in the scenes that often accompany this text, the ‘‘heart’’ is placed in the pan of a balance scale and is ultimately weighed against ‘‘ma at’’ itself, which is represented as a feather (Silverman 1991: 51, n.32). Therefore, both thoughts and deeds of the deceased were adjudged as to whether they conformed to the divine standard of ma at/justice; which is partially specified as the following: I have not killed; I have not robbed; I have not coveted; I have not stolen; I have not committed sacrilege; I have not trespassed against sacred property; I have not committed Social Justice/Responsibility in Ancient Egypt 107 a ritual impurity; I have not committed adultery; I have not blasphemed; I have not robbed my fellow human-being; I have not slandered another; I have not added to the weight of the balance; I have not falsified the placement of the scales; I have not increased nor reduced the measure; I have not been neglectful of the proper offerings; I have not interfered with the actions of the god. (De Buck 1948: 116–22) Inasmuch as such statements appear consistently in tomb inscriptions and funerary stela over millenia and are also alluded to in legal stipulations, judicial documents, and wisdom-texts, one may refer to these tenets of ma at as being in a real sense, ‘‘canonical’’—precepts to which all segments of ancient Egyptian society were expected to adhere.13 Again, monarchs were especially adjured to be kindly disposed to the less fortunate of their subjects. In the Instruction to King Merikare, mentioned above, forbearance and toleration are specifically commended as part of ‘‘the laws’’ (hpw) or ‘‘customs of kingship’’: Execute justice (ma at), that you may endure on earth. Calm the weeper, and do not oppress the widow. Do not expel a man from his father’s property. Do not wrongfully remove an official from his office. Beware lest you punish wrongfully. Do not kill, for it is of no benefit to you. Punish (instead) with beatings and with imprisonment, for this land shall be well-founded under such actions. (Helck 1977: 27–28) Not unexpectedly, Egyptian rulers and their high officials are often addressed by the common ancient Near Eastern epithets, ‘‘defender of the orphan,’’ ‘‘husband to the widow,’’ ‘‘rescuer of the fearful,’’ and ‘‘savior of the distressed’’ (Kitchen 1979: 151). These titles aptly point to the special role that the king and his deputies were to assume in protecting those who had been improperly deprived of legal recourse. Indeed, the assumption of such a role defined the contents of ma at, as something other than simply the implementation of ‘‘order’’ by coersive means.14 IV Clearly, mercy, tolerance, and rectitude in office, formed the ‘‘ideal’’ basis of the ancient Egyptian ethos; yet one must ask how these demands were put into actual practice. Was there—apart from the evidence of laudatory statements and exhortations to demonstrate virtue from ‘‘literary’’ texts—any special preference exhibited by the king and royal elites for the ‘‘poor’’ in the course of administering their duties of office? Has there, in fact, survived any actual legislation that would support such an inference at all? These questions are difficult to answer as it pertains to surviving legal acta of the king. First, and important, the Egyptian terms often rendered in English 108 The Practice of Social Justice as the ‘‘poor’’ (nmh /nmh yw), are not equivalent to our modern definition of the . . word that primarily denotes ‘‘victims’’ of poverty. Indeed, the Egyptian word nmh , has predominantly legal and religious rather . than economic implications. The juridical usage of the term refers to private citizens who were not in the king’s employment and, therefore, who were outside of the machinery of the state. This sense of the word as denoting ‘‘private citizens’’ unaffiliated with the royal bureacracy is well attested in judicial documents where the so-called ‘‘poor’’ are described as owning land, property, slaves, and as gainfully employed (Kruchten 1981: 169).15 The religious connotation is clearly related, since it refers to individuals who were not formally associated with the temple cults (Morschauser 1985: 169). Understood in the general legal sense of nonroyal persons and not as the economically disadvantaged, there is ample evidence that such people were protected by the king from abuses by means of ‘‘law,’’ the most famous case being the ‘‘Decree of Horemheb’’ (Kruchten 1981: 28–192), in which the king—the last pharaoh of the eighteenth Dynasty—attempted to rectify abuses perpetrated by state officials against private citizens; that is, the so-called ‘‘poor.’’ Horemheb specifically condemns: (1) tax-collectors for robbing citizens of items intended for royal imposts; (2) the theft of cattle-hides from private estates by the soldiery, and (3) illegal detention and impressment of slaves and servants of private citizens for unauthorized business of the state (Kruchten 1981: 193– 201). This edict probably incorporates older stipulations in the body of the text and should not be seen as the result of Horemheb’s formulation alone (Kruchten 1981: 206–14). Thus, one may infer that the actions undertaken by the king represent a reaffirmation and continuation of earlier pharaonic policy towards that segment of the populace supposedly designated as ‘‘the poor.’’ In this regard, it should be noted that actual ‘‘legislative’’ material from ancient Egypt has come down to us primarily in the form of royal decrees, although the focus of such documents is more restricted than the stipulations attributed to Hormeheb. In fact, such edicts as have been preserved for us are often concerned with the king’s granting of exemptions and tenant rights to groups associated with religious estates; for example, their cultic and support staffs.16 Royal decrees of this type forbade the removal of any priest, artisan, or landed farmer for the king’s business. They were not to be used as cultivators on any other property of the state, nor were they to be press-ganged for building projects or military service. Exempted institutions and their personnel likewise, were not required to supply food or shelter for royal commissioners on official duty. While such stipulations are usually addressed to provincial and local officials in whose district the temple was located, there are also provisions that the general populace report any actual knowledge or rumor of an infraction against the institution and its staff to the royal courts (Morschauser 1991: 185–86). However, it is significant that letters of protest to the king and his courtiers have also survived, denouncing appointees of the state for blatant disregard of Social Justice/Responsibility in Ancient Egypt 109 an estate’s exempt status (Gardiner 1937: 123–24);17 and violations against protected property and personnel appear to have been widespread, and in some cases, tolerated. Nevertheless, despite an otherwise lack of primary legal documentation, it should be stressed that officials and individuals of wealth and influence were enjoined in wisdom texts to care for and exhibit ‘‘preferential’’ treatment to the disadvantaged, as the following admonitions from a late New Kingdom instruction demonstrate (see Lichtheim 1976: 155–56, 161): If you find a large debt against a private citizen: Make it into three parts; Forgive two, let one stand: You will find it a path of life. After sleep, when you wake in the morning, You will find it good news. Better is praise with the love of men, Than wealth in the store-house. Better is bread with a happy heart, Than wealth with vexation. Do not startle a widow when you find her in the fields, and then fail to be patient with her reply. Do not refuse your oil jar to a stranger. Double it before your companions. God prefers him who honors the one in need, To him who worships the wealthy. It should be pointed out that literature of this type—used to educate scribes and employees of the royal administration—is attested for millenia; and this fact suggests that such appeals on behalf of the needy, again, represented a widely held standard of morality, undoubtedly embodying the very requirements of ma at. Indeed, even with its shortcomings, as evidenced by the very need for ‘‘laws’’ to prevent and punish wrongdoing, ancient Egyptian society—its legal thought, religion, and political structures—was undergirded by the concept of ma at: a transcendental norm of justice and order bequeathed to them by the gods from the creation of the world. Inherent in this, was an overarching belief in individual responsibility: There could be no evasion of justice, either by king or commoner, since the entire cosmos was under divine ordinance and command. Whatever the historical failures of this system (though it worked fairly well for over two and a half millenia), and no matter how much the ruling authorities may have attempted to identify their personal wishes with ‘‘justice,’’ it was understood that ma at—the ultimate standard of righteousness—would prevail in the end.18 110 The Practice of Social Justice ‘‘Justice’’ itself, was thoroughly grounded in eschatology, in the concept of a ‘‘Last Judgment’’; and, therefore, Egyptian ethics and behavior were themselves regarded as penultimate in nature. Justification and vindication rested not in the successes wrought by power, but in the righteousness of a supreme deity, Re —the maker and protector of humankind, or ‘‘his precious cattle.’’ The principle of ma at, its formulation originating in the primordial utterance of God, proclaimed that the king and his officials were appointed as temporary herdsmen and shepherds of humanity. These privileged few were understood to have been granted divine permission to rule and maintain order. However, they were also given the responsibility to ensure that life in ancient Egypt was lived according to the blessings and intentions given to the cosmos and its inhabitants at Creation. NOTES 1. Egyptian historiographers recalled monarchs who ruled without divine authorization, nor in accordance with divine command (see generally Redford 1986: 269–75). 2. Morenz (1973: 117–20), however, calls ma at, ‘‘a basic value’’ that was ‘‘established by God,’’ and ‘‘commanded by his word,’’ but that was ‘‘not an explicit law.’’ 3. See also Baines 1991: 128. 4. See also Hornung 1971: 214–16. The relation of such actions to the principle of ma at is explicitly linked in official inscriptions, wherein rulers claim to have promulgated and upheld ‘‘order’’ through the construction and expansion of divine shrines and sanctuaries throughout Egypt. Benefactions to a cult were regarded as fostering the goodwill of the gods, not only toward the king, but by extension, toward the entire country. Conversely, the king’s failure to perpetuate this system could result in disaster. In Egyptian causality, divine displeasure could be manifested by defeat in war, by the outbreak of disease among the populace, or by low levels of the Nile, accompanied by famine— triggering social discord and strife—which were themselves blatant signs that ma at or ‘‘order’’ had been violated and disrupted (see Morschauser 1985: 148–49). 5. See also Lichtheim 1976: 23, and particularly, the monograph of van den Boorn 1988. 6. See the discussion of Lorton 1977: 29–30. 7. This is not to say that kings did not execute criminals (cf. the discussion of Willems 1990: 27–54). However, the fear of committing wrongful death was real and is attested as early as the Old Kingdom. See, for example, the inscription of the courtier Re -Wer (Sethe 1935: 232). There, the king accidently brushes his retainer, Re -Wer, with the scepter denoting ‘‘punishment.’’ The monarch immediately decrees, ‘‘It is well!’’— that is, Re -Wer was innocent of any crime. On the related question of amnesty and the pardoning of criminals (or innocent parties falsely accused or imprisoned), there are instances where the king or a royal official administers sdjf(3)-tr(yt), ‘‘the expunging/wiping away of sin/wrong.’’ The term— wrongfully called a ‘‘loyalty oath’’—is used for the pardoning of rebellious vassals following their defeat in battle, and their readmittance into the Pharaonic imperium; as well as for individuals charged with crimes (e.g., theft, embezzlement, treason). The latter usage is interesting since sdjf(3)-tr(yt) appears to be used in legal manuevering, whereby Social Justice/Responsibility in Ancient Egypt 111 the accused is ‘‘pardoned’’ so as to turn ‘‘state’s evidence.’’ Such a practice, however, seems to have been misused, and there are denunciations of officials for letting criminals free without proper punishment (see the discussion of Morschauser 1988: 93–103). References to ‘‘amnesties’’ from royal hymns of the Ramesside Period are difficult to evaluate as far as ‘‘general’’ policy is concerned. It is unclear if the supposed release of prisoners was a routine act of the king’s office (e.g., at his accession) or whether it represented a personal—and hence, isolated—act of largesse. Despite the large amount of inscriptional material available to us from Ramesside rulers, we are still unsure as to the historical context in which supposed grants of amnesty occurred. 8. See generally the monograph of Goedicke 1967; see also Lorton 1977: 6–12. 9. See Liverani (1990: 150–59) for a discussion of the ordeal of war in the ancient Near East. Curiously, we do have a number of tantalizing references in Ramesside texts, implying the possibility that pharaohs—negligent in their capacity as leaders in war— could be arraigned before a divine tribunal (perhaps an oracular setting?). Historically, there does seem to be at least two instances where such a procedure was instituted. Indeed, it is likely that Ramesses II was somehow implicated by the priesthood of Amun at Thebes for the pharaonic losses suffered at the Battle of Kadesh at the hands of the Hittites. Ramesses defends charges that he had been rejected by the god Amun on the battlefield, specifically citing as support the king’s fulfillment of a written ‘‘testament’’ that he had made with the deity, enumerating in detail all the building activities and donations he had given to the cult of Amun prior to the battle. Ramesses argued, in effect, that he had acted in accordance with ma at by enforcing his religious duties (see Morschauser 1985: 139–53, 206, n.578). The second case involves Ramesses II’s son and successor Merneptah. In his famous ‘‘Israel’’ stela, the king himself is depicted as appearing before the divine tribunal in Heliopolis, where he is questioned about foreigners who had trespassed and ravaged territory around Memphis. Although such a scene is often pronounced—and dismissed—as ‘‘stereotyped,’’ the text is clearly cast as an apology against charges of royal negligence; that is, Merneptah had not adequately protected Memphite territory and had failed to control foreign groups who had settled in the Nile-Delta (see Morschauser 1987: 501–6). 10. See the comments of Posener 1956: 32–33 and Spalinger 1982: 39–44 for the term nswt-mnh, ‘‘benevolent king.’’ ˘ 11. See Redford’s discussions (1984: 231, and 1986: 189–90) of the opprobrium attached to the reign of Akhnaten. 12. See Morschauser 1987: 411–37 for ‘‘loyalty oaths’’ in ancient Egypt. 13. For a partial list of ‘‘taboos’’ and restricted and condemned actions, see Morschauser 1991: 37–70, 265–66, n.4. Stipulations of threats and curses clearly represent societal norms. 14. Note especially Ramesses III’s apologetic (in Edgerton and Wilson 1936: 133– 34) regarding his assumption of the throne: ‘‘I have not tyrannized; I have not taken my office by bribery.’’ 15. See also Lorton 1983: 360. 16. See generally Goedicke 1967: 231–48; Edgerton 1947: 219–30; Theodorides 1975: ´ ` 1037–43. 17. See also Wente 1990: 74, 128, 131. Note, however, Ramesses II’s comment in the Battle of Kadesh (‘‘Literary Record’’) that he had ‘‘released’’ to his officers ‘‘their servants whom others [i.e., Ramesses’ predecessors] had impressed’’ (Morschauser 1985: 157–59). 112 The Practice of Social Justice 18. See Morschauser 1991: 267–68 for an ancient Egyptian ‘‘justification’’ for ‘‘curses and threats’’ and their relation to the concept of ma at. REFERENCES Assmann, J. (1970). ‘‘Der Konig als Sonnenpriester: Ein Kosmographischer Begleittext zur kultiscen Sonnenhymnik.’’ Abhandlungen des Deutschen Archaologischen Instituts, 7, 17–22. Baines, J. (1991). ‘‘Society, Morality, and Religious Practice.’’ In Shafer (ed.), Religion in Ancient Egypt, 123–200. Bjorkman, G. (1971). Kings at Karnak. Uppsala: Acta universitatis upsaliensis. ¨ De Buck, A. (ed.). (1948). Egyptian Reading Book. Vol. I, Exercises and Middle Egyptian Texts. Leyden: Nederlandsch Archaeologisch-Philologisch Institut. Edel, E. (1944). Untersuchungen zur Phraseologie der Agyptischen Inschriften des Alten Reiches, Mitteilungen des Deutschen Archaeologischen Instituts 13, Kairo. Edgerton, W. F. (1947). ‘‘The Nauri Decree of Seti I: A Translation and Analysis of the Legal Portion.’’ Journal of Near Eastern Studies, 6, 219–30. Edgerton, W. F., and J. Wilson. (1936). Historical Records of Ramesses III. Chicago: University of Chicago Press. Gardiner, A. (1937). Late Egyptian Miscellanies, (Bibliotheca Aegyptiaca 7). Bruxelles: Edition de la Foundation Egyptologique, Reine Elisabeth. Goedicke, H. (1967). Konigliche Dokumente aus dem Alten Reich. Wiesbaden: Harras¨ sowitz. Goedicke, H. (ed.). (1985). Perspectives on the Battle of Kadesh. Baltimore: Halgo. Helck, W. (1977). Die Lehre fur Konig Merikare. Wiesbaden: Harrassowitz. ¨ ¨ ¨ Helck, W. (1980). ‘‘Maat.’’ In Helck, Otto, and Westendorf, eds. Lexikon der Aegyptologie. Vol. 3, 1110–1119. ¨ Helck, W., E. Otto, and W. Westendorf, eds. (1972–). Lexikon der Aegyptologie. 7 vols. Wiesbaden: Harrassowitz. Hornung, E. (1971). Conceptions of God in Ancient Egypt: The One and the Many. Ithaca, N.Y.: Cornell University Press. Kitchen, K. (1979). Ramesside Inscriptions. Volume 2, Historical and Biographical. Oxford: Blackwell. Kitchen, K. (1983). Ramesside Inscriptions. Volume 5, Historical and Biographical. Oxford: Blackwell. Kruchten, J. M. (1981). Le Decret d’Horemheb: Traduction, commentaire, epigraphique, ´ ´ philologique et institutionnel. Bruxelles: Universite de Bruxelles. Lichtheim, M. (1976). Ancient Egyptian Literature. Volume 2: The New Kingdom. Berkeley: University of California Press. Liverani, M. (1990). Prestige and Interest: International Relations in the Near East, ca. 1600–1100 B.C. Pardova: Sargon SRL. Lorton, D. (1977). ‘‘The Treatment of Criminals in Ancient Egypt (Through the New Kingdom).’’ Journal of Economic and Social History of the Orient, 20, 1–64. Lorton, D. (1983). Review of Kruchten’s Le Decret d’Horemheb. Bibliotheca Orientalis, ´ 40, 359–68. Morenz, S. (1973). Egyptian Religion. Ithaca, N.Y.: Cornell University Press. Morschauser, S. (1985). ‘‘Observations on the Speeches of Ramesses II in the Literary Social Justice/Responsibility in Ancient Egypt 113 Record of the Battle of Kadesh.’’ In Goedicke (ed.), Perspectives on the Battle of Kadesh, 123–206. Morschauser, S. (1987). ‘‘Threat Formulae in Ancient Egypt.’’ Ph.D. diss., Johns Hopkins University, Baltimore. Morschauser, S. (1988). ‘‘The End of the Sdjf(3)-Tr(yt) ‘Oath’.’’ Journal of the American Research Center in Egypt, 25, 93–103. Morschauser, S. (1991). Threat-Formulae in Ancient Egypt: A Study of the History, Structure and Use of Threats and Curses in Ancient Egypt. Baltimore: Halgo. ´ Posener, G. (1956). Litterature et politique dans l’Egypte de la XIIe dynastie. Paris: H. ´ Champion-Bibliotheque de l’ecole des hautes etudes. ` ´ ´ Redford, D. (1984). Akhenaten: The Heretic King. Princeton: Princeton University Press. Redford, Donald. (1986). Pharaonic King-Lists, Annals and Day-Books: A Contribution to the Study of the Egyptian Sense of History. Missisauga, Ontario: BenBen Publications. Sethe, K. (1928). Aegyptische Lesestucke zum Gebrauch im akademischen Unterricht: Texte des Mittleren Reiches. 2nd ed. Leipzig: J. C. Hinrichs’sche Buchhandlung. Sethe, K. (1935). Urkunden des Alten Reiches (Urk. 1). Leipzig: n.p. Sethe, K. (1961). Urkunden der 18. Dynastie. 4. Berlin: Akademie-Verlag. Shafer, Byron E. (ed.). (1991). Religion in Ancient Egypt: Gods, Myths, and Personal Practice. Ithaca, N.Y.: Cornell University Press. Silverman, D. P. (1991). ‘‘Divinity and Deities in Ancient Egypt.’’ In Shafer (ed.), Religion in Ancient Egypt, 7–87. Spalinger, A. (1982). Aspects of the Military Documents of the Ancient Egyptians. New Haven: Yale University Press. Theodorides, A. (1975). ‘‘Dekret.’’ In Helck, Otto, and Westendorf (eds.), Lexikon der ´ ` ¨ Agyptologie, Vol. 1. 1037–43. van den Boorn, B. P. F. (1988). The Duties of the Vizier: Civil Administration in the Early New Kingdom. London: Kegan Paul International. Wente, E. (1990). Letters From Ancient Egypt. Ed. Edmund S. Meltzer. Atlanta, Ga.: Scholars Press. Willems, H. (1990). ‘‘Crime, Cult, and Capital Punishment (Mo’alla Inscription 8).’’ Journal of Egyptian Archaeology, 76, 27–54. 10 Social first sight far from the philosophy that led to modern welfare legislation. In many surats, the Koran forbids the believer to question social inequalities. It considers social differentiations as willed by Allah. One surat, for instance, states: ‘‘See how we have given preference one over the other, and verily the Hereafter will be greater in degrees and greater in preferment’’ (XVII:21); and ‘‘Covet not the thing in which Allah hath made some of you excel others. Unto men a fortune from that which they have earned and unto women a fortune from that which they have earned’’ (IV:32); and ‘‘Allah finds in the Koran elements of ‘‘social justice’’ in the form of 116 The Practice of Social Justice recommendations to the believers or even duties imposed on them. Thus, there are no less than sixty-nine instances concerning almsgiving and related matters. The Koran goes as far as to link these injunctions to the faith itself, as in the following surat: ‘‘Hast thou observed him who belieth religion? That is he who repelleth the orphan and urgeth not the feeding of the needy’’ (CVII:1–3). Regarding all the references to mutual assistance and help to the needy contained in the Koran and the Hadith (Sunna: tradition of the prophet), many Muslim writers conclude that an ‘‘elaborate system of social justice’’ existed in the early days of Islam. Notwithstanding the differences between the social precepts of the Koran and the modern concept of social justice, one can agree with these writers. Indeed, every society, past or present, has its own conception of justice. What the Koran and Muhammad brought to the Arabian peninsula was a new idea and new ways of taking care of the poor and the deprived (Rodinson 1966: 11). In this chapter, I will consider the problem only in the early times of the rise of Islam. For purposes of clarity, I will divide my remarks into two parts: (1) the precepts in the Koran and Hadith (Sunna) and (2) social justice in the community created by the Prophet in Medina and in the early years of Islam’s expansion. THE TEXTS According to history, Islam appeared in the early years of the seventh century in Arabia, an arid country that could not support a large population. The limited number of underground pools sustained only a few oases. People lived in nomadic tribes that fought one another in order to loot their respective small possessions. A few tribes had settled where water supplies permitted and had established cities like Mecca and Medina on caravan routes. The Ummayad branch of the Quraish tribe (to which belonged the Hashemite clan of the Prophet) ruled in Mecca. In contrast to the rich Ummayads, Muhammad’s family was very poor. His father had died before his birth, and his mother had died when he was six. Thus, since his infancy, he had understood what poverty and orphanage meant (Farrah 1968: 39). Moreover, in Mecca sharp differences separated the masses of poor from the rich minority. When his mission started, Muhammad’s preaching of monotheism and social reform went hand in hand. Actually, at the beginning, Muhammad was, in a way, calling for the reform of an unjust society, and his emphasis was indeed on the plight of the poor, the weak and the needy. Later, when Higra took place, Muhammad applied his social precepts in the ‘‘community of the believers’’ he set up in Medina (Umma). As one author puts it: ‘‘If he gained converts, it was due less to the threats of eternal fire than to the strong justice and equalitarian principles embedded in his message of sub- Social Justice in Early Islamic Society 117 mission to God. The promise of sharing with the ‘haves’ had a particular appeal to the ‘have-nots’ of Mecca. The aristocracy of Qureish did not hesitate to remind him: Why is it that thou art followed only by the most abject from our midst?’’ (Farrah 1968: 43). As already stated, the Revelations contained many references about solidarity among the believers and about the necessity of alleviating the lot of the poor. And more precisely the compulsory almsgiving called Zakat was considered as the third pillar of the religion, out of five (it came after the Shahada, or bearing witness that there is but one God and Muhammad is his envoy—and after the Salat or five daily prayers—and before the Sawm or Ramadan’s fasting and before the Hajj or pilgrimage to Mecca). A kind of ‘‘poor tax’’ or ‘‘poor due,’’ the Zakat literally means giving back to God a portion of his bounty as a means of expiation or purification of what the believer retains for himself. It is embodied in the following verse: ‘‘Establish worship and pay the poor-due and obey the messenger, that happily ye may find mercy’’ (XXIV:56). At the beginning Zakat was rendered as an act of faith, but quite rapidly, it became a legal tax. The Koran specifies: ‘‘The alms are only for the poor and the needy, and those who collect them, and those whose hearts are to be reconciled, and to free captives and debtors, and for the cause of Allah and the wayfarer; a duty imposed by Allah. Allah is Knower, Wise’’ (IX:60). Under the Prophet and the first four caliphs, the alms went to: (1) the poor and the needy; (2) officials who gathered the Zakat; (3) the recalcitrant Meccans whose hostility had to be bought off; (4) slaves to purchase their freedom; (5) individuals for paying back debts incurred as a consequence of acts of benevolence; (6) to the State for arming soldiers engaged in a holy war against infidels; (7) institutions dedicated in the way of Allah; and (8) the poor travelers. (It was sometimes used for other purposes, and later, under the Ummayad dynasty, became part of the general budget of the state.) In addition to Zakat, there were ‘‘voluntary’’ or ‘‘nonobligatory’’ contributions suggested by the scriptures under the name of sadaqua. Indeed, in many surats, the Koran summons men to be generous. And as the community of the believers grew larger, some scholars, basing their opinions on the Hadith, suggested that those who had superfluous possessions should voluntarily donate to the public treasury (Bait-al-Mal) (Nait-Belkacem 1978: 144). The precepts concerning social justice in the Koran and the Hadiths have prompted many apologists to write extensively on the subject. In their opinion, Islam’s welfare system is superior to what has been developed in the Western world. Thus Anwar Iqbal Qureishi, a Pakistani, writes: ‘‘The concept of social welfare covers every aspect of the ideal human society to which Islam points. In Islam ethics not merely inculcate the attitude of self-sacrifice and social cooperation, but also promotes virtues in the individual that make it possible for him to subordinate his own interest to the collective good. . . . The ethical code so prescribes the obligations towards members of one’s family, one’s neigh- 118 The Practice of Social Justice bours, one’s colleagues in trade and profession, the incapacitated, and the generally needy from orphans and widows down to the needy traveller and stranger’’ (Qureishi 1978: 62). In Qureishi’s view, the prohibition of usury by the Koran means that Islam is opposed to excessive wealth (72). Yet another apologist, Yusuf (1971), considers that Islam’s goal consists of the eradication of poverty. Yusuf concludes: ‘‘The concern for the satisfaction of the basic needs of every individual member of the society and for maintaining the standards of justice and equity in the development of economy is grounded in the moral conscience of man’’ (14). Another scholar (Shaikh 1970) affirms: ‘‘Islamic laws of inheritance make significant contributions to the construction of an equalitarian society (31). Here one should point out the inequalities that beset women in Muslim scriptures as well as in legal practice. Women were (and still are) treated as secondclass citizens. Moreover, human rights in the modern sense did not exist in Muslim societies. Maxim Rodinson (1966), a French scholar, sums up the Islamic ideal of social justice in the following way: ‘‘a State directed in accordance with the principles revealed by God, treating all believers as equal before Divine law, practicing within the Muslim community an advanced form of mutual aid, at the expense of the better-off and to the benefit of the poorer sort. This is the ideal that the reforming and revolutionary movements so numerous in Muslim history strove, again and again, to realize’’ (26). Even the apologists recognize that this ideal was rarely put into practice. One of them, Qureishi (1978), concedes that ‘‘the benevolent aspects (of the Koran) began to be dishonoured with the rise of kingships in the Muslim world’’(70). Another apologist, Nait-Belkacem (1978), writes: ‘‘The social justice which was the mark of Islamic civilization during its days of splendour remains as much in the letter as in the spirit, a far-off work, offering to those who wish to realize it, a vast field of theoretical moral codes and objectives yet to be attained’’ (136–37). In order to avoid the conclusion that the ideal of social justice was never put into practice, most authors locate a so-called ‘‘ideal period’’ during the few years of the Prophet’s rule in Medina and in the twenty-nine years between his death and the rise of the Ummayad dynasty. This was the period during which the companions of Muhammad, the first four caliphs (Abu Bakr, Umar, Uthman, Ali), directed public affairs. These twenty-nine years referred to as a kind of ‘‘golden age,’’ were, in fact, full of turmoil and unrest. Actually, after the twoyear term of Abu Bakr, the three other caliphs were assassinated. THE PRACTICE Muhammad preached in Mecca. But in Medina he assumed the role of head of state (or ruler of the community of believers). Those Muslims who had followed him in the Higra, contrary to Medina’s new converts, were poor, and the Social Justice in Early Islamic Society 119 Prophet had to cater to their needs. He established a public treasury (Bait-alMal) through which taxes were collected and, then, were used to pay pensions to the needy and cover other necessary expenses. This practice was more or less pursued by the first four caliphs after Muhammad’s death. Solidarity and help was extended to the non-Muslim as well. For instance, chronicles recount the story of Umar’s (the second caliph), inviting an old abandoned Jew to his home, giving him his own food and having the public treasury bestow on the Jew a pension until the end of his days. But as the Muslim community (Umma) increased in size with the Islamization of the whole peninsula, the normal sources of revenue proved insufficient. Rich people were exhorted to donate voluntarily to the Bait-al-Mal. In addition, the authorities resorted to public ownership. Thus, it is said, that the prophet sequestered a piece of land in Medina to serve as pasture for horses belonging to Muslims (Nait-Belkacem 1978: 145). For the same purpose, Umar put aside a piece of land at Rabdha. The proprietors complained to him. The second caliph replied: ‘‘All goods belong to Allah! People are the creatures of Allah! If I were not obliged to do certain things to remain in the path of God, I would not have sequestered a single span of land (Nait-Belkacem 1978: 145). Umar also refused to distribute among the Arab conquerors the regions gained in Mesopotamia and Syria, justifying his decision in the following manner: ‘‘If we were to divide these lands, nothing would remain for those who come after you. What would they say, these Muslims, when they saw the land already distributed, inherited and possessed? . . . What would be left of these lands for the orphans and widows of these countries?’’ (NaitBelkacem 1978: 196). Instead of dividing the lands, Umar and the two other caliphs after him preferred to establish a large number of small cultivators in village groups and to let them use the lands. According to some chronicles, there were no beggars in the community of believers (Umma) at the time of the Prophet and of the first four caliphs (NaitBelkacem 1978: 149). Not only did the public treasury (Bait-al-Mal) care for the poor, but the Prophet and the caliphs protected the workers and the orphans. According to the Hadith, the Prophet says: ‘‘He who willingly works and does not have shelter, must be given shelter. If he is single, then he must be given a wife. If he does not have a camel let him claim one.’’ In the Hadith, he adds: ‘‘He who leaves after his death dependants deprived of support or very young children, his affair is my concern. I become guardian.’’ It is not possible to verify the extent to which the prescriptions of the Koran, in the field of social justice, were really put into practice. The only thing that seems certain is that during those early days the growing Muslim society presented in general the features of an ethical society (Gibb 1962: 197). But things were to change quite rapidly after the Ummayads had proclaimed the hereditary caliphate. The Prophet himself and the first four caliphs were already in the habit of using the Bait-al-Mal for other purposes than mere social justice (Rodinson 1966: 38). After these caliphs, this became the general rule. 120 The Practice of Social Justice Moreover, with the conversion of the conquered people, many inequalities appeared: between Arabs and non-Arabs, between Muslims and non-Muslims, and, more generally between rich and poor. Very rapidly under the Ummayads, huge fortunes, both in land and in money, were constituted at the hands of a few privileged members of the society. At that time, society was divided into four classes. At the top were the ruling Arab Muslims. Next came the converted, or neo-Muslims. They were sort of second-class citizens, reduced to the position of ‘‘clients’’ (mawali)—a status they resented. The third class was made up of the members of tolerated sects—namely, the Jews, Christians, Sabians, and, in Iran, the Zoroastrians (Dhimmis), who were compelled to pay a special tax in return for Muslim protection. Although these sects enjoyed a wide measure of toleration, at times they were subjected to humiliating treatment (they had to dress in a special manner, were not allowed to ride horses, etc.). At the bottom of society were the slaves. Although appreciably ameliorating the condition of the slave, Islamic rulers still preserved the institution. In early Islamic society, slaves were recruited among prisoners of war, including women and children, unless ransomed, and were obtained by purchase or raiding. Nevertheless, the liberation of slaves was always looked upon as a good deed, entitling the master to a reward in the next world. When liberated, the slave enjoyed the status of a ‘‘client’’ (Hitti 1960: 231–37). Naturally, the Ummayads, who represented the aristocracy of the Quraish tribe and who ruled Mecca before Islam, were not as inclined toward social justice as were the first four caliphs. They used the Bait-al-Mal largely for purposes other than the care of the needy. Moreover, the Ummayads subjected the newly converted (mawali) to taxes other than the Zakat (except for a short period under Umar II, who was a devout Muslim and who ordered the application of Islamic rules as they existed at the time of the Prophet and the first four caliphs) (Hitti 1960: 218). Pressured by heavy taxation, many peasants flocked to the cities to enlist in the army and enjoy military privileges. But since this meant a loss for the public treasury, the authorities forced them to return to their villages and pay the same tribute as before conversion. Labor in the large estates (latifundia) was underpaid. Inequalities between those who had received landed properties and others who had not—in general, between rich and poor—grew steadily. It is obvious that such a situation would arouse protests, revolts, and conflicts— which, in turn, would nurture schisms (Kharijites, Shiites, etc.). This situation was so much against the aspirations of the masses that revolutionary movements shook almost regularly the Islamic world over the centuries (Rodinson 1966: 70–72). On top of that, Umar II imposed humiliating restrictions on Jews and Christians, excluding them from public offices and forbidding them to wear Muslim garb (Tritton 1930: 35). Discontent was growing in many circles, as caliphs and aristocrats estranged themselves from the community of believers. Opposition to their rule was developing throughout society. The ever-growing chasm between the poor and the rich aggravated social antagonisms in the cities as well Social Justice in Early Islamic Society 121 as in the countryside (Meuleau 1984: 606). Such antagonisms sometimes reached the level of ‘‘civil’’ wars, as was the case with black slaves in Mesopotamia in the early ninth century: These slaves were from Zanzibar and were subjected to very harsh treatment in the agricultural development of the region. Under their leader, who pretended to be a descendant of Ali, the son-in-law of the Prophet, they occupied Obolla, Abadan, and Ahwaz, where they established a kind of ‘‘communist’’ society. In 871 they even succeeded in raiding Basra. This terrible insurrection lasted for more than fifteen years. Finally, the black slaves were massacred (Wiet 1957: 90–91. Since the Ummayads grasped power there were many other instances of such turmoil and disorder in the history of Islam. But such unrest does not pertain only to the period under review, that is, the early times of Islam’s rule. The above-mentioned cases suffice to show that the practice of social justice rapidly fell short of the ideal of the Koran and even the Sunna. Broadly speaking, the principles and the prescriptions in these two sources represent Islamic society as a balanced community in which each individual forms a unity with his fellow citizens, based on fraternity, social solidarity, and equality of rights and duties. As Moloud Kassim Nait-Belkacem, a former minister of religious affairs of Algeria, puts it: ‘‘This society must work towards a common objective. Its activity must be organized under the aegis of a just arbitration which can assure work for everyone according to his capability and merit, and an equal chance to all. The wealth of the Umma (the Islamic community) must be evenly distributed to all members according to need, taking into account the solidarity which binds them’’ (Nait-Belkacem 1978: 137). In all societies, social justice goes hand in hand with a certain degree of economic justice. Although the Koran respects private property and private ownership and encourages trade, Muhammad established economic justice in the small community he set up in Medina. The first four caliphs tried to follow in his path. But very soon injustices and inequalities appeared (as indicated by social unrest and assassinations under Uthman, the third caliph, who was accused, among other things, of nepotism). Later, the situation deteriorated. For a short period at the beginning of the Abbassids (750), the new authorities tried to apply the prescriptions. But once again, the gap between rich and poor rapidly widened. Paradoxically, this happened in a period of incomparable affluence. Indeed, the eighth and ninth centuries were a period of very high prosperity that spanned well into the tenth century. Constantly growing trade, large agricultural output, and important ‘‘industrial’’ production contributed to an increasing enrichment of the entire Muslim world. Wealth accumulated rapidly in the hands of certain classes of society. Merchants and court aristocrats profited much more than other members of the community of believers. As a consequence, while the rich were getting richer, a deepening impoverishment struck the lower classes of society, in the cities as well as among the peasants (Lombard 1971: 165). Social protest movements sprung up everywhere 122 The Practice of Social Justice and gained momentum. They reached a peak in the tenth century in the ‘‘Qarmatian’’ movement, named after Hamdan Qarmat, an Iraqi peasant who claimed to have read in the stars that the Iranians were going to gain once again the upper hand over the Arabs. The movement stressed the importance of tolerance, equality, and social justice. It even had some ‘‘communistic’’ overtones in as much as some of its proponents advocated community of property—and even wives! The movement supported itself from a ‘‘common fund’’ created through voluntary contributions, which were rapidly transformed into obligatory taxes! The ‘‘Qarmatian’’ movement started as a more or less secret organization. It ended up grouping workers and artisans into guilds (sinf in Arabic), (Hitti 1960: 444–45). These innovations eventually reached Europe where, according to the well-known French orientalist Louis Massignon, they influenced the formation of guilds and the birth of Freemasonry (see Encyclopedia of Islam 1960). By the end of the ninth century and by the beginning of the tenth, the ‘‘Qarmatians’’ founded an independent state on the western shore of the Persian Gulf. From there, they conducted bloody raids into the caliph’s empire! They even occupied Oman and a part of southern Mesopotamia, cutting off the pilgrimage road. In the year 930, they seized Mecca and removed the Black stone, which they took with them. CONCLUSION In the Koran as well as in the traditions of the Prophet (Hadith or Sunna), one finds prescriptions that, put together, can be considered as a coherent system of social justice, especially with regard to the time (i.e., seventh century) at which they were promulgated. Moreover, both sources contain directives on economic justice, without which social justice would seem meaningless. Nevertheless, it is not possible to agree with some Muslim apologists who regard these prescriptions as comparable or even superior to social security and welfare systems in contemporary societies. As explained in the introduction of this chapter, today’s concept of social justice is based on a philosophy that emphasizes the individual and his or her basic freedoms and imposes a complete separation of religion (church) and state. Be that as it may, the Islamic social ideal lasted for only a very short period, referred to by Muslim scholars as a ‘‘golden age.’’ In the view of these scholars, this period covers the rule of Muhammad in Medina (622–632) and that of the first four caliphs (632–661). Afterward, with the exception of a few short periods, inequalities widened, and social justice fell far behind the ideals defined in the revelations. Today, according to Muslim scholars themselves, the situation has barely improved. Thus one scholar writes: Sadly we are forced to admit that our situation is much worse (than in Europe and America); we cannot even establish any comparison. Even in the richest of the Muslim Social Justice in Early Islamic Society 123 countries . . . we see the existence of the most atrocius poverty alongside the most scandalous opulence, together with all the tragedy inevitable in such a situation. In our community (of believers) it is no longer just a matter of the kind of cases which surprise journalists, as in Europe and America; there is a gulf, a bottomless chasm, between the social justice defined by Islam and the situation of Muslims to-day. (Nait-Belkacem 1978: 151) In conclusion, it is useful to quote another scholar, this time a Muslim cleric from King Abdul Aziz University in Mecca: ‘‘In this world which is called ‘Islamic World,’ you look and then you see a social reality which is not pleasing. Then you open your eyes and ascertain that there are social institutions which do not guarantee justice’’ (Nait-Belkacem 1978: 151). REFERENCES Brohi, A. K. (1978). Islam and Human Rights. In A. Gauhar (ed.), The Challenge of Islam. London: Islamic Council of Europe. Encyclopedia of Islam. (1960). Leiden: Brill. Farrah, C. (1968). Islam. New York: Barron’s Educational Services. Gibb, Hamilton A.R. (1962). Studies on the Civilization of Islam. Boston: Beacon. Hitti, P. K. (1960). History of the Arabs. London: Macmillan. Lombard, M. (1971). L’Islam dans sa premiere grandeur. Paris: Flammarion. Meuleau, M., and L. Pietre. (1984). Le monde et son histoire. Vol. 1. Paris: Robert Laffort. Nait-Belkacem, M. K. (1978). The Concept of Social Justice in Islam. In A. Gauhar (ed.), The Challenge of Islam. London: Islamic Council of Europe. Qureishi, A. I. (1978). The Economic and Social System of Islam. Lahore: Islamic Book Service. Rodinson, M. (1974). Islam and Capitalism. London: Penguin. Shaikh, M. A. (1970). Social Justice in Islam. Lahore: Institute of Islamic Culture. Tritton, A. S. (1930). The Caliphs and Their Non-Muslim Subjects. Oxford: Oxford University Press. Wiet, G. (1957). L’Islam. In R. Grousset and E. G. Leonard (eds.), Histoire universelle. Vol. 2. Paris: Gallimard. Yusuf, S. M. (1971). Economic Justice in Islam. Lahore: St. Mahmoud Ashraf. 11 The Idea of Social Justice in Ancient China THOMAS H. C. LEE JUSTICE AS A PROBLEMATIC Introduction: Justice as Morality One of the most important characteristics of Chinese social philosophy is its conspicuous lack of one word that we can readily translate as ‘‘justice.’’ On the other hand, might it not also be true that the entire Chinese philosophical tradition, distinctly marked by ‘‘this worldliness’’ and by an overriding concern about social order or good society, is fundamentally a perennial search for what we may call ‘‘social definition of social justice. Any careful reading of the ancient texts and reports of recent archaeological findings will nevertheless show that the rise of a ‘‘. 126 The Practice of Social Justice Political Authority as the Center of Discourse Early Chinese cities were distinctly characterized by a relative lack of social tension and underdevelopment of social stratification. David Keightley suggests that such characteristics, implying a somewhat nonpluralistic nature of culture and an optimist inclination in the Chinese worldview, perhaps reflected a favorable natural environment or climate in neolithic times that accompanied the development of early Chinese agricultural settlement and life (Keightley 1991: 48–49). By the time of state building in the late Shang times (later second millennium B.C.)1 certain Chinese ‘‘optimistic’’ views about man being capable of handling his own affairs had been well developed, perhaps as a result of the favorable natural conditions. The self-assurance is not immediately clear from archaeological evidence. But the fact seems to be clear that within cities, or, later, ‘‘citystates,’’ tension between the many and the few, or the demarcation between the wealthy and the poor, were not acute; the state seemed to be more concerned with how to possess as much labor as possible in the sense of good management (Keightley 1991: 49). Social control and social organization (often kinship organization writ large) were thus more important to the ruling group (class) than fighting nature for wealth or the accumulation of wealth per se. Power/authority and its proper use took precedence over the amassing of wealth. The doyen of ancient Chinese history, K. C. Chang, would have this to say: ‘‘in ancient China, wealth was procured primarily through political power and was, as well, a necessary condition for the acquisition and maintenance of that power. Rulers could wield political power only by first establishing political authority’’ (Chang 1983: 124). One does not wish to deny that in the process of state-formation and in consolidating its rule over other contending city-states, control of resources was also an important factor (Chang 1983: 107–20). But even more important, the exercise of authority or institutionalized violence was almost always accompanied by the manipulation of ‘‘communication with gods’’ and the control of ‘‘arts’’ and skill of ‘‘writing.’’ The intimate relation between such skills that carried religious overtones (especially rituals or shamanist ‘‘communications’’2), and the political authority, demonstrated the importance of political control. Thus, rituals in general, and ancestor worship in particular, were constructed on the need to relate the transcendental (or, better, the numinous) to the human and were performed in the context of consolidating political power. It is no wonder that ancestor worship has commonly been characterized as sociopolitical in nature (Schwartz 1985: 20–27; Keightley 1991: 29–33). The centrality of sociopolitical philosophy thus is even reflected in early Chinese approaches to religion. The importance of political power, therefore, has to be taken into consideration in any discussion of the ancient Chinese idea of social justice. Social Justice in Ancient China 127 The Sacred, the Transcendental, and the Foundation of Law Before entering a more detailed analysis of ancient Chinese ideas of social justice, one may wish to consider, briefly, how the transcendental or, at least, the numinous sphere actually affected Chinese articulations of moral issues. Clearly, the idea of some personal god and afterlife was there. Most scholars, however, agree that there was a distinct lack of interest in or imagination about how the divine operated in this world. What Fingarette has to say about Confucian thought is generally applicable to other contemporary schools of thought: ‘‘The this-worldly, practical humanism of the Analects is further deepened by the teaching that the moral and spiritual achievements of man do not depend on tricks or luck or on esoteric spells or on any purely external agency’’ (Fingarette 1972: 3). The prominent place of ‘‘ritual’’ (lia as a secular virtue comprising all the essential teachings of the great philosopher shows how the ‘‘secularized’’ Confucian age reflected a residual attachment to something divine. But rituals were meant to be rituals,3 and beginning with Confucius, there arose a determined effort to be concerned only with what Fingarette calls ‘‘the stuff one has to begin with’’ (Fingarette 1972: 3). The combination of a premium on the ritualistic symbolism and an overriding stress on the sociopolitical had grave consequences: The ruling authority became increasingly interested only in social order and social control, even if it continued to believe that, in order to succeed, the rituals had to be meticulously enacted. The discussion on the proper exercise of authority to maintain a ‘‘just’’ society dwelled on the much humanized rituals as such and, thus, took precedence over: (1) the definition or analysis of the foundation, especially a transcendental one, of what must be understood as ‘‘justice’’ as such, and, (2) the articulation from the individual’s angle of his own right or justified sense of need. In other words, there was no real interest in whether ‘‘justice’’ was autonomous and dependent on a suprahuman order or the transcendental. The ancient Chinese was content that there was a ‘‘no-speaking’’ (Confucius, Analects xvii: 19; Waley 1938: 214) supernatural being or, more specifically, the Way of Heaven (t’ien-tao), which somehow guaranteed the functioning of nature.4 They, however, stopped short of seeking to define the nature and scope of power of this ‘‘being.’’ Such efforts would be quite counterproductive. As long as rituals were observed, then social order and harmony could be achieved. It was the rituals that actually became the center of Chinese social philosophy, taking up, on the theoretical level, the function of justice. Confucian Attitude toward the Origin and Role of Law This is a place to pause and ponder how ancient Chinese attitudes toward law were like. And this actually brings us to Confucius whose ideas about this matter are important. First of all, Confucius’ articulation of the rituals deserves a greater 128 The Practice of Social Justice attention than what was just provided. I shall now discuss it within the context of his distrust of law, especially coded law, as such. In his succinct discussions on the ancient Chinese theories of the origin of law (fa, hsing, and lu), Derk Bodde (1981: 176) cites an interesting story from ¨ The Book of History (Shang-shu). This story deserves quotation here: The people of the [barbarian] Miao refused to adopt moral government; instead, they promulgated penal laws (hsing), comprising of five penalties and called them law. They used these penalties to kill innocent people. The administration of such penal laws was severe and no one could avoid being applied with them. The people, however, became deceitful. Confusion also followed, and no one was faithful. What was agreed on was often overturned later. The employment of penalty was threatening, and people therefore appealed to the Lord on High about their innocence. The High God (Shang-ti) was watching over the people, and noticed that the sacrifices no longer carried the fragrance of good virtue, but was full of ill smell because of penalties. The Splendid God (huangti) had pity over the innocence of the common people, and therefore exercised His power by killing all the Miao people, so that they had no descendants.5 The mythical account serves as an excellent reminder that Confucian intellectuals held law in great suspicion. The failure of sacrificial rituals to produce the ‘‘fragrance of virtue’’ is in perfect accord with the Confucian stress on rituals, against the use of, particularly, the coded law. Confucius’ objection to the promulgation of law by Tzu-ch’an (d. 522 B.C.) is famous (Bodde 1981: 177–78; Schwartz 1985: 326–29). For him, working to introduce a moral justification for social stratification and to give meaning to rituals, promulgation of written law would undermine his teaching that the ruling class, composed of morally superior people, could serve as the moral vanguard of commoners.6 Confucian stress on the moral significance of humanity (jen) as a part of the Confucian agenda for social life as a grand ritual, however, did not lead the Confucianists to refute the idea that legitimate penal law was necessary in human society (Schwartz 1985: 307).7 The great difference between Confucian and nonConfucian (especially the Legalist) perceptions of law lay precisely in the implication of law for moral behavior, which in Confucian thinking could only be achieved through knowledge and the performance of the rituals. To summarize Confucius’ attitude toward law and rituals, I must point out the two aspects of his optimistic view about social order. First, Confucius must have shared the view that the law was for commoners only, whereas the rituals were appropriately meant for the ‘‘ruling class,’’ morally defined.8 Confucius also took the view that the morally upright officials (the ideal and moral gentlemen—chun-tzu) could influence the common people to act morally. Obvi¨ ously, Confucius was quite optimistic about how the ethical conduct of the ruling class could bring about adequate moral influence to fashion an ideal society. The optimism is uniquely interesting. What Thomas Metzger calls the ‘‘epistemological optimism’’ can be applied to the ancient Chinese approach to the foundation of justice (or ‘‘justification of justice’’) (Metzger 1985–87: 66). The Confucian lack of interest in finding the ‘‘law behind positive law’’ reflected a fundamental optimistic view about nature and society. Social Justice in Ancient China 129 In short, the Confucian attitude was representative of the main trend of thinking about the role of law in creating a satisfactory society. The distrust was paradoxically founded on an optimistic view about how moral persuasion could be relied on for the creation of a moral world order. Naturally, one must ask whether this optimism, simple-minded as it was, will indeed prevent us from discovering any coherent thinking among ancient Chinese thinkers on why justice was possible. Also, we shall see that the optimism was taken over and consolidated into an important Mencian notion of the basic goodness of human nature. Mencian Morality and the Idea of Righteousness Mencius is the first person to address the issue of the foundation of justice or how man was capable of goodness. To me, his articulations of the idea of yi (righteousness) is most original and demonstrates a keen awareness of the complexity of problems related to justice in general and of the right relationship between an individual and his social environment in particular. To understand his concerns, one has to begin with an examination into the then-widespread notion that doing good was ‘‘profitable’’ (li). There is evidence that this was a popular notion among many ancient Chinese rulers, and was perhaps somewhat condoned by Confucius himself (Huang 1991: 144). In his important study of the issue, Huang Chun-chieh points out that it was widely held that the ruling ¨ authority chose to act morally because it was ‘‘appropriate’’ (yia),9 and, believably, would result in a good government. Thus, the whole justification (or at least ‘‘purpose’’) of moral government was utility or profit. Confucius’ many utterances attest to this argument. It is true that ‘‘utilitarianism’’ has been exclusively used to interpret the Mohist school of thinking, which is generally accepted as an intellectual reaction against Confucian philosophy of morality. However, one may ask if ‘‘utilitarianism’’ could not be used to explain the Confucian position in terms of an ultimate belief in the usefulness of morality in the construction of a just society. The use of ‘‘utilitarian’’ here is deliberate, because ‘‘utilitarianism’’ occupies an important position in any serious study of the concept of ‘‘justice.’’ My intention of introducing it here is to highlight the paradoxical position that Confucius adopted regarding the purpose of morality in the context of creating a just society, a dilemma that Mencius would soon have to work on. While Confucius maintained a residual belief in a supernatural force—or even supernatural being—his interest was only in the numinous, the ‘‘holy,’’ and this is why he talked little about god, or even tao, and was evidently uninterested in its nature and content. In this way, Confucian moral teachings were actually predicated on the conception of an autonomous moral man. When this is compared with the Kantian notion of ‘‘autonomous will,’’ one sees that both almost were speaking of the same thing. What for Kant was ‘‘the source of all moral laws and of the corresponding duties’’ (Copleston 1964: 121) was man’s autonomous will; similarly, within the context of Confucian agnosticism, man’s de- 130 The Practice of Social Justice termination, strengthened by ritualistic performance, was really the very source of moral behavior and the resultant just action. The problem is that Confucius did not follow through on his notion that autonomous man and his moral imperative, accompanied by the corresponding duty, could enable man to discover universal moral principles. Confucius did not see much use in further exploring the feasibility of man’s moral absoluteness or rationality. Instead, he shifted to grounding man’s ability for moral action on the utilitarian purpose of morality. Thus, a middle ground was struck to accommodate a somewhat ambivalent attitude toward the motivation (or origin) and purpose of morality or justice. Confucius’ ambivalence in his moral philosophy regarding the issue of moral absoluteness and of a pragmatic or utilitarian purpose of morality could not satisfy Mencius. Mencius cared more about the moral man as an individual. The well-known parable used by Mencius to illustrate how man was endowed with a commiserating mind and, therefore, was by nature good is well known (Mencius II, a, 6; Lau 1970: 82; Schwartz 1985: 167–68).10 His notion of the ‘‘four sprouts’’ (ssu-tuan, also translated into ‘‘four germs’’ or ‘‘four potentials’’; Mencius II, a, 6; Lau 1970: 82–83) helps to explain how man’s good nature could develop by and large without institutional sanction.11 Mencius’ articulation of this matter can be understood as his answer to Confucius’ ambivalence toward the source of morality. In Mencius, we are provided with an explanation of how man’s good potentials could serve as the foundation of morality. Compared with Confucius, Mencius was metaphysically more sophisticated. Mencius pressed further for abandoning the utilitarian purpose of moral obligation. He systematically contrasted the idea of ‘‘righteousness’ (yi) with that of ‘‘profit’’(li). The chapter on ‘‘debates between righteousness and profit’’ begins the Book of Mencius and is central to the Mencian philosophy. This brought an end to the widespread utilitarian approach to political thinking that even Confucius had earlier implicitly condoned (Hsiao 1979: 154–55).12 The conception of ‘‘righteousness’’ is often placed in the context of the Confucian discourse on jen (humanity). Huang Chun-chieh has analyzed it splen¨ didly by referring it to the notions of ‘‘individual duties versus social obligations’’ and ‘‘the purpose of morality’’: The inevitable tension or conflict that must arise in between an individual’s own sense of morality and the obligations the society imposes on the individual concerned Mencius. This is one area of moral philosophy that Confucius did not articulate systematically. For Mencius, external or institutional factors that could affect the individual’s practice of moral responsibility created some kind of existential tension for the individual.13 The ability or determination to make the rightful or just choice is ‘‘righteousness.’’ To be righteous was to be able to come to a rightful judgment about how to resolve or how not to resolve the conflict.14 Mencius is uncompromising when it comes to the purpose of morality. Whereas Confucius occasionally seems willing to compromise—and, therefore, appeared to be ambivalent, for example, about hereditary rights versus merito- Social Justice in Ancient China 131 cratic principle—Mencius was never unclear about the priority of the moral criterion (Hsiao 1979: 119–20, 165–66, 170–77). Such determination required a steadfast confidence in moral absoluteness. The Mencian position about why morality or justice was necessary and how it could be founded on man’s ‘‘good nature’’ (or moral potential) has dominated Chinese thinking on the issue. Because Mencius was traditionally accepted as the orthodox successor to Confucius, the slight difference between the two in the articulation of the foundation of justice has often been neglected.15 In all, Mencius paid greater attention than Confucius to the motivation of morality and sought to situate it on a universally accepted ground (Hsiao 1979: 155). In Western thinking, the idea of ‘‘natural law’’ has been closely related to the discussion of justice and morality. Is it possible to argue that the Mencian conviction of a universal foundation of justice was similar to the ‘‘natural law’’ notion? It is worthwhile to refer to Joseph Needham who has pointed out that ‘‘natural law’’ as a conception in jurisprudence somehow existed in Chinese intellectual tradition (Needham 1956: 518–83), even though it did not develop into ‘‘laws of nature’’ in the Western sense. Other scholars have furthered his argument by pointing out that in the idea of justice there indeed was a ‘‘natural law’’ tradition in China (Bodde 1979; Creel 1970: 163–64).16 Between Dependence and Independence Although Mencius’ idea about morality and his somewhat individualist concern remained in the mainstream of Chinese thought, his ‘‘commiserating mind’’ has been understood more as an idea in political philosophy than a metaphysical notion. The injustice done to this metaphysical idea reflects how Mencius really was an exception, especially within the Confucian tradition. His most important intellectual opponent or, better, compatriot, was Hsun-tzu (fl. 298–238 B.C.). ¨ Hsun-tzu also sought to give an interpretation of man’s capability of goodness: ¨ He begins with the moral inadequacy of man (who, according to him, is born evil). He then returned to the notion of rituals and secularized it by arguing that rituals were moral social and environmental influences. It is here that rituals were concretely understood as education (Schwartz 1985: 318). Education was important, and the use of external influences was often well intended (optimism again); the lia thus remained a positive notion for individual moral upbringing.17 Moreover, Hsun-tzu refrained from attributing any moral power to supernatural ¨ ‘‘heaven’’ and thus sharpened Mencius’ thinking by furthering the idea of ‘‘natural law,’’ however unclear and merely suggestive it was. The meaning and content of ‘‘natural law’’ remained little explored in the Chinese intellectual tradition. Before we turn to the practical aspect of ancient Chinese ideas of social justice, it is necessary to include a brief discussion of Mo-tzu’s views of a just society. Mo-tzu took a very utilitarian approach and made serious attempts to provide a foundation for social justice. The efforts by him and his followers are interesting mainly as a response to Confucius’ somewhat accommodating ap- 132 The Practice of Social Justice proach to social hierarchy and hereditary privilege and his ambivalence about the realm of the transcendental. Mo-tzu argued for a religious foundation on which moral government, or a just social order, could be built. He was determined that hereditary rights should be abolished in favor of an equal social meritocracy. He preached that justice was necessary because this was a profitable thing to do. Further, Mo-tzu placed a great emphasis on the almost egalitarian application of moral action toward the world.18 For him, this ‘‘universal love’’ would benefit the greatest number of people—society at large. It is no wonder that Mohist philosophy is characterized as utilitarian. But this stock of utilitarianism is theistic. It is quite interesting to observe how Mo-tzu approached the issue of a just society by combining the idea of the transcendental19 and the idea of the profitability of moral goodness. The transcendental authority could be invoked to assist the moral man to complete what would be the most profitable thing to do. Thus, Mo-tzu’s utilitarianism was different from the utilitarianism in British empiricist moral philosophy, which largely gives up on the notion of the transcendental. The Mohist approach is interesting. First, it was a reaction against the notion of man’s moral autonomy, as held by the Confucianists; and, second, it was a failed attempt to strike a middle ground between the dependent and independent approaches to justice, as we see in the history of Western approaches to justice (Forkosch 1968: 652–59). SOCIAL JUSTICE Discussions on social philosophy or social justice in ancient China often centered on the just or moral exercise of political authority. The premise was that the ruling class should act morally and that the commoners (the ruled) would then follow. A just society must satisfy the moral and material needs of the common people. The great irony, thus, is that there was a distinct lack of interest in approaching ‘‘social justice’’ from the viewpoint of the poor or the oppressed, even if the entire philosophy could be characterized as an exposition on how to pass out justice to the impoverished or the oppressed. Equitable Distribution Following the above discussion on the political aspect of social control in Chinese thinking about a ‘‘just’’ society, one immediately sees that the idea of distribution must have been an important concern. One may also ask how the Aristotelian conception of ‘‘distributive justice’’ would fare in the Chinese context. First, both Confucius and Mencius shared the idea of ‘‘equitable distribution’’ (Hsiao 1979: 154).20 Social hierarchy was an accepted norm and reality, but the gentlemen should play the role of moral vanguards. The first duty of the government was to ‘‘enrich the people,’’ and then to distribute or manage the provision equitably. The emphasis, thus, was on how to govern, and the corollary was the equitable distribution of material goods (Hsiao 1979: 110–11). ‘‘He is Social Justice in Ancient China 133 not concerned lest his people should be poor, but only lest what they have should be ill-apportioned,’’ said Confucius (Analects, xvi: 8; Waley 1938: 203). The emphasis on distribution is also evident in Mencius. The first part of the chapter ‘‘T’eng-Wen kung’’ of Mencius touches on the social aspects of what Mencius defines as ‘‘politics of humanity’’ ( jen-cheng). One paragraph is cited here to give a general flavor: Humane government must begin with land demarcation. When boundaries are not properly drawn, the division of the land according to the well-field system and the yield of grain used for paying officials will not be equal. For this reason, despotic rulers and corrupt officials always neglect the boundaries. Once the boundaries are correctly fixed, there will be no difficulty in settling the distribution of land and the determination of emolument (Mencius III, a, 1; Lau 1970: 99, with modification). The fair distribution is for both Confucius and Mencius a condition of general prosperity. Mencius is even more emphatic on how to increase the wealth of the people.21 The concern for equal distribution received less attention by Mo-tzu. Nonetheless, as characterized by Benjamin Schwartz, this idea nonetheless was taken for granted in Mo-tzu’s studies on material goods and their purpose, and for Mo-tzu, ‘‘the problem is thus not that of the ‘growth of the forces of production’ but the task of distribution’’ (Schwartz 1985: 156). The idea of equal distribution received a greater and more systematic treatment in Hsun-tzu. ‘‘It is the lord of men who is the essential agency for con¨ trolling the allotments and assignments ( fen) [in society],’’ said Hsun-tzu ¨ (Hsun-tzu, 10 (Fu-kuo); Hsun K’uang 1965: 4; Knoblock 1988: II, 123 with ¨ ¨ modification). Continuing the Confucian emphasis on enriching the people, Hsun-tzu placed the notion in a more realistic context of how this could actually ¨ be carried out (Hsiao 1979: 186–88, 192). The idea of fen probably best approximates the idea of ‘‘equity’’ (Knoblock 1988: I, 251). Hsun-tzu’s analysis ¨ has influenced many philosophers after him. The Book of Kuan-tzu is a good example: Kuan-tzu’s definition of righteousness (yi) is reflective of what is said of Hsun-tzu: ‘‘righteousness is each getting what is [inherently] appropriate’’ ¨ (Kuan-tzu, 36 (Hsin-shu); Kuan Chung, 1966: 221). Such a definition of the idea of yi is almost Aristotelian and serves to explain why justice as a term was translated into ‘‘cheng-i’’ (lit., ‘‘correct and righteous,’’ or ‘‘correct righteousness’’) when it was first introduced into the Chinese language.22 The Book of Kuan-tzu appeared toward the end of the period we are concerned with. This is a time, according to Kung-chuan Hsiao, when the more complicated idea of ‘‘social equality’’ began to appear (Hsiao 1979: 161n., 189, 253). The accompanied development was a strengthened concern about equal distribution or its management, often at the expense of production.23 The ‘‘Legalist’’ in the Discourses on Salt and Iron says it well in the first century B.C.: ‘‘Wealth lies in the technique of legal calculations (management), not in physical toil’’ (Huan 134 The Practice of Social Justice K’uan 3 (T’ung-yu) 1958: 4; Gale 1931: 18, with modification). After a long grappling with what ‘‘benefit’’ (profit) was, the Han Confucian intellectual, Huan K’uan (fl. first century B.C.), the author, returned to the basic moral notion that effective government was the way to an orderly society. Coached in Legalist terms, the message nevertheless reflected the managerial orientation characterizing earlier thinkers. Equitable distribution is this legalist/managerial idea in action. The moralist approach to social philosophy must necessarily handle the idea of good government from the viewpoint of meritocracy in terms of equality of opportunities. Clearly, this goes beyond the procedural idea of equity and involves a whole spectrum of ideas to which we must now turn. Equality: Equal Opportunities ‘‘Equal opportunity’’ is a conventional definition of justice. In this section, I will examine how ‘‘equality of opportunity’’ may have been understood by ancient Chinese thinkers. As mentioned in the last section, Kung-chuan Hsiao considers that the idea of ‘‘equality’’ (in a sociopolitical sense) perhaps made its appearance only after Confucius and that both Confucius and Mencius continued to allow heredity as legitimate (just) in the ideal society (Hsiao 1979: 253, but also Schwartz 1985: 282-83). It is my opinion that both Confucius and Mencius were simply being realistic about the hereditary social hierarchy (Schwartz 1985: 70). However, they argued forcefully that only a moral criterion could be relied on for constructing a healthy social stratification. Speaking from the viewpoint of the ruling class, Confucius addressed the issue of equality in terms of moral influence and privilege as well as material rewards. His thesis is that education (rituals) could be made available to all and that all would thus have equal opportunities for office. Equality in a moral sense has a similar significance in Mencius’ thinking. Although he was satisfied that hereditary emolument should continue, he was concerned that a hereditary social hierarchy could be abusive. All morally qualified men could become sages and should have access to position.24 Even regicide could be tolerated if the ruler did not live up to the moral standard. This part of Mencius’ thinking has been much discussed; clearly, his attention focused on the equality of man’s potential for practicing morality, including the ruler. Thus, one could say that, for both Confucius and Mencius, equality of opportunities could only have meaning within the framework of moral philosophy. In Mo-tzu, one finds less concern about the idea of heredity. Mo-tzu was able to advance an egalitarian social philosophy founded on utilitarian principles. However, the problem of political equality certainly was more complicated than the somewhat utilitarian egalitarianism that Mo-tzu was advocating. Let me explain. Social Justice in Ancient China 135 What Mo-tzu sought to propose was an answer to the crucial question of how social equality could work within the context of social hierarchy. How does one achieve genuine equality in a moral sense within a world of division of labor and of necessary social stratification? This is a question that all ancient Chinese thinkers shared, but I think it was Mo-tzu who first systematically worked on it. Mo-tzu’s practical approach to the social problems of his times is interesting in terms of his articulation of social equality and equal opportunities. First of all, Mo-tzu held a simple belief that a well-‘‘unified’’ social structure in which all individual interests coincided with the general interest of the society would safeguard the needed division of labor and social hierarchy. Once such a social structure was created, equality could be guaranteed in terms of roles; differences in individual talents and power would thus become irrelevant in terms of the roles they played (Schwartz 1985: 163). And yet, Mo-tzu was not advocating social stratification based strictly on occupation or division of labor. In other words, the modern liberal ideal of fair competition and equality of opportunity in the sense of reward for merit and careers open to talent was not what Mo-tzu was striving for; instead it was again within the framework of moral philosophy that he sought to define his meritocracy. Mo-tzu, however, seemed to believe that there was a conflict between the reality of occupational division and the ideal of moral meritocracy. His egalitarianism was designed to solve the conflict: While morally qualified persons should be in high positions,25 there was no reason that they were justifiably to rule without physical labor. He has a lot of comments on how the rulers should actively engage in the works that otherwise could be delegated to subordinates. Hsun-tzu was therefore not without a point in denouncing Mo-tzu: ‘‘Whether it ¨ be [the ruler] grandly possessing the empire or [the feudal lord merely] having one small domain, if they must do everything themselves before it is properly done, then no greater toil or burden can be imagined. If that were to be the case, the lowliest servants would not trade their places for the power and position of the Son of Heaven’’ (Hsun-tzu, 11 (Wang-pa); Hsun K’uang 1965: 8; Knob¨ ¨ lock 1988: II, 158, with modification). Thus, Mo-tzu could be said to have raised the issue that is dear to a modern philosopher exploring the meaning of equality, even though he returned to the belief common to his contemporaries that equal opportunity meant moral meritocracy (Schwartz 1985: 153–54) and proposed no satisfactory answer to the dilemma. Equality in moral meritocracy can be at odds with equality in the practice of moral life within the social nexus of human relations. Ideally, moral meritocracy in action will guarantee the perfect exercise of moral human relationships. Confucius approaches the issue of equality and harmonious human relationships through the principle of what may be characterized as ‘‘reciprocity’’26 (Schwartz 1985: 70). While moral meritocracy is the foundation to social ranking or hierarchy, the principle of ‘‘reciprocity’’ should provide an answer to how to carry out differentiated treatment of the people one interacts with in social life. Rec- 136 The Practice of Social Justice iprocity directs one’s behavior in such a network of human relationships by informing one about what is just or ‘‘equal’’ in that complex of differentiated treatments. The long tradition of kinship organization and the state-society continuum as family writ large provided a point of reference when it came to the exercise of reciprocity. This is why social hierarchy was eventually less important than ‘‘social circles’’ in the practice of social justice.27 To sustain a society whose structure and stratification are based on moral criteria, equal opportunity in the usual sense (meritocracy of talent)—and, actually, equal distribution—have no real meaning; once the basic livelihood of all people is guaranteed (see next section), ‘‘equality of opportunities’’ beyond equality of moral potential is also meaningless. This is to say that the distribution of (especially) material goods should be directed by the principle of reciprocity, according to the roles that each individual plays in the network of social circles. On the surface, this may look like inequality. It also sounds like running counter to such ideas as basic human rights. However, the consideration is based on what is assumed to be man’s natural instinct as understood by Confucius and Mencius. Mo-tzu was not happy with such an approach of differentiated ‘‘equality.’’ But his objection did not prevail. Later, in Legalist writings, one sees an emphasis placed on the shortterm usefulness of moral reciprocity, even though, ultimately, the fen would cease to be defined in terms of reciprocity. In general, it is clear that the predominant ancient Chinese idea about human relationships relied on an idea of ‘‘moral equality’’ that was strictly humane and that was natural to the assumed instinct of man as a social animal. In short, equal opportunity meant ‘‘equal moral potentials.’’ This idea provides a justification for the reality of social hierarchy, but it does not satisfactorily solve the problem of a just management of social relationships. Man exists in different social circles, and ancient Chinese thinkers saw that an idea must be proposed to make social equality sensible within this framework. The idea of reciprocity is therefore proposed to direct the management of the differentiated treatment of people in the complex social setting. The application of reciprocity in the equitable distribution of material goods also makes reciprocity realistic and meaningful. Thus, social equality as a definition of justice finds its Chinese expression. The Right of Individuals and the Principle of Equity The moral approach to equality led to a couple of important, if somewhat secondary, arguments that I propose to examine in this section. The first argument has to do with individual right in the context of equal opportunity. This is of course an important subject in Western discourse on equality. Hsun-tzu ¨ and, later, the Legalists were the only ones to have addressed this issue in a more systematic, if negative, manner.28 Whereas Confucius and Mencius singled Social Justice in Ancient China 137 out moral cultivation as the central part of social philosophy, and Mencian thinkers went further in entertaining the paradoxical notion of ‘‘moral rectitude even when alone’’ (shen-tu; Huang 1991: 84–89), Hsun-tzu apparently did not find ¨ such concerns meaningful. Hsun-tzu cannot award the individual any moral sig¨ nificance or right more than his entitlement of a position in society and considered that ‘‘beyond political life there can be no area of personal ethical life’’ (Hsiao 1979: 193). This notion was followed by the Legalists, whose concern for a centralized state furthers this notion. They contended that individual right made up only a secondary factor in the sociopolitical equilibrium between the state/society and the individual. Equal opportunity as an ideal of political or social justice thus became submerged under the emphasis on state authority. The second argument has to do with the role of Confucian ‘‘humanity and righteousness’’ in the exercise of justice or law. One of the greatest insights in the history of the discourses on justice is to admit the complexity of human conditions and to allow a degree of discretion in the application of the law— articulated by such thinkers as Plato and Aristotle and, subsequently, becoming the ‘‘equity’’ principle in the English and American common law (Aristotle, Bk. V: ch. 10; Konvitz 1968: 148–54). The Legalist philosopher Han Fei tzu (d. 233 B.C.) gave a preliminary consideration to this, again within the context of grappling with the Confucian discourse on moral social order, and decided that humanity and righteousness had no place in the realm of rigorous law or justice. Although the Legalists generally did not enter any systematic examination of the foundation of justice (see Part I of this chapter, ‘‘Justice as a Problematic’’), it is evident that their view about law was more than instrumentalist; the Legalists clearly believed that the perfect world was one in which legal justice prevailed. They considered morality (in the form of ‘‘humanity and righteousness’’) was but a step toward just government/society: ‘‘In early antiquity, people loved their relatives and were fond of what was their own; in the middle era, they elevated the worthy and talked of moral virtue; and in later ages, they prized honor and venerated office’’ (Duyvendak 1963: 227). ‘‘To give alms to the poor and the destitute is what the world calls a humane (benevolent) and righteous act; to take pity on the common people, and hesitate to inflict censure and punishment on criminals is what this world calls an act of grace and love. To be sure, when the ruler gives alms to the poor and destitute, men of no merit will also be rewarded; when he hesitates to inflict censure and punishment upon criminals, then ruffians never will be suppressed’’ (Han Fei tzu, 14 (Chien, chieh, shih ch’en); Han Fei tzu 1974: 248; Liao 1959: I, 127, with modification). Thus, for Han Fei tzu, ‘‘what preserves the state is not humanity and righteousness’’ (Han Fei tzu, 47 (Pa-shuo); Han Fei tzu 1974: 975; Liao 1959: II, 254). The absolutist conviction about law and justice left no room for humanization or ‘‘loving kindness’’ (Hebrew yosher; Konvitz 1968: 151).29 The consequence was disastrous for the development of the idea of social justice.30 Indeed, there has been a misplaced accusation against Confucian thought concerning justice, namely, that Chinese legal thinking left too much 138 The Practice of Social Justice room for discretion. The Confucian philosophy of justice actually could have developed the notion of creative compassion so that the legal system did not have to rely heavily on penal codes. The intellectual history of Chinese speculations on justice was such that the Legalists, in their fervor to combat the Confucian moralist legal thinking, stopped short of considering this important aspect of justice that has served as a cornerstone in Western legal thinking. The irony is that because of the Confucian emphasis on the humanist approach to justice, those capable of delving into the depth of legal thinking came out defending the absolute rigor of law and its uncompromising applicability. The significance of the Legalist refusal to approach justice from the moral viewpoint, perhaps out of a need to fight the Confucian tradition, to me not only forestalled the possibility of the idea of ‘‘equity principle’’ from developing but also probably accounted for the failure of the idea of equality or ‘‘equal opportunity’’ to go beyond its moralist parameter. In any case, and this is not for me to pass a judgment on, the discourse of social justice was kept within the context of ethics, and any attempt to study the rigor of law and its compassionate potential became stillborn. ‘‘Enrich the People’’ When asked about the achievements of Tzu-ch’an, Confucius singled out four virtues that Tzu-ch’an possessed. Of the four, one was ‘‘in enriching the people, he was abundantly kind’’ (Analects 5: 15; Waley 1938: 111, my translation). This says a lot about Confucius’ approach to social philosophy. However, Confucius was basically concerned with the moral rectitude of individuals, even if it is always placed in the context of good social order. It is Mencius who placed the greatest emphasis on the responsibility of the ruling class in providing the people with a satisfactory livelihood: ‘‘This is the way (tao) of people. Those with constant means of support will have constant hearts, while those without constant means will not have constant hearts. If they do not have constant hearts, there is nothing they will not do in the way of self-abandonment, of moral deflection, of depravity and of wild license’’ (Mencius, III, a, 3; Lau 1970: 97, with modification). The same attitude is shared by Hsun-tzu who sometimes ¨ even went beyond Mencius in terms of ‘‘enriching the state’’ (here, ‘‘state’’ reads as ‘‘people’’; Hsiao 1979: 187). For the way to a good state/society was to ‘‘regulate the use of goods through the rites (lia), and provide the people generously through administrative measures’’ (Hsun-tzu, 10 (Fu-kuo); Hsun ¨ ¨ K’uang 1965: 119). He could be quite specific about implementing such ideas in actual policy; there are too many examples to cite to demonstrate. Mo-tzu’s assumption remains the same (see above), although he was more directly involved in figuring out how material goods could be distributed equally through universal ‘‘love,’’ which was the cultivated feeling of wishing for the greatest benefit for the greatest number of people.31 It was in Kuan-tzu that we see an even more comprehensive treatment, almost Social Justice in Ancient China 139 exclusively at policy level, of the state management of an ordered society. He systematically looked at the problem of productivity, one that few other Chinese thinkers at the time paid much attention to (see above). But even so, management remained his central concern, and his philosophy was utilitarian: many quotations could be culled from the book that echo Mencius’ message. While scholars have generally concentrated on Kuan-tzu’s motivation—which was to elevate the ruler’s position and his control32 —his approach to the ordered (just?) society remained within the mainstream of ancient Chinese social philosophy of ‘‘enriching the people.’’ In fact, the Legalists after him employed the same argument. The problem with this type of moral philosophy is how we can reasonably relate it to the concept of ‘‘social justice.’’ Again, the articulation of how best to ‘‘enrich the state’’ or ‘‘enrich the people’’ reflected the concern with how an ordered society could be constructed that would provide the greatest benefit to the people. Whereas Confucian thinkers began with a compassionate consideration and appealed to the moral vanguards (the ruler and the ruling ‘‘gentleman’’ class) to provide the people with adequate livelihood, Kuan-tzu and, later, the Legalists, believed that satisfying the needs of the people was due, not so much to compassion, but to the utilitarian results of satisfying those needs. Social justice, ironically, for the ancient Chinese thinkers was thus only realizable from the initiative of the ruling authority. The ideal result is envisioned in the famous passage from the Records of Rites (Li-chi), which is worth quoting at length: When the Great Way was in practice, a public and common spirit ruled everything under Heaven; men of virtue and ability were selected; sincerity was emphasized and harmonious relationships were cultivated. Thus men did not love only their own parents, nor did they treat as children only their own children. A competent provision was secured for the aged till their death, employment was given to the able-bodied, and a means was provided for the upbringing of the young. Kindness and compassion were shown to widow, orphans, childless men, and those who were disabled by disease, so that they all were sufficiently maintained. Men had their proper work and women had their homes. They hated to see the wealth of natural resources unused [so they develop it, but] not for their own use. They hated not to exert themselves [so they worked, but] not for their own profit. In this way selfish scheming was thwarted and did not develop. Bandits and thieves, rebels and trouble-makers did not show themselves. Hence the outer doors of houses never had to be closed. This was called the Great Community (or Great Harmony) (Li-chi, 7 (Li-yun), 1; Legge 1966: iii, 364–66; Hsiao 1979: 125). It is interesting to note that this paragraph actually sounds somewhat utopian socialist: The ‘‘entitlement’’ was not spelled out in individual terms, and the dominant tone is that such a utopia was the responsibility of the rulers to effect; the right or even duty of the individual as a moral being is irrelevant in this landscape.33 There is no question that, for all of the Confucian emphasis on an individual’s moral upbringing as the beginning of a good society, the ultimate 140 The Practice of Social Justice picture is holistic; and the contribution of the moral vanguards, in their positions as moral cum political authorities play the leadership role. The people become part of the general scene because their leaders have provided them with their needs, moral and material. A few words are in order on social welfare and the idea of reciprocity. Clearly there is some incongruence between the two notions. Social welfare as a part of the social justice conception was actually what ‘‘enriching or nourishing the people’’ was about. One could even say that all ‘‘common people’’ are socially disadvantaged and that it is the government that should shoulder the responsibility. Since the state is a big family and all people are its children, the notion of reciprocity in its peculiar way of achieving social justice becomes feasible. Similarly, an individual’s responsibility toward members of his circles, from the closest to the farthest, can theoretically also be defined or based on the same principle of a kinship network. CONCLUSION Although justice as such was not an independent discourse within the Chinese intellectual tradition, and there is no word in the Chinese language that we can readily translate into ‘‘justice,’’34 one has to allow that justice was an important part of Chinese moral philosophy. In this chapter, I have simply placed the discussion of Chinese ideas of justice within the context of how ancient Chinese thinkers articulated on how to construct a good, harmonious—and, ultimately, moral—society. In fact, one may as well argue that Chinese concerns about justice have been almost exclusively about the idea—and, especially, the practice—of social justice. The first conclusion that one may draw from the discussions above is that there was a prevalent distrust of law as such. Instead, a good and just society, as perceived by ancient Chinese thinkers, should only be founded on the ideals of ‘‘rituals.’’ Rejecting the concept of a transcendental being or power early on, these thinkers, the Confucian ones in particular, have stressed the ‘‘sacredness’’ of rituals and have argued that through the practice of rituals, man’s moral instinct will be realized in the world he finds himself in. Part of this concept of a good society is the Chinese disinterest in whether there really was a law behind laws. Whereas Chinese thinkers vaguely accepted a natural law idea, this probably was not more than a rationalist justification of the applicability of universal standards to life and the political process. Beyond it, there was no further interest in examining the nature or content of this universal foundation. From the beginning, Chinese political life was dominated by how to effect a benevolent government. The power and influences of the rulers and their elite officials were trusted with almost all moral authority, and it has been accepted universally that only the ruling vanguards with their moral power could create a perfect social and political order. All philosophical discussions that had a Social Justice in Ancient China 141 bearing on the issue of social justice reflected this premise of the moral omnipotence of the ruling authority. The Legalists pushed this notion to its highest plateau and brought about the realistic interpretation of ‘‘rituals’’ by placing them in the context of penal law and the constraining power of social and political institutions (bureaucratic organization). As a consequence, discussions on how to effect a good, or just, society seldom touch on the individual’s moral responsibility or right. Mencius did seek to provide a metaphysical justification to man’s ability to be moral, and attacked the problem of the inevitable conflict between an individual’s needs and his societal responsibility. In that sense the idea of ‘‘righteousness’’ is somewhat individualistic. In that sense, too, Mencius is quite exceptional. He also brought an end to Confucius’ pragmatic, or utilitarian, approach to morality. The emphasis on the priority of management over productivity necessarily meant that distribution was important. Obviously, distribution was central to all discussions of moral social philosophy. Nonetheless, the idea of equality or equitable distribution did not begin with the distribution of material goods; rather, it was equality in human moral potential that came to dominate Chinese thinking about a good social hierarchy. Equality also meant that the distribution of material goods and man’s moral commitments should operate within the framework of kinship circles (the key term being reciprocity), which was juxtaposed to social hierarchy. Universal love or love without discrimination was to be rejected. A moral government takes it upon itself to provide the people with basic needs. The ultimate responsibility of a moral government is to enrich or nourish the people. Once the moral social hierarchy is constructed, and the basic needs of the people are met, then equality founded on social circles will result in a utopian-like society of ‘‘Great Harmony.’’ The poor and the oppressed should always take comfort that their morally superior leaders will always have their needs in mind; the problem with such a discourse on social justice in ancient China was, of course, its practice. But then an examination of this issue requires another lengthy study. NOTES 1. For a succinct summary of the state formation, see David Keightley 1983: 523– 63. See also Schwartz 1985: 37–38 for a criticism of Keightley’s association of ‘‘secularization’’ with the rise of kingly power. Schwartz’s reservation is well taken, but does not deny that the Chinese state really rose at the time. 2. How important shamanism was for the Shang rulership is a point of debate. Schwartz 1985: 25–27, citing Maspero, appears to think that this was of no great significance in our understanding of ancient Chinese religio-political life, but Chang (1983: 44–47) gives it a more distinct position. 3. In a famous incident in the Analects (III, 17; Waley 1938: 98), one sees how Confucius approached rituals: ‘‘Tzu-kung wanted to do away with the presentation of a 142 The Practice of Social Justice sacrificial sheep at the Announcement of each New Moon. The Master said, Ssu (name of Tzu-kung)! You grudge sheep, but I grudge ritual.’’ Obviously, both Confucius and Tzu-kung did not think that the sacrifice could actually result to anything, but it was the ritual that was important. 4. Discussions of the idea of justice in the West often cite the famous appeal to the ‘‘immutable and unwritten laws of Heaven’’ by Sophocles’ Antigone against Creon as a good example of the Western search for the foundation of positive law. Similar appeals, of course, also existed in Chinese thinking. In remarking on the failure of the ‘‘heavenly way,’’ Ssu-ma Ch’ien (145–90 B.C.), the Grand Historian, had this to say: Some people say, ‘. . . . Robber Chih day after day killed innocent men, making mincemeat of their flesh. Cruel and willful, he gathered a band of several thousand followers who went about terrorizing the world, but in the end he lived to a ripe old age. For what virtue did he deserve this? . . . I find myself in much perplexity. Is this so-called Way of Heaven right or wrong? (translation Watson 1969: 13–14) I do not think, however, that this quotation has been often cited, throughout Chinese history, in relation to discussions of justice or social philosophy. 5. Sun Hsing-yen 1966: ch. 27 (‘‘Lu-hsing’’), 522. It is important to note that chapter ¨ 27 belongs to the ‘‘modern text’’ and is believed to be a later (post-Confucian) interpolation. Its ideas, therefore, reflected much later opinions, though clearly with Confucian influences. 6. Confucius was seeking to maintain the social structure that was visibly declining. He was not totally dissatisfied with the tradition but tried to develop a general moral philosophy to interpret and justify the social hierarchy. Hsiao Kung-chuan detects a strong traditionalist tendency in Confucian moral and political philosophy. We shall see more below. Incidentally, for the beginning of legal codes in Chinese history, see also Creel 1970: 161–64. 7. The influence of Confucianism on Legalist philosophy is briefly discussed in Hsiao 1979, 66. The shift in the Confucian attitude to concede that law was a necessary evil is noticed by Ch’u T’ung-tsu 1961: 267. ¨ 8. I have used ‘‘class’’ here for convenience. In the Records of Rites (Li-chi) it says: ‘‘The rituals do not extend down to the common people; the punishments are not applied upwards as far as the officials.’’ The Records of Rites was compiled in the third and second centuries B.C., containing materials of earlier times and is generally regarded as a Confucian text. See also an interesting short essay on the comparison between Confucian rituals and Western jus by Wang Te-mai (1989). 9. This word has been subsequently used interchangeably with ‘‘righteousness’’ (also pronounced yi). 10. ‘‘Commiserating mind’’ (compassion, ts’e-yin chih hsin) is also expressed as pujen (cannot endure [the sufferings of others]). See Hsiao 1979: 149–50. 11. Roger Ames (1991: 143–75). See also Irene Bloom (1994: 19–54). 12. Mo-tzu’s ‘‘utilitarianism’’ predated Mencius’. 13. Thus, followers of Mencius developed the idea of shen-tu (care about moral aptitude even when one is alone). See Huang 1991: 81–89. 14. Morton A. Kaplan: ‘‘The very stuff of tragedy occurs when the vital needs of a particular individual are in irreconcilable conflict with the needs of society. Must life be Social Justice in Ancient China 143 sacrificed for honor? Should one commit treason to save one’s life? Secondary or unimportant conflicts may be resolved one way or another and forgotten. But the great conflicts are inherently insoluble.’’ (See Kaplan 1976: xvii.) The author goes on to say: ‘‘There is only one escape from this dilemma. That escape is to modify the environment in such a way that the two sets of needs cease to be irreconcilable. Thus, in most social situations, there is an underlying strain toward social change. But as change occurs, the society itself changes. The ways in which man and his needs are viewed change also’’ (xvii). The solution as proposed would be acceptable to ancient Chinese philosophers who, however, would place the emphasis on whom to initiate the change: theoretically, the ruler. In historical reality, however, the solution is to press the individual to give up on his individualistic needs. 15. Mencius talked little about rituals and paid little attention to such matters as characterized by Fingarette as ‘‘sacred.’’ Schwartz does detect certain differences Mencius developed against Confucius. See, for example, Schwartz 1985: 279, 282. 16. Incidentally, a permanent law behind the positive laws was a conception that Legalists, for all of their efforts to stress its importance, did not adopt. See Bodde 1981: 181. 17. Comparison between this argument with Plato’s idea of educational necessity in his Laws is enlightening. See Schwartz 1985: 207. A few words about the idea of ‘‘ritual’’: Clearly, once Hsun-tzu secularized this conception, it was only natural that ¨ later thinkers would give it a meaning as simple as ‘‘social norms’’ or even ‘‘regulations.’’ The Kuan-tzu is a good example: The book uses lia and law almost interchangeably. See Hsiao 1979: 333. It is therefore very easy for us to simplify the idea of lia as primitive law. See William Alford’s critique on Roberto Unger’s misreading of lia (1986: 915–72). 18. Hence, ‘‘love’’ (ai), as distinct from Confucian jen, which is less emphatically societal than personal moral perfection. See Schwartz 1985: 145–50. 19. Mo-tzu’s view about the transcendental is somewhat Augustinian: The realm of God does not allow the existence of ‘‘fate.’’ See St. Augustine’s The City of God, Bk. V, chaps. 3–7. 20. Equity here is used in the general meaning of ‘‘treating equals equally and unequals unequally but in proportion to their relevant difference,’’ as formulated by Aristotle. See Stanley I. Benn and R. S. Peters 1964. Later, I shall discuss the idea in greater detail. 21. Hsiao 1964: 154. Here, Hsiao makes it clear that equal distribution was less important in Mencius’ ideas about good government. See also Chan 1963: 70 for Mencius’ casual remark on the natural inequality of things. 22. See Hsiao 1979: 355–62 for a full discussion of Kuan-tzu’s social philosophy. Rickett (1985) unfortunately does not provide an introduction. 23. Hsiao 1979: 461, citing later Mohists. And even if productivity is emphasized, it is to ‘‘enrich the state.’’ See Hsiao 1979: 358. 24. Mencius does consider that some are so ill endowed that they cannot even realize their good potential. He would in this sense certainly find John Rawls’ theory of justice incomprehensible. Confucius was realistic and said that some are so ignorant that they cannot be educated. He proposed no remedy to such a social ill. 25. In this he was essentially similar to Mencius whose notion was that the ones who labored with their minds should rule, while those who labored with their physical strength should be ruled. See Hsiao 1979: 254. 26. The English term reciprocity has a strict definition in philosophical discussions 144 The Practice of Social Justice on justice and is not related to what I am concerned with here. Also, ‘‘reciprocity’’ is generally used as a translation of Confucius’ shu (Chan 1963: 16–17). Here I am using reciprocity in a broader sense. 27. I have benefited from discussions with Professor Cho-yun Hsu of the University of Pittsburgh on this point. 28. Kung-chuan Hsiao often equates the idea of equality with democracy. This is of course a useful but somewhat simplistic assumption. Mencius has been labeled as the first Chinese theoretician of democracy (because of his idea of legitimate regicide), but Mencius did not really enter a systematic examination of equality within the context of the political process. 29. Han Fei tzu’s elevation of law and justice relied exclusively on law (esp. coded law), and his denunciation of ‘‘humanity and righteousness’’ does not exactly mean that he refuted the Aristotelian notion of the ‘‘equity principle.’’ In a sense, systematic investigation of this issue of ‘‘equity principle’’ was never carried out in the Chinese intellectual tradition, although in practice it is clear that discretion by officials executing the law was so great that one can almost see that the law and, hence, justice, was to be interpreted totally at the discretion of the officials. To me, this is precisely because the equity conception was not adequately and sufficiently explored and defined. 30. The following is a telling example: ‘‘Once, when Ch’in had a great famine, Marquis Ying petitioned His Majesty and said: ‘The grass, vegetables, acorns, dates, and chestnuts in the Five [imperial] Parks are sufficient to save the people. May Your Majesty give them out?’ In reply King Chao-hsiang said: ‘’ ’’ (Han Fei tzu, 35 (Wai-ch’u shuo, yu hsia); Han Fei tzu 1974: 771; Liao 1959: 126). 31. See an interesting discussion of the meaning of ‘‘love’’ as used by Mo-tzu in Schwartz 1985: 145–51. 32. Hsiao 1979: 322–33. Hsiao clearly thought that Kuan-tzu was simply addressing the issue of how to strengthen the ruler’s control and riches (‘‘enrich the state,’’ equating ruler with state). In any case, Kuan-tzu laid out a comprehensive treatise on how best to ‘‘give people ease and happiness,’’ to ‘‘enrich and ennoble them,’’ to ‘‘give them security and to preserve them,’’ etc. Not counting the purpose of such policy considerations, Kuan-tzu’s social philosophy was not very dissimilar to that of Mencius and Hsun-tzu. ¨ 33. There has been a lot of speculation, certainly not without foundation, that this paragraph is an interpolation of non-Confucian writing or at least does not reflect orthodox Confucian social thinking. Still, the Confucian ideal world is premised on the total integration of individuals into the overall welfare system, each contributing his share. 34. ‘‘Justice’’ is not found as an index item in any of the four major general works on Chinese thought: Wm. Theodore de Bary (1963), Chan (1963), Hsiao (1979), and Schwartz (1985). In Creel (1970), we do find a whole chapter dealing with Western Chou (ca. 1100–771 B.C.) ‘‘justice’’ in the context of a discussion on government. But Creel’s interest is more in the administrative side of the law. REFERENCES Alford, William. (1986). ‘‘The Inscrutable Occidental? Implications of Roberto Unger’s Uses and Abuses of the Chinese Past.’’ Texas Law Review, 64, 915–72. Social Justice in Ancient China 145 Ames, Roger. (1991). ‘‘The Mencian Concept of Ren Xing: Does it Mean Human Nature?’’ In Henry Rosemont, Jr. (ed.), Chinese Texts and Philosophical Contexts: Essays Dedicated to Angus Graham. La Salle, Quebec: Open Court, 143–75. Aristotle. (1941). ‘‘Nichomachean Ethics.’’ In Richard McKeon (ed.), The Basic Works of Aristotle. New York: Random House. Benn, Stanley I., and R. S. Peters (eds.). (1964). The Principles of Political Thought. New York: Colliers. Bloom, Irene. (1994). ‘‘Comments on Roger Ames’ ‘The Mencian Concept of Renxing.’ ’’Philosophy East and West, 44, 19–54. Bodde, Derk. (1989). ‘‘Chinese ‘Laws of Nature’: A Reconsideration.’’ Harvard Journal of Asiatic Studies, 39, 139–55. Bodde, Derk. (1981). ‘‘Basic Concepts of Chinese Law: The Genesis and Evolution of Legal Thought in Traditional China.’’ Essays on Chinese Civilization. Ed. Charles Le Blanc and Dorothy Borei. Princeton: Princeton University Press. Chan, Wing-tsit. (1963). A Source Book in Chinese Philosophy. Princeton: Princeton University Press. Chang, Kwang-chih. (1983). Art, Myth, and Ritual. Cambridge: Harvard University Press. Ch’u, T’ung-tsu. (1961). Law and Society in Traditional China. Paris: Moutton. ¨ Copleston, Frederick. (1964). A History of Philosophy. Vol. 6, pt. I, no. 2. 6 vols. Garden City, N.Y.: Doubleday. Creel, H. G. (1970). The Origins of Statecraft in China. Chicago: University of Chicago Press. De Bary, Wm. Theodore (ed.). (1963). Sources in Chinese Tradition. New York: Columbia University Press. Duyvendak, J.J.L. (1963). The Book of Lord Shang. Chicago: University of Chicago Press. Fingarette, Herbert. (1972). Confucius: The Secular as Sacred. New York: Harper and Row. Forkosch, Morris D. (1968). ‘‘Justice.’’ In C. E. Pettee (ed.), Dictionary of the History of Ideas, vol. 2. New York: Scribner’s. Gale, E. M. (ed.). (1931). Discourses on Salt and Iron, by Huan K’uan. Leiden: E. J. Brill. Han, Fei tzu. (1974). Han Fei tzu chi-shih. Commentary and textual criticism by Ch’en Ch’i-yu. Hong Kong: Chung-hua. Hsiao, Kung-chuan. (1979). A History of Chinese Political Thought. Trans. F. W. Mote. Princeton: Princeton University Press. Hsun-tzu (K’uang). (1965). Hsun-tzu chien-shih. Commentary by Liang Ch’i-hsiung. Tai¨ ¨ pei: Shang-wu. Huan, K’uan. (1958). Yen-t’ieh lun. Textual criticism by Chang Tun-jen. Taipei: Shih-chieh. Huang, Chun-chieh. (1991). Meng-hsueh ssu-hsiang shih-lun. Taipei: Tung-ta. ¨ ¨ Kaplan, Morton A. (1976). Justice, Human Nature, and Political Obligation. New York: The Free Press. Keightley, David N. (ed.). (1983). The Origins of Chinese Civilization. Berkeley: University of California Press. Keightley, David N. (1990). ‘‘Early Civilization in China: Reflections on How It Became Chinese.’’ In Paul O. Ropp (ed.), Heritage of China, Contemporary Perspectives on Chinese Civilization. Berkeley: University of California Press. Knoblock, John. (1988). Xunzi. 3 vols. Stanford, Calif.: Stanford University Press. 146 The Practice of Social Justice Konvitz, Milton R. (1968). ‘‘Equity in Law and Ethics.’’ In C. E. Pettee (ed.), Dictionary of the History of Ideas, vol. 2. New York: Scribner’s. Kuan, tzu (Chung). (1966). Kuan-tzu chiao-cheng. Commentary by Yin Chih. Edited by Tai Wang. Taipei: Shih-chieh. Lau, D. C. (1970). Mencius. Harmondsworth: Penguin. Legge, James. (1879). The Sacred Books of China: The Texts of Confucianism. Vols. 3 and 4. Delhi: Motilal Barnarsidass. Liao, W. K. (1959). The Complete Works of Han Fei Tzu. 2 vols. London: Arthur Probsthain. Metzger, Thomas A. (1985–87). ‘‘Some Ancient Roots of Ancient Chinese Thought: This-worldliness, Epistemological Optimism, Doctrinality, and the Emergence of Reflexivity in the Eastern Chou.’’ Early China, nos. 11–12, 66–72. Needham, Joseph. (1956). Science and Civilization in China. Vol. 2. Cambridge: Cambridge University Press. Rickett, W. Allyn. (1985). Guanzi: Political, Economic and Philosophical Essays from China. Princeton: Princeton University Press. Schwartz, Benjamin. (1985). The World of Thought in Ancient China. Cambridge: Harvard University Press. Sun, Hsing-yen. (1966). Shang-shu chin-ku wen chu-shu. Peking: Chung-hua. Waley, Arthur. (1938). The Analects of Confucius. New York: Macmillan. Wang Te-mai (Leon Vandermeesch). (1989). ‘‘Li-chih yu fa-chih.’’ In Chung-kuo K’ung¨ tzu chi-chin hui (ed.), Ju-hsueh kuo-chi hsueh-shu t’ao-lun chi. Chi-nan, China: ¨ ¨ Ch’i-Lu shu-she. Watson, Burton (trans.). (1969). Records of the Historian: Chapters from the Shih-chi of Ssu-ma Ch’ien. New York: Columbia University Press. Part IV Social Justice and Reform in the Ancient World 12 Social Justice in the Ancient Near East RAYMOND WESTBROOK In this chapter I will deal mainly with the sources in cuneiform from Mesopotamia, dating from the third to the first millenium B.C.E., but I will also consider the sources in cuneiform from Syria and Anatolia in the second millenium, and the Hebrew Bible as evidence of ancient Israel in the first millenium, since all these societies shared a similar social and political structure, a common legal tradition, and a common view of social justice.1 The societies of the ancient Near East were organized hierarchically. The basic unit was the household, headed by a paterfamilias and containing wives, children, and slaves as its subordinate members. Above the households of the citizens lay those of the nobility, above them that of the king, and above the king the gods, whose pantheon itself was conceived in terms of household and hierarchical structures. The structure of the society is illustrated by the native use of the term slave.2 While it denotes real slaves, that is, unfree persons, who were of course at the bottom of the ladder, the term was also used relatively to describe one’s relationship to any hierarchical superior. Thus, a free citizen was called a slave of his king, and both were slaves of the gods. The concept of social justice in such a society was not at all one of equality, nor was it identified with the relief of poverty as such, given that large sections of the population existed at subsistence level. Social justice was conceived rather as protecting the weaker strata of society from being unfairly deprived of their due: the legal status, property rights, and economic condition to which their position on the hierarchical ladder entitled them. The ideal was expressed by such phrases as ‘‘that the strong not oppress the weak, that justice be done to 150 Social Justice and Reform the orphan and widow’’3 or ‘‘the orphan was not delivered up to the rich man, the widow was not delivered up to the powerful man, the man of one shekel was not delivered up to the man of sixty shekels.’’4 A whimsical tale entitled ‘‘The Poor Man of Nippur’’ (Cooper 1975: 170– 74), although fiction, is revelatory of Mesopotamian attitudes as to the sort of poor and weak who were embraced by such high-sounding ideals: There was a man, a citizen of Nippur, destitute and poor, Gimil-Ninurta was his name, an unhappy man, In his city, Nippur, he lived, working hard, but Had not the silver befitting his class, Nor had he the gold befitting people (of his stature). His storage bins lacked pure grain, His insides burned, craving food, and His face was unhappy, craving meat and first-class beer; Having no food, he lay hungry every day, and Was dressed in garments that had no change. (I 1–10) Poverty, then, is relative. Our hero was a free citizen down on his luck, who could no longer maintain himself in the style to which his status entitled him.5 The story then goes on to tell how, as a result of his condition, he suffered oppression at the hands of the powerful. His solution to his hunger is to sell his coat in exchange for a goat. He decides, however, not to eat the goat himself, because it would be no feast without beer and because his neighborhood friends and family would be angry with him for not inviting them. Instead, he presents the goat as a gift to the mayor of the city, hoping thereby to garner a greater favor in return. The mayor, however, behaves churlishly: He orders his servant to give the man a drink of third-class beer and to throw him out. The rest of the story is taken up with our hero’s elaborate revenge, whereby he succeeds in administering the mayor not one but three good beatings. To begin his revenge, the Poor Man of Nippur first approaches the king and asks him for the use, on credit, of a chariot for a day, so that he can play the part of a noble. The kings accedes without hesitation or without inquiry into his motives. Improbable as this scenario may seem, it is true in principle regarding a further aspect of social justice presumed by the story. In real life, it was indeed to the king that oppressed citizens looked to fulfill the demands of social justice. A principal function of the king was to intervene in cases of oppression, for the legitimacy of a king’s reign was based upon a divine mandate, the terms of which included ensuring social justice in his realm (Finkelstein 1961: 103). The oppression that he was expected to guard against was abuse of administrative power, as in the story above (albeit resulting in more than mere loss of face), or of economic power. It is for this reason that widows and orphans were singled out for protection Social Justice in the Ancient Near East 151 by the king. A widow or an orphan need not necessarily be poor; but on the death of the head of a household there might be no one to defend their rights, especially their inheritance rights, against those who coveted the deceased’s property. The king, therefore, being head of the household for the population as a whole, intervened as substitute paterfamilias. Thus, King Hammurabi of Babylon (eighteenth century) wished to be remembered by the oppressed for whom he had done justice as ‘‘the master who is like the father of a child to his people. . . . ’’6 The vulnerability of the weaker classes in general is illustrated by a paragraph from the earliest recorded legislative act in history, the Edict of King Uruinimgina, ruler of the Sumerian city-state of Lagash in the twenty-fifth century:7 Should the house of a noble adjoin the house of a commoner and the noble says to him: ‘‘I wish to buy it from you,’’ and he says: ‘‘If you wish to buy it from me, pay me a satisfactory price; my house is a basket—fill it with barley!’’ If he does not then buy from him, the noble shall not, in his anger, ‘‘touch’’ the commoner.8 What measures are involved in ‘‘touching’’ the commoner are not made clear, but it is evident that the noble’s action was not benign and was aimed at acquiring the commoner’s property without having to pay the asking price. As would be expected with such an archaic text, much of its language is obscure. The paragraph apparently does not impose a sanction upon the oppressive noble. The versions of the Edict that we possess are not contemporaneous with its promulgation; but inscriptions from later in the king’s reign boasting of his earlier achievements, and much that is recorded in them, may be no more than propagandistic hyperbole. Nonetheless, they would seem to provide sufficient evidence that on his accession to the throne King Uru-inimgina did institute a number of practical reforms, with particular emphasis on the state administration and its bureaucracy (Maekawa 1973–74: 114–36). Various practices of officials are detailed—the appropriation of property, the receipt of payments and the use of services—which we are given to understand were regarded as abusive, because the officials in question were removed from those areas of responsibility. One reform is clear: The former charges by different functionaries for expenses connected with funerals were listed and a new tariff posted in which some of the payments had been drastically reduced, for example, from 420 loaves for the Uhmush to 80. In paragraph 163 of the law code of King Hammurabi, punishment is explicit and is severe where abuse of power takes the form of maltreatment of a subordinate by an official: If a ‘‘captain’’ or a ‘‘lieutenant’’ takes a soldier’s possessions, deprives a soldier of his due, gives a soldier out for hire, delivers a soldier into the hands of the powerful in a law-suit, or takes a gift that the king gave the soldier, that ‘‘captain’’ or ‘‘lieutenant’’ shall be killed. 152 Social Justice and Reform The ancient legal systems did not strictly separate administrative and judicial powers. An official could act in a quasi-judicial capacity, deciding the legal rights of those subordinate to him without a formal trial, even in cases where the official himself had an interest. The best recourse for the injured party was to the king by way of petition. King Hammurabi writes to a senior official as follows (Thureau-Dangin 1924: 15): To Shamash-hazir, speak! Thus says Hammurabi. Sin-ishme anni of Kutalla, the orchardkeeper of the Dilmun date-palms, has informed me as follows: ‘‘Shamash-hazir expropriated from me a field of my paternal estate and gave it to a soldier.’’ Thus he informed me. The field is a permanent estate—when can it be taken away? Examine the case and if that field does belong to his paternal estate, return the field to Sin-ishme anni. In this case, apparently, the official had wrongfully exercised his discretion to expropriate land, probably for failure by the landowner to meet certain public obligations. Not every act of oppression, however, involved illegality. Even while operating within the letter of the law, it was possible to achieve results that were regarded as unjust because of their harmful social or economic consequences. This was the case with the laws regarding debt in the ancient Near East. The law allowed a creditor, if unpaid, to acquire by way of foreclosure not only the debtor’s property but also his family and even his own person in slavery. The burden of debt was a serious socioeconomic problem, leading to the dispossession and enslavement of the class of small farmers. Several different measures were therefore employed to restore families to their patrimony and debt slaves to their families, in derogation from the strict rights of the creditor under the contract of a loan. The first measure was the right of redemption. If property was pledged for a loan, by the nature of things that property would be released by the creditor to its owner upon repayment of the loan. The courts, however, extended this principle to property sold outright, where the transaction was in effect a forced sale at undervalue to pay off a debt. The seller was, under certain conditions, allowed to buy back—to redeem—his property at the original price. This equitable principle applied only to certain types of property, namely members of the family sold as slaves and family land (Westbrook 1991: 90–117). Paragraph 119 of Codex Hammurabi deals with a case arising in the first category: ‘‘If a debt has seized a man and he sells his slave-woman who has borne him children, the owner of the slave-woman may pay the silver that the merchant paid and redeem his slave-woman.’’ By virtue of her having borne her master children, the slave acquires the status of a member of the family insofar as the right of redemption is concerned. Note that she does not gain her freedom as a result; the purpose Social Justice in the Ancient Near East 153 of redemption is to protect the integrity of the family, not necessarily to improve the lot of the individual. Paragraph 39 of Codex Eshnunna9 deals with a sale of family land: ‘‘If a man grows weak and sells his house, the day that the buyer will sell, the owner of the house may redeem.’’ The phrase ‘‘grows weak’’ is an indication that a forced sale for debt is meant (Westbrook 1991: 100–102). The law protects not the poor as a class, but the impoverished, that is, those families who are in danger of losing their place on the socioeconomic ladder. It was not intended to bar the normal sale of land at its full market price, but was intended for those cases where the ‘‘price’’ was really the amount of the loan and the property was in effect being confiscated for default on that sum. A contract from Emar, a citystate that flourished in north Syria in the late second millenium, depicts the circumstances contemplated by the law (Arnaud 1986: no.123): A owed twenty shekels of silver to B and ten shekels of silver to C and could not repay. Now A has sold his house to B and C for thirty shekels of silver as full price and has handed over to them the old tablet of his house that was sealed with the seal of (the god) Ninurta. If in the future A repays the thirty shekels of silver to its owners in a single day, he may take his house. If not, and if two days have passed, whoever in the future claims this house may pay the same amount of silver and take his house. The final clause is an oblique reference to the fact that in default of its exercise by the seller, the right of redemption accrued to the seller’s nearest relative. Again, it is the family (in the sense of extended family or clan) that this social law is primarily designed to benefit, not the individual. The order in which the right may be exercised is given in the redemption law of Leviticus 25.47–49: If a resident alien grows successful among you and your brother grows poor with him and he is sold to a resident alien among you or to the descendant of an alien clan, after he is sold he shall have redemption: one of his brothers may redeem him or his uncle or his cousin or a further relative from his clan may redeem him, or he may be redeemed by his own resources. A further document from Emar shows this right in operation (Arnaud 1986: no.205): A died and his sons entered B’s house and he (B) released the 25 shekels of silver. And now B brought the two sons of A before . . . the city elders and their father’s brothers. He spoke thus: ‘‘Take your two nephews and give me back my 25 shekels. . . . These two nephews entered voluntarily into my slaveship.’’ Their father’s brothers refused to give the 25 shekels belonging to B and they confirmed by a sealed tablet, voluntarily, the enslavement of their two nephews to B. Dead or alive, 154 Social Justice and Reform they are B’s slaves. In the future, if C and their father’s brothers say: ‘‘We will redeem our two nephews,’’ they shall give B two souls for D and two souls for E, the blind one, and they may take their two nephews. Redemption, therefore, was not a very reliable form of social protection. The seller might be unable to raise the amount necessary to repay his debt, even though it was less than the market price of the property, and other members of the family might be equally unable or unwilling to do so in his stead. In the book of Ruth (4.3–6), Naomi’s closest relative decides to forego his right of redemption when Boaz reveals to him that it will trigger the duty of levirate marriage and thus render his investment unprofitable (Westbrook 1991: 63–67). If redemption failed, however, all was not lost. A second, more radical, remedy might be available. According to Codex Hammurabi 117, ‘‘If a debt seizes a man and he gives his wife, son and daughter in sale or ana kissatim, they ˇˇ ¯ shall serve in the house of their purchaser or holder for three years; in the fourth year their freedom shall be established.’’ The same remedy for debt slavery is provided by Exodus 21.2 and Deuteronomy 15.12, except that the period of service before release is six years. In all these laws, release from slavery occurred by operation of law; there was no need for any redemption payment. This was a special privilege for members of the family; it did not apply to family land. It is curious that the period of service varies so radically between the biblical and cuneiform laws. Despite their apparently absolute language, such paragraphs in the law codes may possibly reflect an equitable discretion of the court that was applied in differing measure according to the circumstances of the case. The rationale for release appears to have been that the debt slaves by their period of service had paid off the capital of the debt. This somewhat more flexible criterion is used in Codex Lipit-Ishtar, a Sumerian law code predating Codex Hammurabi by about a hundred years. According to paragraph 14, ‘‘If a man has returned his slavery to his master and it is confirmed (that he has done so) twofold, that slave shall be released.’’ A similar underlying principle is alluded to in the remark of Deuteronomy 15.18 that ‘‘he has served twice the hire of a hireling in serving you for six years.’’ In practice then, the actual lapse of time needed for a court to declare the release of debt slaves will have varied. Nonetheless, it was still linked to the contract between the parties and acted upon its terms in a manner that could be anticipated. This was not the case with the third and final measure, which sought to achieve social justice through a sweeping and arbitrary intervention in the normal economic life of the society. It was the practice of Mesopotamian kings every so often to issue a decree annuling debts throughout the kingdom. The decrees were retrospective: They applied to existing contracts at whatever stage of completion they happened to be at the moment of proclamation. Affected also were those same ancillary transactions that the mechanisms of redemption and limitation of servitude Social Justice in the Ancient Near East 155 sought to control: the pledge or forced sale of family land or the enslavement of members of the family. The king, in issuing a decree, was said to ‘‘establish equity for the land’’— literally, a ‘‘straightening out.’’10 The normal judicial activity of the king in answering individual petitions was defined in the same way. It was regarded as the correction of imbalances, the restoration of a status quo that had been destroyed temporarily by some act of injustice. ‘‘Equity for the land’’ was the same action on a grand scale, where the imbalance affected whole strata of the population. The earliest mention of such a decree is in an inscription of a predecessor of Uru-inimgina at Lagash, King Entemena (twenty-fifth century). He boasts that he ‘‘caused the son to return to the mother, he caused the mother to return to the son, he established the release (‘freedom’) of interest-bearing loans.’’11 Entemena is here indulging in a rhetorical game, since the Sumerian term for ‘‘freedom’’ (amar.gi4) means literally ‘‘return to the mother’’; but its literal sense had long since given way to a technical legal meaning, as is shown by its use in this inscription for the release of debts. Debt release also formed part of Uru-inimgina’s Edict: ‘‘He cleansed the citizens of Lagash, who were living in debt for planted acres(?), late grain, theft and murder—he established their release.’’12 The association of murder and theft with debts for crops and commodities may seem strange, but is perfectly logical in the context of the ancient Near Eastern system of criminal justice. I shall postpone discussion of it for the moment, however, since it is the subject of much more detailed provisions in a later edict. The Sumerian documents of the third millenium yield few further references to the release of debts and no information on its operation in practice. It is the following period, the early second millenium (usually referred to as the ‘‘Old Babylonian Period’’), that provides us with an abundance of sources: royal inscriptions, references in letters and private legal documents, and the partially preserved text of three decrees.13 The sources then decline precipitately in the following periods, but there are sufficient scattered references to establish that the custom had not died out and that our dearth of information is probably due to the random preservation of ancient records.14 In particular, an edict of a Hittite ruler of the twelfth century has recently been identified as containing debt release provisions (Westbrook and Woodard 1990: 641–59). The most complete text of a debt release decree is the Edict of King Ammisaduqa of Babylon, the great-great-grandson of Hammurabi (Kraus 1984: 168– . 83). The twenty-two paragraphs preserved reveal a complex set of provisions designed to focus the effects of the decree on its intended beneficiaries while limiting disruption of normal commerce. The provisions are of two types, those canceling various categories of debts and those concerned with problems of implementation. The central provisions are paragraphs 3 and 8, which contain a crucial distinction. According to paragraph 3, ‘‘Whoever lends silver or barley to an Ak- 156 Social Justice and Reform kadian or Amorite at interest . . . . . . and has had a tablet drafted, because the king has established equity for the land, his tablet is broken. He may not collect silver or barley in accordance with his tablet.’’ Silver and barley are the normal media of exchange. Akkadians and Amorites are the two main ethnic components of the population. The wording could be intended to privilege these two ethnic groups in particular, but it is more probably a means of referring to the population as a whole, as opposed to the citizens of specific towns, who are the beneficiaries of other provisions in the decree. The paragraph is thus drafted in the most general terms, annulling the normal type of loan that would be made to farmers, who composed the bulk of the population. In contrast, paragraph 8 states: ‘‘An Akkadian or an Amorite who has received barley, silver or goods as a purchase-price, for a (business) journey, for partnership or as a capital advance: his tablet shall not be broken; he shall pay according to his contract.’’ Trade was thus exempted from the operation of the decree. Various business transactions that involved the giving of credit would continue to be enforced by the courts, as long as the profit element was not derived from interest. Paragraph 9 specifies that if such a contract contains a penalty clause imposing interest after the due date for repayment has passed, that clause is void, but the contract itself remains valid. A distinction between valid and invalid loans is an open invitation to fraud by moneylenders seeking to preserve their investment, and several paragraphs of the edict contain complicated measures to counter evasion. Paragraph 7 reads: If a man has lent barley or silver at interest and has had a tablet drafted but has kept the tablet in his possession and said, ‘‘I did not lend at interest; the barley or silver that I gave you was for a purchase-price, for a capital advance or for another such purpose,’’ the man who borrowed the barley or silver from the merchant shall bring witnesses to the wording of the tablet that the lender denies. They shall make their declaration before the god, and because he distorted his tablet and denied the transaction, he shall pay sixfold. If he cannot pay his penalty, he shall die. Note that the term merchant is synonymous with moneylender. Merchants were the source of capital for both trade and agriculture and thus would be in a position to claim that a transaction belonged to one sphere of their activities rather than another. A slightly different type of annulment was the cancellation of arrears on unspecified debts that was made in favor of certain sections of the population only. The criterion appears to have been socioeconomic: Some of the groups named are known to be types of feudal tenants and it is possible that they may all have been dependants of the palace in one way or another. The intention of the legislation is expressly stated to be ‘‘to strengthen them and to deal equitably with them,’’ a statement that is made only with reference to these groups. At least part of the arrears in question, possibly all of them, were owed to the Social Justice in the Ancient Near East 157 palace itself in the form of feudal dues or taxes. Other paragraphs of the Edict (11, 12) reveal a complicated arrangement whereby merchants acted as wholesalers to market commodities owned by the palace, part of which the merchants received from palace stores but part of which they had to collect themselves from feudal tenants who owed the commodities by way of taxes. Special consideration is given in the Edict to the position of the taverness. This lady was an important factor in the economic life of the society—and one to whom strict regulations applied to prevent her from engaging in fraud or exploitation.15 Beer was a staple commodity that was sometimes supplied as rations or wages. The taverness would market the beer of those who had a surplus and would supply beer on credit, or rather beer mash, which could keep for much longer, against payment in barley at the next year’s harvest (Kraus 1984: 254). Although not in form a loan at interest, it was one in substance, since the taverness gained her profit by supplying in one commodity and receiving payment in another. Paragraph 17, therefore, bars her directly from claiming payment for this type of transaction. The last provision from this Edict that I wish to discuss is directed, not at the debt itself, but at its consequences. Paragraph 20 reads: ‘‘If a citizen of Numhia, Emut-balum, Idamaraz, Uruk, Isin, Kisurra (or) Malgium has been bound by a debt and has given [hims]elf, his wife or [his child] in sale, ana kissatim, or in pledge, because the king has established equity for the land, he ˘˘ ¯ is released, his freedom is established.’’ Why the citizens of these particular towns should have been singled out is not clear. There is no common link between them and it is unwise to speculate as to special social conditions or pressures, for reasons that will be explained shortly. What is also remarkable is the similarity of language between this provision and CH 117 discussed above, which released the debtor’s family after three years. It casts further doubt on the effectiveness—or, at least, the general applicability—of the law code provision. The following paragraph of the edict contains an important proviso: The release in question is not to apply to house-born slaves of the citizens of those towns. Once again we see that the purpose of the edict is to aid citizens fallen on hard times; its conception of social justice does not extend to the truly weakest strata of society, those born into slavery or poverty. One type of debt that is not covered by the Edict of Ammi-s aduqa but which . we have already met in a tantalizingly brief reference in the Edict of Uruinimgina is that arising from crime. Crimes such as murder, adultery, rape, and theft, which in modern law are prosecuted and punished by the state, were dealt with on an entirely different basis in the ancient systems. Such crimes gave rise to a dual right on the part of the victim or his family: to revenge or to accept payment in lieu of revenge. The payment was therefore neither a fine nor compensation, but composition, whereby the culprit ransomed his own life, limb, or liberty, depending on the nature of the revenge appropriate. The ransom agreement was a contract like any other and, therefore, gave rise to a debt that had 158 Social Justice and Reform to be paid or satisfied in some other way, whether by transfer of the debtor’s property, his family, or his own person (Westbrook 1988: 39–83). Because a ransom agreement was a kind of forced sale, the question arises whether its consequences might be annulled under the terms of a debt release decree. That question appears to be addressed in the Edict of the Hittite king Tudhaliya IV:16 And if someone has given ransom for blood, and he has purchased himself from you; whether (the ransom be) a field or a person, no one shall release it. If he (i.e., the holder of the ransom) has taken those things along with his (i.e., the culprit’s) wives and sons, he shall release them(?) to him. And if someone has given ransom for theft, if it is a field, they shall not release it. (II 3–10) The edict distinguishes between two cases. In the first, a person has committed homicide and has paid a ransom for his own life: He has ‘‘bought himself.’’ Can the property that he handed over as the price of his life be released by the decree? The edict answers in the negative, even if the property be land or persons, which could refer to slaves or, possibly, dependent members of his family. In the second case, on the other hand, the creditor (i.e., the avenger) appears to have made a general seizure of the homicide’s property and family, and their release is authorized. The edict then goes on to discuss debts arising from theft, along the same lines. It may seem strange that criminals could be regarded as potential objects of social justice, but it should be remembered that payment of ransom would usually apply to less serious degrees of homicide and that the thief’s condition might evoke some sympathy. As the book of Proverbs puts it: A thief is not held in contempt For stealing to appease his hunger; Yet if caught he must pay sevenfold; He must give up all he owns (6.30–31). Under what circumstances were debt release decrees promulgated? It is clear that, traditionally, a king would be expected to declare a release in the first year of his reign, as part of the pomp and circumstance surrounding his accession to the throne. The copious evidence of the Old Babylonian period, however, reveals that a king in the course of his reign might issue one or more further decrees. Thus, Hammurabi appears to have issued a decree in the twelfth and again in the thirty-third year of his reign; his third successor, Ammi-ditana, in his twentyfirst year; and the latter’s successor, Ammi-s aduqa, in his tenth year. A contem. porary of Hammurabi, King Rim-Sin of Larsa, is thought to have issued at least Social Justice in the Ancient Near East 159 three extra decrees, in the twenty-fifth, thirty-fourth, and some time after the fortieth year of his sixty-year reign.17 According to Bottero (1961: 152–53), the frequency of these decrees indicates ´ serious economic disorder in the kingdoms of the period. It took the form of the disastrous indebtedness of the majority of the population, which paralyzed production or, at least, failed to encourage it sufficiently, for the yield to satisfy the collective needs of the society. The decrees were to some extent acts of desperation, which attempted to cure the worst effects of the economic situation without dealing with its underlying causes. I regard such conclusions with scepticism. The debt release decree was an ancient custom that formed part of the religious duty of kings. There is no evidence that the economic situation was worse in the Old Babylonian period than at other times nor that indebtedness, however widespread and crushing, would have had a serious effect on overall production. It would, on the other hand, have altered the distribution of land ownership, with a tendency toward the formation of latifundia. Accordingly, we should look to social rather than economic stability as the motive for these recurrent decrees. The cuneiform records give little evidence of social unrest. It is true that they represent the voice of the establishment, rather than the opposition, but one would still expect to find some echo of widespread discontent in the sources. The ‘‘protest’’ of the individual debtor lay in flight, abandoning his home and family and seeking refuge in a foreign kingdom or perhaps in the lightly populated steppe. It is also possible that the various social measures were effective in keeping economic grievances from becoming too widespread. Tudhaliya IV informs us at the beginning of his edict that it was promulgated as a direct result of a protest by his citizens: When I had destroyed Assuwa and returned to Hattusa, I refurbished the gods; the men of Hatti all began to bow down to me, and they spoke as follows: ‘‘O great king, you are our lord, a leader of campaigns. Are you not able to judge in matters of justice? Behold, evil people [ . . . ] have utterly destroyed [ . . . ] the feudal holdings and the sarikuwa tenants [ . . . ] (I 1–11). Unfortunately, the broken state of the tablet prevents us from learning what the point of the protest was. Nonetheless, it does show the ability of the citizens as a group to petition the king about a particular abuse—and in fairly bold terms. Similar group petitions are found elsewhere in the Hittite sources. Paragraph 55 of the Hittite Laws records the king’s accession to a petition by a certain class of feudal tenants to receive equal treatment to that of other classes. In a document from Ugarit, PRU IV 17.130 (Nougayrol 1956: 103–5), a vassal state of the Hittites, the king of Ugarit petitions the Hittite emperor on behalf of his free citizens, who have complained that Hittite merchants are ‘‘heavy upon the land.’’ The emperor grants a seasonal restriction on the merchants’ activities at Ugarit. By contrast, the dire political consequences of failing to heed popular 160 Social Justice and Reform grievances are revealed in the biblical account of King Rehoboam’s refusal to grant a petition of his citizens led by one Jeroboam (I Kings 12.1–20). The Old Babylonian decrees do not mention any specific occasion for their promulgation; the only motivation given is religious—that it is pleasing to the god of justice.18 The same motivation, it should be noted, is present in the Hittite decree. Tudhaliya’s remark that he refurbished the gods would appear to have no relevance to his account, unless it is to suggest that part of the ‘‘refurbishment’’ was to correct injustices displeasing to the gods. Fear of the gods may provide a clue to the specific occasion for some of the decrees. It will be recalled that the edict of Uru-inimgina referred to the release of debts as a process of ‘‘cleansing.’’ If an accumulation of injustice could, like murder or sacrilege, ritually pollute the land, then the anger of the gods would express itself in general disasters such as crop failure, plague, and defeat in war; and debt release would be a means of assuaging their anger. An example from the Bible is the slave release decree of King Zedekiah, proclaimed when Jerusalem was besieged by the Babylonian army (Jer. 34.1–10). While nothing so dramatic can be correlated with any of the Old Babylonian decrees, it is possible that their occasional nature may be linked to natural disasters, such as failure of the harvest, that resulted in a year of famine and provided good grounds, political and religious, for relief of debts. Whatever the occasion for their promulgation, the one character that the decrees from cuneiform sources share is their unpredictability, depending entirely on the discretion of the ruler. The same is true of the decree promulgated in an emergency by King Zedekiah. In contrast, the equivalent measures enshrined in biblical laws—the famous Sabbatical and Jubilee years—are cyclical in occurrence and automatic in operation. Deuteronomy 15.1–3 directly annuls debts: ‘‘Every seventh year you shall make a cancellation. The cancellation shall be as follows: every creditor is to release the debts that he has owing to him by his neighbor; he shall not press his neighbor for payment.’’ Leviticus 25.9 annuls transactions founded on debt which resulted in the alienation of family land or the enslavement of members of the family: ‘‘You shall make the fiftieth year a holy year and declare freedom in the land for all its inhabitants: it shall be a Jubilee for you and each man shall return to his estate and each shall return to his clan.’’ Now this cyclical aspect changes the whole nature of the debt release and ultimately destroys its usefulness. It was the very unpredictability of the decree that made it effective: It acted retrospectively and without warning on existing contracts. But a creditor who knows that his loan is bound to be annulled at a certain point in the future and any security taken lost will simply not give credit or will find some means of evading the release. The effect on debtors will be far worse than before, drying up their sources of credit or driving it underground into a black market. The biblical measures, unlike their cuneiform counterparts, must therefore be regarded as utopian. The question then arises, why a practical measure, which was used by Israelite Social Justice in the Ancient Near East 161 kings in the same manner as Mesopotamian and Hittite rulers, was turned into an impractical one. The answer is suggested by the aftermath of King Zedekiah’s decree. The decree ordered the release of debt slaves, which indeed occurred, but subsequently the same persons were enslaved again by their former masters (Jer. 34.10–11). This breach of faith elicited divine anger, as conveyed through the prophet Jeremiah: ‘‘Thus says the Lord: Because you have not obeyed me by declaring freedom, each man to his brother and his neighbor, I hereby declare freedom for you, says the Lord, to the sword, to plague, and to hunger, and I shall make you an object of horror to all the kingdoms on Earth.’’ In general, the Hebrew prophets repeatedly inveighed against the Israelite ruling class for their failure to do social justice: ‘‘Woe to them who make evil decrees and who write documents of suffering; to turn aside the indigent from judgment and to oppress the poor in court, to make widows their booty and orphans their plunder’’ (Isa. 10.2). Like the prophets, but unlike the cuneiform sources, Leviticus and Deuteronomy derive from circles representing the voice of the opposition. In their eyes, the Israelite kings had failed in their constitutional duty; they had not taken the necessary measures to ensure the social justice that their divine mandate demanded of them. Since the king of flesh and blood could not be trusted to proclaim a debt release when needed, these circles advocated its removal from his discretion to the authority of the divine king and—to make sure that it happened—made its occurence cyclical. In summary, social justice was regarded in the ancient Near East as the preservation of the status quo—as the privileges owed to each citizen as member of a family unit with a certain recognized socioeconomic status. Where those privileges were lost through an act of oppression, certain mechanisms were available to restore the balance. If due to abuse of administrative power, a petition to the king was expected to result in an order canceling the administrative act and, if necessary, punishing the offender. If due to abuse of economic power, the right of redemption was available to the debtor or his family. If that right could not be exercised, there remained for debt slaves the possibility of release without payment after a period of service. Finally, the king could intervene by a general cancellation of debts and of transactions ancillary thereto. Ultimately, it was the responsibility of the king, as part of his divine mandate, to ensure that these mechanisms functioned effectively. Mesopotamian kings boasted of having fulfilled their mandate, but evidence from the Bible suggests that the practice of kings sometimes failed to live up to the ideals of social justice. NOTES 1. On the common legal tradition, see Paul 1970; on the common view of social justice, see Weinfeld 1985. Epsztein 1986 is a general survey based on secondary sources. 162 Social Justice and Reform 2. Sumerian arad; Akkadian (w)ardu; Hebrew ‘ebed. 3. Codex Hammurabi rev. xxiv 59–61. Pritchard 1969: 163–80. 4. Codex Ur-Nammu 162–68. Pritchard 1969: 523–25. 5. Dearman (1988: 52–53) finds a similar profile in the Bible for the class of poor for whom the prophets demand social justice. 6. Codex Hammurabi rev. xxv 20–21. 7. See Steible 1982: 288–312; English translation Cooper 1986: 70–76. 8. In the edition of Steible 1982: Ukg. 4.11.32–12.11. Ukg. 5.11.1–18; cf. Cooper 1986: 72. The Sumerian term here translated ‘‘touch’’ (tag) is translated by Steible as ‘‘(den Zorn daruber) fuhlen lassen,’’ and by Cooper as ‘‘strike at him.’’ ¨ 9. A kingdom to the north of Babylonia in the eighteenth century. The name of the king responsible for this code is not preserved. Most probably it is to be attributed to King Dadusha, an earlier contemporary of Hammurabi. In that case, it would predate Codex Hammurabi by several decades. 10. Sumerian: nıg.si.sa; Akkadian: mısharum. ´ ´ ¯ˇ 11. Entemena 79.4.2–5. Steible 1982: 269. 12. In the edition of Steible 1982, Ukg. 4.12.13–22 5.11.20–29. 13. Kraus (1984) contains all known Old Babylonian references to that date and an edition of the three extant decrees. 14. See the Chicago Assyrian Dictionary, vol. 1/2, sub anduraru, g and h, pp. 116– 17, for references from Nuzi (fifteenth century) and the neo-Assyrian period (eighth– sixth century). On the latter, see Lewy 1958: 30*–31*. 15. Codex Hammurabi 111 fixes the rate at which the taverness could give beer on credit, and paragraph 108 prescribes the death penalty for a taverness using false weights. A slightly earlier law code, Codex Eshnunna, in paragraph 41, obliges the taverness who sells nonresidents’ beer on their behalf to obtain the current market price. 16. Westbrook and Woodard 1990: 642–44. 17. See Kraus 1984: 16–110 for a full list of all possible edicts alluded to in the Old Babylonian sources. 18. An example is the following petition to the king: ‘‘When my lord raised the Golden Torch for Sippar and established equity for Shamash (the god of justice) who loves him’’ (Finkelstein 1965: 236). REFERENCES ´ Arnaud, Daniel. (1986). Recherches au pays d’Astata-Emar VI.3. Paris: Editions Recherches sur les Civilizations. Bottero, Jean. (1961). ‘‘Desordre economique et annulation des dettes en Mesopotamie ´ ´ ´ ancienne.’’ Journal of the Economic and Social History of the Orient, 4, 113– 64. Cooper, Jerrold. (1975). ‘‘Structure, Humor and Satire in the Poor Man of Nippur.’’ Journal of Cuneiform Studies, 27, 163–74. Cooper Jerrold. (1986). Sumerian and Akkadian Royal Inscriptions. New Haven, Conn.: The American Oriental Society. Dearman, John. (1988). Property Rights in the Eighth-Century Prophets. SBL Dissertation Series 106. Atlanta, Ga.: Scholars Press. Epsztein, Leon. (1986). Social Justice in the Ancient Near East and the People of the Bible. Eng. transl. London: SCM Press. Social Justice in the Ancient Near East 163 Finkelstein, Jacob. (1961). ‘‘Ammisaduqa’s Edict and the Babylonian ‘Law Codes.’ ’’ . Journal of Cuneiform Studies, 15, 91–104. Finkelstein, Jacob. (1965). ‘‘Some New Misharum Material and Its Implications.’’In Guterbock and Jacobsen (eds.), Studies in Honor of Benno Landsberger, Assyriological Studies 16. Chicago: University of Chicago Press. Kraus, Fritz. (1984). Konigliche Verfugungen in altbabylonischer Zeit. Studia et Docu¨ ¨ menta ad Iura Orientis Antiqui Pertinentia 11. Leiden: E. J. Brill. ˆ Lewy, Julius. (1958). ‘‘The Biblical Institution of Deror in the Light of Akkadian Documents.’’ Eretz-Israel 5, 21∗–31∗. Maekawa, Kazuya. (1973–74). ‘‘The Development of the E-MI in Lagash during Early Dynastic III.’’ Mesopotamia 8–9, 77–144. Nougayrol, Jean. (1956). Le Palais Royal d’Ugarit IV. Mission Ras-Shamra 9. Paris: C. Klincksieck. Paul, Shalom. (1970). Studies in the Book of the Covenant in the Light of Cuneiform and Biblical Law. Supplements to Vetus Testamentum 18. Leiden: E. J. Brill. Pritchard, James (ed.). (1969). Ancient Near Eastern Texts Relating to the Old Testament. 3rd ed. with supplement. Princeton: Princeton University Press. Steible, Horst. (1982). Die altsumerischen Bau- und Weihinschriften. Pt. 1. Freiburger Altorientalische Studien 5. Wiesbaden: Franz Steiner. ˇ ˇ Thureau-Dangin, Francois. (1924). ‘‘La correspondance de Hammurapi avec Samashasir.’’ Revue d’Assyriologie, 21, 1–58. Weinfeld, Moshe. (1985). Justice and Righteousness in Israel and the Nations (in Hebrew). Jerusalem: Magnes Press. Westbrook, Raymond. (1991). Property and the Family in Biblical Law. Journal for the Study of the Old Testament, Supplement Series 113. Sheffield: JSOT Press. Westbrook, Raymond, and Roger Woodard. (1990). ‘‘The Edict of Tudhaliya IV.’’ Journal of the American Oriental Society, 110, 641–59. 13 Social Reform in Ancient Mesopotamia BENJAMIN R. FOSTER GENERAL CONSIDERATIONS Social reform in contemporary experience implies change in society with longterm consequences, usually legal and economic, for a group within that society. Examples of social reform from modern times include universal suffrage and abolition of slavery. When we survey the three thousand years of Mesopotamian written tradition, we cannot readily identify social reforms understood in this way. Unless avowed Marxists, we find little direct evidence for social discontent, popular movements, charismatic crusaders, or other familiar forerunners of social reform. This is no doubt to a large extent due to the nature of the written record, which tends to reflect the interests and concerns of the literate elite. Social discontent as expressed in literature does not, so far as we know, result in long-term change: We have no Uncle Tom’s Cabin to point to. But in a culture where only a small percentage of the population could read, mass movements inspired by the written word are not to be expected. OLD BABYLONIAN INSCRIPTIONS, EDICTS, AND TARIFFS We have an assortment of Mesopotamian documents that record government action to modify certain social conditions—and, thus, are candidates for the modern category ‘‘reform.’’ Most date to the period 2000–1550 B.C.E., for reasons that need to be considered. Translations and bibliographies for certain of these documents are given in the Appendix to this chapter. The first text to be considered (see Appendix, Text 1) records a nine-point royal program analyzable as follows: 166 Social Justice and Reform Good Living Conditions 1. ending hunger 2. easing the task of earning a living 3. security of dwelling 4. promoting happiness and contentment Government Cutbacks 5. reducing taxes 6. reducing the draft for compulsory government service 7. curtailing a specific government practice that was the cause of popular complaint Law and Order 8. promoting law and order 9. reinforcing of honest citizenry Modern experience suggests, and ideologies often insist, that social reform is brought about by individuals determined to alter institutions that they find unjust. Here the author of change is a king. Our suspicions are aroused. Why would kings profess interest in social change, when they themselves sit at the apex of the society they propose to change, presumably enjoying the highest material well-being and prestige? Suspending our skepticism, we find the king describing his social program from three aspects. First is promotion of stability and prosperity for the good of the citizenry as a whole, without regard to class. Second is reduction of government exactions of goods and services, thus placing the interests of the citizenry as a whole, so far as we know without regard to class, ahead of those of the palace administration and economy. Third is expression of concern for honest citizens as individuals, without regard to class. Where is the reform in all of this? We sense a contrast, express or implied, with the preceding period, reign, or administration, though this text, unlike some to be considered later, does not draw such a contrast. What strikes us is the vagueness of much of it. The only specific measures alluded to are reductions in certain dues from the citizenry to the government and curtailment of one unpopular practice. These are packaged as symptomatic of an era of bliss, described with literary topoi well known even 3,000 years ago, though they were fresher then.1 So our first example of social reform dissolves into specific royal enactments announced with a rhetoric in which good times are implicitly contrasted to bad times, and the success of a reign is portrayed as the result of divine election of a worthy agent. The historical background of this document was a period of rival city-states in Babylonia, often more or less of equal strength—a time of frequent warfare for regional hegemony and access to water.2 Development of irrigation and competition for control of upstream water may reflect a population increase in Babylonia, perhaps through migration and resettlement from northern Syria at Social Reform in Ancient Mesopotamia 167 the end of the third millennium in the face of drier conditions there.3 Security and prosperity in this period were more often sought than achieved. The Babylonian ruler was wont to present himself as a shepherd, a leader responsible for feeding his flock, protecting it from outside enemies (no inside ones are visualized), and making a legitimate profit from his herd.4 The profit-taking aspect is normally expressed in terms of statements of prosperity, such as we already have here. The only sacrifices are those made by the government. Let us look at another type of reform document, from a century or more later, which demands sacrifice from a broader range of the population, Appendix Text 2. This has none of the overt literary appeal of the first example. If the first text is a commemorative inscription, designed for posterity, this is the careful wording of official contemporaneous implementation. Much of this decree is fragmentary and obscure, and its social background a matter of debate, so our discussion will focus on a few better-preserved provisions with a view to discerning what the Babylonians thought it accomplished and why they thought it was necessary. First, it is clear that certain provisions of the edict (Appendix Text 2: 3, 20), abolished debt and debt slavery in effect at the time of the edict, and even stipulated restitution of certain debts collected prior to the issuance of the edict, with the death penalty for failure to comply (Appendix Text 2: 4). What sector of the population benefited from such an act, and why was it promulgated? Here we may fall back on recent studies of the structure, functioning, and evolution of Babylonian society in this period. It appears that in certain cities wealthy individuals amassed substantial fortunes through short-term loans at high interest, ranging from 25 to 33 1/3 percent, in grain and silver. Debts were normally repaid at harvest time. Furthermore, there is evidence that some of these moneylenders could advance as loans money that they had collected locally from royal tax revenues—and were responsible for gathering or converting into cash—and that they were not under immediate pressure to remit to the palace: Hence, maximum profit at minimum risk.5 Debtors unable to pay the loan and interest could become debt slaves of the creditor, ransomable only by payments collected by their relatives and friends. We need not be advanced economic theoreticians to suppose that there might be a relation between such high rates of interest and the possibility of an edict abolishing debt, although we may ask which was first, the risk or the rate. If the funds loaned in some instances were not even the personal resources of the creditor, then his losses were insignificant, assuming that the palace might forfeit loans made from tax revenues. Among Marxist historians, especially, there prevails the notion that the possibility of edicts remitting debt will cause a low price for land (especially if land sales could under certain circumstances be voided anyway), a high rate of interest, and a shortage of long-term credit.6 We may well wonder if edicts were part of the problem or the solution. We might further wonder if the edicts did not in fact favor moneylenders in the long term, even if unintentionally—and, thus, we might wonder whose benefit the edicts ultimately served. 168 Social Justice and Reform What is most important for our present purpose is the understanding that the Babylonians had that these did not constitute reform in the sense of a new departure but constituted ‘‘restoration’’ to a former, natural state. Society was seen to be in need of periodic readjustment—and then indebtedness could begin over again.7 Contemporary perception of reform need not presuppose cyclical reversion; we prefer linear evolution, whereby society adapts to the needs of different times and people. In contrast, the Babylonian perception of reform was reversion to a past norm. Before we essay the more difficult question of what the norm in society was viewed to be—and how these measures were intended to bridge the gap between what was and what was supposed to be—let us consider some indirect, even quantifiable, evidence for conceptions of a properly balanced society. Ideal economic conditions were often expressed in Mesopotamia by tables of prices of certain commodities, which, despite their variegated nature, we tend to construe as a sort of market basket (see Appendix, Text 4). From what we know of actual prices in this period, these figures may be a third or less of reality.8 The figures quoted in a prayer of Assurbanipal (see Appendix, Text 6), a thousand years later, are fantastic, as if the table had been turned from wishful thinking into make-believe. Of the examples of reform and prosperity that we have noted, the table of prices is the longest to survive, and, for whatever reasons, lived on as a terrestrial observation in astronomical diaries of the Hellenistic period. There are also what appear to be formal tariffs, such as the example quoted in Appendix Text 5. There is no indication of sanctions to enforce such prices. It is noteworthy that the tariffs are paired with rates of hire, as if prices and wages were both aspects of the same regulatory policy. The tariffs may bear the same relation to the prices as the edict does to the commemorative inscription: the one allegedly descriptive, the other prescriptive. Again, we have little evidence in favor of their foundation in reality. With both Sin-kashid and Assurbanipal we have the impression that low prices were considered symptomatic of divine favor for the reign as manifested in a strong economy. A strong economy was seen as a state of blissful normalcy rather than the result of economic intervention. THE ‘‘REFORMS’’ OF URUINIMGINA No discussion of Mesopotamian social reform can avoid the group of commemorative inscriptions known today as the ‘‘Reforms of Uruinimgina’’ (formerly read Urukagina). This group of texts dates to around 2300 B.C.E., centuries earlier than the texts discussed so far, a period as different socially, ethnically, and economically from the Old Babylonian period as the London of Elizabeth I might be from that of Elizabeth II. I have hazarded a translation of selections from these documents in the Appendix as Text 3, and arbitrarily numbered the provisions for convenience of reference. Social Reform in Ancient Mesopotamia 169 If the reader of these translations feels uncertain as to what the text means, he is in the good company of generations of scholars who have labored to understand these unique and perplexing documents. Before we hail them as early examples of social reform, as has often been done, and from quite different ideological perspectives,9 we should at least note that the majority of the provisions are obscure, containing words and expressions of unknown meaning and that even those words where the surface sense seems clear are opaque as to their application or significance. Unlike the texts discussed so far, the Uruinimgina documents draw a sharp line between customs of the past and those after the implementation of the changes listed. This makes ‘‘reform’’ an attractive interpretation. Interpreters have leaped to the conclusion that the conditions listed in the first part of the text were ‘‘abuses’’ that the text corrected; that is to say, Uruinimgina is said to have restored society to an earlier state of affairs by cutting back on government usurpation while restoring to temples their old prerogatives. It is regrettable, for this interpretation, that Uruinimgina did not say this (if we understand the text correctly), but insists that the institutions he was changing had existed from earliest times.10 The rhetoric of his inscription is not one of restoring ancient practices but of changing them, so he himself wished his changes to be seen as innovations, a new normalcy. Thereby, he is at least a candidate for the category ‘‘social reformer,’’ even if, according to some distinguished critics of his program, he was trying to gain popular support at the expense of vested interests or to strengthen his position against the temples.11 The opening clauses (1) are straightforwardly expressed: Certain people took possession of certain assets. Did the boatmen take for themselves boats that were actually temple property? There is no indication of this in the text. Does it mean that in the past everyone owned his own boat, but that in the new era boats were ‘‘nationalized’’ in some way? Why did people put down silver for certain sheep? Was this an exaction? We have no idea, despite numerous proposals, and thus have no way of evaluating the new program. The passage that states that the city ruler’s gardens were on temple lands (Appendix Text 3: 2), if considered an abuse, would suggest a usurpation: the ‘‘secular establishment’’ had encroached on the temples. Therefore, it is all the more regrettable that the inscription does not actually say this, but suggests that this had always been the practice and that it was changed. If we stay close to the wording of the text, we see rather the creation of a new, allegedly theocratic state: All land belongs to the gods now. In practical terms, this could easily mean that the city ruler had taken over all the temples, proclaiming that the gods had taken over the rule of the city (‘‘all power to the gods’’). This could account for the removal of ‘‘inspectors’’ from the realm (Appendix Text 3: 10); there was no longer interface between a palace and a temple economy where both were combined. Burial customs were reformed (Appendix Text 3: 4, 11). We do not know if the Uhmush-person was a sort of undertaker, or, since a bed and the like were 170 Social Justice and Reform included in the costs, if the goods listed were actually grave goods. There are also provisions for rations and offerings of various kinds, not all of them obviously lower, or an adjustment on, previous provisions (Appendix Text 3: 12). Another vexing passage has to do with women who could have two men (Appendix Text 3: 15.) Far from suggesting polyandry in ancient Sumer, this reform could have abolished the possibility of a woman distrained for debt being liable to sexual exploitation by a creditor. In short, despite its length and complexity, the corpus of documents from Uruinimgina remains an enigma. Some of these changes were presented as improvements for the common benefit, but others sound suspiciously like the creation of a new ideology, wherein the ruler and his family administered the temples and their lands as servants in a new theocratic state. We do not find in our documents any trace of either increased prosperity or promotion of justice, the two staples of the later Mesopotamian documents considered here. Rather, the gods have taken over the government. Uruinimgina’s program, which looks at our distance like a case of extreme centralization couched in theological rhetoric, remains baffling to us. LATER REFORMS Reform in Babylonia during the second half of the first millennium B.C.E. was often expressed as a return to age-old values and institutions that had fallen into disuse through forgetful generations. Rulers boast in their inscriptions of reviving ancient rites and practices, even archaeological excavations to reconstruct the plans of ancient buildings. Indeed, reform of the present often took on an antiquarian aspect. One of the most interesting records of such activity appears in the document excerpted as Appendix Text 7. This implies a moral standard that had fallen into desuetude, the terms of which can be easily paralleled from wisdom literature that enjoins care for the widow, orphan, and poor. Here the motif is refurbished into a vivid personal narrative that includes a description of a water ordeal that may itself have been a revival of a longobsolete legal practice.12 We learn nothing here of remission of taxes, debts, or service, though royal abuse of service and requisition are referred to in texts such as the ‘‘Furstenspeigel,’’ otherwise known as ‘‘Advice to a Prince.’’13 ¨ LITERATURE Rulers have had their say. We detected in Babylonian sources from the first half of the second millennium B.C. a sense that there was a norm for society, that society tended to get out of balance, and that kings had to restore society to its normal state. The earlier Sumerian example was different in that it implied an old norm was replaced by a new one. If kings are not always the most reliable spokesmen for the social conditions of their time, we need to consider the observations of others. At about the same time that King Ammisaduga was can- Social Reform in Ancient Mesopotamia 171 celing debt slavery, a Babylonian scholar was copying out a lengthy narrative poem about the origin and development of human society. We do not know exactly when this was first written or who wrote it, but from what survives we recognize a masterpiece.14 Like all great poems, it offers a wide range of considerations to the reader, including the student of Babylonian social reform. The key phrase ‘‘establish restoration’’ occurs several times at crucial turns in the plot, the same phrase used in commemorative inscriptions to describe how kings righted imbalanced societies (cf. Appendix Text 2: 20). As the poet tells it, once there was a division among the gods such that great gods imposed corvee labor on lesser gods for the purpose of digging the Tigris ´ and Euphrates rivers. Sick of the labor, the lesser gods burned their tools, rioted, and staged a protest at the house of the chief god. The great gods held a conference and a proposal was made that a substitute be created to do the work of the lesser gods so as to maintain all the immortals. With the collaboration of the god of wisdom and the birth goddess, the gods executed the ringleader of the riot and used his blood and heartbeat to make a new creature, a human being (whence, one may assume, the rebellious spirit of the human race). The lesser gods were freed of labor service: Divine society had been reformed and a new servitor created. ‘‘I abolished labor service, I removed cause of complaint, I caused the citizenry of heaven to dwell in peace (no more riots) and prosperity,’’ so an imaginary inscription might run. We suspect that the poet did not see the reform of heaven as necessarily just or equitable. The social background against which this text was written included corvee ´ service (‘‘[only] four days a month,’’ see Appendix, Text 1). Few institutions were so hated, and more than one ruler sought favor by reducing or modifying it.15 As late as the first millennium, literary texts refer to corvee and recruitment ´ as examples of tyranny. Thus, this part of the composition must have found a lively response in its readership. The gods’ human creatures went forth and multiplied. So great became their clamor and bustle that the chief terrestrial god, Enlil, lost sleep. Increasingly drastic measures undertaken to decimate humanity (starvation, plague) proved inadequate, so finally the gods agreed on a catastrophic flood to wipe out the whole human race. A man and woman survived by building a boat and taking aboard an assortment of animals. The gods soon repented their deluge because no one was left to feed and provide for them. Therefore, they welcomed the repopulation of the earth but invented stillbirth, celibacy, childlessness, and other means to keep the population under control and instituted the last and most significant of their reforms, namely, death for the human race. The human lot is by divine design unfair and exploitive. There is no word about decreeing justice or prosperity for the human race; this is left for mere kings to carry out. Human beings carry within them the spirit of a sublime troublemaker—meaning, ultimately, that reform will always be necessary and doomed to failure. To the poet, death was the final social reform—instituted by the gods so that they would not be bothered by a procreative human race. 172 Social Justice and Reform To a contemporaneous observer, reform could therefore be an instrument of tyranny. It kept the population constant so as to permit effective exploitation, rather like culling a herd. So, too, the Old Babylonian royal decrees put the population into economic balance and thereby created, intentionally or not, fresh opportunities for exploitation, making a phoenix of the dying golden goose. APPENDIX Text 1: Reforms of an Early Old Babylonian King Source: Frayne, Douglas R. (1991). The Royal Inscriptions of Mesopotamia: Early Periods. Vol. 4, Old Babylonian Period (2003–1595 B.C.). Toronto: University of Toronto Press, 87–90. O god Enlil, this is my destiny which you established at (your) temple: I established justice in (your city) Nippur, I made righteousness appear. As if for sheep, I sought out forage and fed (the people) in green pastures. I lifted the heavy yoke from their necks. I settled them in secure abodes. The righteousness which I established in (your city) Nippur made (the people there) happy . . . I made the land content. I reduced to one tenth the grain tax that formerly was one fifth. I made the ordinary citizen perform labor service (only) four days a month. The cattle of the palace which used to graze in certain fields, and which were a source of complaint, I removed those cattle from the plowed land. I made anomalous the person with a complaint. I am a judge who loves righteousness. I abolished evil and violence. I rehabilitated the just man. Text 2: From the Edict of Ammisaduga Source: Kraus, Fritz Rudolf. (1984). Konigliche Verfugungen in altbabylonischer Zeit. ¨ ¨ Studia et Documenta ad Iura Orientis Antiqui Pertinentia 11. Leiden: Brill, 168–83. . . . When the king established justice in the land, (1) With respect to arrears of tenant farmers, shepherds, tanners, seasonal herdsmen, and those liable for support of the palace, to protect them and to treat them justly, it is decreed: the government collector shall take no action against the household of those liable for support of the palace. (3) Whoever loaned grain or silver to an Akkadian ( Mesopotamian) or an Amorite . . . and had a document drawn up (recording the debt), his document is null and void. He shall not collect grain or silver according to the terms of the document. (4) Furthermore, if, from the second day of the intercalary month (of a certain year) of (the preceding king) he has required repayment, inasmuch as he required repayment and collected out of the normal period for repaying debts, he must give back whatever he required to be repaid in this manner. Whoever shall not give back according to the king’s ordinance shall die. (20) If a citizen of Numhi, a citizen of Emutbal, a citizen of Idamaras, a citizen of Uruk, a citizen of Isin, a citizen of Kisurra, a citizen of Malgium has contracted a debt according to the terms of which he himself, his wife, or [his children] may become debt Social Reform in Ancient Mesopotamia 173 slaves or pledges, because the king has established justice in the land, he is released, his restoration is established. (21) ( this provision does not apply to chattel slaves) Text 3: From the Reforms of Uruinimgina Source: Steible, Horst. (1982). Die altsumerischen Bau- und Weihinschriften; Inschriften aus ‘Lagas.’ Freiburger Altorientalische Studien 5. Wiesbaden: Franz Steiner GMBH, ˇ 278–324. For a full English translation, see Jerrold Cooper (1986), Sumerian and Akkadian Royal Inscriptions. Vol. 1, Presargonic Inscriptions. New Haven, Conn.: American Oriental Society, 70–78. (1) From distant days, from the very beginning, boatman would take possession of boat, herdsman would take possession of donkey, shepherd would take possession of sheep, overseer of fishermen would take possession of the . . . , gudu-priest would measure out grain in the (district called) Ambar. Shepherd would put down silver on account of a white sheep. Surveyor, chief cult singer, steward, brewer, all supervisors would put down silver on account of an offering sheep. (2) The gods’ cattle plowed the ruler’s onion patch. The onion and cucumber patches of the ruler lay on the good agricultural land of the gods. Teams of oxen and draught oxen were hitched up for temple administrators. Grain of temple administrators was distributed to the ruler’s troops. (3) (4 types of garments), (a linen textile), (2 items made with flax), a bronze helmet, a bronze peg, (various other bronze objects), (an object of leather), a raven’s wing, (3 other objects) temple administrators used to deliver for tax payment. (Another type of temple administrator) used to strip(?) trees in the orchard (called) Ama ulu and garner the fruit. (4) In order to entomb a corpse, the (Uhmush-person) took as his beer 7 pots, as his bread 420 loaves, 2 measures of (a certain kind of) grain, 1 garment, 1 good quality goat, 1 bed. In the place (called) Gi-Enki, the (Uhmush-person) took as his beer 7 jars, 2 (measures) of barley, 1 garment, 1 bed, 1 chair. The (Umum-person) took 1 measure of barley. (5) The artisan had ‘‘prayer bread.’’ The men (in pairs?) had the ‘‘gate-food allotment.’’ (6) The house of the ruler, the field of the ruler, the house of the (ruler’s) wife, the field of the (ruler’s) wife, the house of the (ruler’s) children, the field of the (ruler’s) children bordered one on the other. (7) From the (northern?) boundary of Ningirsu (Lagash), as far as the sea ( the Gulf), there were inspectors. The (servile class called) ‘‘subordinate to the king’’ dug wells at the side of their fields and took possession of blinded people (for labor), they took blinded people for the irrigation ditches which were in the fields. These were the practices then. (8) When (the god) Ningirsu, heroic son of Enlil, gave kingship of Lagash to Uruinimgina and took his hand from among 36,000 men, he set aside what had been the destiny then. He took to himself the command which his lord Ningirsu spoke to him. (9) Boatman was removed from boat, herdsman was removed from donkeys and sheep, . . . was removed from overseer of fishers. Supervisor of grain storage was removed from 174 Social Justice and Reform the barley yields of the gudu-priests. Inspector of silver payments on account of white sheep and offering lambs was removed. Inspector of tax payments of temple administrators to the palace was removed. (The god) Ningirsu became owner of the house of the ruler and the fields of the ruler. (The goddess) Baba became mistress of the house of the (ruler’s) wife and the fields of the (ruler’s) wife. (The goddess) Shulshagana became owner of the house of the (ruler’s) children. (10) From the (northern?) border of (the god) Ningirsu to the sea ( Gulf) no one was inspector. (11) In order to entomb a corpse, (the Uhmush-person) took as his beer 3 jars, as his bread 80 loaves, 1 bed, 1 first-quality kid. The (Umum-person) took 3 (smaller) measures of barley. In the (place called) Gi-Enki, the (Uhmush-person) took as his beer 4 jars, his loaves of bread 240, 1 (measure) of barley. The (Umum-person) took 3 (smaller measures of) barley. The high priestess took one woman’s headband, 1 quart of fine aromatic, 420 loaves of bread. (12) The bread delivery is 40 hot loaves, the eating-bread is 10 hot loaves, the tray bread is 5 loaves of the ‘‘man who is summoned,’’ 2 large vessels and 1 regular vessel of beer is the portion of the cult singers of Lagash . . . 406 loaves, 1 large vessel and 1 regular vessel is the portion of the (other) cult singers. 250 loaves, 1 large vessel of beer is the portion of the old women who sing laments. (13) (From another text): If a man divorced (his) wife, the ruler took 5 shekels of silver; the courier took 1 shekel of silver. (14) Unreasonable liability(?) for stolen property is abolished; lost property is hung(?) at the city gate. (15) Women of former days (could?) have two men, (but) for women of these days, that unreasonable liability(?) is abolished. Text 4: Prices under Sin-kashid of Uruk Source: Frayne, Old Babylonian Period (see Text 1), 454–63. In his period of kingship, in the market values of his land, 3 gur of barley, 12 minas of wool, 10 minas of copper, 3 (measures of vegetable) oil cost 1 shekel of silver. May his years be years of abundance. Text 5: Tariff in the Laws of Eshnunna Source: Goetze, Albrecht. (1951–52). ‘‘The Laws of Eshnunna.’’ Annual of the American Schools of Oriental Research, 31, 24–25. 1 gur of barley is (priced) at 1 shekel of silver 3 quarts of oil are (priced) at 1 shekel of silver 12 quarts of vegetable oil are (priced) at 1 shekel of silver 15 quarts of lard are (priced) at 1 shekel of silver 4 quarts of pitch(?) are (priced) at 1 shekel of silver 6 minas of wool are (priced) at 1 shekel of silver 2 gur of salt are (priced) at 1 shekel of silver 1 gur of (a spice?) is (priced) at 1 shekel of silver Social Reform in Ancient Mesopotamia 3 minas of copper are (priced) at 1 shekel of silver 2 minas of refined copper are (priced) at 1 shekel of silver 175 Text 6: From the Coronation Prayer of Assurbanipal Source: Foster, Benjamin R. (1993). Before the Muses: An Anthology of Akkadian Literature. Bethesda, Md.: CDL Press, 713–14. . . . Just as grain and silver, oil, cattle, and salt (from the place called) Bariku are desirable, so too may the name of Assurbanipal, king of Assyria, be desirable to the gods . . . May the [resident] of Assur obtain 30 gur of grain for 1 shekel of silver, may the resident of Assur obtain 30 quarts of oil for 1 shekel of silver, may the [resident] of Assur obtain 30 minas of wool for 1 shekel of silver. May the [great] listen when the lesser speak, may the [lesser] listen when the great speak, may harmony and peace be established [in Assur]. Text 7: Reforms of a Neo-Babylonian King Source: Foster, Before the Muses (see Text 6), 763–66. . . . nor would he make a decision concerning them (the cripple or widow). They would eat each other like dogs. The strong would oppress the weak, while they had insufficient means to go to court for redress. The rich would take the belongings of the lowly. Neither governor nor prince would appear before the judge on behalf of the cripple or widow, they would come before the judges but they would not proceed with their case; a judge would accept a bribe or present and would not consider it (the case). They (the oppressors) would not receive an injunction (such as this): ‘‘The silver which you loaned at interest you have increased five-fold! You have forced households to be broken up, you have had fields and meadowland seized, families were living in front and back yards. You have taken in pledge servants, slaves, livestock, possessions, and property. Although you have had silver and interest in full, these (mortgaged properties) remain in your possession!’’ . . . For the sake of due process, he (the king) did not neglect truth and justice, nor did he rest day or night. He was always drawing up, with reasoned deliberation, cases and decisions pleasing to the great lord Marduk (and) framed for the benefit of all the people and the stability of Babylonia. He drew up improved regulations for the city, he rebuilt the law court . . . NOTES 1. Edzard 1976; for general discussion, see also Yaron 1993: 19–41. 2. Frayne 1989. 3. Adams 1981: 165; Weiss 1994. 4. Kraus 1971: 235–61. 5. Van de Mieroop 1992: 112–15. 6. Diakonoff 1982: 44–46. 7. Bottero 1961: 113–64. ´ 8. For the difficult matter of prices at this time, see Farber 1978; see also Snell 1982: 183–88. 176 Social Justice and Reform 9. Diakonoff 1956: 193–95 (takes a cautious position); Kramer 1963: 80–83; Von Soden 1954: 8–15 (‘‘the first social reformer’’). 10. Foster 1981. 11. Diakonoff 1958: 12–13. 12. Lambert 1965; Foster 1993: 763–66. 13. Lambert 1960: 110–15; Foster 1993: 760–62. 14. Lambert-Millard 1969; Foster 1993: 158–201. 15. Evans 1963: 20–26; Komoroczy 1976. ´ REFERENCES Adams, Robert McC. (1981). Heartland of Cities: Surveys of Ancient Settlement and Land Use on the Central Euphrates Floodplain of the Euphrates. Chicago: University of Chicago Press. Bottero, Jean. (1961). ‘‘Desordre economique et annulation des dettes en Mesopotamie, ´ ´ ´ ´ a l’epoque paleo-babylonienne.’’ Journal of the Economic and Social History of ` ´ ´ the Orient, 4–2, 113–64. Diakonoff, Igor M. (1956). Obscestvennyj i gosurdarstvennyj stroj drevnego Dvurec’ja ˇˇ ˇ ˇ Sumer. Moscow: Nauka. Diakonoff, Igor M. (1958). ‘‘Some Remarks on the ‘Reforms’ of Urukagina.’’ Revue d’Assyriologie, 52, 1–15. Edzard, Dietz O. (1976). ‘‘ ‘Soziale Reformen’ im Zweistromland bis ca. 1600 v. Chr.: Realitat oder literarischer Topos?’’ In J. Harmatta and G. Komoroczy (eds.), Wirt¨ ´ schaft und Gesellschaft im alten Vorderasien. Budapest: Akademiai Kiado. Evans, D. G. (1963). ‘‘The Incidence of Labour-Service in the Old Babylonian Period.’’ Journal of the American Oriental Society, 83, 20–26. Farber, Howard. (1978). ‘‘A Wage and Price Study for Northern Babylonia during the Old Babylonian Period.’’ Journal of the Economic and Social History of the Orient, 21–1, 1–51. Foster, Benjamin R. (1981). ‘‘A New Look at the Sumerian Temple State.’’ Journal of the Economic and Social History of the Orient, 24–3, 225–41. Frayne, Douglas. (1989). ‘‘A Struggle for Water: A Case Study from the Historical Records of the Cities Isin and Larsa (1900–1800 B.C.).’’ Bulletin of the Canadian Society for Mesopotamian Studies, 17, 17–28. Komoroczy, Geza. (1976). ‘‘Work and Strike of the Gods: New Light on the Divine ´ Society in the Sumero-Akkadian Mythology.’’ Oikumene, 1, 11–37. Kramer, Samuel Noah. (1981). History Begins at Sumer: Thirty-Nine Firsts in Man’s Recorded History. Philadelphia: University of Pennsylvania Press. Kraus, Fritz Rudolf. (1974). ‘‘Das altbabylonische Konigtum.’’ In P. Garelli (ed.), Le ¨ Palais et la royaute: Archeologie et civilisation. XIXe rencontre assyriologique ´ ´ internationale. Paris: Geuthner. Lambert, W. G. (1960). Babylonian Wisdom Literature. Oxford: Clarendon. Lambert, W. G. (1965). ‘‘Nebuchadnezzar: King of Justice.’’ Iraq, 27, 1–11. Lambert, W. G., and A. R. Millard. (1969). Atra-hasıs: The Babylonian Story of the ¯ ˘ Flood. Oxford: Clarendon. Snell, Daniel C. (1982). Ledgers and Prices: Early Mesopotamian Merchant Accounts. Yale Near Eastern Researches 8. New Haven: Yale University Press. Social Reform in Ancient Mesopotamia 177 Van de Mieroop, Marc. (1992). Society and Enterprise in Old Babylonian Ur. Berliner Beitrage zum Vorderen Orient 12. Berlin: Dietrich Reimer. ¨ Von Soden, Wolfram. (1956). Herrscher im alten Orient. Berlin: Springer Verlag. Weiss, Harvey. (1994). ‘‘Causality and Chance: The Genesis and Collapse of West Asian Society in the Late Third Millennium B.C.’’ In O. Rouault (ed.), Le Djezire et l’Euphrate Syrienne. Paris: CNRS. Yaron, Reuven. (1993). ‘‘Social Problems and Policies in the Ancient Near East.’’ In Baruch Halpern and Deborah W. Hobson (eds.), Law, Politics and Society in the Ancient Mediterranean World. Sheffield: Sheffield Academic Press. 14 Prophets ‘‘prophetic first recall the words of the prophets. I. ISRAEL’S PROPHETS AND SOCIAL JUSTICE As portrayed by Amos and his successors the Israelite society of the eighthseventh centuries suffers terribly from severe oppression of the poor, injustice, 180 Social Justice and Reform commercial dishonesty, and official indifference combined with love of ‘‘bribes’’ (actually fees paid for the issuance of writs and judgments [see P&M 127–28]). All of this is linked to the lifestyle of a new, well-to-do middle class. The central image is a familiar one, the blight of poverty amid affluence. Several examples should serve to demonstrate the point.2 Therefore because they have beaten the poor with their fists, though you have received from them choice gifts; you have built houses of hewn stone; but in them you shall not dwell. (Amos 5.11) Listen to this you who devour the needy, annihilating the poor of the land, saying, ‘‘If only the new moon were over, so that we could sell grain; the sabbath, so that we could offer wheat for sale, using an ephah [measure] that is too small, and a shekel that is too big, tilting a dishonest scale, and selling grain refuse as grain! We will buy the poor for silver, the needy for a pair of sandals.’’ The Lord swears . . . ‘‘I will never forget any of their doings.’’ (Amos 8.4–7) You must return to your God! Practice goodness and justice and constantly trust in your God. A trader who uses false balances, who loves to overreach, Ephraim [the Israelites] thinks, ‘‘Ah I have become rich.’’ (Hosea 12.7–9) Ah, those who plan iniquity and design evil on their beds; when morning dawns, they do it, for they have the power. They covet fields, and seize them; houses, and take them away. They defraud men of their homes and people of their land. (Mic. 2.1–2) Will I overlook in the wicked man’s house, the granaries of wickedness and the accursed short ephah? Shall he be acquitted despite wicked balances and a bag of fraudulent weights? Whose rich men [of the city] are full of lawlessness . . . I, in turn have beaten you sore . . . for your sins. (Mic. 6.10–13) Learn to do good. Devote yourselves to justice and the wronged. Uphold the rights of the orphan; defend the cause of the widow. . . . If, then you agree to give heed, you will eat the good things of the earth, but if you refuse and disobey you will be devoured [by] the sword. (Isa. 1.17, 19) Who of us can dwell with the devouring fire, he who walks in righteousness, speaks uprightly, and spurns profit from fraudulent dealings. . . . Such a one shall dwell in lofty security. (Isa. 33.14–16) For among My people are found wicked men, who lurk, like fowlers lying in wait; they set a trap to catch men. As a cage is full of birds, so their houses are full of guile; that is why they have grown so wealthy. . . . They will not judge the case of the orphan, nor give a hearing to the plea of the needy, Shall I not punish such deeds. (Jer. 5.26–28) Thus, if a man is righteous and does what is just and right. . . . If he has not wronged anyone: if he has returned the debtor’s pledge to him and has taken nothing by robbery; if he has given bread to the hungry and clothed the naked; if he has not lent at interest; if he has abstained from wrongdoing and executed true justice between man and man . . . Such a man shall live—declares the Lord God. (Ezek. 18.5, 7–9) Prophets and Markets Revisited 181 There can be little doubt that the prophets wished to reform an unjust society. Given their emphasis on the plight of the ‘‘poor,’’ ‘‘weak,’’ and ‘‘needy,’’ it is clear that they were thinking of welfarist economic reforms.3 Social injustice, the prophets believed, had to be eliminated by a resolute act of social will. And this will—that is, the necessary force—was to be supplied by the rulers. We have the explicit testimony of the Bible that King Hezekiah was at least influenced by the social reformer Micah (Jer. 26.18–19), while Jeremiah 22.11– 16 relates that King Josiah ‘‘dispensed justice and equity’’ and ‘‘upheld the rights of the poor and needy.’’ But this is only the tip of the iceberg of prophetic influence in royal circles. Isaiah was consulted by kings Ahaz (Isa. 7.1–9) and Hezekiah (Isa. 37, 38) and composed royal records of kings Uzziah and Hezekiah (2 Chron. 26.22; 32.32), and it is possible that Amos secured a similar position under Jeroboam II. Jeremiah was consulted by a representative of King Zedekiah (Jer. 21.1–2) and was an associate of the most powerful in the land. Zephaniah, very likely, was a powerful priest and relative of King Josiah (cf. P&M, chap. 13). The political program of the prophets as spelled out in the book of Deuteronomy was accepted and implemented in ca. 751 by Israel’s Jeroboam II and by the Judean kings Hezekiah and Josiah in ca. 716/715 and 621, respectively (cf. P&M, chap. 16). But are there precedents in the ancient world for a welfarist reform agenda? This question will be explored in Section 3 of this chapter. First, however, it is necessary to consider the ideological underpinnings of ancient social reform. II. THE INTELLECTUAL/IDEOLOGICAL FRAMEWORK OF ANCIENT SOCIAL REFORM Ancient intellectuals, Near Eastern and Greek, were well aware that societies periodically experienced ‘‘dark ages’’ of economic and social retrogression. To judge by the Uruk Lament (twentieth century) and the myths of Atrahasis (early seventeenth century) and Erra (earlier first millennium), ancient Mesopotamian intellectuals were inclined to attribute cyclic socioeconomic disasters or ‘‘deluges’’ (Akkadian abubu, CAD s.v.) to overpopulation or to economic evils, ¯ including, probably, the striving for material betterment and economic oppression. The appropriate interpretation depends on how one understands the motif of men (or lesser gods) disturbing the gods (or greater gods) with their ‘‘activity’’ or ‘‘noise’’ (Akkadian rigmu/(c)huburu or (c)habaru) (CAD (c)huburu ¯ ¯ ¯ B). In the Atrahasis myth (Lambert and Millard 1969) and the Sumerian myth of Enki and Ninmah the lesser gods had to do hard labor digging canals under the supervision of the greater gods (Jacobsen 1987: 153–55; Komoroczy 1976). ´ Their ‘‘noise’’ (cries of outrage) caused the awakening of the great god Enlil or Enki. Here we find the themes of activity and oppression rather than (or in addition to) overpopulation. Pettinato sees a connection between the ‘‘noise’’ in the Mesopotamian myths and the se‘aqah (‘‘outcry’’) heard by the Lord in Genesis 18.21 and the story 182 Social Justice and Reform of Sodom and Gomorrah in Genesis 19 (Pettinato cited by J. J. M. Roberts 1985: 91). To this example we may add Isaiah 5.7: ‘‘And He hoped for justice, but behold, violence. For righteousness but behold an outcry.’’ The word outcry, according to Von Rad (1972: 211), is a technical legal term designating the scream for help of one who suffers a great injustice. The cry was (c)hamas ¯ ¯ ‘‘Foul play!’’ (Jer. 20.8; Job 19.7), a term that has the same force as Akkadian (c)habalu (‘‘to oppress, wrong, deprive a person of something to which he has ¯ a right’’) (Speiser 1964: 117, n.5; CAD A.1). Finkelstein (1956: 329, n.7) who translates the Hebrew word as ‘‘violence’’ notes that it occupies a place in the biblical story of the flood (Gen. 6.5, 11–12) that is analogous to (c)huburu in ¯ the Mesopotamian literature.4 Shupak (1992: 11, n.44) adds several Israelite examples: The woman whose son Elisha resurrected ‘‘cried’’ to the king for having taken her field and home (2 Kings 8:3, 5). Another woman, the wife of one of the sons of the prophets, ‘‘cried’’ to Elisha about her creditor who came to take her children into slavery (2 Kings 4.1). The poor man whose garment was taken as pledge ‘‘cries’’ to God (Exod. 22.26). Shupak (1992: 11) finds a quite similar pattern in Egypt: ‘‘From the terms nis and nkhi, it appears that the complaint or legal claim is close to the semantic field of ‘cry,’ ‘call.’ The wronged man addresses his cry to the judge charged with defending justice.’’ A further indication that the ‘‘activity,’’ ‘‘noise,’’ and ‘‘outcry’’ that disturbed the gods might have an economic/commercial nature or origin is that the Akkadian (c)huburu also means ‘‘a type of large storage vessel’’ and ‘‘association, ¯ trade association.’’ Similarly, in Arabic the root (c)hbr means ‘‘unite, be joined’’ and ‘‘tell, report,’’ a meaning that, as Cazelles (1977: 193) observes, ‘‘suggests some kind of audible phenomenon.’’5 With respect to the Greek evidence, we might begin by noting the myth of Pandora and the pithos (‘‘storage vessel’’) from which the evils of the world were ‘‘scattered’’ (Hesiod, Works and Days, 90–104). Even more striking is the apparent similarity of Akkadian (c)huburu and Greek hybris (‘‘violence, lust, ¯ outrage’’) (LSJ s.v.). Chantraine (1968 s.v.) states that the etymology of hybris is inconnue. The poet Theognis (perhaps during the first half of the sixth century B.C.E.) virtually identifies hybris with the striving for kerdos (‘‘personal gain, profit’’) and with koros (‘‘insatiability’’) of wealth, and he refers, significantly I suspect, to his fear that ‘‘perhaps a wave will swallow the ship’’ (Nagy 1985: 23, 42, 45, 53). Nagy (1985: 52, 57) adds citing Athenaeus, that the prime manifestation of the hybris of the city of Kolophon was ‘‘the luxuriance [tryphe] ˆ of excessive wealth,’’ and he notes that for Hesiod (Works and Days, 213) the hybris of Perses manifests itself in his striving for excessive wealth. Against this background it is easier to grasp why the motive force of social justice in the ancient Near East is economic oppression. The social justice/social reform scenario requires innocent victims, materialistically motivated evildoers, and righteous saviors who strike the evildoers down and rescue their victims. The ancient Near East designated victims by terms more or less convention- Prophets and Markets Revisited 183 ally translated as ‘‘orphan,’’ ‘‘widow,’’ ‘‘poor person,’’ and ‘‘peasant.’’ The referents are much less real-world social groupings than intellectual constructs. That is, the terms refer to the ideal victim. This inference is amply supported in Mesopotamian social history by the mysterious mushkenu, a term found in ¯ texts from the earliest periods. According to Dandamaev (1984: 643–44), who cites Speiser, the term is derived from ‘‘the verb shukenu ‘to bow down,’ ‘to ˆ prostrate oneself,’ and, hence, came to have such nuances as ‘wretched, poor, humble, weak’.’’ Dahood (1981: 313) suggests that the literal meaning of the term may be ‘‘the one who emits laments.’’ Dandamaev (1984: 643) notes that a ‘‘great number of studies maintaining various opinions have been devoted to it [the mushkenu problem].’’ The complexity of the problem and the inconclu¯ siveness of the studies arise, I submit, from the fact that mushkenu is an abstrac¯ tion: the ideal victim, not a reference to persons with a concrete socioeconomic status (cf. Westbrook in this volume). This is equally true of Amos’ dal (Amos 2.7, 4.1, 5.11, 8.6). The Hebrew word dal is formally related to Akkadian dullu ‘‘misery,’’ ‘‘corvee work,’’ ‘‘work’’ (CAD s.v.). In Amos’ hands the dal is ´ transformed from ‘‘free person who needs to work for a living’’ into ‘‘totally helpless person’’ (Fabry 1977: 222).6 The names assigned to the economic oppressors are more varied and less transparent than those given to their victims. Nevertheless, it seems clear that the oppressor is the businessperson in the inscriptions attributed to Nebuchadnezzar (‘‘King of Justice’’) (below). The writings of the classical prophets (above) very obviously target merchants and traders. One of their lines of attack merits special attention. In the historical books of the Bible the terms Canaanite and Canaan are often pejorative. The hostile attitude toward the inhabitants of the ‘‘promised land’’ is best understood as a reflection of the heated competition for cultic supremacy between the ‘‘jealous god’’ Yahweh and Canaan’s other gods (see Exod. 23.23–33; 33.2–3; 34.11–16; etc.; Lemche 1991: esp. 112–13). The classical prophets traded on this hostility by transferring the negatively loaded ethnic/geographic term Canaanite/Canaan to Israelites generally and, more specifically, to Israelite businesspersons. As Lemche (1991: 135–39) has pointed out, this process begins with Hosea 12.8–9, wherein the prophet writes the equation: (northern) Israel (Ephraim) foreign Canaanite merchant: ‘‘A Canaanite (trader) who uses false balances, who loves to overreach. Ephraim thinks, ‘Ah I have become rich.’ ’’ In an obvious reference to Nebuchadnezzar and Israel’s Babylonian exile, Ezekiel 17.4 adds: ‘‘He plucked its highest twig and carried it off to the land of Canaan (land of traders), planted it in a city of merchants’’ (Lemche 1991: 131). Zephaniah 1.11 writes the pejorative equation in the following form: ‘‘Wail, you inhabitants of the Lower Town of Jerusalem, for all the Canaanites (merchants) are destroyed, and the dealers in silver are all wiped out’’ (Lemche 1991: 140). In the ancient Near East the savior hero is a nation’s ‘‘good shepherd’’—that is, its king. Edzard (1974: 156) explains that 184 Social Justice and Reform The ancient Orient paints a picture of the ruler as a just, kind shepherd. Just as the shepherd was responsible for the proliferation and well-being of his flock, so also was the ruler responsible for the welfare of his people. He looks out for the well-being of the flesh of the country, leads the people as well as the animals to green pastures, protects since Uru-KA-gina [a Sumerian ruler dated 2364–2342] the widows, and orphans, so that they will not be sold as slave to the rich and mighty, the king protects the weak from the strong so no wrong will be done to them. (Translation mine) Thus, for example, a king of Isin, probably Enlil-bani (1860–1837), wrote that he had ‘‘established justice and righteousness’’; and speaking of the mushkenu, ¯ he added that ‘‘I sought out nourishment for them like sheep, and fed them with fresh grass’’ (Postgate 1992: 239). A hymn praises another king of Isin, LipitIshtar (1934–1924), in the following terms: ‘‘Lipit-estar you rage against the ˇ enemies, from evil and oppression you know how to save people, from sin and destruction you know to free them. The mighty do not perpetrate robbery, and the strong do not make the weaker ones into hirelings—Thus you established justice in Sumer and Akkad . . . O leading shepherd, youthful son of (the god) Enlil, Lipit-estar be praised! (Vanstiphout 1978: 38–39). ˇ Again, an inscription of the Babylonian king Nebuchadnezzar II (604–562) or one of his immediate successors tells that the rich were oppressing the poor until a king devoted to justice went into action: The strong used to plunder the weak, who was not equal to a lawsuit. The rich used to take the property of the poor. Regent and prince would not take the part of the cripple and widow before the judge . . . [several obscure lines] ‘‘The silver which you have loaned on interest you have multiplied five times. You have broken up houses, you have seized land and arable land.’’ . . . He [the new king] was not negligent in the matter of true and righteous judgment, he did not rest night or day, but with council and deliberation he persisted in writing down judgments and decisions and arranged to be pleasing to the great lord [god] Marduk, and for the betterment of all the peoples and the settling of the land of Akkad. He drew up improved regulations for the city, he built anew the law court. (Lambert 1965: 8) Let us now examine the facts of reform. III. WELFARIST ECONOMIC REFORM IN THE ANCIENT NEAR EAST Douglass North (1985: 560) believes that a distinctive feature of the premodern world is that ‘‘the state played no, or a very nominal, role, or was simply extortionist in its relationship to economic activity.’’ But a closer look at the historical record shows that the oldest civilizations experienced lengthy periods of unfettered market activity, even affluence, interspersed with periods of pervasive, not obviously extortionate, economic regulation by the state. The evidence for welfarist type reforms is reasonably extensive in Babylonia Prophets and Markets Revisited 185 during the Old Babylonian period (1900–1600), whose most famous representative is Hammurabi (1792–1750). Prior to the reigns of Hammurabi in Babylon and his contemporary Rim-Sin in Larsa, there is evidence that commercial life had reached a high level of development. It was the custom of Rim Sin, Hammurabi, and his successors to issue edicts of ‘‘social justice/equity’’ (Lemche 1979). These mısharum edicts may have been issued several times in one reign ¯ and at irregular intervals (Westbrook 1971a: 216–17; cf. Balkan 1974: 32–33). They mainly served to remit certain types of obligation and indebtedness. One edict excludes aliens from the benefit of a debt release and calls on creditors not to dun debtors for payment (cf. Westbrook in this volume). There are numerous references to the decrees in contracts, letters, and year formulae (Olivier 1984; cf. Balkan 1974: 33). Contracts for the sale of real estate mention that the transaction was concluded after the mısharum, obviously to protect the pur¯ chaser against future litigation based on the mısharum. ¯ There were also more permanent measures. Their nature is not entirely clear, but they probably involved government intervention in the sale and rental of houses and fields; minimum wages; maximum prices of barley, wine, bricks, and other commodities; and maximum interest rates. A business letter from the reign of Hammurabi’s son makes reference to ‘‘the wage of the hired laborer written on the stele’’ (CAD s.v. naru A.1), possibly Hammurabi’s. ˆ The evidence demonstrates that Near Eastern governments possessed the capability to enforce their economic measures and tried to do so. The point is illustrated by a text from the time of Hammurabi or one of his successors. In this text an individual petitions the ruler for the return of title to real estate that he purchased but was deprived of by a royal mısharum edict. The sale tablets ¯ were reviewed by a government official, and a decision was rendered. Finkelstein (1965: 242) concludes: ‘‘Astounding as it must appear to our normally skeptical eyes, there is no way of discounting the factual account of our text that at the promulgation of the mısharum formal commissions were established ¯ to review real estate sales and that they executed their mandate in a presumably conscientious manner.’’ IV. WELFARIST REFORM IN ISRAEL Given this historical background, it should not be difficult to believe that Israel’s rulers might also introduce welfarist reforms. It is true that we have no surviving mısharum edicts as we do for Mesopotamia. However, we do have at ¯ least one fragment. In ca. 588 during Babylon’s first invasion of Judah, King Zedekiah made a covenant ‘‘that everyone should set free his Hebrew slaves, both male and female, and that no one should keep a fellow Judean enslaved’’ (Jer. 34.8–9). According to Jeremiah (34.11) the owners repudiated this mıs¯ harum act. More important, we have a major source in Deuteronomy’s laws. As Weinfeld (1985: 317–18) points out, while these laws ‘‘are colored with ideological and utopian colors . . . this does not give us the right to dismiss the laws 186 Social Justice and Reform as pure fiction.’’ Basically, Deuteronomy (meaning ‘‘repeated law’’ or ‘‘second law’’) is a revision and expansion of the old divine law code in favor of the poor and underprivileged. There is little doubt that Deuteronomy should be associated with the ‘‘scroll of teaching’’ that, during Josiah’s reign (640–609), was ‘‘found’’ in the course of repairs of the Jerusalem temple by the priest Hilkiah (2 Kings 22). However, the presence of a variety of northern features has led a number of scholars to conclude that the basic core of Deuteronomy originated, not in seventh-century-Judah, but in eighth-century Israel. In the first place, the book obviously echoes the views and words of the northern prophet Amos, who was active in the first half of the eighth century (P&M, 132–33, 198–99). Further, several kinds of evidence make it reasonable to credit the authorship of Deuteronomy to the northern prophet Hosea, sometime in the second half of the eighth century (P&M, 194–98). The Bible provides several striking indications that the Deuteronomic program was not only first composed but was also implemented in the northern kingdom in ca. 751 (P&M, 213ff.). Now, let us set forth in summary form the character of Deuteronomy’s welfarist thrust. Deuteronomy 14.28–29 commands that, triennially, a tenth part of agricultural output shall be put aside for the poor: ‘‘Every third year you shall bring out the full tithe of your field of that year but leave it within your settlement. Then the Levite who has no hereditary portion as you have, and the stranger, and the fatherless, and the widow in your settlement shall come and eat their fill.’’ Apparently, Deuteronomy 15.1–3 went beyond the earlier Mesopotamian practice by incorporating the mısharum act in the Israelite constitution: ‘‘Every sev¯ enth year you shall practice remission of debts. This shall be the nature of the remission: every creditor shall remit the due that he claims of his neighbor or kinsman, for the remission proclaimed is of the Lord. You may dun the foreigner; but you must remit whatever is due you from your kinsmen [whatsoever of yours is with your brother your hand shall release].’’ The wealthy are enjoined not to ‘‘harbor iniquitous thoughts when . . . the seventh year is near and look askance at your needy countryman and give him nothing’’ (Deut. 15.9). Exodus 21.2–3 states that ‘‘when you acquire a Hebrew slave, he shall serve six years; in the seventh he shall go free, without payment.’’ It should be understood that the ‘‘Hebrew slave’’ was not a captured but a contractual slave— he had either been enslaved for debt or had sold himself into slavery. Throughout antiquity the ability of an individual to borrow on the security of his own person or to sell himself or a family member into slavery was a mainstay of the capital market. Self-sale was especially important in financing training and migration (see P&M, 68–72). Exodus’ provision is revised by Deuteronomy (15.13), which mandates that when the ‘‘Hebrew man or woman’’ is set free he shall not go ‘‘empty-handed’’ but instead be supplied ‘‘out of the flock, threshing floor, and vat.’’7 King Zedekiah’s mısharum act in ca. 588 (see above) was ¯ probably repudiated because it mandated emancipation with compensation for Prophets and Markets Revisited 187 slaves who had served less than the legally required six years (see P&M, 234– 35). Deuteronomy 19.14 (see also 27.17) warns the Israelites that ‘‘you shall not move your neighbor’s landmarks, set up by previous generations, in the property that will be allotted to you in the Land that the Lord your God is giving you to possess.’’ The formulation is rather obscure; but I suspect, with several other scholars, that the aim is to outlaw the sale of land, or at least land in ancient Israelite settlements. Scholars are agreed that Exodus 22.24–25 is the Bible’s earliest legal statement regarding the charging of interest on loans: ‘‘If you lend silver to My people, to the poor who is in your power, do not act toward him as a creditor: exact no interest from him. If you take your neighbor’s garment on pledge, you must return it to him before the sun sets. . . . ’’ A prohibition on collecting interest from poor countrymen is understandable, perhaps even rational, within the context of early Israelite society, in which, presumably, production was mainly agricultural and for direct consumption. As Posner (1980: 15, 23) has pointed out, societies in this position have sought to provide ‘‘hunger insurance’’ by encouraging generosity toward neighbors and kinsmen. In this context a loan is often just the counterpart to the payment of an insurance claim in more advanced societies. But this line of explanation cannot explain why Deuteronomy (23.20–21) calls for more stringent and comprehensive barriers to the charging of interest, during the affluent, market-oriented eighth and seventh centuries: ‘‘You shall not lend upon interest to your brother: interest on silver, interest on victuals, interest on anything that is lent upon interest. You may lend to a foreigner on interest; but to your brother you shall not lend upon interest.’’ No mention is made of the economic status of the borrower, and therefore, the law seems to rule out all interest-bearing loans including consumption loans to the well-off and commercial loans. The blow to the Israelite economy might have been mitigated by access to, say, the Phoenician loan market. Or, perhaps, resident aliens gave loans at interest to Israelites much as in medieval times Jews lent to Christians and vice versa. But even the most cursory look at medieval European history starkly reveals the fragile nature of such expedients. In the absence of reasonably inexpensive international enforcement, loan defaults were not infrequent, while Jews and Lombards were hounded, robbed, and ultimately expelled. Any attempt to enforce the Deuteronomic regulation would have raised interest rates or would have led to credit rationing. Obviously, a ban on interest would have made it difficult for small farmers to acquire capital to irrigate their land.8 In the standard translation, Deuteronomy 15.1–3 calls for the cancellation of debts every seventh year. But the prohibition of interest in Deuteronomy 23.20 would have eliminated the main motive for lending. It would appear that the seventh-year ‘‘release’’ actually applied to the ‘‘pawns’’ held by the creditor— that is, to the labor or land pledged to the creditor in lieu of interest. Evidence of this practice is provided by a document (the Mesad Hashavyahu letter) dating 188 Social Justice and Reform from the time of King Josiah. It records a complaint to the governor of a Judean fortress from the head of a team of reapers that the reaper’s garment was seized (see P&M 238–39). The garment is obviously a pledge (see Exod. 22: 24–25), and the failure to return it probably indicates that the reapers had not performed the agreed upon harvesting services. To the extent that ‘‘interest on money, interest on victuals, interest on anything that is lent upon interest’’ is prohibited, economic actors can be expected to seek out second-best alternatives such as the disguise of illegal interest payments as the performance of labor (or land) services. If this interpretation of the Judean document is valid, we have indirect evidence that the Judean state sought to enforce the interest rate regulations and, further, perhaps, that Deuteronomy 15.1–3 sought to discourage disguised interest rates by means of a seventh-year remittance. It should be added here that Deuteronomy 16.18–20 deals directly with the problem of bureaucratic resources by calling for the appointment of (salaried?) magistrates (judges) and officials (recorders? bailiffs?) in every town. Such officers would then be available to settle controversies ‘‘over homicide, civil law, or assault—matters of dispute in your courts’’ (Deut. 17.8–9). The availability of bureaucratic resources for enforcing the reform is also indicated by the reaper’s complaint to a local official. Leviticus 25.17–26, generally referred to by scholars as the ‘‘Holiness Code,’’ sets forth several economic reforms (for an excellent commentary, see Levine 1989). Clearly, this material represents a reworking of the laws in Deuteronomy (see Levine 1989: 273–74). Kaufman (1984: 281–82) notes that ‘‘Deuteronomy and Leviticus are . . . mutually incompatible systems, a fact that prohibited the practical acceptance of either when the Pentateuch was adopted as the torah of Judaism.’’ But if this material is to be properly utilized, it must be dated. It has been established that there are striking affinities between Ezekiel and the ‘‘Holiness Code.’’ This code contains expressions that otherwise occur in Ezekiel alone. Indeed, the similarities are so striking that several scholars have concluded that Ezekiel was the author or compiler of the ‘‘Holiness Code.’’ This analysis would place the Code of Leviticus in the early sixth century. In this event, the provision in the ‘‘Holiness Code’’ regarding interest-bearing loans takes on a new dimension of significance: ‘‘And if your brother be waxen poor, and his means fail with you; then you shall uphold him; as a stranger and settler shall he live with you. Take no interest [neshekh] or increase [tarbıt and marbit]; but ¯ fear your God; that your brother may live with you, you shall not give him your money upon interest, nor give him your victuals for increase’’ (Lev. 25.35–38). Two points stand out. First, like Exodus, but unlike Deuteronomy, Leviticus makes explicit reference to the economic status of the borrower. Second, while Exodus and Deuteronomy both use the term neshekh, only Leviticus adds the additional terms tarbıt and marbit. The last two terms are translated as ‘‘in¯ crease’’ and are understood to refer to the collection of accrued interest, while neshekh, which means ‘‘bite,’’ is taken to refer to the deduction of interest in advance. What happened, I propose, is that in the years following Josiah’s en- Prophets and Markets Revisited 189 forcement of the Deuteronomic law code, the Judeans learned the hard way that a blanket provision on interest is irrational and suicidal, so they retreated to the earlier provision of Exodus. On the other hand, they discovered that the word for interest in Exodus and Deuteronomy, neshekh (‘‘bite’’), opened an etymological loophole. Those who wished to lend and borrow legally insisted that only the deduction of interest in advance was banned. The argument was settled by adding the additional terms tarbıt and marbit. ¯ Perhaps the damaging effects of a total ban on the sale of lands, or ancestral lands, was also perceived at this late date, for the ‘‘Holiness Code’’ does not, as does Deuteronomy, refer to the sin of moving ancient landmarks. Instead, the ‘‘Holiness Code’’ (Lev. 25.8–28) introduces a year of Jubilee (yovel, literally ‘‘ram’’ or ‘‘ram’s horn’’) when ‘‘each of you shall return to his holding’’ and makes ‘‘provision for the redemption of land.’’ It is not entirely clear whether the redemption provision is available only to those who were poor at the time they sold their land. Perhaps such a provision might have been enforced by declaring certain years as years of poverty or ‘‘bad prices,’’ a practice noted in third millennium Sumer and first millennium Assyria. In second millennium Egypt we hear of ‘‘the year of the hyena when people were hungry.’’ Depending on how it was interpreted, the land redemption provision could have operated against long-term capital improvements, but it nevertheless would represent an improvement as compared to a total prohibition on land sales. The net effect of the Deuteronomic reforms of the eighth and seventh centuries is difficult to ascertain. At the very least, they would have slowed Israel’s rate of economic growth. At the other extreme, the resource misallocations resulting from attempts to eliminate or inhibit land and capital markets and the work incentive effects of welfare payments had the potential to reduce the standard of living in absolute terms. The prophets also damaged the Israelite economy by undermining the oath, antiquity’s central contractual instrument. Given a world of slow communications and limited public enforcement of contracts, especially in international transactions, business persons lowered their costs of transacting by relying on promises witnessed by gods that were, by reason of this witness, largely self-enforcing (see Silver 1985: 14–18). But for Amos (2.6– 8) to swear a commercial oath was to ‘‘profane God’s name’’ (cf. Jer. 34.13– 16). The responses of the average Israelite to economic regulation were probably not so dramatic as those that he made to the attempt to convert him to the worship of social justice via cult centralization. Nevertheless, the effects of the economic policies must have added to the disenchantment and alienation of the masses and must have made a contribution to the destruction first of Israel and, finally, of Judah. Why, then, did the kings of the Israelites agree to implement such counterproductive policies? The answer that comes immediately to mind is that the kings of Israel/Judah—and, earlier, of Babylonia, did not understand elementary economic principles and, consequently, were not aware that these policies would damage their economies. It is probably true that the kings were naive about 190 Social Justice and Reform economics. Nevertheless, this line of explanation fails to recognize that ignorance is a constant. Why did the kings adopt the harmful policies when they did and not earlier? V. THE ROLE OF TEMPLE CULTS IN ANCIENT SOCIETY9 It is well understood that as the gods offered safe and honest dealing—an implicit surety or guarantee—many temples of the ancient Near East and GrecoRoman world served as places of worship and centers of local and international commerce. Merchants made contracts and settlements and safely stored their valuables in temples. Some deities openly combated commercial opportunism (self-interest pursued with guile) and lowered transaction costs by actively inculcating professional standards. The protection enjoyed by visitors to marketplaces was extended to ports by means of a nearby temple. Commerce was also facilitated by the construction of temples at international borders, especially where, like islands and ports, they were well demarcated geographically. Perhaps the most important contribution of gods and their temples to ancient society was the oath. Oaths involving property transfers and other civil and criminal matters were regularly sworn in temple courtyards before images or symbols of the host gods. In the words of the Egyptologist J. A. Wilson (1948: 156) the oath ‘‘called upon the name of a god or upon the god-king [in Egypt] and . . . therefore assumed very serious obligations vis-a-vis a force of far` reaching intelligence and penalizing power.’’ A Sumerian proverb puts the matter nicely: ‘‘An (unfavorable) legal verdict is acceptable, (but) a curse is not acceptable.’’ In short, by means of the oath-curse mechanism the temples of antiquity provided a measure of social control otherwise prohibitively expensive or unavailable in a world of high costs of communication. In addition, the trust given to the gods by the populace permitted many temples to function as relatively efficient financial intermediaries or (possibly) banks and, thereby, to improve the allocation of resources in their societies. On the one hand, the temples were able to supplement tithes, donations, land rents, fees to keep valuables safe, and income earned by directly participating in agriculture and industry by attracting private deposits at relatively low (possibly zero) interest cost, while, on the other hand, the natural reluctance of debtors to default on loans given by gods or priests operated to lower both contracting costs and interest rates. The temples of antiquity were also centers devoted to the collection and preservation of economically and socially valuable knowledge. Understandably the views of the gods on economic and social issues as expressed by their cultic spokespersons influenced ancient public policy, just as in later times. Beyond this, however, the gods possessed a formalized or constitutional role. In Mesopotamia, kings often boasted that a god (e.g., Ningursu) ‘‘took him by the hand,’’ meaning that the god approved his ascension to the throne (e.g., Ur-Nammu) or even selected him to rule (e.g., Urukagina). The joint participation of gods and kings in issuing codes of law is well known in Prophets and Markets Revisited 191 Hammurabi’s Babylonia and, indeed, throughout the ancient Near East. Social reforms such as the remission of debts were often announced by means of cultic symbols—the raising of the torch or the blowing of the ram’s horn. Less concretely, but more generally, it appears that in the Near East the governmental structures of humans and gods had to be congruent. One of the gods, the ‘‘divine counselor,’’ advised the gods; and his priest, called ‘‘father’’ or ‘‘steward,’’ advised the king. While the Bible includes references to a divine council, such as we find in Mesopotamia, there is no conclusive reference to an office of ‘‘divine counselor.’’ Nevertheless, the reflections of a priest/royal advisor at the Israelite court are numerous and unmistakable. We know, first of all, that the prophet Samuel ‘‘told the people the manner of the kingdom and wrote it in a book and laid it before the Lord’’ (1 Sam. 10.25). Moreover, when, in 2 Samuel 24, King David conducts a census, no doubt as a prelude to imposing new taxes, he is opposed by ‘‘the prophet Gad, David’s seer’’ (24.11; emphasis added). Isaiah undoubtedly spent part of his career as royal advisor, and I believe that Amos held this role in the northern kingdom. More concretely, Deuteronomy 17.14–15, the law book of the prophetic revolution, permits the Israelites to establish a monarchy, but the king must be one ‘‘whom the Lord thy God shall choose.’’ Clearly, a cultic input is demanded. The image of the King under Torah (i.e., under the cult) is stressed by the selection of motifs that suggest the dependence and subordination of the king (Kenik 1983: chap. 7). Before King Josiah of Judah initiated his welfarist and cultic reforms he read to the assembled populace ‘‘all the words of the book of the covenant which was found in the house of the Lord [by the priest Hilkiah, no doubt, Deuteronomy]. And the king . . . made a covenant before the Lord, to walk after the Lord, and to keep His commandments, and His testimonies, and His statutes, with all his heart, and all his soul, to confirm the words of this covenant that were written in this book’’ (2 Kings 23.2–3).10 So, then, why did the kings implement the perverse reforms put forward by the cultic spokespersons, the prophets? Because they believed that the prophets conveyed the word of God or because they thought it was suicidal to oppose them or because they thought it was good politics to go along with the reforms. The gods, we must understand, handed the king the ‘‘scepter of justice’’; and if—and only if—he used it as they wished could he count on their blessings for a long and prosperous reign (Olivier 1979).11 But again, this line of explanation is not intellectually satisfying. In the earliest Israelite literature Yahweh is a national god concerned primarily with the military security and material prosperity of his people. Threats of punishment and doom arise only in response to the worship of foreign gods whose exemplars are the Baalim. This perspective is radically altered by the classical prophets of the eighth century: Yahweh is transformed from a national god to a god of social justice threatening his own worshippers with destruction if they do not alleviate the plight of the poor. Why did this prophetic revolution take place 192 Social Justice and Reform when it did? The fact that similar transformations have taken place in other places and times indicates that Israel’s experience is not completely idiosyncratic and encourages the social scientist to seek a systematic explanation. VI. AFFLUENCE AND ALTRUISM A central theme of my 1980 study on Affluence, Altruism, and Atrophy (AA&A) is that altruism or the taste for helping others is one of the higher needs described by the psychologist Abraham M. Maslow. Review of a substantial body of behavioral evidence together with an examination of the implications of consumer choice theory12 suggests that rising income markedly increases the demand for altruistic consumption. Consideration of historically affluent societies strongly suggests that the increased demand for altruistic consumption takes, in large part, the form of state actions intended to improve the lot of the poor. The above considerations are quite relevant for our present theme. The altruistic transformation of Israelite cult and state took place against the background of increasing affluence. During the eighth and seventh centuries, specialized production centers emerged and applied mass-production techniques, most notably in the areas of ceramics and residential housing. Israelite agriculture exported its products and displayed notable technical sophistication, including a rather remarkable adaptation of the desert environment of the Negev. We find growing use of stone in building, warehouse facilities, firms with complex managerial structures, brand names, land consolidation (probably in the interests of exploiting new commercial opportunities), and the development of significant population centers such as Jerusalem and Samaria. During this period IsraelJudah also expanded territorially, gaining control over Bashan’s great granary, over parts of the fertile Philistine Plain, over ports, and over the two major north-south highways. The new wealth was consumed in a variety of forms. There was a significant extension in the quantity and quality of housing and other consumer durables. Second, the average Israelite enjoyed a diet that was tastier as well as more varied and nutritious. True bread (raised or leavened bread) was substituted for hard barley-cakes and gruel, and finely sifted white flour for the coarser varieties. Meat consumption also increased, as did its quality with the substitution of beef for mutton and of fattened for unfattened animals. Affluent Israelites, being necessarily ‘‘poor’’ in terms of modern amenities, chose their bundles of luxuries accordingly. They participated in great feasts, made lavish provision to memorialize their ancestors, and gave large public and cultic donations. (Note Hos. 10.1: ‘‘When his fruit was plentiful, he made altars aplenty; when his land was bountiful, cult pillars abounded.’’) Affluent Israelites enjoyed their many children, winter and summer homes, fine artwork, gardens, songs, and dramas and archaeological objects; they concerned themselves with wisdom and questions of human character and duty. And, of course, they sought to improve the position of those less fortunate than themselves. Prophets and Markets Revisited 193 CONCLUSION: ANCIENT ISRAEL WAS DONE IN BY RATIONALLY IGNORANT AFFLUENT CITIZENS The kings of Israel/Judah implemented altruistic social reforms at the urging of the classical prophets. The prophets, and the cult generally, were responding to the desires of the affluent Israelites. Although this element is not entirely absent, the struggle for social justice should not be seen as a confrontation between the wealthy and the royalty. Rather, the wealthy, royal and nonroyal, sought with the guidance of the prophets to employ the state power to nullify the laws of economy and society. The elite was talking to itself. The affluents did not understand the principles governing social and economic life, and they had no incentive to learn what was then known by intellectuals about these principles. As Schumpeter (1950: 215) observed: ‘‘Without the initiative that comes from immediate responsibility, ignorance will persist in the face of masses of evidence.’’ Given the fact that masses of evidence were not available to the ancients and the difficulties of understanding the little that was known, even the most altruistic person would conclude that his cost of becoming informed about the effects of social policies would exceed the expected return in social improvement.13 To the ancients, and many moderns, the solutions to the problems of poverty and exploitation put forward by the classical prophets seemed to be obviously correct and to embody good common sense. The affluents, then as now, saw no reason to delve more deeply into the counterarguments put forward by other intellectuals. The latter, after all, were obviously flinthearted reactionaries. Those cultic officials and intellectuals who refused to support the lofty goals of the prophetic revolution were branded as ‘‘false prophets,’’ and, in one way or another, they disappeared from the scene. So in the end did ancient Israel. But in reaching this end the Israelites might console themselves with the thought that they had merely followed a path well trodden by other ancient and modern societies. NOTES 1. A version of this chapter was presented at the 1992 Conference of the Western Economic Association. I wish to express my thanks to Thomas Figueira for his perceptive comments. This research was facilitated by a grant from a fund created by the will of the late Harry Schwager, a distinguished alumnus of the City College of New York, Class of 1911. 2. The Jewish Publication Society’s (JPS) English translations of the Masoretic text of the Bible (see P&M 8, n.2) are recommended to the reader. 3. The Bible provides no evidence that popular unrest underlay the prophetic denunciations. Jack Hirshleifer, in a letter (August 24, 1992), cautions me to distinguish between two types of reforms: (1) reforms that are consistent with efficient working of markets (e.g., regulation of weights and measures, protection against fraud), and (2) reforms that subvert the working of markets (e.g., prohibition of interest). However, I would not credit the classical 194 Social Justice and Reform prophets of the later eighth and seventh centuries with an interest in the first category of reforms. I understand the references of the prophets to debased merchandise and corrupt measures as polemics: Business is evil and all businessmen are greedy cheats. Regulation of weights and measures was familiar in Israel long before Amos, Isaiah, and Ezekiel. We hear already of the ‘‘king’s weight’’ in David’s time (2 Sam. 14.26) and of the ‘‘shekel of the sanctuary’’ in Exodus 30.13 and Numbers 3.47. Similarly, those who ‘‘seized’’ (the verb gzl) fields did not take them by force; they purchased them. (Many ancient terms for ‘‘purchase’’ also mean ‘‘seize’’ [Silver 1985: 90; 1989: 51–52].) From the perspective of the prophets any ‘‘unequal exchange’’ is theft (Jackson 1972: 4–5ff.; cf. P&M 114–15, 127–28, 237–38; cf. Westbrook 1991: 13). 4. Sources for ‘‘activity, noise’’ in Near Eastern myth are Cagni 1977: 20–21, 29, n.12, 33, n.36, 41, n.84; Dalley 1989: 1–20; M. W. Green 1984: 254; Jacobsen 1976: 116–21, 227–81; Jacobsen 1987: 151–57; Komoroczy 1976: 11; Machinist 1983: 254. ´ 5. There is a real question whether the Hebrew roots hbr (‘‘to associate’’) and hbr . . (‘‘noise’’) are really distinct. Sources for (c)hbr are Arbeitman 1981; Cazelles 1977: 193–97; Finkelstein 1956: 328; Maisler 1946: 10; and O’Connor 1986: 77–80. 6. Sources for victims are Fabry 1977; Finkelstein 1961: 96–99; Fensham 1962; Gray 1965: 218–22; Lanczowski 1960: 82–83; and Shupak 1992: 14–15. Similarly, a closer identification of the social group called (c)hupshu, a Semitic designation for persons of ‘‘low status,’’ remains unavailable (Lemche 1975: 140–42; Lemche 1985: 167; cf. A. R. W. Green 1983: 196–97. 7. That Exodus is earlier than Deuteronomy is indicated by various criteria. First of all, as already noted, there are marked terminological and ideological similarities between the books of the northern prophets Amos and Hosea and Deuteronomy. Another central consideration is that unlike Exodus’ Covenant Code (20.22–23.33), Deuteronomy 12.4–6 demands cultic centralization. Another clue is provided by references to iron (barzel). Sawyer (1983: 130) explains that ‘‘a conspicuous example of this is to be found by comparing the law banning the use of a metal instrument in the building of the altar in Exodus 20.25, where the metal is unspecified with the parallel in Deut. 27.5, where iron is specially mentioned as though by then it was in common use . . . .’’ Note also Deuteronomy 8.9 where reference is made to the ‘‘promised land’’ as ‘‘a land whose stones are iron.’’ But ‘‘analysis of iron artifacts from ancient Palestine, Assyria and Persia has conclusively shown that the manufacture of iron tools and weapons was still at a fairly primitive stage in most if not all parts of the ancient Near East until as late as the ninth or even eighth centuries BC’’ (Sawyer 1983: 129). 8. See P&M, chap. 2. It would appear that Deuteronomy 28.12 (also 11.10–14) not only anticipates this suggestion, but also rebuts it by denying the need for irrigation: ‘‘The Lord will open unto you His good treasure the heaven to give the rain of your land in its season, and to bless all the work of your hand; and you shall lend to many nations, but you shall not borrow.’’ 9. Much of the material in this section is extracted from chapter 1 of my Economic Structures of the Ancient Near East (1985). 10. Weinfeld (1991: 56–57) cites evidence indicating that Assyrian, Hittite, and Egyptian rulers were also expected to comply with written instructions pertaining to national socioreligious policy. 11. This ‘‘contract’’ is clearly reflected in Psalms 72. 12. To facilitate the exposition, all other higher needs are ignored and the consumer is viewed as a rational altruist choosing, subject to a budget constraint, only between Prophets and Markets Revisited 195 ‘‘others’ necessaries’’ and ‘‘own amenities.’’ Altruism, represented by ‘‘others’ necessaries,’’ is viewed within Maslow’s growth actualization framework as a higher desire. Thus, other things being equal, as money income increases, the quantity of altruism demanded increases in both an absolute manner and a manner relative to the lower desires represented by ‘‘own amenities.’’ However, since technological change has lowered the relative price of amenities, the modern consumer chooses to purchase more ‘‘own amenities’’ relative to ‘‘others’ necessaries’’ than would, say, an ancient Israelite consumer enjoying the same level of real income (i.e., satisfaction). The American and the Israelite consumer move along different income consumption curves. 13. See AA&A (37–55) on the problems of rational ignorance and counterintuitive complex systems. ABBREVIATIONS AA&A. CAD. LSJ: P&M. Morris Silver, Affluence, Altruism, and Atrophy I. J. Gelb et al., The Assyrian Dictionary of the Oriental Institute ´ Chantraine: Pierre Chantraine, Dictionnaire Etymologique de la Langue Grecque Lidell, Scott, Jones, Greek-English Lexicon Morris Silver, Prophets and Markets REFERENCES Arbeitman, Yoel L. (1981). ‘‘The Hittite Is Thy Mother.’’ In Yoel L. Arbeitman and ¨ ¨ Allan R. Bomhard (eds.), Boni Homini Donum, Pt. 2. Amsterdam: Benjamins. Balkan, Kemal. (1974). ‘‘Cancellation of Debts in Cappadocian Tablets from Kultepe.’’ ¨ In K. Bittel, P. H. J. Houwink Ten Cate, and E. Reiner (eds.), Anatolian Studies. Istanbul: Nederlands Historisch-Archaeologisch Institut in het Nabije Oosten. Botterweck, Johannes G., and Helmer Ringgren (eds.). (1977). Theological Dictionary of the Old Testament. Rev. ed. Grand Rapids, Mich.: Eerdmans. Cagni, Luigi. (1977). The Poem of Erra. Malibu: Undema. Cazelles, H. (1977). ‘‘chabhar.’’ In Botterweck and Ringgren (eds.), Theological ¯ Dictionary of the Old Testament. ´ Chantraine, Pierre. (1968–1990). Dictionnaire Etymologique de la Langue Grecque: Histoire des Mots. Paris: Klincksieck. Dahood, Mitchell. (1981). ‘‘Afterword: Ebla, Ugarit, and the Bible.’’ In Giovanni Pettinato, The Archives of Ebla. Garden City, N.Y.: Doubleday. Dalley, Stephanie. (1989). Myths from Mesopotamia: Creation, The Flood, Gilgamesh and Others. Oxford: Oxford University Press. Dandamaev, Muhammad A. (1984). Slavery in Babylonia: From Naboplassar to Alexander (626–331 B.C.). Rev. ed. Marvin A. Powell (ed.). De Kalb: Northern Illinois University Press. Edzard, Dietz Otto. (1974). ‘‘ ‘Soziale Reformen’ im Zweistromland bis ca. 1600 b. Chr.: Realitat oder literarischer Topos.’’ Acta Antiqua, 22, 145–56. ¨ Evelyn-White, Hugh G. (1936). Hesiod: the Homeric Hymns and Homerica. London: Heinemann. 196 Social Justice and Reform Fabry, H.-J. (1977). ‘‘dal, dalal, dallah, zalal.’’ In Botterweck and Ringgren (eds.), ¯ ¯ ¯ Theological Dictionary of the Old Testament. Fensham, F. Charles. (1962). ‘‘Widow, Orphan, and the Poor in Ancient Near Eastern Legal and Wisdom Literature.’’ Journal of Near Eastern Studies, 21, 129–39. Finkelstein, J. J. (1956). ‘‘Hebrew [hbr] and Semitic ∗[(c)hbr].’’ Journal of Biblical Literature, 13, 328–31. Finkelstein, J. J. (1961). ‘‘Ammisaduqa’s Edict and the Babylonian ‘Law Codes.’ ’’ . Journal of Cuneiform Studies, 15, 91–104. Finkelstein, J. J. (1965). ‘‘Some New Misharum Material and Its Implications.’’ Assyriological Studies, 16, 233–46. Gelb, I. J. et al. (eds.). (1956- ). The Assyrian Dictionary of the Oriental Institute of the University of Chicago. Locust Valley, N.Y.: Augustin. Gray, John. (1965). The Legacy of Canaan. Leiden: Brill. Green, Alberto R. W. (1983). ‘‘Social Stratification and Cultural Continuity at Alalakh.’’ In H. B. Huffmon, F. A. Spina, and A. R. W. Green (eds.), The Quest for the Kingdom of God. Winona Lake, Ind.: Eisenbrauns. Green, Margaret Whitney. (1984). ‘‘The Uruk Lament.’’ Journal of the American Oriental Society, 104, 253–79. Hesiod. (1936). Works and Days. Trans. Evelyn-White. Jackson, Bernard S. (1972). Theft in Early Jewish Law. Oxford: Oxford University Press. Jacobsen, Thorkild. (1976). Treasures of Darkness: A History of Mesopotamian Religion. New Haven: Yale University Press. Jacobsen, Thorkild. (1987). The Harps That Once . . . : Sumerian Poetry in Translation. New Haven: Yale University Press. Kaufman, Stephen A. (1984). ‘‘A Reconstruction of the Social Welfare Systems of Ancient Israel.’’ In W. Boyd Barrick and John R. Spencer (eds.), In the Shelter of Elyon. Sheffield: JSOT Press. Kenik, Helen A. (1983). Design for Kingship: The Deuteronomistic Narrative Technique in 1 Kings 3:4–15. Chico, Calif.: Scholars Press. Komoroczy, Geza. (1976). ‘‘Work and Strike of Gods: New Light on the Divine Society ´ ´ in the Sumero-Akkadian Mythology.’’ Oikumene, 1, 9–37. Lambert, W. G. (1965). ‘‘Nebuchadnezzar: King of Justice.’’ Iraq, 27, 1–11. Lambert, W. G., and A. R. Millard (1969). Atra-Hasıs: The Babylonian Story of the ¯ Flood. London: Oxford University Press. ˘ Lanczkowski, Gunter. (1960). Altagyptischer Prophetismus. Wiesbaden: Harrassowitz. ¨ Lemche, Niels Peter. (1975). ‘‘The ‘Hebrew Slave’: Comments on the Slave Law, Ex. xxi 2–11.’’ Vetus Testamentum, 25, 129–44. Lemche, Niels Peter. (1976). ‘‘The Manumission of Slaves: The Fallow Year, The Sabbatical Year, The Jobel Year.’’ Vetus Testamentum, 26, 38–59. Lemche, Niels Peter. (1979). ‘‘Andurarum and Mısarum: Comments on the Problem of ¯ ¯ Social Edicts and Their Application in the Ancient Near East.’’ Journal of Near Eastern Studies, 38, 11–22. Lemche, Niels Peter. (1985). Early Israel: Anthropological and Historical Studies on the Israelite Society Before the Monarchy. Leiden: Brill. Lemche, Niels Peter. (1991). The Canaanites and Their Land: The Tradition of the Canaanites. Sheffield: Sheffield Academic Press. Levine, Baruch A. (1989). The JPS Torah Commentary: Leviticus. The Traditional He- Prophets and Markets Revisited 197 brew Text with the New JPS Translation and Commentary. Philadelphia: Jewish Publication Society. Liddell, Henry George, and Robert Scott. (1968). A Greek-English Lexicon. Henry Stuart Jones and Roderick McKenzie. Rev. ed. London: Oxford University Press. Machinist, Peter. (1983). ‘‘Rest and Violence in the Poem of Erra.’’ Journal of the American Oriental Society, 103, 221–26. Maisler (Mazar), B. (1946). ‘‘Canaan and the Canaanites.’’ Bulletin of the American Schools of Oriental Research, 102, 7–12. Nagy, Gregory. (1985). ‘‘Theognis and Megara: A Poet’s Vision of His City.’’ In Thomas J. Figueira and Gregory Nagy (eds.), Theognis of Megara: Poetry and the Polis. Baltimore: Johns Hopkins University Press. North, Douglass C. (1985). ‘‘Transaction Costs in History.’’ Journal of European Economic History, 14, 557–76. O’Connor, M. (1986). ‘‘Northwest Semitic Designations for Elective Social Affinities.’’ Journal of the Ancient Near Eastern Society, 18, 67–80. Olivier, Hannes. (1984). ‘‘The Effectiveness of the Old Babylonian Mesarum Decree.’’ ¯ Journal of Northwest Semitic Languages, 12, 107–13. Olivier, J. P. J. (1979). ‘‘The Sceptre of Justice in Ps. 45:7b.’’ Journal of Northwest Semitic Languages, 7, 45–54. Posner, Richard A. (1980). ‘‘A Theory of Primitive Society with Special Reference to Law.’’ Journal of Law and Economics, 78, 1–53. Postgate, J. N. (1992). Early Mesopotamia: Society and Economy at the Dawn of History. London: Routledge. Von Rad, Gerhard. (1972). Genesis: A Commentary. Rev. ed. Philadelphia: Westminster. Roberts, J. J. M. (1985). ‘‘The Ancient Near Eastern Environment.’’ In Douglas A. Knight and Gene M. Tucker (eds.), The Hebrew Bible and Its Modern Interpreters. Philadelphia: Fortress Press for the Society of Biblical Literature. Sawyer, John F. A. (1983). ‘‘The Meaning of Barzel in the Biblical Expressions ‘Chariot of Iron,’ ‘Yoke of Iron,’ etc.’’ In John F. A. Sawyer and David J. D. Clines (eds.), Midian, Moab and Edom. Sheffield: Sheffield Academic Press. Schumpeter, Joseph A. (1950). Capitalism, Socialism, and Democracy. 3rd ed. New York: Harper and Row. Shupak, Nili. (1992). ‘‘A New Source for the Study of the Judiciary and Law of Ancient Egypt: ‘The Tale of the Eloquent Peasant.’ ’’ Journal of Near Eastern Studies, 51, 1–18. Silver, Morris. (1980). Affluence, Altruism, and Atrophy: The Decline of Welfare States. New York: New York University Press. Silver, Morris. (1983). Prophets and Markets: The Political Economy of Ancient Israel. Norwell, Mass.: Kluwer Nijhoff. Silver, Morris. (1985). Economic Structures of the Ancient Near East. London/Savage, Md.: Croom Helm/Barnes and Noble. Silver, Morris. (1992). Taking Ancient Mythology Economically. Leiden: Brill. Speiser, E. A. (1964). Genesis: Introduction, Translation, and Notes. Garden City, N.Y.: Doubleday. Vanstiphout, H. L. J. (1978). ‘‘Lipit-Estar’s Praise in the Edubba.’’ Journal of Cuneiform Studies, 30, 33–61. Weinfeld, Moshe. (1985). ‘‘Freedom Proclamations in Egypt and in the Ancient Near 198 Social Justice and Reform East.’’ In Sarah Israelit Groll (ed.), Pharaonic Egypt, the Bible, and Christianity. Jerusalem: Magnes Press of the Hebrew University. Weinfeld, Moshe. (1991). Deuteronomy 1–11: A New Translation and Commentary. New York: Doubleday. Westbrook, Raymond. (1971a). ‘‘Jubilee Laws.’’ Israel Law Review, 6, 209–26. Reprinted in Westbrook (1991: 36–57). Westbrook, Raymond. (1971b). ‘‘Redemption of Land.’’ Israel Law Review, 6, 367–75. Reprinted in Westbrook (1991: 58–68). Westbrook, Raymond. (1991). Property and the Family in Biblical Law. Sheffield: Sheffield Academic Press. 15 Demands for Land Redistribution and Debt Reduction in the Roman Republic RICHARD E. MITCHELL In every period of Roman history readers encounter cries for justice, and we can learn a great deal about Roman attitudes toward social justice by concentrating on the earliest demands for land redistribution and debt relief. Furthermore, instead of a comprehensive treatment of social justice, this discussion will serve as a ‘‘still’’ photograph to elucidate what remained static and what changed in the demands for social justice throughout Roman history.1 Roman history, of course, was not systematically chronicled, nor was the city’s past interpreted until after 200 and our extant treatments of the earlier period are even later—much later.2 The momentous social, economic, and political events of the second and first centuries shaped the portrayal of earlier events, and later laments were telescoped back into the early history of Rome. ‘‘The Roman revolution,’’ says P. A. Brunt, ‘‘which transformed an oligarchic Republic into the Principate of Augustus, had its origins . . . partly in the misery of the poor, in a social crisis . . . ; it began with the Gracchi and with agrarian reform, and agrarian reform remained a leitmotiv in the turbulent century that followed. . . . Modern accounts tend to obscure or even deny the unity of this theme throughout the period. It is true,’’ Brunt continues, ‘‘that in the earlier [Gracchan] phase reformers were more concerned to find remedies for social distress as such, and in the later to provide homes for veterans. But the Gracchan settlers and the veterans had two things in common: they were mostly countrymen, and they desired to obtain a secure livelihood by owning their own land’’ (1962: 69). I will concentrate on features accepted as accurate reflections of early Roman society, because, as Brunt further points out, there are no late Republican anal- 200 Social Justice and Reform ogies to them, and they could ‘‘never have occurred in the time of any annalist’’ (1971: 639, n.1). The Roman aristocracy was military in nature, and warfare was its primary occupation. When Livy introduced the reign of King Numa Pompilius, he said that Numa founded Rome anew because Romulus’s city had been conditam vi et armis, but Livy added that war dehumanized the human spirit and Numa wanted to soften the savage behavior of the Romans by introducing the cult of Janus, whose temple doors were to be closed when the state was at peace. Peace seldom broke out. The only time that the temple doors were closed before the Battle of Actium was after the First Punic War when a ceremonial closing highlighted the end of a vigorous campaign, but the occasion was immediately followed by a great deal of unceremonious military preparation and activity (Livy 1.19; Ogilvie 1960: 93–94). Livy understandably praised peace, but before his generation such an attitude was unique. In fact, war was commonplace and was considered natural between sovereign states, the enslavement of defeated peoples was the natural consequence of war, and the successful creation of empire by extensive warfare was a desirable goal. Moreover, while aristocratic ‘‘Romans accepted war and military service as fields in which a man’s virtus could be seen to best advantage’’ (Ogilvie 1960: 95), there is little doubt that warfare was also the most profitable endeavor undertaken during the archaic period and that economic motives—broadly perceived—were the principal impetus behind such activity. There is less doubt that warfare was not uniformly beneficial to all Romans even when victorious, and this brief investigation attempts to arrive at a better understanding of some social, economic, and political effects of continuous warfare on those who fought.3 Soldiers are the focus because the first cries for justice came from poor citizens oppressed by military service. The story of Rome’s foundation is familiar, but it is worth remembering that the city presumably began as an asylum for paupers and outlaws, who had to steal women in order to be fruitful and multiply. In general, Roman kings were depicted as more popular with the masses descended from those paupers than they were with the aristocracy, which is to say that plebeians supported monarchy more than patricians did. We can skip over how earlier kings gained popularity among plebeians and will confine our survey of kingly behavior to Servius Tullius’ repayment of the debts of the poor from his own purse. The king thought it unjust that soldiers who had fought, won, and guaranteed liberty for others should lose it themselves. Servius declared that borrowers should not be imprisoned for their indebtedness, and he prohibited making loans on the security of free persons, that is, requiring free persons to give their bodies— and liberty—as security. Creditors had to be satisfied with the debtor’s property. The king also introduced the census so that property owners would pay their share of the war tax. ‘‘For I regard it as both just and advantageous to the public,’’ Servius said, ‘‘that those who possess much should pay much in taxes and those who have little should pay little’’ (Dion. Hal. 4.9). He declared that Land Redistribution and Debt Reduction 201 public lands acquired by the military success of the poor should not be monopolized by the wealthiest citizens. Ager publicus was to be divided into lots and given to those without property so that they, as freemen, could cultivate their own lands and not have to work the lands of others as slaves. A list of debtors was compiled and tables set up in the Forum from which creditors were paid and an edict was issued demanding that those currently enjoying the use of public lands should give up possession and that those citizens without allotments of land should make their names known.4 Servius believed that patricians plotted against him because his program benefited the poor and because the patricians were not allowed to treat plebeians unjustly and to consider them slaves. Creditors were unhappy because they could not haul debtors off to prison, and wealthy and prominent individuals—that is, senators and patricians—who misappropriated public property were unhappy because they were not allowed to retain land acquired by the blood of the poor and to continue considering the land their private inheritance. The census also angered those who were no longer exempt from taxes and who were now required to pay their fair share. Mostly, however, the opposition to Servius was because he made everyone subject to written laws and made justice impartial; as a consequence the poor were no longer treated like chattel slaves (Dion. Hal. 4.11–13; cf. Livy 1.41.6, 46.1). Servius is really a prototype and the reports of his written laws, land redistribution, debt relief, or collection of taxes are not reliable.5 Servius had seized the throne and courted the support of poor citizens to counter aristocratic opposition to his reign. The conservative views expressed by our sources overwhelmingly favor the status quo and firmly endorse the notion that those who called for land redistribution or debt relief actually were trying to parlay popularity into monarchy or tyranny. As the example of Servius demonstrated, anyone advocating popular reform was up to no good.6 But there can be little doubt that the motivation for reform during any period of Roman history was not simply the personal ambition or factional alliance of those who advocated redressing grievances. The first cries for justice during the Republic repeat those heard during the monarchy, but Livy first reported them after the death of Tarquin Superbus when patricians began to indulge themselves excessively at the expense of plebeians. Heretofore plebeians were shown every deference out of fear they would make common cause with Tarquin. Following his death, those pressed into military service complained about losing their farms and becoming debtors as a result of service (Livy 2.21). The best illustration of the aforementioned condition is the story of the first plebeian secessio in 494. The Romans had defeated the Latins at Lake Regillus and, although war with the Volsci was imminent, civil strife raged because the preservers of the state’s liberty were losing their own: Soldiers were being enslaved for debt. Particularly graphic is the description of the old veteran who appeared in the Forum. Although disheveled, ragged, and emaciated, he was 202 Social Justice and Reform recognized as a well-decorated courageous centurion whose scars of honor were visible on his chest. The crowd that gathered wanted to know how he came to this sorry state. He said that while serving during the Sabine War, his fields were destroyed, his house burned, and his animals driven off. Consequently, he was unable to pay the war tax and was forced to borrow. The interest mounted and, when unable to pay, he lost his ancestral lands and was seized and enslaved along with, Dionysius of Halicarnassus added, his two sons (Livy 2.23; cf. Dion. Hal. 6.22–26). Thus, our sources assign the origins of nexum, or debt bondage, to the period after 495, seeing it as an immediate consequence of military obligations and clearly part of the struggle between patricians and plebeians. Here we encounter another familiar stereotype of military service, namely, that patricians and senators repeatedly used real and imaginary external threats to justify conscription and, thereby, to divert plebeian attention from their demands for reform. Levies were used ‘‘to bring seditious mobs under control,’’ and warfare was seen as a deterrent to popular programs (Brunt 1971: 640). The ploy was first used following the appearance of the veteran centurion. A riot nearly occurred when other nexi enslaved for debt poured into the streets. Plebeians applauded when Volscians were reported to be marching on Rome. The plebeians refused to fight and called on patricians to bear the hardships of war since they alone were enriched by it. The Senate convinced a proplebeian patrician consul, Publius Servilius, to win over the plebeians and defend the state. In return, the Senate supported Servilius’ edict making it illegal to imprison or fetter a Roman citizen—and, thereby, prevent him from enlisting. The property of soldiers would not be seized or sold, nor would their children or grandchildren be detained. Since debtors could no longer be legally detained, they rushed to join the army in considerable numbers and greatly distinguished themselves in the coming war (Livy 2.24–25; cf. Dion. Hal. 6.23–33, 40.1). In fact, several pitched battles were fought with several different foes during a brief period, and when the victorious soldiers returned they fully expected Servilius’ edict prohibiting debt bondage to become law. However, Servilius’ colleague Appius Claudius was hostile to plebeians and began to condemn debtors and hand them over to their creditors. The soldiers demanded support from Servilius; but he failed them, and they lost faith in both the consulship and the Senate. Taking matters into their own hands, they prevented condemnation of debtor soldiers and beat up creditors who were now the ones threatened with loss of liberty (Livy 2.27). Neither the imminent danger of a Sabine attack nor Appius’ threat to arrest troublemakers and deal with all matters alone moved the plebeians—and, eventually, Appius and Servilius left office. News of plebeian secret meetings prompted the Senate to instruct the new consuls to conduct a military levy because idle plebeian hands were the devil’s plaything. However, as long as plebeians were overwhelmed by debt, they refused enlistment. Some aristocrats wanted to meet their demands; finally, the consuls gave way, and Manlius Valerius was made dictator. Since his brother had carried the law granting provocatio to citizens, plebeians respected Manlius, Land Redistribution and Debt Reduction 203 and he justified their respect by issuing another edict prohibiting debt bondage (Livy 2.2–8, 28–31). Valerius was thereby able to enlist a very large army— ten legions we are told—to confront the Aequi, Volsci, and Sabines. The warfare was successfully completed, and some conquered lands colonized, but Valerius resigned when the Senate supported moneylenders and again refused to outlaw debt bondage. To prevent plebeian sedition, the Senate tried to retain the soldiers under arms by insisting that they had taken the military oath to the consuls, not the dictator. Rather than kill the consuls—and, thereby, free themselves from their obligation—plebeians prudently marched out of the city to the Sacred Mount (Livy 2.32; Dion. Hal. 6.45; cf. Ogilvie 1960: 311). This first plebeian secessio ‘‘was essentially a military strike’’ (Brunt 1971: 640; cf. Ogilvie 1960: 309–14) whereby plebeians obtained the right to elect their own representatives, plebeian tribunes, modeled on the military tribunes of the legion (Varro LL 5.81; see Mitchell 1990: 139–48). Hereafter, plebeian tribunes led the fight for debt reform and land distribution. Clearly, those demanding justice were soldiers, although also called plebeians; and those who opposed their demands were patricians, senators, consuls, and other men of money and privilege. When their demands were not met, plebeian soldiers resorted to self-help, refused to fight, and threatened those who opposed them. Because agriculture was neglected during civil strife, famine conditions existed, and there was a concomitant rise in grain prices. We are told that slaves and the poor certainly would have starved if external sources of grain were not found: Presumably they were the last fed and the first denied. Eventually, grain came from Etruria and Sicily, but plebeians found the price too dear. Marcius Coriolanus was among those who insisted that if the aristocracy’s old privileges were returned then the old grain prices would return (Livy 2.34; cf. Dion. Hal. 7.12). There are many references to famine resulting from shortages and to attendant increases in grain prices that followed shortages (e.g., Livy 2.9, 27, 52; 4.12–13, 52). In the early Republic, efforts to import grain were mentioned frequently (Ogilvie 1960: 256–58). Just as often the expectation of famine was the context for another stereotypical subplot in the ongoing conflict, namely, the danger that individual Romans would use popularity achieved from supplying grain—often at their own expense—in an attempt to create a tyranny (Livy 4.13; cf. CAH 7.2: 183–84). The aforementioned attitudes certainly reflect late Republican aristocratic ideology and are not reliable indications of archaic sentiments. Demands for state subsidized grain distributions, for widespread agrarian reform, and for debt relief were all part of a general cry for social justice so familiar to those who know the history of the late Republic. Gaius Gracchus carried the first lex frumentaria in 123, and attempts to control grain prices or sell it at predetermined prices are even later.7 There certainly were grain shortages earlier, and, doubtless, Roman magistrates did what they could to alleviate the condition. Usually shortages were alleviated by demanding food, clothing, and other subsidies from the vanquished—to the victor goes the spoils (see, e.g., Livy 2.54.2; 7.37; 8.2.4; 9.41.5– 204 Social Justice and Reform 7; 9.43.6–21; 10–37.5). Defeat often resulted in enslavement or death for most soldiers and veritable starvation for most noncombatants—women, the elderly, children, and slaves (Livy 2.34.2–3). This was not the normal fate of victors, although poor plebeian soldiers constantly complained about indebtedness brought on by military service during the first two centuries of the Republic. Great hardship arose when peasants were absent for months or even years from their lands, but this did not occur, as the tradition asserted, as early as the fourth-century war with Veii because the city was only a few miles from Rome. The war against Veii presumably lasted for ten years and resulted in the introduction of pay, stipendium, for soldiers, the collection of the war tax, tributum, to pay for it (Livy 4.59–60; cf. 5.11.5; Diod. 14.16.5), and the imposition of indemnities on defeated communities (Livy 5.27.15; Ogilvie 1960: 622–23, 688– 89).8 Some tribunes opposed the introduction of pay because it required taxation to pay for it, and they demanded that soldiers be allowed to return home during the winter to revisit families and exercise civil rights (Livy 5.2–10). Veii is so near Rome that the argument is ridiculous, and the sentiments are appropriate only for a much later period. Moreover, ‘‘the absence of Roman coinage before the last quarter of the fourth century proves that earlier soldiers followed their leaders in full expectation of sharing booty. . . . From the beginning, the source of stipendium was the movable booty and the indemnity from defeated enemies, and sometimes the share weighed out—not counted out—to soldiers was considered inadequate. . . . [It was only in] the late third century that a . . . regular tax levied on property, tributum,’’ was collected to pay the troops, and it would appear that initially it was not collected from those who served (Mitchell 1990: 162–63). In other words, the depiction of the poor farmer burdened by prolonged campaigns and taxes in the early fourth century is rhetorical not historical. At the time Rome was small, her enemies near at hand, and the depiction is inappropriate. Campaigns took place over weeks or days, and farmers were not away from their fields for prolonged periods; but they could suffer from hostilities or raids in their area. However, ‘‘it is not likely,’’ says Brunt, ‘‘that military service as such did him [the farmer] or his family much harm, though naturally it was another matter if he was killed and a widow and young children were unable to cultivate his land.’’ Death aside, military service was not a ‘‘substantial grievance early in the fifth century’’ (1971: 640–41). On the contrary, I suggest that Rome’s military success resulted in the personal economic success of those in the military who expanded the state, a fact underscored by noticeable shifts in emphasis that appear in the story that begins to unfold about events in the fourth century. The Gallic sack followed hard on the war against Veii and exacerbated conditions: Both events produced a debt crisis. Manlius Capitolinus, aided by geese, not only saved the capital (Livy 5.47) he also saved many soldiers from being enslaved by selling his own property to pay their debts. The economic plight of plebeian soldiers is illustrated by the appearance of yet another brave centurion in bondage, and Manlius wonders if he saved the capital so that those who Land Redistribution and Debt Reduction 205 defeated the Gauls could be enslaved as if the Gauls had won. Even the recaptured Gallic ransom was hidden to deprive plebeians of their share. Manlius claimed not only that the Senate and state appropriated public lands and funds but that they could end indebtedness if they wished. Indebtedness appears as a public issue, and Manlius insisted that the state reduce the indebtedness of those who helped to make Rome what she was. This is the same attitude expressed by Servius Tullius. Consequently, Manlius’ goal in assisting the poor was characteristically viewed as regnum, and plebeians would desert him because he was also a threat to their liberty. Here Livy interjected a strange thought about those who helped, or tried to help, the poor. He reproached the multitude ‘‘because they always by their favours raised their champions to a dizzy eminence, and then at the critical juncture left them in the lurch.’’ Spurius Cassius offered plebeians land and was destroyed, Spurius Maelius tried to save his fellowcitizens from starvation at his own expense, and now ‘‘it was so with Marcus Manlius, who finding a part of the citizens overwhelmed and sunk in debt, was dragging them out into light and liberty, when they betrayed him to his adversaries; the plebs fattened their own defenders for the shambles. . . . Had their half-pound measures of meal requited the saviour of their country?’’ (Livy 6.14– 20; cf. old soldier, 2.23.2–7). This was the sum that Manlius received from each soldier for saving the capital (Livy 5.47.8). In other words, amidst the rhetoric we learn that soldiers were rewarded with grain and foodstuffs for their prowess, just as they received prisoners as personal slaves (Livy 4.34.4; cf. Livy 7.37).9 Thereafter, economic woes continued, though Livy suggests that colonial foundations alleviated the condition. Early Republican history has many examples of colonization following military success, and the juxtaposition makes it absolutely certain that land was considered booty and was therefore shared by victorious soldiers. According to the terms of the foedus Cassianum, even Roman allies were entitled to land in colonial settlements as their share of the spoils. But the implication that anyone who advocated granting the allies a share was aiming at tyranny is a sentiment taken directly from the Gracchan period (Livy 2.41–42; Dion. Hal. 8.69–80; cf. Ogilvie 1960: 337–45; and CAH 7.2: 326–32). There were nearly two dozen agrarian bills before 367, beginning with the one sponsored by Spurius Cassius in the early fifth century. However, following the agitation and legislation in 367, the only agrarian law proposed until well into the second century was that of Gaius Flaminius in 232 (Polybius 2.21–8). In 367 the amount of public land that individuals could claim was limited to 500 jugera (Livy 6.35.4; cf. Appian BC 1.8); and although debt and usury remained issues, colonization became more and more a feature of the tradition and replaced demands for land. The reports of colonial foundations are reliable records of lands granted to soldiers as their share of the booty. The many references to agrarian reform concentrate on distributing lands taken from the enemy to the poor, but the clear implication is that the land went to soldiers. If reliable, the so-called plebeian agitators for agrarian reform were actually sol- 206 Social Justice and Reform diers complaining about being cheated out of their rightful share of the booty— that is, land.10 In fact, judging from the lack of clear-cut Roman military victories before 390, it is entirely possible that the amount of booty and land that accrued to Roman soldiers before this date was limited.11 Colonization becomes a more prominent part of the record precisely at the point when Roman military successes are more frequently and more reliably documented. Consequently, I conclude, soldiers received their share of the booty in the form of colonial allotments; and, therefore, plebeian demands for agrarian reform are not heard again until the second century when problems were entirely different but much closer to the rhetorical complaints attributed to the early Republic.12 There is, moreover, a noticeable absence of famine notices in Livy beginning in the same period following the war with Veii and the Gallic sack (CAH 7.2: 133–34), which also suggests a dramatic change in the course of events following the defeat of Veii. Roman soldiers are persistently and consistently portrayed as farmers of relatively small properties constantly in peril even without performing required military service. As K. D. White observes, the lot of the peasant farmers—‘‘the so-called backbone of the Roman state before the rot set in’’—was extremely harsh (1977: 9–10). According to Shelton (1988), the presumption that only property owners were eligible for military service has been taken as proof that ‘‘in the early republican period most men did own some land. Otherwise Rome would not have had an army large enough to make the conquests it did.’’ Shelton continues: ‘‘It is indeed one of the great ironies of history that Roman farmers who went to war to defend their property against a foreign enemy ultimately lost their property to fellow Romans and also lost farming jobs to slaves whom they themselves had helped capture’’ (1988: 153–54, n.153). Their plight is neither as great nor ironic as asserted because the idea that only Roman property owners fought is more rhetorical than ironical or historical. Most Roman soldiers were not men of property. In fact, the rhetorical nature of the depiction is obvious. Latter Romans believed that they were descendants of sturdy, self-reliant farmers who owned the small plots which they worked and who were willing to fight bravely to defend the land which they owned. They believed, in addition, that their ancestors had succeeded both in farming and in war because they had possessed qualities such as diligence, determination, and constancy, and these qualities became enshrined by generation after generation as traditionally Roman virtues. Small Roman farms, according to legend, had produced great military heroes who embodied these virtues and, with them, conquered all of Italy. The legends of these men were passed on from generation to generation, and there became firmly entrenched in the Roman national consciousness the notion that ‘‘Rome owed her greatness to a sturdy breed of smallholders, content with little above bare subsistence, and working their plots with their own hands. (Shelton 1988: 153, the quote is from White 1977: 5) The aforementioned is accepted as historical because archaic soldiers are believed to have supplied their own armor and because the state introduced a fixed Land Redistribution and Debt Reduction 207 property level for participation, from which the propertyless were excluded. The evidence for this view is not consistent, however, and we ought to concentrate our attention on soldiers as the first citizens rather than focus on small farmers as the first soldiers. In fact, we often hear of volunteer and even privately recruited forces (e.g., Livy 4.48–49; 5.16.5; 28.45–46; 29.1.8). Moreover, the idea that Gaius Marius first recruited proletarii flies in the face of considerable evidence (Brunt 1962: 74). Proletarii fought in the Pyrrhic War (Gellius 16.10.1), and Hannibal captured Roman slaves at Cannae (Livy 22–52.3). Later, in the Second Punic War, slaves were mobilized, and even prisoners and enslaved debtors were released on the condition that they serve. After acquitting themselves well, they were manumitted (Livy 23.32–35; 24.10–16; 25.20–22; 27.38; 28.10, 46; 29.5).13 Did Rome eschew the services of the propertyless and those below a particular minimum census level in favor of slaves? Hardly! It is abundantly clear that the so-called Servian classes were a later introduction and were designed to preserve the political—that is, electorial—strength of the wealthy (Mitchell 1990: 8–11, 155, 239–42). The underlying organizational principle of comitia centuriata was that more weight was given to the vote of the wealthy because they, not the small farmer, had greater military and economic responsibility. As a consequence, Cicero, in his Republic, says that Servius’ centuriate system divided the population in such a way that the greatest number of votes belonged, not to the multitude, but to the rich, on the principle that ought to guide all republics, namely, ‘‘that the greatest number should not have the greatest power’’; and Cicero added that ‘‘equality results in inequality since it allows no distinction in rank’’ (1.43; 2.39). The original Roman aristocracy consisted of those wealthy individuals who supplied their own armor and horses. Equites were clearly the wealthiest and most privileged group in early Rome; and, originally, Roman aristocrats—senators, to be specific—belonged to the equestrian order. The most archaic feature of the comitia centuriata was the sex suffragia, the six centuries of equestrians who were the first ones to ‘‘break into sound’’—that is, to vote. Eventually the sex suffragia were supplemented by infantry centuries, the Roman classici, drawn up in three lines of deployment. The aforementioned were all wealthy, and for our purposes there is no need to draw subtle distinctions between the various groups (see Gellius 6.13). But we do see a fundamental contradiction in both the ancient and modern depictions of those who fought for the early Roman state. Warfare is described as both an economic obligation and personal liability disproportionately borne by the rich landowners—locupletes—who were the chief beneficiaries of Rome’s imperial success (cf. Cicero, Repub. 2.9.16; and Gellius 10.5). On the other hand, poor soldiers—that is, the plebeians—are portrayed as property owners indebted and enslaved by the very military obligation and successes that enriched the aristocracy. Something is wrong with any depiction that has small property owners fighting and agitating to gain access to small parcels of land distant from their current holdings (see Mitchell 1990: 7–10, 35–62, 154–55, 239–42). 208 Social Justice and Reform Throughout the fourth century, Rome’s military system did not consist of soldiers recruited according to property classification but consisted of soldiers bound by personal ties to particular chiefs for economic and, I would offer, military and political interests. The first phalanx was a coterie of men led by an aristocratic chief. It consisted of his clients, retainers, dependents, and tenants, not all of whom necessarily possessed sufficient property to arm themselves. They were ‘‘recruited’’ along with neighbors, kinsmen, friends, and even mercenaries. Prominent local headmen obviously were the only agents that the central authority had to mobilize into military units. The organization was advantageous to both patrons and clients, who were mutually dependent. For example, freedmen became clients of owners who manumitted them, and their status was that of dependent hoplites with military obligations to their patrons and, only subsequently, to the state. Clients and patrons were under a mutual obligation to ransom one another. The major change occurred with the transformation of these private, locally recruited military forces (hoplites and clients) into an army of soldiers publicly recruited from a considerably expanded pool of citizens, most of whom were without personal ties to Roman aristocrats. This change did not occur until the third century, at the earliest, and when it occurred there was a corresponding alteration in political life, which increasingly focused on the social, economic, and political concerns of the broader class of citizens. These concerns, in turn, were telescoped back into the story of Rome’s early history by those who began to write about the past, and the plight of the original soldier was commingled with that of the later citizen after the two ceased to be one and the same (Mitchell 1990: 8–11, 48–52, 236–42, 253). If we cannot assign property to every soldier, it is equally difficult to restrict aristocratic possession of ager publicus to 500 iugera. Moreover, before the second century, attempts to do so are premature and unnecessary. As we have seen, agitation for agrarian reform took the form of a proposal that land taken from the enemy should be divided into individual lots and given to those who conquered it. Innumerable references create the clear impression that very early in the Republic aristocrats possessed vast amounts of ager publicus illegally (Livy 4.48.2; 4.51.5). Even Licinius Stolo, who proposed the limitation in 367, was convicted of violating the limitation by emancipating his son and thereby obtaining 1,000 iugera (Livy 7.16.9). But, in fact, we know that large tracts of public land held in excess of the legal limit were commonplace and routinely ignored before the second century. Before that time, an individual generally occupied as much ager publicus as he could cultivate or ‘‘as his patrimonial resources would permit’’; but even if he exceed the limit he suffered only a fine (CAH 7.2: 326). As in warfare, the patron-client relationship was originally mutually beneficial when it came to occupying and working expanded estates. The wealthy had an advantage in the occupation of ager publicus because, in addition to using their extensive clientele, they could afford to use slave labor to work more land (Appian BC 1.7–9). These were not slaves purchased in a market, but were prisoners of war obtained by Roman soldiers as their share of Land Redistribution and Debt Reduction 209 the booty, with commanders and officers obtaining the lion’s share in this as in all spoils.14 Slaves worked the public lands occupied by wealthy Romans up to and in excess of the legal limit. Even after manumission, freedmen continued to work the land and were tied to their patrons, who easily converted their obligations into social, economic, and political clout. The patron for his part, also was obligated to look after the interests of the client (Gellius 5.13; 20.1.40; cf. Ogilvie 1960: 479–80). Until late in the third century there was no scarcity of ager publicus to occupy, and no profusion of people to demand it. Eventually, records of occupation were lost and lands began to be treated as ancestral property and annexed to private estates.15 We superficially have taken care of popular demands for agrarian reform, but what of the outrage expressed by those enslaved for debt? Nexum, or debt bondage as it is called, is an extremely complicated question, and only the essentials can be addressed. The primary detail to keep in mind, as in the case of demands by the poor for land, is that we are again dealing with soldiers. Agitation against enslavement for debt is a prominent feature of the internal struggles between rich and poor in early Roman society, and it is most vividly depicted by those manacled soldiers who had lost everything, including their liberty, in the service of their country (Livy 2.23–27; 6.14.3–5; 7.19.5; Ogilvie 1960: 296–99, 303). That nexum has a basis in fact is suggested by its prohibition, nearly two centuries after it was first promised, by a law that Livy describes as a new beginning of liberty for Roman plebeians (8.28). However, whatever nexum was and whatever the lex Poetilia outlawed in 313, ‘‘debt bondage was still known to Republican and classical law, and in particular afflicted the Sullan veterans. . . . It is indeed precisely in the late Republic that we have the best evidence that debt was a persistent social problem, and the annalists’ view that in early times it was aggravated, if not caused, by conscription helps to show how the problem arose much later’’ (Brunt 1971: 644).16 One interpretation, favored by many, is that the law ‘‘merely abolished the nexum as a form of labour contract; from now on only defaulting debtors were placed in bondage, following a judgement in court’’ (CAH 7.2: 334). Before they were abolished, such contracts were the primary means by which large landowners obtained laborers for their estates. However, ‘‘the improved economic conditions that resulted from successful warfare and extensive schemes of land assignation and colonization . . . meant that the plebeians were gradually freed from the necessity of entering into bondage. It is probable that by the start of the Second Samnite War (327–304 B.C.) the institution of nexum had already become a relic of a bygone age. Its disappearance did not, however, put an end to indebtedness, which persisted as a major social evil to the end of the Republic’’ (CAH 7.2: 334). It is also argued that prohibiting voluntary bondage contracts created a demand for labor on large estates and, thereby, increased the number of imported slaves (CAH 7.2: 334; cf. Finley 1982: 150–66). Although this interpretation is attractive, I want to stress that nexi were depicted as having been soldiers and were also portrayed as soldiers mobilized 210 Social Justice and Reform despite their bondage (cf. Livy 2.34.7–8 with 2.27.1). Slaves and imprisoned debtors, even criminals, served in the army during the Hannibalic War and were freed on condition of fulfilling military service (Livy 23.32–35; 24.10–16; 25.20–22; 27.38; 28.10, 46; 29.5). Nexum was outlawed, moreover, after the Caudine disaster (Varro LL 7.105; Dion. Hal. 16.5). In that battle, Roman soldiers were forced to surrender and were released under terms of an agreement subsequently disavowed by the Senate. However, the soldiers were not returned to Samnite captivity (Livy 9.2–11), but 600 equestrians were retained as hostages (Livy 9.5.5–12, 12.9, 14.14, 15.3–7). What resulted was the ransoming of Roman soldiers, and the son of one of those surrendered was left in poverty and became a nexus in order to pay his father’s funeral expenses: a noble story, filled with pietas, and very little reliable material, except for the equation of the soldier with nexum—and, therefore, the association of nexum with ransom (Dion. Hal. 16.5). We have evidence suggesting that the state, beginning in the fourth century, used public funds to relieve debtors (Livy 7.21.5–8). Relief was not extended to citizens in general, but the idea of public payment of ransom may have started to take hold. One of the underlying principles of Roman service to the state, or of contractual obligations generally, is that one had to have property as security—or as a hostage, as one source said—for fulfillment of the task. For those without property, patrons or others could stand in. One of the laments of those who claim to have lost everything as a direct result of serving the state was that they were left without even enough money to ransom themselves (Livy 26.35.6). We hear little about ransoming Roman soldiers. The Gauls supposedly ransomed the city (Polybius 2.18.2–6, 22.5; cf. Livy 5.48–49), but, if true, it must reflect the ransom of Roman prisoners. Pyrrhus was said to have freed his Roman prisoners before the payment of ransom, but he sent along prominent men to fix the ransom price (cf. Livy 22.23, 59; Cicero, Brutus 55; Plutarch, Pyrrhus 20.1). Hannibal is contrasted with Pyrrhus, because Hannibal allowed captives to ransom themselves. Livy says that the price of equestrians was a bit higher than agreed upon when they surrendered. The Senate debated the ransom and the implication is that under normal circumstances public funds would have been used. However, because the prisoners were considered cowards, not even private arrangements were allowed; and the Senate refused even to permit loans to be taken out to pay the ransom price (Livy 22.52–61). Still later in time, we are told that redemptores who ransomed individuals were entitled to the labor of those redeemed until such time as those individuals repaid the amount of the ransom loan (Levy 1943: 159–76). It appears that in most cases an individual was obligated to work for a period of five years (inferred from Cicero, Philippic. 8.11.32) but that, contrary to the time when he was a prisoner, he recovered his citizenship. In the late fourth century, the state began to pay the ransom price of Roman soldiers captured by the enemy: at the very least, the rule was established that five years of labor was sufficient not only to discharge the debt owed to redeemers but also to discharge the debt of soldiers enslaved by Rome before the third century.17 Land Redistribution and Debt Reduction 211 ‘‘enormous influenced of them a cave or lair to lurk in; but the men who fight an hereditary altar, not one of all these many Romans an ancestral tomb, but they fight and die to support others in wealth and luxury, and though they are styled masters of the world, they have not a single clod of earth that is their own.’’ (Plutarch, Tib. Gracchus 9.4–5)18 NOTES 1. Crook (1967: 8) is the origin of the idea of a ‘‘still’’ photograph. Limitations placed on space preclude both publication of the complete lecture and full citations of ancient and modern bibliography. For dated events, see Broughton (1951), for the ancient testimony. 2. All dates are B.C.E. 3. Momigliano (1986: 189) sees our failure to comprehend the effect of continuous warfare as one of two difficulties, the other being misunderstanding the fifth-century plebeian movement by focusing on the compromise of 366. 4. Dion. Hal. 4.8–10, has the most complete, but needless to say, the most suspect account. Cicero, Repub. 2.21 (37–38) and Livy 1.41–48 supply other details incorporated into this summary. Galba (1991: 172–89) is an excellent survey of the regal tradition. All translations, unless noted, are from the Loeb editions. 212 Social Justice and Reform 5. Cf. Watson (1972: 100–105) for faith in regal laws, and Momigliano (1963: 95– 121), for acceptance of much of the traditional outline. 6. See Livy 2.46: Servius used land grants to gain support from plebeians; 3.39.9 (cf. Ogilvie 1960: 470–71). Standard is Cicero, Pro Sestio 96: ‘‘Those who have wished their deeds and words to be pleasing to the multitude have been held to be populares and those who have conducted themselves in such a manner that their counsels have met the approval of all the best men have been held to be optimates.’’ 7. Broughton (1951: 514; cf. CAH 7.2: 133–34, 211, 409). In general see Rickman (1980). 8. Cf. CAH 7.2: 199–200, 299–302; and Crawford (1976: 204–7). 9. In general, see Shatzman (1972: 177–205). 10. Complaints about unfair distribution of booty are abundant and doubtless heavily influenced by late Republican conditions. See Livy 4.49; 5.19–22, 25–26, 32.8; cf. Livy 4.59.10. On the political importance of distribution of booty, see Livy 2.42.1; 3.31.4; 4.59.10; 6.4.11; 7.16.3, 24.9, 27.8; 8.29.14, 36.10; 9.13.5, 37.10, 42.5. On later experiences influencing early accounts, see Brunt (1971: 411). Cato the Elder spoke de praeda militibus dividenda stressing how the theft of military spoils by prominent men was the kind of public thief that resulted in a life of luxury (Gellius 11.18.18). 11. Presumably, minor military successes became major, and indecisive battles became victories. For example, in 446, Livy (3.70.14–15) reports a major victory over Aequi/Volsci, but says that no triumph was celebrated. On the other hand, ‘‘It is worth noting that as a general rule major Roman victories are comparatively rare in the tradition as we have it’’ in the period from 509 to 390 (CAH 7.2: 289). Harris (1979: 26) also notes that ‘‘through most of the middle Republic about one consul in three celebrated a triumph,’’ but the fact that there were only twenty-two triumphs and ovations during the entire fifth century ‘‘must suggest that the record is relatively free from contamination, and that it was not simply a fraudulent projection into the remote past of the conditions of the middle Republic’’ (CAH 7.2: 290). 12. Livy 4.47–49 is a good sample, but cf. Livy 6.5.2. On colonization, see Salmon (1969). 13. On slaves in the military, see Rouland (1977: 25–75); cf. Garlan (1988: 163–76). 14. Cf. Gelzer (1969: 21–22; Brunt 1971: passim; and CAH 7.2: 125–26, 312–13, 331–34, esp. 389). 15. In general, see the discussion in Bernstein (1978: especially chaps. 3–5). 16. See Livy 8.27, for the law he incorrectly dated; cf. Dion. Hal. 16.4–5; Varro LL 7.105; Val. Max. 6.1.9. See Sallust, Catalina 33 for the Sullan Veterans. 17. In general, see the discussion of Zuleuta (1946–53, 2: 143–44). I want to thank Raymond Westbrook for comments made following the paper and for his 1988 and 1989 publication that will greatly contribute to the resolution of the nexum controversy. 18. In a later article, I will argue against the common view that the propertyless were only routinely enlisted after Marius’ reform. Soldiers were clearly depicted as propertyless from the beginning, and this was not an incorrect depiction. REFERENCES Bernstein, A. (1978). Tiberius Sempronius Gracchus: Tradition and Apostasy. Ithaca, N.Y.: Cornell University Press. Land Redistribution and Debt Reduction 213 Broughton, T.R.S. (1951). The Magistrates of the Roman Republic. Vols. 1–2. New York: American Philological Association. Brunt, P. A. (1962). ‘‘The Army and the Land in the Roman Revolution.’’ Journal of Roman Studies, 52, 69–86. Brunt, P. A. (1965). ‘‘Italian Aims at the Time of the Social War.’’ Journal of Roman Studies, 55, 90–109. Brunt, P. A. (1971). Italian Manpower, 225 B.C.–A.D. 14. Oxford: Oxford University Press. Cambridge Ancient History. (1989). Ed. F. W. Walbank, A. E. Astin, M. W. Frederiksen, and R. M. Ogilvie. Vol. 7, pt. 2. Cambridge: Cambridge University Press. Crawford, M. H. (1976). ‘‘The Early Roman Economy.’’ Melanges J. Heurgon, Collec´ ´ ¸ tion de l’Ecole Francaise de Rome 27, I, Rome, 197–207. Crook, J. A. (1967). Law and Life of Rome. Ithaca, N.Y.: Cornell University Press. Finley, M. (1982). Economy and Society in Ancient Greece. Ed. B. D. Shaw and R. P. Saller. New York: Viking. Galba, E. (1991). Dionysius and the History of Archaic Rome. Berkeley: University of California Press. Garland, Y. (1988). Slavery in Ancient Greece. Trans. Janet Lloyd. Ithaca, N.Y.: Cornell University Press. Gelzer, M. (1969). The Roman Nobility. Trans. Robin Seager. Oxford: Blackwell. Harris, W. V. (1979). War and Imperialism in the Roman Republic, 327–70 B.C. Oxford: Oxford University Press. Levy, E. (1943). ‘‘Captivus Redemptus.’’ Classical Philology, 39, 159–76. Mitchell, R. E. (1990). Patricians and Plebeians: The Origins of the Roman State. Ithaca, N.Y.: Cornell University Press. Momigliano, A. (1963). ‘‘An Interim Report on the Origins of Rome.’’ Journal of Roman Studies, 53, 93–121. Momigliano, A. (1986). ‘‘The Rise of the Plebs in the Archaic Age of Rome.’’ In K. Raaflaub (ed.), Social Struggles in Archaic Rome. Berkeley: University of California Press. Ogilvie, R. M. (1960). A Commentary on Livy: Books 1–5. Oxford: Clarendon. Rickman, G. (1980). The Corn Supply of Ancient Rome. Oxford: Oxford University Press. Rouland, N. (1977). ‘‘Les esclaves romains en temps de guerre.’’ Collection Latomus, 151, 1–106. Salmon, E. T. (1969). Roman Colonization under the Republic. Ithaca, N.Y.: Cornell University Press. Shatzman, I. (1972). ‘‘The Roman General’s Authority over Booty.’’ Historia, 21, 177– 205. Shelton, Jo-Ann. (1988). As the Romans Did. Oxford: Oxford University Press. White, K. D. (1977). Country Life in Classical Times. Ithaca, N.Y.: Cornell University Press. Watson, A. (1972). ‘‘Roman Private Law and the Leges Regiae.’’ Journal of Roman Studies, 60, 100–105. Westbrook, R. (1988). ‘‘The Nature and Origins of the Twelve Tables.’’ Zeitschrift der Savigny-Stiftung fur Rechtsgeschichte, Romanistische Abteilung, 105, 73–121. ¨ 214 Social Justice and Reform Westbrook, R. (1989). ‘‘Restrictions on Alienation of Property in Early Roman Law.’’ In Peter Birks (ed.), New Perspectives in the Roman Law of Property. Oxford: Clarendon. Zulueta, F. de (1946–53). The Institutes of Gaius. Vols. 1–2. Oxford: Oxford University Press. Selected Bibliography GENERAL Greenberg, Jerald, and Ronald L. Cohen (eds.). (1992). Equity and Justice in Social Behavior. New York: Academic Press. Irani, K. D. (1981). ‘‘Values and Rights Underlying Social Justice.’’ In R. L. Braham (ed.), Social Justice. Boston, Mass.: Martinus Nijhoff. Phillips, Derek. (1986). Toward a Just Social Order. Princeton: Princeton University Press. ANTIQUITY Fensham, F. Charles. (1962). ‘‘Widow, Influence. Sheffield: Sheffield Academic Press. Weinfeld, Moshe. (1985). ‘‘Freedom Proclamations in Egypt and in the Ancient Near East.’’ In Sarah Israelit Groll (ed.), Pharaonic Egypt, the Bible, and Christianity. Jerusalem: Magnes Press. Yaron, Reuven. (1993). ‘‘Social Problems and Policies in the Ancient Near East.’’ In Baruch Halpern and Deborah W. Hobson (eds.), Politics and Society in the Ancient Mediterranean World. Sheffield: Sheffield Academic Press. Index Affluence: and altruism, in ancient Israel, 192; in ancient China, 126; in archaic Greek poetry, 43–55; Hesiodic vision of work and affluence, 55–56; and political power, in ancient China, 126 Agrarian reforms, 199, 205–9 Aquinas, St. Thomas, 15–16, 32 Arabia. See Islamic society, early Aristotle, conceptions of: hierarchy of values, 10, 14, 21; justice, 3, 29; natural law, 12; natural rights of offspring, 10–12 Bacchylides, 43, 44, 46, 47, 49, 50, 51, 52 Book of the Dead, 27, 28, 106 Catholic literature, social justice in, 32 Charity: in ancient Iran, 86; in early Islamic society, 116–17; institutionalization of, 14–17; and natural law, 13–16; Roman ‘‘dole,’’ 13 China, ancient, 125–44; Confucian v. Mencian moral teaching, 129–31; equitable distribution in, 132–34; justice as morality in, 125; natural law conception in, 131; principle of equity in, 137– 38; rights of individuals in, 136–37; rituals and the exercise of authority in, 127–29; social hierarchy and equality in, 131–32, 133–36; utilitarianism of Mo-tzu, 131–32 Class distinctions: in ancient China, 131– 32, 133–36; in ancient Iran, 88; in ancient Rome, 211; in early Islamic society, 115, 120–22; and judicial redress in Indo-European tradition, 6–7 Comparative justice, principle of, 3, 7–8 Concordia ordinum, concept of, 31–32 Confucius, 127–30, 132–33, 134, 135, 136–38 Contract enforcement, 3–4, 83, 13 Crime and punishment: in ancient Egypt, 103–5; ransom contracts in ancient Near East, 157–58 Debt and debt slavery: biblical law on, 160–61, 187–88; debt release decrees and laws, 152–61, 167, 185; in Roman Republic, 200–201, 202–3, 204–5, 207, 209–10 218 Index De Malynes, Gerard, 20–21 Dharma, Hindu concept of, 5–6, 91–92 Economy: of ancient Greece, principle of economic rights in, 10–12; of ancient Iran, 81–86; of ancient Mesopotamia, 149, 167–68; and equitable distribution in ancient China, 132–34; subsistence, 9–22. See also Trade and commerce; Welfarist economic reform Egypt, ancient, 101–10: concept of ma at in, 101–7, 109–10; concept of righteousness in, 27–28; king’s administrative duties in, 102–5, 107; treatment of citizens in, 107–9; treatment of criminals in, 103–5 Epinician poetry: affluence and moral character in, 47–49; divine origin of wealth in, 44–47; poverty in, 51–53; social mobility in, 46, 49–50, 53–55; valuation of prosperity in, 46–47 Gods and divinity: concept of ma at in ancient Egypt, 101–7, 109–10; divine origin of wealth, 44–47; and mandate of king, 102–3, 126, 150; and temple cults, 190–92; Yahweh as god of social justice, 191–92 Greece, archaic, 41–56; justice in early Greek poetry, 61–67; justice and law in, 29–30; medicine as metaphor for justice in, 69–73; nature of wealth in, 43–55; social mobility in, 46, 47, 49– 50, 53–55. See also Aristotle, conceptions of; Epinician poetry; Plato, conceptions of; Theognis of Megara, elegiac poetry of Hadith, the, 116, 117, 119, 121, 122 Hammurabi, law codes of, 151–54, 158, 185 Heraclitus, 70, 71 Herodotus, 72, 88 Hesiod, 55–56, 61, 63–66, 70, 71–72, 182 Hsun-tzu, 131, 133, 135, 136–37, 138 ¨ Human rights, and social justice in ancient Iran, 86–89 India, ancient, 91–98; Mauryan Empire of, 92–97; sanatana dharma in, 91–92; state and social justice guidelines in the Arthasastra, 91–92 ´¯ Intrinsic justice, principle of, 3, 7–8 Iran, pre-Islamic, 75–89; administration of justice in, 79–81; charity in, 86; contract enforcement in, 4l; economic equity in, 81–86; egalitarianism in, 87– 88; human rights in, 86–89; political justice in, 75–79; principle of asha (idealized Truth) in, 5; slavery in, 86– 87; societal structure of, 82; Zarathushtrian culture in, 77–79, 86, 87 Islamic society, early, 115–23; class divisions and social antagonisms in, 115, 120–22; compulsory and voluntary almsgiving in, 117; ‘‘golden age’’ of, 118–22; Muhammad’s social precepts, 116–17, 118–19, 121 Israel-Judah: affluence and altruism in, 192–93; concept of social justice, postExilic period, 25–26, 31, 32–34; Deuternomic reforms of eighth and seventh centuries, 185–90; social reforms of the prophets, 179–81, 191–92 Kant, Immanuel, 129 Kings: divine mandate of, 102–3, 126, 150; as savior hero, 183–84; social justice function, 27, 150–51 Koran, the, 115–16, 117–18, 121, 122 La Moneta Nera, 19–20 Laws, ancient: biblical debt release decrees, 160–61; of China, 127–29; Codex Hammurabi, 151–54, 158, 185; and Confucian philosophy of justice, 127–29, 136–38; of contract enforcement, 3–4, 13, 83; debt and debt slavery, 152–61, 186–87, 202; of Egypt, 27–28; of Greece, 29–30; of India, 95; of Iran, 4, 79–81; of Middle Ages, 32; religious, and doctrine of social justice, 35 n.9. See also Roman law Lives (Plutarch), 11, 12 Loans and credit: in ancient Iran, 82–84; Index 219 in ancient Near East, 155–56; biblical legal statements on, 187–89; money lenders of Middle Ages, 17–19; and usury, 11–12, 18. See also Debt and debt slavery Locke, John, 21 Mencius, 129–31, 132–33, 134, 138–39, 141 Mesopotamia, ancient, 149–62; attitudes toward poverty in, 149–50; king’s social justice function in, 150–51; law code of King Hammurabi, 151–54, 158, 185; mısharum acts in, 185–87; ¯ ‘‘Reforms of Uruinimgina,’’ 168–70, 173–74; righteousness and uprightness concepts in, 27; social reform in, 165– 75 Middle Ages: charity and natural law in, 13–16; credit for the poor in, 17–19; king as source of justice in, 27; lack of social justice concept in, 31; legal justice in, 32; Mendicant Orders of, 10, 14; monetary systems of, 19–20 Money and monetary systems: of ancient Iran, 82–83; and Aristotle’s concept of natural limits, 10; barter and pettyvillage economy, 19–21; of Middle Ages, 19–20 Monte di Pieta, 18–19 ` Mo-tzu, 131–32, 133, 134–36, 138 Muhammad, social precepts of, 116–17, 118–19, 121 Natural law: Aristotle’s conceptions of, 10–12; and charity, in the Middle Ages, 13–16; and demand for social justice, 5–8; and religion, 5–7; in Roman law and philosophy, 6–7, 12–13 Near East, ancient, 149–62; debt laws, debt slavery, and debt release in, 149, 152–61, 167, 185; economic oppressors and ‘‘ideal victims’’ in, 182–83; king’s social justice function in, 183–84; ransom agreement contracts, 157–58; role of temple cults in, 190–92; social reform in, 165–75, 181–84; societal structure and economy of, 149, 167– 68; welfarist economic reform in, 184– 85 Odyssey, 61–62 Pindar, 43, 44, 45, 47, 49, 50, 54, 55 Plato, conceptions of, 9–10, 29 Plutarch, 11, 12, 26 Policraticus (John of Salsbury), 13–14 Politics (Aristotle), 10, 15 Poverty: in archaic Greek ‘‘shame culture,’’ 51–53; and institutionalization of charity, 14–15; Mesopotamian view of, 149–50; and moral right of subsistence, 15–16. See also Debt and debt slavery Religion: canon law and equality of mankind, 35 n.9; debt release in biblical law, 160–61, 187–88; and demand for social justice, 4–5; law of nations (ius gentium) as church principle, 13–14; and notion of natural law, 5–7 Republic (Plato), 9, 29, 69 Righteousness: and Chinese law and justice, 137–38; and equitable distribution, 132–34; as individual virtue, 26, 27–32; Mencian conception of, 129–31, 141 Roman law: absence of social justice in, 26, 28–29, 30–31; civil law (ius civile) in, 12, 30; as divinely inspired, 12; Institutes of Gaius, 26, 30; Institutes of Justinian, 12, 26, 30; language of rights in, 3; law of nations (ius gentium) in, 6, 12, 13, 30; natural-rights tradition in, 6–7, 12–13; as product of human action, 30 Roman Republic: agrarian reforms of, 199, 205–9; charity in, 13; debt bondage in, 200–201, 202–3, 204–5, 207, 209–10; warfare and indebtedness of Roman soldiers in, 200–211 Salsbury, John of, 13–14 Slavery: in ancient Iran, 86–87; in ancient Near East, 149, 152–61, 167, 220 Index 185–87; in ancient Rome, 208–9. See also Debt and debt slavery Social equality: and early Church, 35 n.9; principle of equality before the law, 7; and social democracy, 32; and social hierarchy in ancient China, 131–32, 133–36. See also Class distinctions Social justice: and doctrine of individual righteousness, 26, 27–32; and notion of natural law, 5–7; origins of concept, 3– 8, 25–34; and principles of intrinsic justice and comparative justice, 3, 7–8; religion as foundation of, 4–5 Social reform: in ancient Israel, 179–93; in ancient Mesopotamia, 165–75, 185; Deuteronomic reforms of eighth and seventh centuries, 185–90; intellectual and ideological framework of, 181–84; in Roman Republic, 199–211; temple cults’ role in, 190–92 Social welfare. See Charity; Welfarist economic reform Socrates, 69 Solon, 43, 44, 47, 48, 49, 50, 52, 53, 67, 71, 72 Stoic philosophy: and language of rights, 3; theory of natural justice in, 6–7 Subsistence economy, 9–22; and institutionalization of charity, 14–15; pawnshops and credit associations in, 17–19; provisions policies in medieval towns, 16–17; trade and commerce in, 10–12, 16–17 Summa Theologica (St. Thomas Aquinas), 15–16 Temple cults, social reform role of, 190– 92 Theognis of Megara, elegiac poetry of, 66–67, 71, 182; acquisition and possession in, 42–56; affluence and moral character in, 47–49; divine source of wealth in, 44–47; poverty in, 51–53; social mobility in, 46, 49–50, 53–55; valuation of prosperity in, 46–47 Trade and commerce: ancient market customs, 7–8; barter and petty-village economy, 19–21; in subsistence economy, 11–12, 16–17; taxes in ancient Iran and Mesopotamia, 82–83, 84–85; in temple cults, 190 Universal Declaration on Human Rights of 1948, 115 Wealth. See Affluence Welfarist economic reform: economic oppression as motive for, 81–84; and ‘‘Holiness Code,’’ 188–89; intellectual and ideological framework for, 181–84; in Israel-Judah, 185–90; of Old Babylonian period, 184–85; role of temple cults in, 190–92 Works and Days (Hesiod), 61, 63–66, 182 Yahweh, as god of social justice, 191–92 About the Editors and Contributors HOWARD L. ADELSON is Professor of History at the City College of the City University of New York. Professor Adelson has taught as a visiting Professor at a number of American and foreign universities. He has served as Executive Officer of CUNY’s Ph.D. Program in History, Chairman of City College’s History Department, Director of the Graduate Seminar in Economic History at New York University, and Director of Studies of the Museum of the American Numismatic Society. Professor Adelson has been honored on a number of occasions and, in addition to having been made a Fellow of the Hebrew University (hon. caus.), he is also recipient of the Rothberg Prize from the Hebrew University in Jerusalem and a recipient of the Jabotinsky Centennial Medal from former Prime Minister Menachem Begin of Israel. His primary interests are in early medieval economic history and legal and political theory as expressed in political history and iconography. Among his most significant books are Light Weight Solidi and Byzantine Trade in the Sixth and Seventh Centuries, Medieval Commerce, and A Bronze Hoard of the Period of Leo I. THOMAS J. FIGUEIRA is Professor of Classics and of Ancient History at Rutgers University. He has written widely in ancient Greek history and historiography. His most recent works are Athens and Aigina in the Age of Imperial Colonization and Excursions in Epichoric History: The Aiginetan Essays. BENJAMIN R. FOSTER is Professor of Assyriology and Chairman of the Department of Near Eastern Languages and Civilizations at Yale University. He is the author of numerous studies of ancient Mesopotamian history and civili- 222 About the Editors and Contributors zation. His most recent major work is Before the Muses: An Anthology of Akkadian Literature. FEREYDOUN HOVEYDA, author and statesman, had his early education in Iran and later received his doctorate in law and economics from the Sorbonne (Paris). He was at one time the Iranian ambassador to the United Nations. His recent publications include, in the French language, ‘‘Que veulent les Arabes?’’ (‘‘What Do the Arabs Want?’’) (1991) and ‘‘L’Islam bloque’’ (‘‘Islam ´ Blocked’’) (1992). MARSHALL S. HURWITZ has taught religion at Columbia University and classical languages in the City University at Brooklyn College, the Graduate Center, and City College. He is an ordained rabbi and has published in the field of Hellenistic literature. Several articles on Hellenistic Jewish literature in the Encyclopedia Judaica were written by Professor Hurwitz. K. D. IRANI is Professor Emeritus of Philosophy at the City College of the City University of New York. He has written extensively on the philosophy of mind, theory of action, philosophy of law, and ancient thought. His lectures on the philosophy of the Ancient Indo-European tradition were published in the journal of the K. R. Cama Oriental Institute. THOMAS H. C. LEE is Professor of Chinese History and Chairman of the Asian Studies Department at the City College of the City University of New York. He taught previously at the Chinese University of Hong Kong where he also served as Director of the International Asian Studies Program. He has published widely on Chinese intellectual and social history in the United States, Japan, Hong Kong, Taiwan, and Germany. His books include Government Education and Examinations in Sung China and China and Europe: Images and Influences in the Sixteenth to Eighteenth Centuries. S. TODD LOWRY is Professor of Economics and Administration at Washington and Lee University. His research interests and published articles deal with early economic and legal concepts and their influence on modern thought. He is the author of The Archaeology of Economic Ideas: The Classical Greek Tradition and is editor of and contributor to Pre-Classical Economic Thought: From the Greeks to the Scottish Enlightenment. FARHANG MEHR is Professor of International Relations and International Law at Boston University. Prior to that, he served in ministerial positions in Iran and was Chancellor of the University of Shiraz in Iran. His most recent publication is ‘‘The Zoroastrian Tradition’’ (1991). RICHARD E. MITCHELL is Professor of History at the University of Illinois, About the Editors and Contributors 223 Urbana-Champaign. His research interests extend from numismatics, archaic religion, and law, to the political development of the Roman Republic and the growth of the Roman Empire. Most recently he published Patricians and Plebeians: The Origin of the Roman State. SCOTT N. MORSCHAUSER is Professor of History at Rowan College and has taught courses at the Johns Hopkins University, Princeton Theological Seminary, and the Smithsonian Institute. His principal area of study has been in ancient Egyptian warfare and diplomacy in the Ramesside Period. He is the author of Threat-Formulae in Ancient Egypt: A Study of the History, Structure and Use of Threats and Curses in Ancient Egypt and coeditor of Biblical and Related Studies Presented to Samuel Iwry. GREGORY NAGY (1979), which won the Goodwin Award of Merit, American Philological Association, in 1982. Other publications include Comparative Studies in Greek and Indic Meter (1974), Greek Mythology and Poetics (1990), and Pindar’s Homer: The Lyric Possession of an Epic Past (1990). Professor Nagy’s special research interests are archaic Greek literature and oral poetics, and he finds it rewarding to integrate these interests with teaching, especially in his course for Harvard’s Core Curriculum, ‘‘The Concept of the Hero in Greek Civilization.’’ He is currently the Chair of Harvard’s undergraduate Literature Concentration. M. G. PRASAD is Professor of Mechanical Engineering at Stevens Institute of Technology. He has some sixty-five publications in the fields of acoustics and vibration. In addition to his professional research interests, Dr. Prasad has been active in educational, cultural, and philosophical aspects of the Vedic heritage of India. He has organized several symposia on science and philosophy and has lectured widely on various topics dealing with Vedic heritage, such as the Sanskrit language, basics of Sanatana Dharma, Bhagavad Gita, and features of Vedic chanting. Dr. Prasad is a member of the Institute of Indian Culture, International Foundation for Vedic Education, and Astanga Yoga Vijnana Mandiram. He teaches Vivekananda Vidyapith and Venkateswara Vidyalaya at the Hindu Temple and Cultural Society in New Jersey, where he also cochairs an education committee. MORRIS SILVER is Professor of Economics and Chairman of the Department of Economics at the City College of the City University of New York. He has written widely about business organization, economic justice, and ancient economies. His books about ancient economies include Prophets and Markets: The 224 About the Editors and Contributors Political Economy of Ancient Israel (1983), Economic Structures of the Ancient Near East (1985), Taking Ancient Mythology Economically (1992), and Economic Structures of Antiquity (Greenwood, 1995). Professor Silver is also editor of and contributor to Ancient Economy in Mythology: East and West (1991). RAYMOND WESTBROOK is Professor of Assyriology and Bible in the Near Eastern Studies Department of the Johns Hopkins University. Trained as a lawyer, his field of specialization is ancient law, as attested in cuneiform documents, the Hebrew Bible, and the records of early Greece and Rome. His books include Old Babylonian Marriage Law and Property and the Family in Biblical Law.
https://www.scribd.com/document/46020527/Social-Justice-in-the-Ancient-World-K-D-Irani-Morris-Silver-ed
CC-MAIN-2017-09
refinedweb
98,541
51.38
Groovy, Java's New Scripting Language Pages: 1, 2 Groovy provides some syntax extensions beyond standard Java. One of the most interesting is what are called closures. This term has been overloaded in a lot of places in computer science, but for now just think of Groovy closures as being similar to anonymous inner classes. One difference is that variables can be passed in or out; Groovy closures do not constitute a "lexical scope" the way an inner class does. The example below, closures.groovy, shows how to break a String into a List and print it one word per line, both the "long way" and using closures. String List Example 4. closures.groovy # without closures x = "When in the course of human events ...".tokenize() for (val in x) println val # with closures "When in the course of human events ...".tokenize().each { val | println val } # with closures, default parameter name "When in the course of human events ...".tokenize().each { println it } The closure code is used to print each value of the list. In the first version, a parameter, val, is declared (before the |), and used in the body. In the second version, I use Groovy's default parameter name it (presumably short for "item"). val | it Another interesting syntax enhancement is the use of variable substitution within strings. Almost any String assignment can contain the pattern ${variablename}, and the value of the named variable will be interpolated into the String. This is a much more convenient form than Java's extensive use of the + operator for string concatenation. This can be used in printing, as in this hello.groovy example: ${variablename} + Example 5. hello.groovy and date.groovy i = 42 println "Hello ${i}" This prints "Hello 42". The interpolated value can be a property, as shown in date.groovy: i = new java.util.Date(); println "Today is day ${i.day} of month ${i.month}" I said that Groovy doesn't bring a lot of new API. But it does offer a lot of convenience methods added onto the standard API. For example, the Groovy version of String adds the tokenize() method used in the closure.groovy example above. The file docs/groovy-jdk.html in the Groovy distribution lists all of the methods added to the JDK classes; it's quite an extensive list, and adds up to a great deal of time saved when using Groovy compared to using "raw Java." tokenize() As another example, Groovy's java.io.File class has a newReader method that returns a BufferedReader (and newPrintWriter(), which returns a PrintWriter). java.io.File also has eachLine, which opens the file and reads each line for you; now that's high-level! The example below is wc.groovy, my implementation of wc, a traditional Unix tool that counts the lines, words, and characters in a text file: java.io.File newReader BufferedReader newPrintWriter() PrintWriter eachLine wc Example 6. wc.groovy # simple implementation of Unix "wc" in groovy. # could simplify with File.splitEachLine() but this way gets "chars" right. filename=args[0] chars=0; lines=0; words=0; new java.io.File(filename).eachLine { chars+=it.length() + 1 words+=it.tokenize().size(); lines++; } println "\t${lines}\t${words}\t${chars}\t${filename}" Running the script produces output that is close to the original: Example 7. wc.groovy versus the original ian:136$ wc test.txt 2 25 130 test.txt ian:137$ groovy wc.groovy test.txt 2 25 130 test.txt ian:138$ Groovy also adds several convenience methods for lists and maps; some of these are shown in the lists.groovy example below: Example 8. lists.groovy # List operations list = ["ian","brian","brain"] println list; println "Maximum value: ${list.max()}" # inject is like an iterator with carryover of last value list.inject("foo", { val, elem|println "${val} -- ${elem}"; return elem }) # findAll returns all the elements for which the closure returns true. println "findAll: "+list.findAll({it.contains("ian")}) # Ruby-style ranges, +- operators, etc. validCardYears = 2004..2008 validCardYears.each {println "Valid year: ${it}"} lastValidCardYear = validCardYears[-1] println "Last valid year is currently ${lastValidCardYear}" Running this catch-all script produces the following output. groovy src/lists.groovy [ian, brian, brain] Maximum value: ian foo -- ian ian -- brian brian -- brain findAll: [ian, brian] Valid year: 2004 Valid year: 2005 Valid year: 2006 Valid year: 2007 Valid year: 2008 Last valid year is currently 2008 Finally, just to prove it can be done, I back-ported wc.groovy into Java; the WC.java example gives the right answer, but has roughly twice the amount of code. Example 9. WC.java import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.StringTokenizer; /** simple implementation of unix "wc" in Java. */ public class WC { public static void main(String[] args) throws IOException { int chars=0, lines=0, words=0; String filename=args[0]; BufferedReader r = new BufferedReader(new FileReader(filename)); String it; while ((it = r.readLine()) != null) { chars+=it.length() + 1; words+=new StringTokenizer(it).countTokens(); lines++; } System.out.println("\t" + lines + "\t" + words + "\t" + chars + "\t" + filename); } } Groovy includes a tree-based markup generator called GroovyMarkup that can be subclassed to make a variety of tree-based object representations, including XML markup, HTML markup, SAX event firing, and even Swing user interfaces! The example below, swingbuilder.groovy, shows a user interface with a variety of labels and text fields built from a list, a pop-up "About" box, and two ways of exiting: a push button or just closing the main window (since defaultCloseOperation is set to EXIT_ON_CLOSE). defaultCloseOperation EXIT_ON_CLOSE Example 10. swingbuilder.groovy import groovy.swing.SwingBuilder; theMap = ["color":"green", "object":"pencil", "location":"home"]; // create a JFrame with a label and text field for each key in the Map swing = new SwingBuilder(); frame = swing.frame(title:'A Groovy Swing', location:[240,240], defaultCloseOperation:javax.swing.WindowConstants.EXIT_ON_CLOSE) { panel() { for (entry in theMap) { label(text:entry.key) textField(text:entry.value) } button(text:'About', actionPerformed:{ pane = swing.optionPane(message:'SwingBuilder Demo v0.0') dialog = pane.createDialog(null, 'About') dialog.show() }) button(text:'Quit', actionPerformed:{ System.exit(0) }); } } frame.pack(); frame.show(); There are no actions yet for the text fields, so changing them doesn't actually do anything. A more elaborate Swing demo, and other demos, can be found at the Groovy web site. Here's how it looks in action: Another interesting API that Groovy supports is the J2EE servlet API. Like standard JSPs, GroovyServlet provides an out object that is used here. The handleform.groovy example below is a simple GroovyServlet in action that receives the content of a simple HTML form (with name, address, phone number, and the like) and stores the fields' contents into a JavaBean, which is then persisted using an already written data accessor. out Example 11. handleform.groovy import java.util.Date import beans.Person import beans.PersonDAO bean = new Person(); bean.firstName = ${firstName} // etc for other properties out.println(<<<EOS <html> <head> <title>Thanks for Signing Up Via the Groovy Servlet</title> </head> <body> The Groovy Servlet thanks you, ${firstName} at ${request.remoteHost}, for signing up with us at ${new Date()}. <hr/> </body> </html> EOS) out.println("Bean = " + bean); new PersonDAO().insert(bean); out.println("<hr>"); out.println("(database updated)"); This example also shows use of the here document, an idea borrowed from the Bourne shell and its many derivatives on Unix. Everything from the line following the <<< up to the string that ends that line is copied, in this case to the argument of the out.println(), which causes the whole mess of HTML--after the substitution of ${firstName} and so on--back to the user's browser. <<< out.println() GroovyServlet does not pretend to be a full MVC framework like Struts or JSF, but it is good for some servlet tasks. To make the above Groovy script, one only needs a servlet and servlet-mapping elements in the web.xml file, and two .jar files, groovy.jar and asm.jar, from the distribution. servlet servlet-mapping Read more about GroovyServlet at the Groovy Servlets page. How about using Groovy from within Java? There are several ways. You can use groovyc just like javac to produce bytecode files. Suppose I have this complicated Groovy script, g.groovy: groovyc javac Example 12. g.groovy The command to run this as a script is groovy g.groovy, which produces this output: groovy g.groovy Hello 42 Now to compile it to bytecode, I just say groovyc g.groovy. Then I can call it from within a Java class. For example: groovyc g.groovy public class j { public static void main(String args[]) { new g().run(); } } Then I can compile and run class j using normal javac and java, remembering to include the Groovy .jar and its helper, asm.jar, in my classpath (I know there are better ways of doing so than shown, but I chose the most transparent one here for readers trying it out by hand): j java $ javac -classpath /home/ian/groovy/lib/groovy-1.0-beta-6.jar:/home/ian/groovy/lib/asm-1.4.1.jar:. j.java $ java -classpath /home/ian/groovy/lib/groovy-1.0-beta-6.jar:/home/ian/groovy/lib/asm-1.4.1.jar:. j Hello 42 $ There is far more to Groovy than I have room to explain in this article. If you're a Java developer and you're not already a raving fan of Jython, PNuts, or any of the other Java-related scripting languages, I urge you to download Groovy and give it a try. Even if you prefer one of those other scripting languages, check out Groovy--you might like it. Because Groovy is new, there is still a lot to be done. The Groovy developers are always looking for help. Groovy needs to do a better job of error handling. The groovysh interpreter prints a caught exception, and the Groovy runtime prints a stack trace. But most exceptions are the result of user error, and it would be good if Groovy could report on such errors a little better. groovysh As Groovy continues to mature, expect to see more and more about it in the Java media, and more developers using it for scripting tasks.. In June 2004, O'Reilly Media released Java Cookbook, 2nd Edition. Sample Chapter 8, "Data Structuring with Generics, foreach, and Enumerations (JDK 1.5)," is available free online. foreach.
http://www.onjava.com/pub/a/onjava/2004/09/29/groovy.html?page=2
CC-MAIN-2014-41
refinedweb
1,733
68.26
Welcome to the Parallax Discussion Forums, sign-up to participate. xinfreq = 12000000 clkfreq = 148500000 error = 1e9 for pppp = 0 to 15 if pppp = 0 then post = 1 else post = pppp * 2 for divd = 64 to 1 step -1 Fpfd = round(xinfreq / divd) mult = round(clkfreq * post / Fpfd) Fvco = Fpfd * mult Fout = round(Fvco / post) e = abs(Fout - clkfreq) if (e <= error) and (Fpfd >= 250000) and (mult <= 1024) and (Fvco > 99e6) and ((Fvco <= 201e6) or (Fvco <= clkfreq + 1e6)) then result_divd = divd result_mult = mult result_post = post result_pppp = (pppp-1) & 15 '%1111 = /1, %0000..%1110 = /2..30 result_Fpfd = Fpfd result_Fvco = Fvco result_Fout = Fout error = e endif next next print "XINFREQ: "; xinfreq, " (XI Input Frequency)" print "CLKFREQ: "; clkfreq, " (PLL Goal Frequency)" print print "Divd: "; result_divd, "D field = "; result_divd-1 print "Mult: "; result_mult, "M field = "; result_mult-1 print "Post: "; result_post, "P field = "; result_pppp print print "setclk(%1_"; print right(bin(result_divd-1),6); "_"; print right(bin(result_mult-1),10); "_"; print right(bin(result_pppp),4); "_10_11, "; clkfreq; ")" print print "Fpfd: "; result_Fpfd print "Fvco: "; result_Fvco print print "Fout: "; result_Fout print "Error: "; result_Fout - clkfreq I've got the Spin2 interpreter lodged into PNut.exe now, so F12 compiles and downloads Spin code. I made a quick list of all the things I need to do to get it set up right, but I got sidetracked on this PLL thing all night. I think it was ozpropdev who came up with the code I use that includes: Maybe _XDIV might be nice to still play around with? But, actually, I guess one could just restart the clock in assembly if one wanted to explore different settings... Does the listing file include the report above ? Also, it can be useful to allow users to specify the error threshold, and to have the search software function report all found values (_XDIV _XMUL _XDIVP) < given error Sometimes jitter matters more than absolute precision, or users may be wanting to do some margin testing. dgately EDIT: Obviously, my modifying "clk_mode" variable isn't correct for Chip's fully calculated version. It would be a case of replacing the four instructions of "replace old with new ..." with a simple "MOV clk_mode, result_clkmode" instead. Here is the PLL calculator in 80386 that is inside the compiler now: Man, the forum software hides things when it sees two @ symbols together. ModEdit: Code attached in a txt file Only one of these schemes at a time is acceptable to the compiler. It checks to make sure valid label sets are in the user's code and then acts accordingly. Whoops! I accidentally edited your post instead of quoting it... It would have to be an object to be so, unless I made it part of the interpreter. FYI.. That issue is top of the list to be resolved, and need not be an issue much longer. As a quick solution, the code has been attached as a text file to your post above. > cgracey wrote: » > > > Man, the forum software hides things when it sees two @ symbols together. > > > > > FYI.. That issue is top of the list to be resolved, and need not be an issue much longer. > > As a quick solution, the code has been attached as a text file to your post above. Thanks. I noticed earlier that sometimes, rather than quote a message, it would just put '>' signs in front of each paragraph. I'd been trying to figure out the source of that, and I think I just found the issue in the same plugin that's spoiling the [@ @] chars (and a bunch of other char combos). Thanks for mentioning it, as I wasn't entirely sure if that's something you were deliberately doing ! Anyone needing a runtime change need only include and call it? > @cgracey , what is the default _clkfreq to use if only _xtlfreq or _xinfreq is given? You need to assign a value to _xtlfreq or _xinfreq and that value becomes clkfreq. Also, clkmode is set to %1110 or %1010 for _xtlfreq or %0110 for _xinfreq. There is no default clkfreq value for those cases. The previous clkmode must be known in order to safely switch away from it. That value is always kept in Spin2, so there's never a chance of the clkmode being unknown. Well, if a programmer didn't use the CLKSET instruction and just did a HUBSET, that would cause the value to become unknown. If you switch clocks you have to wait until both clocks are high (or both are low) to avoid glitches. So when you switch from a faster clock to a slower one it sometimes takes more than serveral clock cycles of the faster one. If the PLLs is switched off before the clock switchover is completed then the processor hangs. This could have been avoided if PLL shutdown had been delayed until after switchover was sucessful. But I guess this wasn't implemented in the current silicon. It just locks the current clock state (0/1) and then waits for the new source to transition to the same state before switching over to it. The whole thing worked fine until I added a divide-by-one PLL output mode which bypassed the post-divider. When deselected, it glitches before the clock switcher grabs hold of the current state. Now, in case you are using the divide-by-one mode, you need to keep the PLL mode bits in the same state while switching to another clock source. This means you need to keep a copy of the current clock mode in RAM somewhere that you can employ to switch the clock mode later. You need to switch from PLL mode to RCFAST mode while keeping the same PLL mode bits. In Spin2, this is all taken care of automatically with a SETCLK(mode,freq) instruction. Here is the code that goes into the Spin2 compiler that is in PNut.exe: That is correct. (*edit: I think Chip has clarified below that it's PLL modes rather than xtal modes that have the issue). The convention that fastspin, TAQOZ, p2gcc, Catalina, and riscvp2 have adopted is that the current clock mode is stored at $18 in HUB memory and the current clock frequency is at $14. MicroPython and proplisp also follow this convention because the compilers used to build them do so. loadp2 and the default ROM bootloader leave the system in RCFAST mode before they start the loaded program, so it's safe to set any mode in a freshly loaded program. The exception is that if the -PATCH option is given to loadp2 then it patches the loaded binary to contain the current clock frequency and mode at $14-$18 and leaves the system in that frequency (whatever was given as the -f option to loadp2). What about changing from one PLL clock mode to another? Do you have to know the current clock mode in order to do this? It's just switching to the PLL mode or away from the PLL mode that is problematic. Switching among crystal, RCFAST, and RCSLOW modes is no problem.
http://forums.parallax.com/discussion/171044/pll-settings-calculator
CC-MAIN-2020-29
refinedweb
1,179
67.89
I often code user interfaces that have some sort of cancel button on them. For example, in my upcoming ‘Decoupling Workflow’ presentation, I have the following screen: Notice the nice cancel button on the form. The trick to this situation is that I need to have my workflow code understand whether or not I clicked Next or clicked Cancel. Depending on the button that was clicked, I need to do something different in the workflow. If I click cancel, throw away all of the data that was entered on the form. If I click next, though, I need to store all of the data and continue on to the next screen. The Result<T> and ServiceResult In the past, I’ve handled these types of buttons in many, many different ways. I’ve returned null from the form, I’ve checked the DialogResult of the form, I’ve done out parameters for methods, and I’ve done specific properties on the form or the form’s presenter to tell me the status vs the data. Recently, though, I’ve begun to settle into a nice little Result<T> class that does two things for me: - Provides a result status – for example, a ServiceResult enum with Ok and Cancel as the two options - Provides a data object (the <T> generic in Result<T>) for the values I need, if I need them Here is the code for my ServiceResult and my Result<T> object. public enum ServiceResult { Ok = 0, Cancel = 1 } public class Result<T> { public ServiceResult ServiceResult { get; private set; } public T Data { get; private set; } public Result(ServiceResult serviceResult): this(serviceResult, default(T)){} public Result(ServiceResult serviceResult, T data) { ServiceResult = serviceResult; Data = data; } } Putting Result<T> To Work With this simple little solution, I can create very concise and clear workflow objects that know how to handle the cancel button versus the next button. The code becomes easier to read and understand, and makes the real workflow that much easier to see. The workflow code that runs the “Add New Employee” process for the screen shot above, is this: public void Run() { Result<EmployeeInfo> result = GetNewEmployeeInfo.Get(); if (result.ServiceResult == ServiceResult.Ok) { EmployeeInfo info = result.Data; Employee employee = new Employee(info.FirstName, info.LastName, info.Email); Employee manager = GetEmployeeManager.GetManagerFor(employee); manager.Employees.Add(employee); } } Notice the use of Result<EmployeeInfo> in this code. I’m checking to see if the result.ServiceResult is Ok before moving on to the use of the data. The GetNewEmployeeInfo class return a Result<EmployeeInfo> object from the .Get() method. The EmployeeInfo object contains the first name, last name, and email address of the employee as simple string values (and in the “real world”, the EmployeeInfo object would probably contain the input validation for these). Because Result<T> is a generics class and returns <T> from the .Data property, I can specify any data value that I need and it returned from the presenter in question. This is where the real flexibility of the Result<T> object comes into play. When I have verified that the user clicked OK, via the result.ServiceResult property, I can then grab the real EmployeeInfo object out of the result.Data parameter which isstrongly typed to my EmployeeInfo class. Once I have this data in hand, I can do what I need with it and move on to the next step if there are any. Conclusion Having tried many different approaches to workflow code, I’m fairly well settled into this pattern right now. That doesn’t mean it won’t evolve, though. The basic implementation would cover most of what I need right now, but could easily be extended to include different “status” values instead of just the ServiceResults of OK and Cancel. Overall, though, this simple Result<T> class is saving me a lot of headache and heartache trying to figure out what to return from a method so that a workflow can figure out if the user is continuing, cancelling, or whatever. Get The Best JavaScript Secrets! Get the trade secrets of JavaScript pros, and the insider info you need to advance your career! Post Footer automatically generated by Add Post Footer Plugin for wordpress.
http://lostechies.com/derickbailey/2009/05/19/result-lt-t-gt-directing-workflow-with-a-return-status-and-value/
CC-MAIN-2014-52
refinedweb
701
52.39
Better Spring with IntelliJ IDEA 10.5 Yes! The sunny Spring has finally come to St.Petersburg too. However, it’s not that “Spring” we want to talk now… We realize that many of you use the Spring framework in your every day work. So, many should be interested in the new Spring-related features that can be found in the upcoming IntelliJ IDEA 10.5 release. 1. Better navigation between xml configs and annotated stereotype components 2. Advanced usage search for @Autowired beans 3. More inspections for your configs, for instance, deprecated classes and members highlighting. 4. More powerful placeholder support. All spring model inspections get and analyze placeholder values before highlighting. 5. More clear Bean Dependencies Graph view. For instance, it obtains beans and dependencies from custom namespaces. Check out this spring integration schemas example. There are also smaller changes here and there… Download IntelliJ IDEA 10.5 RC to try it and enjoy the improved Spring framework support. 2 Responses to Better Spring with IntelliJ IDEA 10.5 Joseph says:May 9, 2011 Hi all Thanks for the new features In order to be a fantastic release for spring, i think new spring projects must be supported as well such as spring data and spring social i am not very familiar with spring social , but i currently use spring data , so i created a ticket for it at youTrack IDEA-68745 Add support for Spring data project it will be fantastic to close this issue b4 10.5 final thanks joe magicprinc says:May 10, 2011 cool!
https://blog.jetbrains.com/idea/2011/05/better-spring-with-intellij-idea-105/
CC-MAIN-2021-10
refinedweb
260
65.12
For some reason you may want or need to implement an RPM Compare method, i.e. rpmvercmp(), in C#. This is a working model I adapted from a C version of RPM Compare, see:. I wrote my version sometime in 2017, some of the links from my source are now dead. I added links here for you to walk through part of the path I took. RPM Compare works by comparing each part of the package name in a well-formed RPM. I won’t try to explain the RPM version comparison logic. I found Jason Antman’s Blog post “How Yum and RPM Compare Versions” to be very helpful. He explains the madness well. Like the official rpmvercmp() method, the C# version here compares string a to string b: if string a is equal to string b, return 0 if string a is newer than string b, return 1 if string a is older than string b, return -1 The RPM compare assumes a check separately on each of the five parts of the full RPM package name. Jason’s blog post is great at helping wrap your head around the comparison model. This version is basically a translation from the C version. When I looked at the original code, I wanted to cry. I have a dislike to multiple return statements in a function. I find them difficult to debug or walk through. Multiple exit points in method screams the need to split the code into easy-to-follow functions. My intent was to make that change but thought better of it. It is more important for someone to compare to the original and make any updates to match when bugs are found. There are test values for rpmvercmp() to validate the method. You can adapt this list for your own implementation. Below the class sample is a pseudo-code example. RPM Version Compare in C#, Class Implementation using System; using System.Text; public partial class RpmMethods { /// <summary> /// compare alpha and numeric segments of two RPM versions strings /// </summary> /// <returns> /// 1: one is newer than two /// 0: one and two are the same version /// -1: two is newer than one /// </returns> /// <see cref=""/> /// <see cref=""/> /// <see cref=""/> /// <seealso cref=""/> /// <remarks>This is taken from the references above and reworked from C to C#. /// The multiple return points are from the original C version. /// This is a translation of the C pointer method into a C# string iteration. /// The RPM.org function ignores Unicode letters, hence the /// Encoding translation of the input arguments into working strings.</remarks> private static int RpmVerCmp(string oneToTest, string twoToTest) { bool isnum = false; int rc; // handle NULL input arguments if (string.IsNullOrEmpty(oneToTest) == true) { oneToTest = string.Empty; } if (string.IsNullOrEmpty(twoToTest) == true) { twoToTest = string.Empty; } // It uses the .NET ASCII encoding to convert a string. // UTF8 is used during the conversion because it can represent any of the original characters. // It uses an EncoderReplacementFallback to convert any non-ASCII character to an empty string. string one = Encoding.ASCII.GetString( Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding( Encoding.ASCII.EncodingName, new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback() ), Encoding.UTF8.GetBytes(oneToTest) ) ); string two = Encoding.ASCII.GetString( Encoding.Convert( Encoding.UTF8, Encoding.GetEncoding( Encoding.ASCII.EncodingName, new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback() ), Encoding.UTF8.GetBytes(twoToTest) ) ); // If the strings are binary equal (a == b), they’re equal, return 0 if (string.Compare(one, two) == 0) { return (0); } // loop through each version segment of one and two and compare them left-to-right while (one.Length > 0 || two.Length > 0) { string oneLeftPart = string.Empty; string twoLeftPart = string.Empty; // Trim anything that’s not [A-Za-z0-9] or tilde (~) from the front of both strings. while (one.Length > 0) { if (char.IsLetter(one, 0) == false && char.IsDigit(one, 0) == false && one.StartsWith("~") == false) { one = one.Substring(1, (one.Length - 1)); // the parts after the segment } else { break; } } // same for string two as above while (two.Length > 0) { if (char.IsLetter(two, 0) == false && char.IsDigit(two, 0) == false && two.StartsWith("~") == false) { two = two.Substring(1, (two.Length - 1)); // the parts after the segment } else { break; } } // handle the tilde separator, it sorts before everything else if (one.StartsWith("~") == true || two.StartsWith("~") == true) { // If both strings start with a tilde, discard it and move on to the next character if (one.StartsWith("~") == true && two.StartsWith("~") == true) { one = one.Substring(1, (one.Length - 1)); // pop 1 char off two = two.Substring(1, (two.Length - 1)); // pop 1 char off } else { // If string one starts with a tilde and string two does not, return -1 (string one is older) // and the inverse if string two starts with a tilde and string one does not if (one.StartsWith("~") == true) { return (-1); } if (two.StartsWith("~") == true) { return (1); } } continue; } // End the loop if either string has reached zero length. if (one.Length == 0 || two.Length == 0) { break; } // Note, "Segments" are represented by oneLeftPart and twoLeftPart strings // If the first character of one is a digit, pop the leading chunk of // continuous digits from each string // (which may be "" for two if only one starts with digits). // If one begins with a letter, do the same for leading letters. // grab first completely alpha or completely numeric segment // leave one and two pointing to the start of the alpha or numeric // segment and walk oneRightPart and twoRightPart to end of segment if (char.IsDigit(one, 0) == true) { while (one.Length > 0) { if (char.IsDigit(one[0]) == true) { oneLeftPart += one[0]; // append the leading char of one onto oneLeftPart one = one.Substring(1, (one.Length - 1)); // pop 1 char off } else { break; } } while (two.Length > 0) { if (char.IsDigit(two[0]) == true) { twoLeftPart += two[0]; two = two.Substring(1, (two.Length - 1)); // pop 1 char off } else { break; } } isnum = true; } else // loop on letter segment { while (one.Length > 0) { if (char.IsLetter(one[0]) == true) { oneLeftPart += one[0]; one = one.Substring(1, (one.Length - 1)); // pop 1 char off } else { break; } } while (two.Length > 0) { if (char.IsLetter(two[0]) == true) { twoLeftPart += two[0]; two = two.Substring(1, (two.Length - 1)); // pop 1 char off } else { break; } } isnum = false; } // this cannot happen, as we previously tested to make sure that // the first string has a non-null segment //if (one[i] == oneRightPart[0]) //{ // return (-1); // arbitrary //} // If the segment from two had 0 length, // return 1 if the segment from one was numeric, or -1 if it was alphabetic. // The logical result of this is that if one begins with numbers and two does not, one is newer (return 1). // If one begins with letters and two does not, then one is older (return -1). // If the leading character(s) from one and two were both numbers or both letters, continue on. // take care of the case where the two version segments are // different types: one numeric, the other alpha (i.e. empty) // numeric segments are always newer than alpha segments // XXX See patch #60884 (and details) from bugzilla #50977. if (twoLeftPart.Length == 0) { return ((isnum == true) ? 1 : -1); } // If the leading segments were both numeric, discard any leading zeros and whichever is longer wins. // If one is longer than two (without leading zeroes), return 1, and vice-versa. // If they’re of the same length, continue on. if (isnum == true) { int onelen, twolen; // this used to be done by converting the digit segments // to ints using atoi() - it's changed because long // digit segments can overflow an int - this should fix that. // throw away any leading zeros - it's a number, right? while (oneLeftPart.StartsWith("0") == true) { oneLeftPart = oneLeftPart.Substring(1, oneLeftPart.Length - 1); } while (twoLeftPart.StartsWith("0") == true) { twoLeftPart = twoLeftPart.Substring(1, twoLeftPart.Length - 1); } // whichever number has more digits wins onelen = oneLeftPart.Length; twolen = twoLeftPart.Length; if (onelen > twolen) { return (1); } if (twolen > onelen) { return (-1); } } // Compare the leading segments with strcmp() (or <=> in Ruby, string.CompareOrdinal() in C#). // If that returns a non-zero value, then return that value. Else continue to the next iteration of the loop. // Compare will return which one is greater - even if the two segments are alpha or numeric. // don't return if they are equal because there might be more segments to compare rc = string.CompareOrdinal(oneLeftPart, twoLeftPart); if (rc != 0) { return (rc < 1 ? -1 : 1); } } // If the loop ended (nothing has been returned yet, // either both strings are totally the same or they’re the same up to the end of one of them, // like with “1.2.3” and “1.2.3b”), then the longest wins if // what’s left of one is longer than what’s left of two, return 1. // Vice-versa for if what’s left of two is longer than what’s left of one. // And finally, if what’s left of them is the same length, return 0. // this catches the case where all numeric and alpha segments have // compared identically but the segment separating characters were different // whichever version still has characters left over wins if (one.Length > two.Length) { return (1); } else if (one.Length < two.Length) { return (-1); } else // (one.Length = two.Length) { return (0); } } } Example Pseudo-code Implementation of RpmVerCmp() // pseudo-code example of use, based on parts of the RPM package full name // The format for the whole string is n-e:v-r.a // for example // assume 'a' RPM is: 0:kernel-3.10.0-1127.13.1.el7.x86_64.rpm // assume 'b' RPM is: 0:kernel-3.10.0-1160.36.2.el7.x86_64.rpm // parse the RPM into the relevant parts // 'a' strings // and // 'b' strings string aEpoch = "0"; string bEpoch = "0"; string aName = "kernel"; string bName = "kernel"; string aVersion = "3.10.0"; string bVersion = "3.10.0"; string aRelease = "1127.13.1.el7"; string bRelease = "1160.36.2.el7"; string aArchitecture = "x86_64"; string bArchitecture = "x86_64"; int result; int iEpc; int iNam; int iVer; int iRel; int iArc; // 1: one (a) is newer than two (b) // 0: one and two are the same version // -1: two is newer than one iEpc = RpmVerCmp(aEpoch, bEpoch); iNam = RpmVerCmp(aName, bName); iVer = RpmVerCmp(aVersion, bVersion); iRel = RpmVerCmp(aRelease, bRelease); iArc = RpmVerCmp(aArchitecture, bArchitecture); // check each RPM part in order, first non-zero is final result if (iEpc <> 0) // epoch result = iEpc; else if (iNam <> 0) // name result = iNam; else if (iVer <> 0) // version result = iVer; else if (iRel <> 0) // release result = iRel; else if (iArc <> 0) // architecture result = iArc; else result = 0; // must be same if you get here return result;
https://nerva.com/implementing-rpm-compare-in-c/
CC-MAIN-2022-40
refinedweb
1,745
67.04
Making Wiggly div is most interesting and at the same time a complex thing. It will be good for cases for like some cool portfolio, a landing page with some important text etc. Its more like making a div more funny. In this article we will gonna learn how we can create a wiggly div in React. react-wiv This package is a react version of wiv.js. It uses a library named wiv.js internally. It super simple and easy to create wiggly div using react-wiv. In just few lines of code we can accomplish our task without need to worry about the complexity. Installation and Usage Like any other npm package we can install it using npm command. npm install --save react-wiv Once this package is installed. You need to import this package using below code. import Wiv from 'react-wiv' and we are good to use it. <Wiv color="#00FF00" height={4} tightness={6} thickness={2} speed={0.55}> Blogreact </Wiv> We just provided few props like color, height, speed etc and got this output. Feel free to comment your thoughts. How to send SMS using Bandwidth in Node Discussion (0)
https://dev.to/narendersaini32/how-to-make-wiggly-div-in-react-2282
CC-MAIN-2022-05
refinedweb
196
76.72
Devices in PyZMQ¶ See also ØMQ Guide Device coverage. ØMQ has a notion of Devices - simple programs that manage a send-recv pattern for connecting two or more sockets. Being full programs, devices include a while(True) loop and thus block execution permanently once invoked. We have provided in the devices subpackage some facilities for running these devices in the background, as well as a custom three-socket MonitoredQueue device. BackgroundDevices¶ It seems fairly rare that in a Python program one would actually want to create a zmq device via device() in the main thread, since such a call would block execution forever. The most likely model for launching devices is in background threads or processes. We have provided classes for launching devices in a background thread with ThreadDevice and via multiprocessing with ProcessDevice. For threadsafety and running across processes, these methods do not take Socket objects as arguments, but rather socket types, and then the socket creation and configuration happens via the BackgroundDevice’s foo_in() proxy methods. For each configuration method (bind/connect/setsockopt), there are proxy methods for calling those methods on the Socket objects created in the background thread or process, prefixed with ‘in_’ or ‘out_’, corresponding to the in_socket and out_socket: from zmq.devices import ProcessDevice pd = ProcessDevice(zmq.QUEUE, zmq.ROUTER, zmq.DEALER) pd.bind_in('tcp://*:12345') pd.connect_out('tcp://127.0.0.1:12543') pd.setsockopt_in(zmq.IDENTITY, 'ROUTER') pd.setsockopt_out(zmq.IDENTITY, 'DEALER') pd.start() # it will now be running in a background process MonitoredQueue¶ One of ØMQ’s builtin devices is the QUEUE. This is a symmetric two-socket device that fully supports passing messages in either direction via any pattern. We saw a logical extension of the QUEUE as one that behaves in the same way with respect to the in/out sockets, but also sends every message in either direction also on a third monitor socket. For performance reasons, this monitored_queue() function is written in Cython, so the loop does not involve Python, and should have the same performance as the basic QUEUE device. One shortcoming of the QUEUE device is that it does not support having ROUTER sockets as both input and output. This is because ROUTER sockets, when they receive a message, prepend the IDENTITY of the socket that sent the message (for use in routing the reply). The result is that the output socket will always try to route the incoming message back to the original sender, which is presumably not the intended pattern. In order for the queue to support a ROUTER-ROUTER connection, it must swap the first two parts of the message in order to get the right message out the other side. To invoke a monitored queue is similar to invoking a regular ØMQ device: from zmq.devices import monitored_queue ins = ctx.socket(zmq.ROUTER) outs = ctx.socket(zmq.DEALER) mons = ctx.socket(zmq.PUB) configure_sockets(ins,outs,mons) monitored_queue(ins, outs, mons, in_prefix='in', out_prefix='out') The in_prefix and out_prefix default to ‘in’ and ‘out’ respectively, and a PUB socket is most logical for the monitor socket, since it will never receive messages, and the in/out prefix is well suited to the PUB/SUB topic subscription model. All messages sent on mons will be multipart, the first part being the prefix corresponding to the socket that received the message. Or for launching an MQ in the background, there are ThreadMonitoredQueue and ProcessMonitoredQueue, which function just like the base BackgroundDevice objects, but add foo_mon() methods for configuring the monitor socket.
http://pyzmq.readthedocs.io/en/latest/devices.html
CC-MAIN-2017-47
refinedweb
588
51.28
The following table describes the important changes to this documentation. AWS Connector for vCenter version 2.7.0 vSphere Web Client support: You can now use AWS Connector for vCenter with vSphere Web Client 5.5 and 6.0. You must register your connector after the upgrade. For more information, see Re-register your connector to use it with vSphere Web Client. Improved error reporting to AWS: When you send logs to AWS, you can provide a description of the issue you are troubleshooting. For more information, see Reporting a Problem to AWS. Improved VM migration: When you migrate a VM, any CD or DVD drives attached to the VM are excluded automatically. January 20, 2016 AWS Connector for vCenter version 2.6.0 You can now use connector to migrate virtual machines with more than one virtual disk to Amazon EC2. This feature may require that you grant additional permissions. For more information, see Additional permissions are required to migrate multidisk virtual machines. October 28, 2015 Added support for exporting a migrated EC2 instance After you migrate a VM to Amazon EC2, you can export the instance if needed. This process creates an OVA file and stores it in an S3 bucket in your AWS account. For more information, see Exporting a Migrated EC2 Instance. August 26, 2015 AWS Connector for vCenter version 2.5.0 vCenter 6.0 support: You can use VMware vCenter 6.0 from the vSphere Client for desktop. New region support: You can create resources and migrate VMs to Amazon EC2 in the EU (Frankfurt) region. Trusted SSL certificates: You can upload an SSL certificate to your connector so that your browser can verify the site. For more information, see Installing a Trusted SSL Certificate. DNS suffix configuration: You can configure the DNS suffix search list through the CLI. July 22, 2015 AWS Connector for vCenter version 2.4.x Automatic upgrades: You can receive automatic upgrades for the connector. VM import: If the connector reaches its limit on the number of active import tasks, it queues additional import tasks until an active import task completes successfully or is canceled. For more information, see Migrating Your Virtual Machine to Amazon EC2 Using AWS Connector for vCenter. Verify untrusted SSL certificates: You can display the SSL certificate of the connector from the setup CLI so that you can manually verify the certificate that the management console presents to your browser. For more information, see Validating an Untrusted SSL Certificate. Debug logs: You can securely send connector logs to AWS. For more information, see Reporting a Problem to AWS. March 05, 2015 Added support for configuration reset and managing existing EC2 instances If you want to change the authentication provider that you used to set up AWS Management Portal for vCenter, you can return to the setup program and reset the trust relationship. You can manage your EC2 instances that you created outside AWS Management Portal for vCenter using AWS Management Portal for vCenter. October 03, 2014 Added support for the connector as an authentication provider Starting with version 2.1.0 of the connector, you can choose the connector as the authentication provider for the management portal. The initial release of AWS Management Portal for vCenter included version 2.0.0 of the connector, which requires that you use an identity provider (IdP) that supports SAML 2.0 as the authentication provider. For more information, see Installing and Configuring AWS Management Portal for vCenter. August 20, 2014 Added support for default environments Default environments enable you manage EC2 instances that were created for your AWS account using tools other than the management portal. For more information, see Managing Environments. Initial release The initial release of the AWS Management Portal for vCenter User Guide. May 30, 2014 Javascript is disabled or is unavailable in your browser. To use the AWS Documentation, Javascript must be enabled. Please refer to your browser's Help pages for instructions.
https://docs.aws.amazon.com/amp/latest/userguide/document-history.html
CC-MAIN-2019-04
refinedweb
659
57.37
On Thu, Mar 15, 2012 at 09:46:24AM -0700, Greg KH wrote:> On Thu, Mar 15, 2012 at 05:27:26PM +0100, Jiri Slaby wrote:> > On 03/15/2012 11:48 AM, Jiri Slaby wrote:> > > On 03/12/2012 09:34 PM, Greg KH wrote:> > >> I'm announcing the release of the 3.0.24 kernel.> > > ...> > >> Heiko Carstens (1): compat: fix compile breakage on s390> > > > > > It looks like we need the same fix as for 2.6.32.59:> > > arch/s390/kernel/setup.c: In function 'setup_addressing_mode':> > > arch/s390/kernel/setup.c:328: error: 'PSW32_ASC_PRIMARY' undeclared> > > (first use in this function)> > > arch/s390/kernel/setup.c:328: error: (Each undeclared identifier is> > > reported only once> > > arch/s390/kernel/setup.c:328: error: for each function it appears in.)> > > > And when that one is fixed, there is another error:> > drivers/s390/char/fs3270.c: In function 'fs3270_ioctl':> > drivers/s390/char/fs3270.c:335: error: implicit declaration of function> > 'compat_ptr'> > drivers/s390/char/fs3270.c:335: warning: assignment makes pointer from> > integer without a cast> > Ick, have a patch for this?This one is declared in arch/s390/include/asm/compat.h:static inline void __user *compat_ptr(compat_uptr_t uptr){ return (void __user *)(unsigned long)(uptr & 0x7fffffffUL);}In 2.6.32, fs3270.c include linux/compat.h. In 3.0 it includes asm/compat.hinstead. I would have thought the later would have been enough.Hoping this helps,Willy
https://lkml.org/lkml/2012/3/15/298
CC-MAIN-2015-14
refinedweb
237
60.82
concert 0.6.0 Lightweight beamline control system Concert is a light-weight control system interface to control Tango and native devices. It can be used as a library: from concert.quantities import q from concert.devices.motors.dummy import Motor motor = Motor() motor.position = 10 * q.mm motor.move(-5 * q.mm) or from a session and within an integrated IPython shell: $ concert init session $ concert start session session > motor.position = 10 * q.mm 10.0 millimeter You can read more about Concert in the official documentation. - Downloads (All Versions): - 215 downloads in the last day - 574 downloads in the last week - 1323 downloads in the last month - Author: Matthias Vogelgesang - License: LGPL - Package Index Owner: Matthias.Vogelgesang - DOAP record: concert-0.6.0.xml
https://pypi.python.org/pypi/concert/0.6.0
CC-MAIN-2014-15
refinedweb
126
52.26
modal panel rerendering bug?Akaine Harga Nov 6, 2010 6:20 PM I'll try to be brief but it's somehow difficult to explain, though relatively easy to simulate. Let's say we have a simple catalogue administration page: <a4j:keepAlive <a4j:form <rich:panel <a4j:commandButton </rich:panel> <!-- some ther stuff including existant cars list, etc. --> </a4j:form> <rich:modalPanel <f:facet <h:outputText </f:facet> <a4j:form <h:panelGrid <h:outputText <h:inputText <h:outputText <rich:comboBox <f:selectItems </rich:comboBox> <h:outputText <rich:comboBox <f:selectItems </rich:comboBox> <h:outputText <rich:inputNumberSpinner </h:panelGrid> <div style="text-align: center;"> <a4j:commandButton <rich:spacer <a4j:commandButton </div> </a4j:form> </rich:modalPanel> And the backing bean: public class ControllerCars { private List<Car> cars = new ArrayList<Car>(0); private List<SelectItem> brandsSI = new ArrayList<SelectItem>(0); private List<SelectItem> yearsSI = new ArrayList<SelectItem>(0); private Car car; //an entity bean with correspondant fields inside @EJB private CarFacadeLocal carFL; // VIEW METHODS ======================================= public String loadPageCars(){ return "LOAD_Cars"; } //a method that is called every time the page is loaded using javascript public void reloadView(){ car = null; cars = loadCars(); //a method that loads the cars list //some other stuff the page needs lo be loaded } // CAR MODAL ========================================== public void flushCar(){ car = null; brandsSI.clear(); yearsSI.clear(); } public void prepareNewCar(){ car = new Car(); //it's a default construtor, no fields initialized brandsSI = fillBrands(); //a private method to fill the list with SelectItems yearsSI = fillYears(); //same as above } public void saveCar(){ carFL.save(car); flushCar(); cars = loadCars(); } // etc. } Looks pretty simple... Now, the actual error I've been experiencing since the beggining of times: 1. I click the "Add new" button and a modal opens (the car object is getting initialized) 2. I fill some data missing a field 3. I click "Save" and a modal_errors window pops up showing the list of errors (the required field I've missed for ex.) 4. I close the errors modal and click the "Cancel" button (the car object is getting nulled at this moment) 5. I click the "Add new" button again (the car object id getting initialized again with ampty fields) and the modal_car is opened At this point the form_car will have the old values I left before I hit the "Cancel" button and I have no explanation for this. - all methods are getting executed as they should - I printed out the Car fields and they all have null value at the moment of initialization - this happens in all popular browsers (FF,IE,Safari,Chrome,Opera) - I have several corporate size applications based on this architecture and they all have this flaw while the rest is working perfectly fine - the modal_errors is a simple modal panel with rich:messages inside and a button to close it, no events attached My guess is that the temporal js backing bean fields counterparts are not getting wiped out when I press "Cancel" and somehow the error modal is affecting the process, since if I don't hit the "Save" button prior to "Cancel" the form is getting cleared as it should. JSF 1.2, Facelets 1.1.15, RF 3.3.3 GA, Jboss 5.1 GA Any ideas? 1. Re: modal panel rerendering bug?liumin hu Nov 8, 2010 3:01 AM (in response to Akaine Harga) hi, i think there is a problem if you rerender modal panel, try rerender the form. liu 2. Re: modal panel rerendering bug?Akaine Harga Nov 8, 2010 2:50 PM (in response to liumin hu) Tried this one in the very beginning... Outputting the messages I see that the modal/form actually gets rerendered, the problem is that the temporal js variabled are not getting reset. 3. Re: modal panel rerendering bug?Ilya Shaikovsky Nov 9, 2010 10:00 AM (in response to Akaine Harga) try to add ajax single="#{true}" to the add new command. In general it's kind of problem 4. Re: modal panel rerendering bug?Akaine Harga Nov 9, 2010 12:21 PM (in response to Ilya Shaikovsky) Already had it everywhere, just forgot to put it in the example code. The article is pretty interesting though: seems I'm slowly beginning to get the idea... 5. modal panel rerendering bug?rafael.sales Feb 9, 2011 7:49 AM (in response to Ilya Shaikovsky) I'm facing the same problem with Richfaces 4 M5, but using rich:popupPanel. Because the RF 4M5 doesn't have the ajaxSingle attribute, I've put the execute="@this" instead of ajaxSingle="true" as said in this article:
https://developer.jboss.org/message/570291
CC-MAIN-2016-50
refinedweb
758
59.23
. £1.6 million is a lifetime’s worth of money, no? It’s median income for the likely 60 year lifespan of a 30 year old. Another way to put it, that’s a house and a holiday home bought outright and the pension fully paid up. Yes, life gets pretty easy once those are all paid for:. Aha. Living well without having to work? That’s a very, very, much more expensive proposition, isn’t it? At one point, the pair were spending up to £30,000 a month, including £1,000 a week on groceries. Blimey. You’d need a capital sum of more like £10 million to buy that lifestyle. Perhaps more actually, 5% return (bit high but dividends from an index fund maybe?) then tax to leave £360,000 a year left over? More than £10 million maybe. I therefore dismiss the claim. About right. Under UK (but not French) law you can leave your entire estate to a donkey sanctuary if you wish. So who was the greedy lawyer who thought this case had any chance of success? Talking of donkey sanctuaries, this guy seems to be a bit of an asshole. 1.6 M quid tax-free as a gift (luckily there’s no UK gift tax…) @ say 4% return (should be doable with a managed portfolio at that level) gives 64k income a year. Enough to be comfortable on without working. But really, this kind of thing is quite common with people who come into a windfall – they blow it and end up destitute at the end. Isn’t there a 7 year inheritance tax rule on gifts? Curious to know what his cause of action purported to be. Promise made and not kept? Verbal contract sorta thing? ‘Bout the only possible one I can see. “Aha. Living well without having to work? “ With the subsequent publicity he’s now brought down on his head, who’ll ever employ him again? @BiND – Yes. Should the donor kick the bucket within 7 years of making the gift its value is rolled back into the Estate for IHT purposes. There is some measure of taper relief, but it’s not generous! Greedy fucking bastard. “He claimed the couple had promised to ensure he and his partner, James Beedle, 34, would never have to worry about money again.” Tim: “Promise made and not kept? Verbal contract sorta thing? ‘Bout the only possible one I can see.” As far as I can see it, the promise was kept. With 1.6M there was no need to worry about money again. That the recipient blew it by being a tit is his own problem. ‘Cor blimey, talking about biting the hand that feeds. .” What a thoroughly unpleasant little man. “bloke in france Under UK (but not French) law you can leave your entire estate to a donkey sanctuary if you wish” Indeed you can. But The Inheritance (Provision for Family and Dependants) Act 1975 provides that adult children are entitled to apply for reasonable provision from the estate of a deceased parent. So such a will could be challenged. Google Ilott v Mitson for a recent example. “I therefore dismiss the claim. And you, sir, are an utter cunt” I bet the judge wished he could say the second bit. How sharper than a serpent’s tooth… There wasn’t a contract, Tim. Consideration didn’t pass both ways. It’s disturbing that this ever got to court. Things like this are killing off generosity. The obvious moral to take from it is, if you ever come into money, don’t give any away, unless you want to find yourself in court. The Telegraph added: ————- After the ruling, Mr Beedle, who has now transferred to the Royal Fleet Auxiliary after leaving the Royal Navy, was philosophical. “There are no hard feelings,” he said. “We just thought we had a genuine claim.” ————- Mr Beedle is the son’s civil partner. Sounds like he was the ‘Lady’ Macbeth here. The only thing I can think of is that sonny boy argued that a constructive trust arose, on the basis that he’d relied on his father’s promise and, having blown the money, it would unconscionable for the father not to have bailed him out. If so, that notion ought to have been, and may even have been, met with what we euphemistically call ‘robust advice’. Anyway, the self-entitled twerp deserved what he got by the sound of it. English justice rocks. Yay. “this kind of thing is quite common with people who come into a windfall – they blow it and end up destitute at the end.” I don’t think thats right, I’m sure I’ve read National Lottery research that shows the vast majority of lottery winners invest their winnings wisely, many continue to work (maybe not in the same manner as previously) and generally the experience is entirely positive for their lives. We hear about the people who blow the lot because they are great news stories, but I think they are a tiny minority of the overall lottery winner population. I bet it was fabulous while it lasted. Watch out, Beedle’s about. “There are no hard feelings” Yeah, you just took them to court. He wasn’t even your fucking father. Christ, some people are massive cunts, aren’t they? “£1000 a week on groceries” WTF??? “Under UK (but not French) law …”: as usual a statement about UK law is bollocks because with few exceptions there is no such thing as UK law. £1000 a week in groceriesmust have meant oysters caviar and champagne all day every day. Mind blowing stupidity from the two self entitled claimants. But that’s still only £50k a year. It was the other spending that must have done them in. Morons. Jim, I think that Camelot took the view that headlines like “I won the pools and it ruined my life” would be bad for business, and decided to offer the necessary advice (or access to advisors, at least) to avoid them. So their research is intended to show how effective they’ve been, not that people generally know what they doing. Maybe O/T but the French lottery maintains a huge chateau on the Cote d’Azur for teaching lottery winners about how to spend / give away their winnings. Mostly unused, except by the guys that run the lotto of course. National lottery payout in UK, about 70% (i.e. a tax rate of 30% overall for “good causes”) Payout from the Lotto below 60%. Could this mean the frogs are happier to pay higher taxes than the Brits? A Legion d’Honneur for Spud if he promises never to set foot in the cuntry. dearime May 19, 2017 at 10:39 am. and dearieme May 19, 2017 at 11:21 am “Under UK (but not French) law …”: as usual a statement about UK law is bollocks because with few exceptions there is no such thing as UK law. Are you auditioning for Rocco? Dunno. What’s Rocco? I have no sympathy for the claimant here, but there must be some kind of story in the apparent extreme stinginess of the parents. They won a hundred million quid, and gave their son an amount they wouldn’t even notice out of one year’s income, let alone their capital? If he hadn’t already done stuff to piss them off – and judging by the court case, that seems unlikely – then that would appear to be pretty fucking harsh. £1.6m doesn’t go too far in the UK these days – that’ll produce a decent income, but not after you buy even a very ordinary house out of it. Obviously a graduate of the Richard Murphy School of Financial Management. Here’s hoping he ends up in Ely. Not sure. If the son is the kind of twat that thought bringing a court case against his own father was the answer, then there’s probably more to this than meets the eye. Dave – Perhaps the claimant’s parents had real doubts about the claimant’s ability to manage such monies, and they gave him that pittance to see if he could manage it correctly. Having a sneaking suspicion that your kid is a fucking moron is not the same thing as being stingy. As the old saying nearly goes – they spent it on wine, men and son, the rest they squandered aimlessly. Manage a million and maybe get more later. Blow a million and father will know that can blow much bigger sums too. 6 months after the million was asking for more. Who among us would happily give offspring more like that? The son was asking for 5 mill more, not long after he was given 1.6mill. Those are not amounts you wouldn’t notice. The way he was spending before too long he’d have plowed through a significant amount of the winnings. Which weren’t his to start with. I wish someone would treat me with “extreme stinginess” and give me £1.6m. I’d struggle through. Once again Dave proves himself to be a moron who either a) can’t read or b) has a brain which filters out inconvenient facts: ‘…but there must be some kind of story in the apparent extreme stinginess of the parents.’ From the link: “The couple’s QC, Richard Wilson, said they had shared their good fortune with their family, giving away some £30m to relatives and close friends, as well as setting up a charity.” Only £30m? Stingy bastards. WE DEMAND MORE OF OTHER PEOPLE’S MONEY! The good thing to come out of this is that when this man crawls back to work, as he has too, everyone he works with will realise what a massive cunt he is, and every time he’s bored or stressed at work he’ll remember he blew a shit load of money. I think they had a great case! ‘Michael Dawes . . . his partner, James Beedle’ The damn judge ruled against LGBTs !!! I can’t believe he did it! The homos can’t either. Your honour, I refer to the comments of m’learned friend Mr Lud, to the effect that ‘that notion ought to have been, and may even have been, met with what we euphemistically call ‘robust advice’.’ I respectfully submit that such advice might indeed have been given, but not by counsel, or at least not until they had banked the brief fee and refreshers. The most amazing thing to me is gay blokes in the Navy. Interested, for sure, the navy’s never been known for chutney ferreting. But seriously. Don’t you have a sister who’s counsel? Maybe I’m thinking of someone else. Anyway. Were it me, I’d get in a conference, find out what he was going on about. Recommend an Advice, having thought about it. Then get the sack for telling him what he didn’t want to hear. Daily refresher for appearances wouldn’t come into it, unless I was instructed at the last minute, and to hold the bag. By which time my views would be irrelevant and I’m being paid to take ak-ak. In my experience, there are rare parties to a case more granite-like in their sanctimonious determination than family members who perceive they’ve been diddled. Perhaps the father could show this twit the wonderful scene from an otherwise mediocre movie, The Gambler. This short scene is a required viewing for anyone who comes into so money. The fact it’s said by a ruthless gambler to a gambling addict doesn’t mean it’s not a good advice. There’s a story in the bible about the prodigal son. This is not him. He acted that way but the father luckily did not. BigFire; Great clip! Thanks for that.
http://www.timworstall.com/2017/05/19/sounds-about-right-14/
CC-MAIN-2018-13
refinedweb
1,991
81.93
Local Market Summary: •PM Hon Peter O’Neill has highlighted great opportunities to come from India as a market for LNG and for development of downstream processing in petrochemicals. These comments come following meetings with executives from Indian Government-owned Oil and Gas Company Group, Petronet LNG and GAIL (India) in New Delhi. An earlier MOU that was signed between Petromin PNG with the ONGC Group and Petronet LNG provides an avenue to advance these negotiations •Amendments to the Oil and Gas Act are underway to cater in the interests of the country Petroleum and Energy Minister Hon Nixon Duban says. “We’ve taken an audit on the Oil and Gas Act” Duban said. With many new petroleum projects being developed in recent times, the government will be pushing some amendments on the Oil and Gas Act which will try and cater for the interest of this country as the Oil and Gas Act at this point in _me is not able to accommodate these changes •Agriculture and Livestock Minister Hon Tommy Tomscoll has announced a major ban on import of more than ten different fruits and vegetables. The ban will be in place until dialogue and protocols are established with the countries of origin he said •Australian vegetable farmers will lose over A$3.8m of market in PNG due to the PNG Government ban on fruits and vegetables. The Australian Department of Agriculture and Livestock is liaising with PNG Government to have the ban lifted immediately •The K732.0m international standard Lae port facilities in the Tidal Basin Project handed over in December last year sits idle, while cargo ships are queuing up at the Lae Harbour for berthing. Lae Port development manager Mr John Relhang said there were several ships waiting to berth at any one _me. While PNG Ports is calling for interested sea port terminal operators, the 240-metre wharf continues to remain idle •The Golpu mining project in Morobe looks promising for Newcrest (NCM) the company said in its financial year report ending June. NCM CEO Mr Sandeep Biswas said “Golpu is an attractive project for the medium term, and our exploration and participation in early stage projects underpin our longer term growth.” According to the report, NCM was seeking value creation through exploration and project entry in Wamum, adjacent to Wafi- Golpu. There was potential for discovery of high grade porphyry mineralisation at depth •InterOil’s analysis of the latest well test data from the Elk-Antelope gas field in Gulf supports a two-train liquefied natural gas project. In announcing financial results for the second quarter for this year, CEO Dr Michael Hession said Antelope-5 well had exceeded all previous Antelope well results. Appraisal of Elk-Antelope is expected to finish later this year and will be followed by certification of the resource volume •Government Inscribed Stock auction were undersubscribed by K89.6m out of the K160.0m on offer. The Weighted average yields for the series 2018; 2020; 2022 and 2023 were 9.8%, 10.8%, 11.1% and 11.6% respectively •This week’s BPNG auctions in Treasury Bills were oversubscribed by K88.3m out of the K152.0m on offer. Weighted average yields were 4.6% for 182 days and 7.4% for 364 days from this week’s auctions •Both KSi Index ended the week down by 2.8% to close at 3,376.80 points while the KSi Home Index ended the week up by 1.6% to close 9,664.70 for the week International Market Summary: •Growth worries in the US rattled stock markets, the S&P 500 hit a five month low this week on concerns a deceleration in the Chinese economy would translate into slower global growth. The Dow Jones industrial average fell 2.8% to 16,990.69, the S&P 500 lost 2.7%, to 2,035.73 and the Nasdaq Composite dropped 3.4% to 4,877.49 for the week •Losses accelerated in European markets after Greek Prime Minister Alexis Tsipras plans to hand in his resignation, clearing the way for early national elections. US and China continue to push European markets down. The FTSE closed the week 2.8% lower 6,367.89 and the German DAX dropped 5.0% in the week to 10,432.19 points •Hong Kong stocks fell into bear-market territory, as the effects of China’s volatility spills across its borders. The Hang Seng index in Hong Kong was down 7.3% for the week, to 22,230.90 points. Shanghai lost 10.5% in the week ending 3,548.54 points •The ASX closed down with banks suffering the worst of the fallout from global jitters, which largely overshadowed a busy week of corporate earnings. The ASX 200 closed at 5205.10, down 2.8% for the week. The benchmark now trades around nine-month lows •Oil prices rose from six-year lows, but analysts say they expect prices to continue falling on worries that the global glut of crude is growing. Light Crude closed lower 4.0% for the week at US$40.80 per barrel while Brent slumped 6.1% to US$46.02 •The weakest Chinese manufacturing data since the global financial crisis accelerated losses in riskier assets, sending emerging-market stocks toward their worst week in two years. U.S. and European index futures fell, while gold surged 4.6% for the week to close US$1,163.80 (refer to graph) •PGK/USD lost 0.3% to 0.3595, while PGK/AUD appreciated by 0.7% to close at 0.4923 for the week Click on the link below to view full report in PDF. KFM Weekly Investment Update: Friday, 21 August 2015
http://www.kina.com.pg/news/weekly-and-daily-reports/kfm-weekly-investment-update-friday-21-august-2015/
CC-MAIN-2018-34
refinedweb
958
66.13
EvmConnControl - Controls information for an EVM connection #include <evm/evm.h> EvmStatus_t EvmConnControl( EvmConnection_t connection, EvmInt32_t request, void *arg ); The connection to be controlled. See the EvmConnCreate(3) reference page. The control action requested. See the DESCRIPTION section for the available requests. The value and use of arg depends on the request. See the DESCRIPTION section for the available meanings and the association to a request. The EvmConnControl() routine allows you to set or get control information for a connection. The following table shows the available values for the request argument and the associated value of the arg argument. Gets the size of the connection's receive buffer. The arg argument is a pointer to an EvmInt32_t field to receive the size value. Sets the size of the connection's receive buffer. Changing this value also causes the EVM daemon to make a corresponding change to the size of its send buffer. The arg argument is an EvmInt32_t value. Gets the size of the connection's send buffer. The arg argument is a pointer to an EvmInt32_t field to receive the size value. Sets the size of the connection's send buffer. Changing this value also causes the EVM daemon to make a corresponding change to the size of its receive buffer. The arg argument is an EvmInt32_t value. Enables checksum generation for posted events. This is the default state when a connection is established. The arg argument should be set to NULL. Disables checksum generation for posted events. This option is intended for use by high-performance applications that post events frequently, using the local EVM daemon. The arg argument should be set to NULL. Queries the connection to find out whether checksum generation is enabled. The arg argument is a pointer to an EvmBoolean_t field to receive a boolean value.). Restores the default set of environmental data items inserted automatically into events posted to the supplied connection. The arg argument should be set to NULL. This request clears the effects of any prior EvmCONN_POST_ITEM_MASK_SET requests.. The operation was completed without error. One of the arguments to the function was invalid. A value in a structure member is invalid. An operation failed because an attempt to acquire heap memory failed. An unexpected error occurred while attempting to acquire or control a system resource. The current operation was interrupted by receipt of a signal. None EVM Support Library (libevm.so, libevm.a) Functions: connect(2), select(2) Routines: EvmConnCheck(3), EvmConnCreate(3), EvmConnSubscribe(3), EvmConnWait(3) Files: kevm(7) Event Management: EVM(5) Event Connection: EvmConnection(5) EvmConnControl(3)
http://nixdoc.net/man-pages/Tru64/man3/EvmConnControl.3.html
CC-MAIN-2013-20
refinedweb
429
52.05
Security Kernel development Four stable kernels were released on August 10: 2.6.27.50, 2.6.32.18, 2.6.34.3, and 2.6.35.1. Seriously, just use an external email account and ignore the broken corporate policy. 'Policy' is just a euphemism for not having to think for yourself. Kernel development news User-visible changes include: int prlimit64(pid_t pid, unsigned int resource, const struct rlimit64 *new_rlim, struct rlimit64 *old_rlim); It is meant to (someday) replace setrlimit(); the differences include the ability to modify limits belonging to other processes and the ability to query and set a limit in a single operation. Changes visible to kernel developers include: void usleep_range(unsigned long min, unsigned long max); This function will sleep (uninterruptibly) for a period between min and max microseconds. It is based on hrtimers, so the timing will be more precise than obtained with msleep(). The merge window remains open as of this writing, so we may yet see more interesting features merged for 2.6.36. Watch this space next week for the final merge window updates for this development cycle. The first. There were two sessions on solid-state storage devices (SSDs) at the summit; your editor was able to attend only the first. The situation which was described there is one we have been hearing about for a couple of years at least. These devices are getting faster: they are heading toward a point where they can perform one million I/O operations per second. That said, they still exhibit significant latency on operations (though much less than rotating drives do), so the only way to get that kind of operation count is to run a lot of operations in parallel. "A lot" in this case means having something like 100 operations in flight at any given time. Current SSDs work reasonably well with Linux, but there are certainly some problems. There is far too much overhead in the ATA and SCSI layers; at that kind of operation rate, microseconds hurt. The block layer's request queues are becoming a bottleneck; it's currently only possible to have about 32 concurrent operations outstanding on a device. The system needs to be able to distribute I/O completion work across multiple CPUs, preferably using smart controllers which can direct each completion interrupt to the CPU which initiated a specific operation in the first place. For "storage-attached" SSDs (those which look like traditional disks), there are not a lot of problems at the filesystem level; things work pretty well. Once one gets into bus-attached devices which do not look like disks, though, the situation changes. One participant asserted that, on such devices, the ext4 filesystem could not be expected to get reasonable performance without a significant redesign. There is just too much to do in parallel. Ric Wheeler questioned the claim that SSDs are bringing a new challenge for the storage subsystem. Very high-end enterprise storage arrays have achieved this kind of I/O rate for some years now. One thing those arrays do is present multiple devices to the system, naturally helping with parallelism; perhaps SSDs could be logically partitioned in the same way. A change of pace was had in the memory management track, where Rik van Riel talked about the challenges involved in resizing the memory available to virtualized guests. There are four different techniques in use currently: The real question of interest in this session seemed to be the "rightsizing" of guests - giving each guest just enough memory to optimize the performance of the system as a whole. Google is also interested in this problem, though it is using cgroup-based containers instead of full virtualization. It comes down to figuring out what a process's minimal working set size is - a problem which has resisted attempts at solution for decades. Mel Gorman proposed one approach to determine a guest's working set size. Place that guest under memory pressure, slowly shrinking its available memory over time. There will come a point where the kernel starts scanning for reclaimable pages, and, as the pressure grows, a point where the process starts paging in pages which it had previously used. That latter point could be deemed to be the place where the available memory had fallen below the working set size. It was also suggested that page reactivations - when pages are recovered from the inactive list and placed back into active use - could also be the metric by which the optimal size is determined. Nick Piggin was skeptical of such schemes, though. He gave the example of two processes, one of which is repeatedly working through a 1GB file, while the other is working through a 1TB file. If both processes currently have 512MB of memory available, they will both be doing significant amounts of paging. Adjusting the memory size will not change that behavior, leading to the conclusion that there's not much to be done - until the process with the smaller file gets 1GB of memory to work with. At that point, its paging will stop. The process working with the larger file will never reach that point, though, at least on contemporary systems. So, even though both processes are paging at the same rate, the initial 512MB memory size is too small for one process, but is just fine for the other. The fact that the problem is hard has not stopped developers from trying to improve the situation, though, so we are likely to see attempts made at dynamically resizing guests in an attempt to work out their optimal sizes. Vivek Goyal led a brief session on the I/O bandwidth controller problem. Part of that problem has been solved - there is now a proportional-weight bandwidth controller in the mainline kernel. This controller works well for single-spindle drives, perhaps a bit less so with large arrays. With larger systems, the single dispatch queue in the CFQ scheduler becomes a bottleneck. Vivek has been working on a set of patches to improve that situation for a little while now. The real challenge, though, is the desired maximum bandwidth controller. The proportional controller which is there now will happily let a process consume massive amounts of bandwidth in the absence of contention. In most cases, that's the right result, but there are hosting providers out there who want to be able to keep their customers within the bandwidth limits they have paid for. The problem here is figuring out where to implement this feature. Doing it at the I/O scheduler level doesn't work well when there are devices stacked higher in the chain. One suggestion is to create a special device mapper target which would do maximum bandwidth throttling. There was some resistance to that idea, partly because some people would rather avoid the device mapper altogether, but also due to practical problems like the inability of current Linux kernels to insert a DM-based controller into the stack for an already-mounted disk. So we may see an attempt to add this feature at the request queue level, or we may see a new hook allowing a block I/O stream to be rerouted through a new module on the fly. The other feature which is high on the list is support for controlling buffered I/O bandwidth. Buffered I/O is hard; by the time an I/O request has made it to the block subsystem, it has been effectively detached from the originating process. Getting around that requires adding some new page-level accounting, which is not a lightweight solution. Back in the memory management track, a number of reclaim-oriented topics were covered briefly. The first of these is per-cgroup reclaim. Control groups can be used now to limit total memory use, so reclaim of anonymous and page-cache pages works just fine. What is missing, though, is the sort of lower-level reclaim used by the kernel to recover memory: shrinking of slab caches, trimming the inode cache, etc. A cgroup can consume considerable resources with this kind of structure, and there is currently no mechanism for putting a lid on such usage. Zone-based reclaim would also be nice; that is evidently covered in the VFS scalability patch set, and may be pushed toward the mainline as a standalone patch. Reclaim of smaller structures is a problem which came up a few times this afternoon. These structures are reclaimed individually, but the virtual memory subsystem is really only concerned with the reclaim of full pages. So reclaiming individual inodes (or dentries, or whatever) may just serve to lose useful cached information and increase fragmentation without actually freeing any memory for the rest of the system. So it might be nice to change the reclaim of structures like dentries to be more page-focused, so that useful chunks of memory can be returned to the system. The ability to move these structures around in memory, freeing pages through defragmentation, would also be useful. That is a hard problem, though, which will not be amenable to a quick solution. There is an interesting problem with inode reclaim: cleaning up an inode also clears all related page cache pages out of the system. There can be times when that's not what's really called for. It can free vast amounts of memory when only small amounts are needed, and it can deprive the system of cached data which will just need to be read in again in the near future. So there may be an attempt to change how inode reclaim works sometime soon. There are some difficulties with how the page allocator works on larger systems; free memory can go well below the low watermark before the system notices. That is the result of how the per-CPU queues work; as the number of processors grows, the accounting of the size of those queues gets fuzzier. So there was talk of sending inter-processor interrupts on occasion to get a better count, but that is a very expensive solution. Better, perhaps, is just to iterate over the per-CPU data structures and take the locking overhead. Christoph Lameter ran a discussion on slab allocators, talking about the three allocators which are currently in the kernel and the attempts which are being made to unify them. This is a contentious topic, but there was a relative lack of contentious people in the room, so the discussion was subdued. What happens will really depend on what patches Christoph posts in the future. A brief session touched on a few problems associated with direct I/O. The first of these is an obscure race between get_user_pages() (which pins user-space pages in memory so they can be used for I/O) and the fork() system call. In some cases, a fork() while the pages are mapped can corrupt the system. A number of fixes have been posted, but they have not gotten past Linus. The real fix will involve fixing all get_user_pages() callers and (the real point of contention) slowing down fork(). The race is a real problem, so some sort of solution will need to find its way into the mainline. Why, it was asked, do applications use direct I/O instead of just mapping file pages into their address space? The answer is that these applications know what they want to do with the hardware and do not want the virtual memory system getting in the way. This is generally seen as a valid requirement. There is some desire for the ability to do direct I/O from the virtual memory subsystem itself. This feature could be used to support, for example, swapping over NFS in a safe way. Expect patches in the near future. Finally, there is a problem with direct I/O to transparent hugepages. The kernel will go through and call get_user_pages_fast() for each 4K subpage, but that is unnecessary. So 512 mapping calls are being made when one would do. Some kind of fix will eventually need to be made so that this kind of I/O can be done more efficiently. Once again, the day ended with lightning talk topics. Matthew Wilcox started by asking developers to work at changing more uninterruptible waits into "killable" waits. The difference is that uninterruptible waits can, if they wait for a long time, create unkillable processes. System administrators don't like such processes; "kill -9" should really work at all times. The problem is that making this change is often not straightforward; it turns a function call which cannot fail into one which can be interrupted. That means that, for each change, a new error path must be added which properly unwinds any work which had been done so far. That is typically not a simple change, especially for somebody who does not intimately understand the code in question, so it's not the kind of job that one person can just take care of. It was suggested that iSCSI drives - which can cause long delays if they fall off the net - are a good way of testing this kind of code. From there, the discussion wandered into the right way of dealing with the problems which result when network-attached drives disappear. They can often hang the system for long periods of time, which is unfortunate. Even worse, they can sometimes reappear as the same drive after buffers have been dropped, leading to data corruption. The solution to all of this is faster and better recovery when devices disappear, especially once it becomes clear that they will not be coming back anytime soon. Additionally, should one of those devices reappear after the system has given up on it, the storage layer should take care that it shows up as a totally new device. Work will be done to this end in the near future. Mike Rubin talked a bit about how things are done at Google. There are currently about 25 kernel engineers working there, but few of them are senior-level developers. That, it was suggested, explains some of the things that Google has tried to do in the kernel.. In general, any new kernel which shows a 1% or higher performance regression is deemed to not be good enough. The workloads exhibit a lot of big, sequential writes and smaller, random reads. Disk I/O latencies matter a lot for dedicated workloads; 15ms latencies can cause phone calls to the development group. The systems are typically doing direct I/O on not-too-huge files, with logging happening on the side. The disk is shared between jobs, with the I/O bandwidth controller used to arbitrate between them. Why is direct I/O used? It's a decision which dates back to the 2.2 days, when buffered I/O worked less well than it does now. Things have gotten better, but, meanwhile, Google has moved much of its buffer cache management into user space. It works much like enterprise database systems do, and, chances are, that will not change in the near future. Google uses the "fake NUMA" feature to partition system memory into 128MB chunks. These chunks are assigned to jobs, which are managed by control groups. The intent is to firmly isolate all of these jobs, but writeback still can cause interference between them. Why, it was asked, does Google not use xfs? Currently, Mike said, they are using ext2 everywhere, and "it sucks." On the other hand, ext4 has turned out to be everything they had hoped for. It's simple to use, and the migration from ext2 is straightforward. Given that, they feel no need to go to a more exotic filesystem. Mark Fasheh talked briefly about "cluster convergence," which really means sharing of code between the two cluster filesystems (GFS2 and OCFS2) in the mainline kernel. It turns out that there is a surprising amount of sharing happening at this point, with the lock manager, management tools, and more being common to both. The biggest difference between the two, at this point, is the on-disk format. The cluster filesystems are in a bit of a tough place. Neither has a huge group dedicated to its development, and, as Ric Wheeler pointed out, there just isn't much of a hobbyist community equipped with enterprise-level storage arrays out there. So these two projects have struggled to keep up with the proprietary alternatives. Combining them into a single cluster filesystem looks like a good alternative to everybody involved. Practical and political difficulties could keep that from happening for some years, though. There was a brief discussion about the DMAPI specification, which describes an API to be used to control hierarchical storage managers. What little support exists in the kernel for this API is going away, leaving companies with HSM offerings out in the cold. There are a number of problems with DMAPI, starting with the fact that it fails badly in the presence of namespaces. The API can't be fixed without breaking a range of proprietary applications. So it's not clear what the way forward will. Patches and updates Kernel trees Core kernel code Device drivers Filesystems and block I/O Memory management Networking Architecture-specific Security-related Virtualization and containers Miscellaneous Page editor: Jonathan Corbet Distributions This article was contributed by Koen Vervloesem On August 3, storage vendor Nexenta Systems hosted a conference call [MP3] announcing Illumos, a project to free the OpenSolaris distribution. Garrett D'Amore, a former Sun and Oracle Solaris developer and now senior director of engineering at Nexenta, disclosed the goal of the project: Illumos will replace all proprietary code that is still in OpenSolaris by open source code. More information can be found in the announcement slides [PDF]. Although its name suggests something else, OpenSolaris has never been completely open source. Some critical components are only available as binaries because of copyright issues. The most critical part is the internationalization (i18n)) framework of libc, but also the NFS lock manager, portions of the cryptographic framework, and numerous critical drivers are proprietary. This presents a lot of challenges to downstream OpenSolaris distributions, such as Nexenta and Belenix. We only have to look at Darwin, Apple's open source part of Mac OS X, to see what the effect can be of some critical components that are closed: Darwin never really took off as an independent operating system. So the first short-term goal of Illumos is open sourcing all of OpenSolaris, or more correctly: all of OS/Net (ON), which is the OpenSolaris kernel, C library, drivers, and some basic commands. Illumos will track OpenSolaris ON closely, but will replace all closed bits by open source alternatives, while still staying 100% ABI compatible. Right now, Illumos libc is completely open: Garrett developed libc_i18n by borrowing code from FreeBSD, picking up a little from NetBSD, and finishing it with his own code. At the moment, Garrett's code is the only one that has been integrated in Illumos, but there are a number of other projects that are near to integration. For example, Anil Gulecha developed GRUB and boot graphics, Steve Stallion and David Gwynne have been working on some open source replacements for drivers, Roland Mainz, Olga Kryzhanovska and Rich Lowe have replaced some user-space utilities, and Jörg Schilling has been working on archivers. But even when all these projects get integrated, there is still the issue that only Sun's proprietary compiler Sun Studio can currently build a bootable OpenSolaris kernel. The intention is to enable a fully open toolset, probably using GCC. So a fully open source self-hosting OpenSolaris derivative is not yet possible, but it should become a reality by the end of 2010. A preliminary version of Illumos using the closed bits and compiled with Sun Studio already boots. So Illumos is not really a fork, it's more of a downstream project that is happy to contribute to upstream ON. Oracle employee Joerg Moellenkamp explains the situation like this: However, the ability to fork is important for OpenSolaris, as Bryan Cantrill explains: So although Illumos is not aimed at creating an OpenSolaris fork, according to Bryan the power to fork is essential for the vitality of the OpenSolaris community. Jörg Schilling looks at this in an historical context: Jörg is right in his description. When Oracle acquired Sun, they talked a lot about MySQL and Java, but said virtually nothing about (Open)Solaris. In February 2010, Peter Tribble complained that Oracle hadn't even mentioned the distribution in a five-hour webcast after the acquisition of Sun. And at the times they did mention OpenSolaris, it was in vague terms. For example, at the OpenSolaris Annual Meeting on IRC in February 2010, Oracle's Dan Roberts said: Almost half a year later, there hasn't been an OpenSolaris 2010.03 (which was due in March 2010); there still isn't a newer release than OpenSolaris 2009.06. Oracle didn't respond to an open letter by Ben Rockwood, a respected OpenSolaris community member. In April 2010, Oracle stopped shipping free OpenSolaris CDs. In general, Oracle's silence continued, and a lot of community members were getting fed up with the insecurity. This led the OpenSolaris Governing Board to the decision to issue an ultimatum to Oracle: if Oracle doesn't appoint a liaison who has the authority to talk about the future of OpenSolaris by August 16, the OGB will disband itself. OGB chair John Plocher explained the issues: Oracle's communication blackout, combined with its disengagement from and disenfranchisement of the community has made it extremely difficult for the OGB to continue in its role of being an advocate for the collective improvement of OpenSolaris. Oracle didn't respond to the ultimatum, and the long radio silence about the future of OpenSolaris has already taken some victims. PulsarOS, a file server operating system, has switched from OpenSolaris to Linux. The high-integrity operating system AuroraUX was first an OpenSolaris distribution but has quietly shifted to become a DragonFlyBSD derivative. And the other OpenSolaris derivatives are stagnant or only reach a small niche, with the exception of Nexenta. The Illumos project (which Garrett started about two months ago, even before the OGB's ultimatum) wants to tackle these issues, not only by writing code but also by building an independent community. In this first phase, Garrett will serve as the benevolent dictator of Illumos, but this dictatorship is a temporary measure. He will appoint some initial members for an Administrative Council, which will work on non-technical matters such as defining a code of conduct. Garrett is not only head of this Administrative Council, but also the technical lead: head of the Developer Council. This will be made up of developers with commit rights, and it is a meritocracy: anyone can join in and will be judged by their code. Development will be consensus driven, but the technical lead is the final arbiter if consensus is not possible. A process to replace the technical lead will be discussed in the future. Nexenta is currently the main sponsor of Illumos (Garrett's efforts have been funded by Nexenta), but the goal is to have a code base that is free from the control of any company. Corporate entities are welcome, though, to contribute. About one week before the launch of Illumos, Garrett invited Oracle to participate in Illumos. He contacted Bonnie Corwin, but she told him that she simply did not know who was responsible for decisions relating to OpenSolaris. She also said that she would endeavor to find out, but Garrett hasn't heard anything back. Right now Illumos has about a dozen developers, many of them well-known people in the OpenSolaris community, working for Nexenta Systems, hosting company Joyent, Greenviolet, Belenix, Schillix, and Everycity. Some have argued that Illumos is purely driven by emotional feelings about OpenSolaris, by people who can't stand thinking about the death of the operating system, but this is far from true. For example, Nexenta and Joyent really depend on OpenSolaris for their business. They obviously don't like that they ultimately depend on what Oracle decides to do with OpenSolaris. So from a business point of view, it makes perfect sense that they want to free OpenSolaris and create an active developer community, independent from Oracle's good will. If they succeed, these companies can be much less concerned about their business continuity. Of course, they have much less development manpower than Oracle (the vast majority of OpenSolaris development has always come from paid Sun/Oracle engineers), but they have some really good ex-Sun developers, like Garrett D'Amore (Nexenta's senior director of engineering), Richard Elling (Nexenta's senior director of solutions engineering), Bryan Cantrill (Joyent's vice president of engineering), and so on. Other notable backers of Illumos are Dennis Clarke, who is the founder of the Blastwave project, and Jörg Schilling, who built the first OpenSolaris distribution (Schillix) even before Sun did. By uniting manpower in an open source community, they can tackle their shared concerns together. This isn't the first time that an external code repository was created by the OpenSolaris community. For example, the Genunix web site that was created in 2006 at the request of the OpenSolaris Community Advisory Board (the precursor of the OpenSolaris Governing Board) maintained an independent SVN repository for some time, and they also have some Mercurial repositories, for instance for OpenSolaris OS/Net. The latter is an active clone that tracks Oracle's repository. However, the repository of Illumos is the first one that will be backed by substantial development by non-Oracle people. This allows OpenSolaris distributions that adopt Illumos as their base to depend less on Oracle. Illumos is also insurance against Oracle pulling the plug on OpenSolaris: if Oracle stops supplying the source code to OpenSolaris, distributions can still build upon Illumos. Of course, the project would then become an OpenSolaris fork by necessity, and it's uncertain whether it has the critical mass to continue without Oracle. For now, it's just a project of open sourcing the whole OS/Net code, but in time Illumos also wants to become a repository for experimental innovations and patches that are not accepted by Oracle. For instance, integration of other architectures like S390, PowerPC, or ARM could be possible in Illumos, because OpenSolaris has no interest in other architectures than x86/x86_64 and SPARC. All source code that will be integrated into Illumos will first be restricted to BSD/MIT licenses and CDDL (Common Development and Distribution License) with a signed SCA (Sun Contributor Agreement), which gives Sun and the contributor joint copyrights on the code. Other possibilities for licenses are still under investigation, and a critical requirement is of course that the license must be acceptable for merging back into the upstream OpenSolaris code. Illumos is looking specifically at the Apache 2.0 license, because, in Garrett's words, "it offers the freedoms of BSD/MIT without the baggage of copyleft, while still providing a protection against submarine patenting." Moreover, Garrett pinpoints one property that he prefers in any license used in Illumos: Illumos is focused only on ON, so it's not an OpenSolaris distribution. However, the project may expand in the future and host some affiliated projects, such as Illumos distributions. For example, there could be a binary ISO with a minimal Illumos system to bootstrap a real Illumos distribution. Although Garrett is a Nexenta employee, Illumos is not focused on Nexenta: for example it imposes no specific package manager, although it has a preference for IPS (Image Packaging System), the OpenSolaris package management system. IPS manifests are the canonical data format in Illumos, but there's a tool to generate .deb files from IPS, which Nexenta uses for its OpenSolaris/Ubuntu hybrid. This system can be extended to generate RPM, SVR4, or any other type of packages from the IPS packages. This is a choice that each derivative distribution can make. In the Linux world, Illumos wasn't received with much enthusiasm. For example, according to Joe "Zonker" Brockmeier OpenSolaris should really die, and he calls Illumos "a misguided attempt to keep the Solaris legacy OS alive for another generation". While Zonker rightly questions Sun's strategy with respect to OpenSolaris, your author finds this death wish to be a bridge too far. But no one can deny that Illumos will face a lot of issues. A project to liberate OpenSolaris probably should have happened five years ago when Sun released the bulk of the Solaris system code. If Illumos had started then, right from the start of OpenSolaris, the closed bits would have been replaced by now, with less hurdles for OpenSolaris derivatives and a more open community as its consequences. So one could ask the question: is Illumos coming too late? The OpenSolaris community has already lost a lot of users and derivatives because of the uncertain future of the distribution, and only time will tell whether Illumos can still change this downward trend. New Releases Full Story (comments: none) Distribution News Debian GNU/Linux Full Story (comments: 11) Fedora New Distributions Newsletters and articles of interest Page editor: Rebecca Sobol Development Lowering the barriers for contributors is something that a lot of projects are trying to do, but the Banshee media player project has gone further than many as Gabriel Burt reported in his talk at GUADEC. Essentially, Banshee has tried to make it as easy as possible for users—not necessarily programmers—to quickly and easily fix a small bug or add an extension. The project is clearly making an outreach effort to grow its community and some of the techniques being used might be helpful for other projects looking to do the same. Burt is one of the four maintainers of Banshee and he started his talk by remembering back to when he was struggling to figure out how to get involved. At that time, he watched the postings on various Planet aggregators and eventually got his start by looking at the GNOME Human Interface Guidelines (HIG), which led him to his first patch. He noticed that the string "Eject When Finished" didn't follow the HIG, so he grepped for that string and changed it to "Eject when finished". That was a simple fix, but he also had to get the code and the dependencies, so that he could build Banshee. One of the things that has been addressed since then is that there is extensive help on the web site that describe how to get started, install the dependencies, and get the code. "If you run [Banshee], and find a bug, you can get started easily" to fix it, he said. There are still things that need to be done to the Banshee interface for HIG compliance, and "you don't need to be a C# programmer" to fix them. But he also demonstrated how quickly one can add a new feature to Banshee with a little programming knowledge. Live on the GUADEC stage, Burt modified the "deduplicate" feature—which detects artist or album names that are textually different, but refer to the same entity—to add genre deduplication. By making a few changes to the AlbumDuplicateSolver.cs file, mostly consisting of changing "Album" to "Genre", along with some minor Makefile modifications, he was able to add the new functionality. Some queries needed changing, which he said "might take ten minutes" to come up with, but the rest of the changes took just a few minutes. Adding a derivative feature like that is a "good way to get started contributing to Banshee". Banshee also has an extension framework that allows easy addition of new functionality, but the project has taken it a step further. Executing ./create-extension Foo will set up everything needed for the extension, including doing a git add for the skeleton code and enabling the extension in Banshee. You can have a "working extension in two minutes", Burt said. Once that is done, editing the code in MonoDevelop gives access to all of the Banshee and .NET classes and methods via tab-completion, simplifying the development process as well. Over the last two-and-a-half years of development, Banshee has averaged 32 commits, ten bugs fixed, and one new contributor every week. There are active IRC channels, forums, and mailing lists for the project. Burt noted that the timezone coverage of the four maintainers is quite good since they live in Sydney, Luxembourg, and both coasts of the US. In short, there are lots of opportunities for those who want to get involved to hook up with the team. Because extensions are available via a Gitorius repository and there are lot of folks running Banshee development versions straight from the git repositories, contributions will be quickly picked up by others: "within days, lots of people will be using your work". Banshee has a one-month release cycle, so "within a month, thousands will be using it". He estimated that some 55,000 users picked up the monthly releases, and that within six months, "millions" would be using the code because Banshee is installed by default on several distributions and is available in the package repositories for many more. At the end of the talk, Burt pointed out some of the more recent Banshee extensions that integrate with various services, including the Amazon MP3 store. It can be browsed in Banshee, as it uses WebKit for the browser functionality, and songs can be downloaded directly into your music library. Through the affiliate program, 10% of any purchases go to the project, which donates all of that money to the GNOME Foundation. He also mentioned Miro Guide and Internet Archive extensions as other useful ways to get audio and video content. Obviously, Burt's talk was another part of the outreach effort for the project. "I hope you'll join in and help us having fun hacking on Banshee", he said. Though Mono and C# leave a bad taste in the mouths of some, Banshee is clearly trying to overcome that by making the project as accessible as possible for new users. But beyond that, there is a clear sense that Banshee is not about making any kind of political or social statement, it's about the enjoyment of hacking on a cutting-edge, multimedia application. Other projects could certainly follow its lead and potentially grow their communities as well. Full Story (comments: 1) Full Story (comments: 15) Full Story (comments: 41) Newsletters and articles Announcements Non-Commercial announcements Commercial announcements Articles of interest New Books Resources Contests and Awards Calls for Presentations Upcoming Events If your event does not appear here, please tell us about it. Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/398843/bigpage
CC-MAIN-2013-20
refinedweb
5,819
58.52
Send data from ESP8266 or ESP32 to Raspberry Pi via MQTT In this tutorial we create a WiFi MQTT communication system with all components to send data from an ESP8266 or ESP32 weather station to a Rasbperry Pi. With this article you learn - the basics of MQTT communication - how to publish data to a MQTT broker - how to setup an MQTT broker - validate the published data as MQTT subscriber In my last article I wrote a tutorial how to send data from an Arduino to a Raspberry Pi via the serial USB communication. But the better solution to create a smart home is of course to send the data via WiFi communication. If we want to send data via WiFi we need a transportation protocol. The most popular transportation protocol I know is MQTT which stands for Message Queuing Telemetry Transport and is suitable for microcontrollers like ESP8266, ESP32 or Raspberry Pi that are able to use WiFi. Table of Contents Build a MQTT System with Microcontroller and Raspberry Pi In this section I want to give a summary how MQTT works. If you are interested in more details about how MQTT works please visit my detailed tutorial about MQTT. Components in a MQTT Communication System In the MQTT communication system contains 3 components with specific roles and objectives: - Publisher who generate and send data to the MQTT broker. In case of a smart home the publisher could be a weather station which sends temperature and humidity every 5 minutes to the broker. - Broker which is like a server to collect the messages from all publishers, save the data and distribute the data messages to the right subscribers. - Subscriber is a component which subscribes to a certain kind of messages coming from publishers. A subscriber in the smart home use case could be a monitor or panel which shows the different temperatures and/or humidity of the home and outside. The following graphic shows how the components in a MQTT communication system are related to each other, the hardware that we use for each component and the variables and settings that we need to define for each component. Variables and Settings in a MQTT Communication System If we want to send data via MQTT we have to define some variables and setting which are linked between the publisher, the broker and the subscriber. The following picture gives a perfect overview about how defines the setting and to which parties are the settings distributed. For our example we use an ESP32 or ESP8266 as publisher. The MQTT Broker will be a Raspberry Pi and we choose Mosquitto as MQTT software for the broker. The subscriber is the same Raspberry Pi as the broker. That the broker and subscriber is on the same device makes no problem and is common practice. The first setting is the IP of the MQTT broker. Of course the IP of the MQTT broker is the same IP address that the Raspberry Pi has in your network. This IP is a variable in the publisher and subscriber script because they have to connect to the broker. The second setting is the MQTT topic which is defined by the publisher. Which data you put in a topic it totally up to you. For me if I had several indoor weather stations in different room in the house I would give each room a topic. But in the end every topic has to be unique. Therefore topics are build like a folder structure. For examples you can have the following topics: - home/bathroom/temperature - home/bathroom/humidity - home/livingroom/temperature - … The advantage is that one subscriber can have the subscription to the bathroom with all data following down the folder structure and a second subscriber can be only interested in the temperature of the bathroom. The MQTT username and password is defined in the configuration file of the MQTT broker (mosquitto.conf). This configuration has to be exactly the same in the publisher and subscriber script to get access to the MQTT broker. Only the publisher gets a MQTT client ID. With this client is the publisher is identified. This prevents the broker for disallowed data from unknown publishers and you know which publisher is sending what data. You can think for the client ID like a name. The last setting is also only for the publisher. It is the SSID and password for your home network. Without this information the microcontroller can not send data via the local network. After we defined all settings and which device has to define what setting or variable we can dive into your example. In this example we want to send the temperature and humidity from a DHT11 sensor or a DHT22 sensor module to the Raspberry Pi. The sensor is connected to the ESP8266 or ESP32 microcontroller. The Raspberry Pi as subscriber should print the last sent temperature and humidity to the terminal. Because we will need all these variables and settings in the following part of this tutorial the table below shows the specific variables and settings. You can copy them or define your one. This is up to you. The following table gives you an overview of all components and parts that I used for this tutorial. But you need only one ESP8266 or ESP32 microcontroller and also only one Rasbperry Pi. I get commissions for purchases made through links in this table. Build the Foundation of the MQTT Publisher (ESP8266/ESP32) The first step is to set up the publisher so that we can be sure that the temperature and humidity is read correctly and published to the network via MQTT. Wiring for the MQTT Publisher Weather Station In the following picture you see the wiring between the ESP8266 or the ESP32 microcontroller and the DHT22 sensor module. Program Code for the MQTT Publisher Weather Station The program sketch is easy. First we have to import the DHT library and define the pin the DHT temperature and humidity sensor is connected to the microcontroller. For the ESP8266 I use the digital I/O pin D5 and for the ESP32 pin 4, which you can see from the fritzing pictures. Depending on your microcontroller, you have to comment one of the two lines. After the definition of the used pin, we choose the DHT type. In my case I use the DHT22 sensor. If you use a DHT11 sensor, you have to change the corresponding line of code. The wiring is the same between the DHT11 and DHT22 sensor module. In the setup function we set the baud rate to 9600 and initialize the sensor. The temperature and humidity are saved in one variable and the sensor values are printed to the serial monitor if they are valid. At the end of the script we pause for 10 seconds. //#define DHTPIN D5 // for ESP8266 DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); dht.begin(); } void loop() { float humidity = dht.readHumidity(); float temperature = dht.readTemperature(); // check if returns are valid and print the sensor data if (isnan(temperature) || isnan(humidity)) { Serial.println("Failed to read from DHT"); } else { Serial.print("Humidity: "); Serial.print(humidity); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" *C"); } delay(10000); } If you did everything right you should see the sensor values in the serial monitor. This was part one of the publisher setup.. Setup the MQTT Broker to Receive MQTT Data (Raspberry Pi) First you have to setup the Raspberry Pi. If you do not know how to setup your Raspberry Pi, here you find the tutorial. The first thing is that we have to connect to the Raspberry Pi via SSH to install the necessary packages and libraries. You should see the terminal in front of you. The first thing is to install the MQTT broker Mosquitto on the Raspberry Pi with the command line clients for debugging in case of error. Use the commands in the following table for the installation. In case the packages can not be found run sudo apt-get update to update what packages are in general available for your Raspberry Pi. After the installation of the MQTT broker Mosquitto we have to change some configurations. There are two different configurations to control Mosquitto: - /etc/mosquitto/mosquitto.conf: Default configuration - /etc/mosquitto/conf.d: Extension to the default configuration. In our example we only want to use the default configuration. Therefore open the configuration file with the text editor nano and the following command: You see the default configuration after the installation of Mosquitto. There are 4 things we want to change apart of the default configuration: - The broker should only include the default settings. That is done be comment the line where the conf.d file is included. - We do not want anonymous users to connected to the MQTT broker: allow_anonymous false - We want to save the passwords in a separate file: password_file /etc/mosquitto/pwfile - The MQTT broker should be accessible on port 1883 After all changes your Mosquitto configuration file should look like the following. Click Ctrl + X, then Y to confirm to save and hit the enter button to save to the existing file. Now we have to set the username and the password that publishers and subscribers get access to the MQTT broker. Use the following command to create a new user and password for this user: In my case I use the following username and password: - Username: cdavid - Password: cdavid Of course this password is bad regarding the security. Feel free to create a stronger password. This username and password is also used in the publisher and subscriber script. If you want to delete an existing user, you can use the following command: At this point we created the MQTT broker as well as every setting we use in this tutorial. Now we want to check is Mosquitto is already running. You can test the current status of the MQTT broker with: My broker is running. The following commands start, stop and restart and start the MQTT broker at boot of the Raspberry Pi. Use the following commands to control the broker: Now after the MQTT broker is ready to receive the data via MQTT we have to make sure that the publisher is sending the data via MQTT to the broker. Add WiFi and enable MQTT to the MQTT Publisher (ESP8266/ESP32) The publisher part 1 finished that the temperature and humidity are stored in a variable and printed to the serial. In this part 2 we establish the WiFi connection to the home network and send the data as payload via the MQTT protocol to the broker. Now we go part by part over the Arduino script for the ESP8266 or ESP32. // Code for the ESP32 // Code for the ESP8266 //#include "ESP8266WiFi.h" // Enables the ESP8266 to connect to the local network (via WiFi) //#define DHTPIN D5 // Pin connected to the DHT sensor DHT dht(DHTPIN, DHTTYPE); // WiFi const char* ssid = "KabelBox-0174"; // Your personal network SSID const char* wifi_password = "9434763855628**"; // Your personal network password // MQTT const char* mqtt_server = "192.168.0.8"; // IP of the MQTT broker const char* humidity_topic = "home/livingroom/humidity"; const char* temperature_topic = "home/livingroom/temperature"; const char* mqtt_username = "cdavid"; // MQTT username const char* mqtt_password = "cdavid"; // MQTT password const char* clientID = "client_livingroom"; // MQTT client ID // Initialise the WiFi and MQTT Client objects WiFiClient wifiClient; // 1883 is the listener port for the Broker PubSubClient client(mqtt_server, 1883, wifiClient); // Custom function to connet to the MQTT broker via WiFi void connect_MQTT(){ Serial.print("Connecting to "); Serial.println(ssid); // Connect to the WiFi WiFi.begin(ssid, wifi_password); // Wait until the connection has been confirmed before continuing while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } // Debugging - Output the IP Address of the ESP8266 Serial.println("WiFi connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Connect to MQTT Broker // client.connect returns a boolean value to let us know if the connection was successful. // If the connection is failing, make sure you are using the correct MQTT Username and Password (Setup Earlier in the Instructable) if (client.connect(clientID, mqtt_username, mqtt_password)) { Serial.println("Connected to MQTT Broker!"); } else { Serial.println("Connection to MQTT Broker failed..."); } } void setup() { Serial.begin(9600); dht.begin(); } void loop() { connect_MQTT(); Serial.setTimeout(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); Serial.print("Humidity: "); Serial.print(h); Serial.println(" %"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C"); // MQTT can only transmit strings String hs="Hum: "+String((float)h)+" % "; String ts="Temp: "+String((float)t)+" C "; // PUBLISH to the MQTT Broker (topic = Temperature, defined at the beginning) if (client.publish(temperature_topic, String(t).c_str())) { Serial.println("Temperature sent!"); } // Again, client.publish will return a boolean value depending on whether it succeded or not. // If the message failed to send, we will try again, as the connection may have broken. else { Serial.println("Temperature failed to send. Reconnecting to MQTT Broker and trying again"); client.connect(clientID, mqtt_username, mqtt_password); delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call client.publish(temperature_topic, String(t).c_str()); } // PUBLISH to the MQTT Broker (topic = Humidity, defined at the beginning) if (client.publish(humidity_topic, String(h).c_str())) { Serial.println("Humidity sent!"); } // Again, client.publish will return a boolean value depending on whether it succeded or not. // If the message failed to send, we will try again, as the connection may have broken. else { Serial.println("Humidity failed to send. Reconnecting to MQTT Broker and trying again"); client.connect(clientID, mqtt_username, mqtt_password); delay(10); // This delay ensures that client.publish doesn't clash with the client.connect call client.publish(humidity_topic, String(h).c_str()); } client.disconnect(); // disconnect from the MQTT broker delay(1000*60); // print new values every 1 Minute } At the beginning of the script we have to include two more libraries. The PubSubClient enables the ESP8266 or ESP32 microcontroller to be a MQTT publisher. To connect the microcontroller to the local WiFi we have to add another library that is different for the ESP8266 and ESP32. For the ESP32 we use the WiFi library and for the ESP8266 the ESP8266WiFi library. If you do not know how to install Arduino libraries, here you find a step by step tutorial. The rest of the code is the same compared to the setup in the first chapter. In the next part we define a lot of variables. Of course you have to fill in your personal data here. The following table gives you an overview of the variables. If you have to modify the variable to your local setting, the row is colored in orange. If you followed the settings and variables I used you can copy them. If for example you want to use another username, make sure you also change the username in the Mosquitto configuration file. After all variables are defined we initialize the WiFi as well as the MQTT client objects. Make sure you use the identical listener port (1883) compared to the Mosquitto configuration file. The next part is a custom function, called connect_MQTT(), to connect to the MQTT broker via the wireless connection. First the SSID and password is printed. Then the script waits until the wireless connection is established and prints the IP of the microcontroller. After the WiFi is setup we connect to the MQTT broker with the client ID, the MQTT username and MQTT password. We print in the serial if the connection is successful or failed. The setup function is the same as in the first chapter. The loop function starts with executing the MQTT connection function we discussed before. You could also setup the WiFi connection in the setup function and do not reconnected every iteration in the loop function. Because I only want to send the temperature and humidity every hour in a real live example, I disconnect the WiFi connection after the MQTT data is send and reconnect after one hour. After the MQTT connection is established, we read the temperature and the humidity from the DHT sensor and print the values to the serial output. New is that the temperature and humidity are also stored as strings because MQTT can only transfer strings and no other data types. The last step is to send the temperature and humidity as strings to the MQTT broker via the established connection. Therefore we use the function client.publish of the PubSubClient library. If the message is not sent successful we try to establish the connection to the broker again and try to send the payload a second time. This is done with the temperature and the humidity. After the temperature and the humidity is sent to the MQTT broker, we disconnect the publisher from the broker and add a delay at the end of the script of 1 minute. Let us quickly summarize the steps in part 2 of the publisher setup: - We establish a WiFi and MQTT connection. - The temperature and humidity are stored as strings. - The strings are send via MQTT to the broker. If everything runs correctly you should see the following output in your serial monitor. Check if MQTT Data is Received by Mosquitto Before we continue, we want to make sure that the MQTT messages from the ESP8266 or ESP32 is received by the Mosquitto MQTT broker. Therefore we start the Mosquitto console on the Raspberry Pi to see the connecting publishers. Enter the following command in the console of the Raspberry Pi to start the Mosquitto console: Subscriber Setup to Receive Data from MQTT Broker At this point the setup of the publisher and the broker are finished. The last step is to setup the subscriber. In our case the subscriber is the same Raspberry Pi. There is no need, that a subscriber is another device like the broker. We want to use the script language Python to program a script that is listen to the MQTT topics of the publisher. Therefore we have to install a python library for MQTT. Use the following command in the Raspberry Pi terminal: So we want to create a python script. To create the file we use the text editor nano again: Like in part 2 of the publisher setup we go step by step through the following python script. import paho.mqtt.client as mqtt MQTT_ADDRESS = '192.168.0.8' MQTT_USER = 'cdavid' MQTT_PASSWORD = 'cdavid' MQTT_TOPIC = 'home/+/+' def on_connect(client, userdata, flags, rc): """ The callback for when the client receives a CONNACK response from the server.""" print('Connected with result code ' + str(rc)) client.subscribe(MQTT_TOPIC) def on_message(client, userdata, msg): """The callback for when a PUBLISH message is received from the server.""" print(msg.topic + ' ' + str(msg.payload)) def main(): mqtt_client = mqtt.Client()() The first thing in the script is to import the MQTT library we installed before. After the library is imported we define all necessary variables. Make sure that the MQTT broker IP (IP of your Raspberry Pi) is correctly as well as the MQTT username and password if you changed them during this tutorial. The MQTT topic is defined with wildcards to create the script as general as possible for reusability. The on_connect function handle what happens when the MQTT client connects to the broker. If our clients connects to the broker we want to subscribe to the temperature and humidity topics and print the message that the connection was established. The variable rc holds and error code if the connection is not successful so the debugging is easier: - 0: Connection successful - 1: Connection refused – incorrect protocol version - 2: Connection refused – invalid client identifier - 3: Connection refused – server unavailable - 4: Connection refused – bad username or password - 5: Connection refused – not authorized - 6-255: Currently unused. The on_message function is called every time the topic is published to. In this case the topic and the message are printed to the terminal. We expect that on this point we will get the current temperature and humidity printed to the terminal. The main function holds the main part of the python script where all defined function are executed. First we create a client object and set the username and password for the MQTT client. Then we tell the client which function is called when we want to connect to the MQTT broker and receive messages. Once everything has been set up, we can connect to the broker with the broker IP and the broker port. Once we have told the client to connect, the client object runs in the loop function forever. Click Ctrl + X, then Y to confirm to save and hit the enter button to save to the existing file. Now we test if everything is running correctly. Therefore run the python code with the following statement in the Raspberry Pi console and watch the terminal if you receive data. You should see the temperature and humidity in the terminal like the following picture. It can take up to 1 minute before the ESP microcontroller is sending new data. And of course make sure that the ESP8266 or ESP32 is running. Conclusion During this tutorial we build a full MQTT pipeline to send sensor data from a ESP8266 or ESP32 to a MQTT broker on a Raspberry Pi. Moreover we created a subscriber who reads the temperature and humidity data published to the broker. It is also possible to change the payload to the status of a light if it is on or off. Also the status of a switch can be send via MQTT. In my apartment I have in total 3 indoor weather stations and 1 outdoor weather station measuring the temperature, humidity and light. All 4 devices send the data to 1 MQTT broker and I can easily add more sensors and devices to the system. If you struggle at some point in this tutorial or if you have questions regarding the project or MQTT in general, fell free to use the comment section below to ask questions. I will answer them as quickly as possible. Are you are interested in a whole section of articles related to MQTT, Home Assistant, InfluxDB and Grafana? The following picture shows the structure of in total 5 articles in this series. 22 thoughts on “Send data from ESP8266 or ESP32 to Raspberry Pi via MQTT” The easiest way to an explanation of MQTT. Great Work… Hi Bhargav, thank you for the feedback. I hope your learned a lot about MQTT. For me one of the best DIY IoT protocols. Great Job David! I will finally succeed to gather all data from my esp8266(s) spread in the house/outside into a common view! I need help! The ESP code is ok! It is sending date to MQQT! Fine!!! But the raspberry, when a write “sudo mosquitto” it return me this: pi@raspberrypi:~ $ sudo mosquitto 1592691877: mosquitto version 1.4.10 (build date Wed, 13 Feb 2019 00:45:38 +0000) starting 1592691877: Using default config. 1592691877: Opening ipv4 listen socket on port 1883. 1592691877: Error: Address already in use I already configured the IP static with “” but my Ip I put 30 and you put 8! Help!! -> email.giovane@gmail.com Giovane Hi Giovane, maybe this answer on stackoverflow helps you: Also version 1.4.10 is an old version of mosquitto. You can try to solve the problem my updating mosquitto to the newest version. Superb tutorial David! I used it as base for doing some home-automation with ESP32-WROOM-32. All lights in my home are switched with 433Mhz buttons + relays, all switches are set up as “flip flop” comtrol. As lomg as I use these switches manually, I see the result and if needed, I just repeat the action. But I can also further turn the lights on and off with PC’s and smartphones via my Raspberry linked 433 Mhz sender and receiver. Because of the flip-flop setup there is no information available about the status. To conclude the status of the outdoor lights these are connected to optocouplers and the optocouplers are connected to ESP32’s. Further a light sensor is connected to conclude night/day. I had to do the following essential amendments in the arduino sketch: #include “WiFi.h” void setup() { //skipped the other sensor Serial.begin(115200); pinMode(sensorPin, INPUT); pinMode(optocPin, INPUT); pinMode(ledPin, OUTPUT); } void loop() ……. else { Serial.println(“Optoc failed to send. Reconnecting to MQTT Broker and trying again”); connect_MQTT(); //client.connect(clientID, mqtt_username, mqtt_password); It could be helpful to add a hint about firewall issues. It took me some time to find out that port 1883 was not open. after sudo ufw allow 1883 the script started working. Before that the script stopped after telling me the WiFi.localIP cheers and thank you Mike MQTT error pi@raspberrypi:~ $ sudo systemctl status mosquitto ● mosquitto.service – Mosquitto MQTT Broker daemon Loaded: loaded (/etc/systemd/system/mosquitto.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Mon 2020-08-03 02:40:31 IST; 16min ago Main PID: 501 (code=exited, status=203/EXEC) Aug 03 02:40:31 raspberrypi systemd[1]: mosquitto.service: Service RestartSec=100ms expired, scheduling restart. Aug 03 02:40:31 raspberrypi systemd[1]: mosquitto.service: Scheduled restart job, restart counter is at 5. Aug 03 02:40:31 raspberrypi systemd[1]: Stopped Mosquitto MQTT Broker daemon. Aug 03 02:40:31 raspberrypi systemd[1]: mosquitto.service: Start request repeated too quickly. Aug 03 02:40:31 raspberrypi systemd[1]: mosquitto.service: Failed with result ‘exit-code’. Aug 03 02:40:31 raspberrypi systemd[1]: Failed to start Mosquitto MQTT Broker daemon. Great work and its the easiest way to understand MQTT This was a REALLY good article. I learned a lot from these two parts. Thank you!! One suggestion or even just a request. Could you review how to setup a mqtt publisher in python for a Rasp Pi? I’m pretty sure I’ve figured it out but would like to see how you do it. Thanks again! Can you put the esp32 code equivalence? It seems to not work like 8266 example here :/ Hi NK, take me some time but now the ESP32 code is fully available. you just need to change the esp8266wifi.h library to wifi.h for the esp32 100% correct. From the code – you’re reconnecting to the WIFI network every cycle – although this might be a safe way to do this, is there no better way to only reconnect when something might be broken? Hi Jef, you could also establish the MQTT connection only in the setup function and also reconnect is there is an error in the transfer of the sensor data. But in a real world example I would only send the data once a hour. Therefore I can disconnect the sensor for this time as my personal preference. There is a great tool to monitor the broker while doing experiments with the IoT devices: MQTT Explorer. See mqtt-explorer.com Kind regards, Urs. Hi Urs, thanks for the hint. I didn’t know the MQTT Explorer and will try it. When running the python code on the raspberry pi (the final step) I get an error socket.error: [Errno 133] No route to host how does one fix this? Hi Priyanshu, do you do the tutorial 1:1 with my program code or do you have your own project and only using parts of the tutorial? Hey, first of all great work. For a beginner into MQTT communication, I learnt a lot. So the issue is, I’m using a similar setup although I’m using a IR temp sensor. In my arduino IDE the output seems to be fine. although when I run the python file in my pi. There is no output. The arduino IDE shows the messages have been sent successfully. Let me know if you can help me out. Cheers, Mo Hi Mo, do you use the exact same topic for the MQTT connection and do you convert the output from the IR temp sensor as string? Maybe a different IP address? Hi, thanks very much for the great tutorial. It helps me a lot. Some questions: 1) Actually I need to remove the “float” in the code “return SensorData(location, measurement, float(payload))” in order to let the script run. Otherwise, there is an error saying the data type conflict. 2) I need to remove the “MQTT_CLIENT_ID” from the code “#mqtt_client = mqtt.Client(MQTT_CLIENT_ID)” . Otherwise, there is no data written to the database. Any ideas? Thanks very much. About my setup: Pi: 3 model B Influxdb: 1.6.4 Arduino yun
https://diyi0t.com/microcontroller-to-raspberry-pi-wifi-mqtt-communication/
CC-MAIN-2021-39
refinedweb
4,779
64.61
mmap - map pages of memory #include <sys/mman.h> void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off); The mmap() function establishes a mapping between a process' an implementation-dependent function of the parameter addr and parameter prot determines whether read, write, execute, or some combination of accesses are permitted to the data being mapped. The prot should be either PROT_NONE or the bitwise inclusive OR of one or more of the other flags in the following table, defined in the header <sys/mman.h>. If an implementation. The implementation will support at least the following values of prot: PROT_NONE, PROT_READ, PROT_WRITE, and the inclusive OR of PROT_READ and PROT_WRITE. The file descriptor fildes will have been opened with read permission, regardless of the protection options specified. If PROT_WRITE is specified, the application must>: MAP_SHARED and MAP_PRIVATE describe the disposition of write references to the memory object. If MAP_SHARED is specified, write references change the underlying object. If MAP_PRIVATE is specified, modifications to the mapped data by the calling process will be visible only to the calling process and will not change the underlying object. It is unspecified whether modifications to the underlying object done after the MAP_PRIVATE mapping is established are visible through the MAP_PRIVATE mapping. Either MAP_SHARED or MAP_PRIVATE can be specified, but not both. The mapping type is retained across fork(). argument addr must also meet these constraints. The implementation performs mapping operations over whole pages. Thus, while the argument len need not meet a size or alignment constraint, the implementation will include, in any mapping operation, any partial page specified by the range [pa, pa + len). The system always zero-fills any partial page at the end of an object. Further, the system never writes out any modified portions of the last page of an object that are beyond its end. References within the address range starting at pa and continuing for len bytes to whole pages following the end of an object result in delivery of a SIGBUS signal. An implementation may deliver SIGBUS signals when a reference would cause an error in the mapped object, such as out-of-space condition. The mmap() function adds an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference is removed when there are no more mappings to the file. The st_atime field of the mapped file may be marked for update at any time between the mmap() call and the corresponding munmap()() with MS_ASYNC or MS_SYNC for that portion of the file by any process. If there is no such call, these fields may be marked for update at any time after a write reference if the underlying file is modified as a result. There may be implementation-dependent limits on the number of memory regions that can be mapped (per process or per system). If such a limit is imposed, whether the number of memory regions that can be mapped by a process is decreased by the use of shmat() is implementation-dependent. addr argument (if MAP_FIXED was specified) or off is not a multiple of the page size as returned by sysconf(), or are considered invalid by the implementation. - [EINVAL] - The value of flags is invalid (neither MAP_PRIVATE nor MAP_SHARED is set). - [EMFILE] - The number of mapped regions would exceed an implementation-dependentOTSUP] -. - [EOVERFLOW] - The file is a regular file and the value of off plus len exceeds the offset maximum established in the open file description associated with fildes. None. Use of mmap() may reduce the amount of memory available to other memory allocation functions. Use of MAP_FIXED may result in unspecified behaviour in further use of brk(), sbrk(), malloc() and shmat(). The use of MAP_FIXED is discouraged, as it may prevent an implementation from making the most effective use of resources. The application must ensure correct synchronisation:becomes:becomes: fildes = open(...) lseek(fildes, some_offset) read(fildes, buf, len) /* use data in buf */ fildes = open(...) address = mmap(0, len, PROT_READ, MAP_PRIVATE, fildes, some_offset) /* use data at address */ The [EINVAL] error above is marked EX because it is defined as an optional error in the POSIX Realtime Extension. None. brk(), exec, fcntl(), fork(), lockf(), msync(), munmap(), mprotect(), sbrk(), shmat(), sysconf(), <sys/mman.h>.
http://man.remoteshaman.com/susv2/xsh/mmap.html
CC-MAIN-2019-22
refinedweb
719
51.78
Here I will explain how to send email using gmail in asp.net or send email using gmail smtp server in asp.net using c#. Description: To implement this mail concept in your asp.net application first we need to add this reference to our application System.Web.Mail namespace What is System.Net.Mail The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery. How we can get this reference (System.Net.Mail) for that we need to add System.web.dll reference to our application. for that we need to add System.web.dll reference to our application. a) On the Project menu, click Add Reference. b) On the .NET tab, locate System.Web.dll, and then click Select. c) Click OK in the Add References. After that design your aspx page like this After that add this namcespace in your codebehind After that write the following code in button click Here we used smtp.Port=587 this is the port number which is used by gmail that’s why we used this port number. In some situations if you get any error regarding security remove smtp.EnableSsl = true; Demo Other related posts are How to send mail with attachment using asp.net i hope it helps you i hope it helps you 68 comments : Hi Suresh Garu, Nice post regarding Gmail Credentials.I had seen so many sites for this but i didn't find clear explanation like this.It helped me.Thank You thanks prasanthi keep visiting...... Thank u sooooooooooooooooo much........ very useful....... i send my first mail through asp.net........ Thank you can u send hoe to send multiple reciepients Simply Great ! answer to send mail Hi Suresh I m getting Error like "Failure sending mail." in catch. check whether you enable your mail settings Forwarding and POP/IMAP in your gmail based on mentioned details in article how to send email to multiple recipients, like we have list of email ids in gridview and program send email to all the user who are selected by user through checkbox control @Imtiaz.. If you want to send multiple recipients you need to append all the emails with semicolon like test@gmail.com;test@gmail.com and send mail as usual it will send mail to all the recipients... hai suresh garu if i check mail in inbox to delte i must get delete button above so can u give suggestion how to write for it my mail id is togaru.kranthi@gmail.com sir how can we track delivery report of these email ?? thanks hai Suresh Garu , I want some help from you , for example In Gmail we sending the mail if mail id wrong wet get one mail that is Delivery sending failed mail..the same functionality how we implement in Asp.net website. hi suresh...i want to send a verfication mail to his email Id when user fills signup form in a website and when he clicks on that link then his account will activate and he will able to navigate in that website.plz help me as soon as possible. hi.. thks a lot man.. how can i attach a file with mail???? i've used your code bt niether m getting any error nor its sending any mail Arpeeta ::kindly Set the break POint. . Thank you very much..........got mail without any error. visited lot of sites but cant got any solution.But this code working fine... Sir,,,Also can you suggest any code for sending SMS...??? any help will be most useful for me.......!!! thanks in advance...... Thanks Man. Your helped me lot. in past i had try various example but had not succeed in sending mail. but your code is working perfectly Thanking your many times. Ankit Patel. Very excellent learned and i just implemented for on blog using godaddy host, but some mails are sending in spam. what is the solution? Thanks, Suresh! in advance. An attempt was made to access a socket in a way forbidden by its access permissions 64.233.167.108:587 this error comes Hello Mr. Suresh I am Getting this Error... The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required i am also set allow less secure app to true
http://www.aspdotnet-suresh.com/2010/12/how-to-send-mail-using-gmail.html?showComment=1359048970842
CC-MAIN-2017-30
refinedweb
755
76.72
This may come in handy if you plan to migrate, for example, an existing WhatsApp group. A good number of users that have already migrated may be a convincing argument to promote such change, specially in communities where Telegram where not that well known so far. In this tutorial we'll be using the Telegram Database Library (or TDLib), which lets you build your own Telegram clients. Happily, there is a nice python wrapper for it. 1. Setting up The first thing is registering a new Telegram Application. Once that we have both api_id and api_hash, we need to get python-telegram. Make sure you use Python 3.6+. python3 -m pip install python-telegram 2. Calling the API We are ready to instantiate the client. from telegram.client import Telegram tg = Telegram( api_id='YOUR API ID', api_hash='YOUR API HASH', phone='+575555555555', database_encryption_key='changeme1234', ) tg.login() A prompt will wait for us to enter a code, which will be sent to our telegram account. The Telegram class has some TDLib methods available, like send_message(), and a few more. For any other we need to use call_method(). In order to check whether a phone number is using Telegram or not, we need to add it as a contact. importContacts() is what we are looking for. It let us add new contacts just by their phone numbers, though you can also specify things like last_name, and others. response = tg.call_method('importContacts', { 'contacts': [ {'phone_number': '+57 555 123 4567'}, ] }) response.wait() user_ids = response.update['user_ids'] If a number is not currently on the platform, it will return 0 as its user id. if user_ids[0] == 0: print('This contact is NOT using Telegram.') else: print(f'¡This contact({user_ids[0]}) uses Telegram!') 3. Cleaning Time to remove those testing contacts. tg.call_method('removeContacts', {'user_ids': user_ids}) And that's it. Hope you enjoyed my first tutorial 🧪 Happy hacking! Discussion (1) Hi Luis, i'm run this code but it gives Error: user_ids = response.update['user_ids'] TypeError: 'NoneType' object is not subscriptable response.wait() returns None
https://practicaldev-herokuapp-com.global.ssl.fastly.net/luvejo/how-to-check-if-a-phone-number-is-on-telegram-using-tdlib-and-python-1kfl
CC-MAIN-2021-17
refinedweb
341
68.16
SecurID::ACEdb - Perl extension to use the ACE/Server Administration Toolkit API use SecurID::ACEdb qw(:basic func1 func2 ...) use SecurID::ACEdb qw(:all); ApiInit(); ... ApiEnd(); The ACE/Server Administration Toolkit API is used to create custom administration applications for ACE/Server, specifically functions that can read and modify the ACE/Server databases. All functions must be explicitly imported into the namespace. The import tag basic imports ApiInit, ApiEnd, and Result. The import tag all imports all functions. Unless otherwise documented, all function calls return 1 if the function succeeded, 0 otherwise. $result = Result(); Returns the result of the last operation as a string. This should be called whenever any function fails to determine the cause of the failure. ApiInit([commitFlag => v]); Initializes and connects to the ACE/Server databases. This is required before subsequent SecurID::ACEdb functions can be called. The commitFlag should be set to true to automatically commit database changes. If not set, then the Commit and Rollback functions can be used to define transactions. This function can only be called once in any program. It cannot even be called a second time after calling ApiEnd. Don't blame me; blame Security Dynamics. Commit(); Commits all API function calls to the database since the last commit or rollback. Only needed if ApiInit was not called with a commitFlag of true. Rollback(); Rolls back all API function calls since the last commit or rollback. Only needed if ApiInit was not called with a commitFlag of true. ApiEnd(); Finishes the API session. Once this function is called, no subsequent API functions can be called, including ApiInit. $rev = ApiRev() Returns the revision number of the API, as a string. AssignToken($lastname, $firstname, $login, $shell, $serial); Adds a user to the database and assigns the token specified by $serial. The token is enabled, the PIN is cleared, and both BadTokenCodes and BadPINs are set to zero. SetUser($lastname, $firstname, $login, $shell, $serial); Sets an existing user's information as specified by the parameters. The token serial number is used to locate the user in the database, so this function cannot be used to change a user's token. $userinfo = ListUserInfo($serial); Returns user information for a user who owns the specified token. The user information is returned in a hashref which contains the keys userNum, lastName, firstName, defaultLogin, createPIN, mustCreatePIN, defaultShell, tempUser, dateStart, todStart, dateEnd, and todEnd. Returns undef if there was an error. UnassignToken($serial) Unassigns the token and deletes the user from the database. The user must be removed from all groups and not be enabled on any clients before calling this function. SetCreatePin($state, $serial); Sets the createPIN modes for the user related to $serial. $state should be a string containing one of the values USER, SYSTEM, or EITHER. AddUserExtension($key, $data, $serial); Adds a user extension record for the user related to $serial. The data field can be no more than 80 characters, while the key field must be no more than 48 characters. DelUserExtension($key, $serial); Deletes a user extension record for the user related to $serial. $ext = ListUserExtension($key, $serial); Returns the user extension data for the specified key of the user related to $serial. Returns undef if there was an error. SetUserExtension($key, $data, $serial); Sets data in an existing extension field for the user related to $serial. DisableToken($serial); Disables the token so that the related user cannot authenticate. EnableToken($serial); Enables the token so that the related user can authenticate. @list = ListTokens(); Returns a list of all tokens in the database, or an empty list if there was an error. Note that the underlying C API requires this function to be called multiple times to get the entire list; the Perl version does not require this. If a call to the function other than the first results in an error, ListTokens will return a partial list, and will not notify the caller of any error condition. The caller should examine the value of Result(); if it is not Done, then the entire list was not returned. $info = ListTokenInfo($serial); Returns a hashref containing token information, or undef if there was an error. The hashref contains the keys serialNum, pinClear, numDigits, interval, dateBirth, todBirth, dateDeath, todDeath, dateLastLogin, todLastLogin, type, hex, enabled, newPINMode, userNum, nextTCodeStatus, badTokenCodes, badPINs, datePIN, todPIN, dateEnabled, todEnabled, dateCountsLastModified, and todCountsLastModified. ResetToken($serial); Resets the token to a known state, so that the token is enabled, next token code mode is off, bad token codes is zero, and bad PINs is zero. This should be done before assigning the token to a user or to remedy token problems. NewPin($serial) Puts the token into new PIN mode. AddLoginToGroup($login, $group, $shell, $serial); Adds the user login to a group in the database. The group must exist and the login must be unique to the group. The shell can be an empty string. DelLoginFromGroup($login, $group); Deletes the login name from a group. $groups = ListGroupMembership($serial); Lists the groups that a token has been assigned to. Returns a listref or undef if there was a problem. Each element of the list is a hashref containing the keys userName, shell, and group. $groups = ListGroups(); Lists the groups in the ACE/Server database. Returns a listref or undef if there was a problem. Each element of the list is a hashref containing the keys group and siteName. EnableLoginOnClient($login, $client, $shell, $serial); Enables a user login on a client. The client must exist and the login must be unique to the client. The shell can be an empty string. DelLoginFromClient($login, $client); Disables a user login from a client. $list = ListClientActivations($serial); Lists the clients that a token is activated on. Returns a listref or undef if there was an error. Each element of the list is a hashref containing the keys login, shell, clientName, and siteName. $list = ListClientsForGroup($group); Lists the clients associated with a group. Returns a listref or undef if there was a problem. Each element of the list is a hashref containing the keys clientName and siteName. $list = ListClients(); Returns a list of all clients in the database. Returns a listref or undef if there was a problem. Each element of the list is a hashref containing the keys clientName and siteName. @serial = ListSerialByLogin($login, [$count]); Looks up the token serial number belonging to the user with login name $count specifies which instance of $login to use if there are multiple instances, and defaults to 1. Returns a listref to the serial numbers assigned to $login. Returns an empty listref if the user does not exist, or if the count was too high, and returns undef if there was another error. $hist = ListHistory($days, $serial, [$filter]); Lists the events in the activity log affecting token $serial. $days specifies the number of days prior to the present date to list the history for. If $filter is true, events performed by an administrator will be filtered from the list, making it easier to view authentication events. Returns a listref or undef if there was a problem. Each element of the list is a hashref containing the keys msgString, localDate, localTOD, login, affectedUserName, groupName, clientName, siteName, serverName, and messageNum. MonitorHistory([$filename, [$close]]); Docs tbd. DumpHistory($month, $day, $year, [$days, [$filename, [$truncate]]]); Dumps the affected events in the log. If $filename is provided, specifies a filename to dump the log to. $filename can also be the empty string. The affected events start at the beginning of the log and end one day prior to the date specified by the $month, $day, and $year parameters. $year should be a 4-digit number. If the $days parameter is non-zero, then the first three parameters are ignored, and the $days parameters specifies the number of days prior to today's date that are not affected. If the $truncate option is set, the entries will be removed from the log. Dave Carrigan <Dave.Carrigan@cnpl.enbridge.com> perl(1).
http://search.cpan.org/dist/SecurID-ACEdb/ACEdb.pm
CC-MAIN-2017-26
refinedweb
1,322
57.27
On Mar 6, 2010, at 5:47 PM, Ben Finney <ben+python at benfinney.id.au> wrote: > "Stephen J. Turnbull" <stephen at xemacs.org> writes: > >> I have to admit Jean-Paul's explanation a pretty convincing reason >> for >> adopting "future" rather than "promise". But I'm with Skip, I would >> prefer that the module be named "future" rather than "futures". > > Has anyone in this very long thread raised the issue that Python > *already* uses this term for the name of a module with a totally > unrelated purpose; the ‘__future__’ pseudo-module? > > That alone seems a pretty strong reason to avoid the word “future” > (singular or plural) for some other module name. > Yes, they have, and putting it in a sub namespace has also come up. In the thread.
https://mail.python.org/pipermail/python-dev/2010-March/098244.html
CC-MAIN-2016-40
refinedweb
128
75
From: Sylvain, Gregory M (GSylvain_at_[hidden]) Date: 2005-07-12 16:11:00 Hello all, We are currently using boost_1_32_0 and I'm trying to write a toolset file to enable us to use Roguewave's LEIF xsd2cpp C++ class generator from within bjam. (The xsd2cpp command is just a C++ class generator that generates C++ class from a respective W3C XSD Schema). I'm not having much luck, I've been through the boost build manual, samples, etc. and I'm still having problems. In the end, I would like to be able to write a library rule such as : lib libclientxml : schemas.xsd ; And have boost run RW's xsd2cpp tool run on the file schemas.xsd and all of the resulting cpp files that are generated would be compiled and archived in libclientxml. I have a toolset file in my boost-build/tools directory as follows: ---- begin file boost-build/tools/xsd2cpp.jam ---- import type ; type.register XSD : xsd ; import generators ; class cpp-generator : generator { rule __init__ ( * : * ) { generator.__init__ $(1) : $(2) : $(3) : $(4) : $(5) : $(6) : $(7) : $(8) : $(9) ; } # after the actions is executed, get a list of the generated targets that # results from this action rule generated-targets ( sources * : property-set : project name ?) { local leafs ; local temp = [ virtual-targets.traverse $(sources[1]) : : include-sources ] ; for local f in $(temp) { leafs += $(f) ; } return [ generator.generated-targets $(sources) $(leafs) : $(property-set) : $(project) $(name) ] ; } } generators.register [ new cpp-generator xsd2cpp.xsd2cpp : XSD : CPP ] ; actions xsd2cpp { # run RW's xsd2cpp command over the source and produce a lot of C++ code. xsd2cpp -STL "$(>)" } ---- end file boost-build/tools/xsd2cpp.jam ---- If anyone has a clue how to do this, please let me know. Or if I've going about this the wrong way, I would like to here that as well. Thanks for any assistance with this, greg 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/2005/07/90174.php
CC-MAIN-2022-40
refinedweb
329
58.99
Typescript by default — A JavaScript journey #5 — What a click bait title?!? — I know, right? So, TypeScript is not new stuff, but it became more and more popular in the JavaScript community those days and this is why is great to use it by default in your JavaScript projects. — But TypeScript is an alternative language to JavaScript, right? — Yeah... no Unlike CoffeeScript, ELM, Reason or any kind of languages that produce executable JavaScript, TypeScript is still your beloved ECMAScript syntax, plus some cool features like type definition, interfaces, etc. Basically, it's half an extended version of JavaScript, half a compiler like Babel. — But you can also compile TypeScript code with Babel — I know, right? Anyway, you can see TypeScript like Sass or SCSS. Even if your styles are compiled with Sass, you can still use only plain old CSS syntax. There is no obligation of using Sass features. It's the same thing with TypeScript; it's not mandatory to define types or to use all of the good stuff brought by it. It means that theoretically, you can already use TypeScript on all your existing JavaScript projects. Cool, right? Now it's time to dig in the small configuration required by each kind of project. It's impossible to describe them all, we'll start with the most popular ones (for me). But remember, with it actual popularity, there is plugins, modules or even core support for TypeScript in almost all libraries and framework. Node/Express server First, you'll need some new dependencies to execute your TypeScript code : Then, you'll need to change the default classic nodemon start command in your package.json : The only difference with your usual configuration, the executable is overrode as ts-node instead of the default node and your entry point is now a .ts file. As you may understand at this point, your files will not be .js anymore, but .ts (obvious, I know). Finally, you need a new tsconfig.json file at your project's root (like in any TypeScript project) for the related configuration. Something like : And that's it! Now your app's code will like something like: Play with the CodeSandbox example! — import in Node projects without Webpack \o/ React applications Good news if you're using react-create-app, it's already embedded in it! The only thing you must do is to use the following command : Same difference for file extensions here, .jsx will be transformed to .tsx. Nothing else change from your favorite React architecture. Next.js applications Because SSR is more than a trendy thing, you'll maybe also add TypeScript to your Next.js powered project. To do that, just use the official plugin with : And follow the official recipe. Gatsby websites Same thing here, official plugin, great doc. Conclusion As you can see, it's a fairly easy process to create a new project or even moving an existing one with TypeScript and still keeping your favorite JavaScript stack. There is no reason in the world, that will prevent you for using TypeScript. Trust me :wink: See also the official migration guide
https://antistatique.net/fr/nous/bloggons/2019/01/23/typescript-by-default-a-javascript-journey-5
CC-MAIN-2021-10
refinedweb
522
73.88
If you are one of those who have still not filed their tax return or are still wondering which ITR form to use or what has changed in the new forms, here's help. The due date for filing income tax return for Financial Year 2017-18 – for certain category of taxpayers – has been extended till August 31 this year. By this time many of you must have filed your tax return. However, if you are one of those who have still not filed their tax return or are still wondering which form to use or what has changed in the new forms, here’s all you need to know about the new ITR forms. It may be noted that the Central Board of Direct Taxes (CBDT) had some time back notified the new ITR (Income Tax Return) forms for Assessment Year 2018-19 or Financial Year 2017-18. These new ITR forms – ITR-1 Sahaj, ITR-2, ITR-3, ITR-4 Sugam, ITR-5, ITR-6 and ITR-7 – incorporate the requirements as per the amendments made by the Finance Act, 2017. For example, for FY2017-18, CBDT has notified a one-page simplified income tax return (ITR) Form-1 (Sahaj). Any individual, who is resident other than not ordinarily resident, and has income up to Rs 50 lakh from salary, 1 house property or other income (like interest, etc), can file Form-1. Parts relating to salary and house property have been rationalised in this new form, while providing the basic details of one’s salary (as per Form 16) and income from house property has been mandated. Also See: Income Tax Return filing for previous years: How many years can tax returns be filed for? Similarly, CBDT has also rationalised the ITR Form-2, which can be filed by individuals & HUFs who have income under any head other than business or profession, while those having income under the head Business or Profession have to file either Form-3 or Form-4. Tax experts say that many changes have been introduced in the new income tax return forms for FY2017-18 or AY2018-19. For example, the requirement of giving details of cash deposited for a given period as required in the ITR Forms for FY2016-17 has now been done away with. However, NRIs are now required to furnish details of any one foreign bank account, for the purpose of credit of refund. Also See: Implications for delay, non-filing of ITR for individual taxpayers “The changes are mainly directed towards extracting more details of the transactions from taxpayers, with an objective to minimize tax evasion. This is also evident as the ITR forms now seek GST details of the businesses. Earlier people used to mention contradicting details in the ITR forms and GST forms. But now with the GST details mandatory in ITR, there will be minimal tax evasion. These changes are aimed at promoting transparency and providing further clarity,” says CA Karan Batra, Founder & CEO of CharteredClub.com. Here are the new requirements in the ITR forms for AY 2018-19: (Source: CharteredClub.com) Get live Stock Prices from BSE and NSE and latest NAV, portfolio of Mutual Funds, calculate your tax by Income Tax Calculator, know market’s Top Gainers, Top Losers & Best Equity Funds. Like us on Facebook and follow us on Twitter.
https://www.financialexpress.com/money/income-tax/filing-income-tax-return-heres-what-has-changed-in-the-new-itr-forms-for-ay2018-19/1270777/
CC-MAIN-2019-39
refinedweb
560
63.83
Maybe this question has been asked around but I couldn't find it. How do I setup a static member object at its creation? And possibly perform some other tasks. The goal is to have some of it's setters called at it's creation time. Example: Header file A.h: class A{ public: A::A(); ~A::A(); static QTimer updateTimer; }; #include "A.h" QTimer A::updateTimer.setInverval(100); // I need to set it's inverval to 100ms // but only once in the beginning of it's life time A::A(){... } ~A::A(){... } This is what constructors are for. If it's your own type, just write a constructor. If the type doesn't have a constructor and you cannot modify it (like, presumably QTimer comes from Qt), then wrap it in a type of your own that does. This is a textbook case of inheritance being useful. Your wrapper class will extend the original class with a bit of new functionality: setting the interval during initialisation. struct QTimerWrapper : QTimer { QTimerWrapper(int interval) { setInterval(interval); } }; struct A { static QTimerWrapper updateTimer; }; QTimerWrapper A::updateTimer(100); Or you could use composition, having the QTimer be a member of QTimerWrapper instead.
https://codedump.io/share/qvB9kuD6b7rW/1/setup-static-member-object
CC-MAIN-2016-50
refinedweb
198
67.04