text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
The official source of information on Managed Providers, DataSet & Entity Framework from Microsoft The information in this post is out of date. Visit msdn.com/data/ef for the latest information on current and past releases of EF. Jarek Kowalski built a great caching and tracing toolkit that makes it easy to add these two features onto the Entity Framework. His code sample plugs in as a provider that wraps the original store provider you intend to use. This guide will help you get started using Jarek’s tools to enable caching and/or tracing in your application. Caching can be especially valuable in an application that repeatedly retrieves the same data, such as in a web application that reads the list of products from a database on each page load. Tracing allows you to see what SQL queries are being generated by the Entity Framework and determine when these queries are being executed by writing them to the console or a log file. When these two features are used together, you can use the tracing output to determine how caching has changed your application’s pattern of database access. Although the Entity Framework currently does not ship with caching or tracing “in the box,” you can add support for these features by following this walkthrough. These instructions cover only the essentials of enabling caching and tracing using Jarek’s provider samples. More advanced details about how to configure these samples are available in the resources Jarek provides online. Below is a diagram that represents the change we will be making to the query execution pathway in order to plug in the caching and tracing features. The extensibility point we will be using is at the store provider level of the entity framework. In addition, below is a diagram that should elucidate why it is referred to as a “wrapping” provider and what it looks like when there is a cache hit versus a cache miss during query execution. As you can see below, the providers conceptually wrap around your existing provider. Let’s get started. Here are the new resources you will need to follow along with this walkthrough: · Download “Tracing and Caching Provider Wrappers for Entity Framework” from MSDN to a folder where you keep your visual studio projects · Download the extended context code generator, “ExtendedContext.vsix,” from the link at the bottom of this post First, install the visual studio extension my colleague Matt Luebbert created that will automatically generate certain boilerplate code for you. A vsix file like this is an installable visual studio extension that adds functionality to your IDE. This particular vsix adds a T4 template that generates a class that extends your existing entity container so that it can work with the new caching and tracing features. Note, however, that it also has dependencies on adding both of Jarek’s caching and tracing resources to your project. This does not necessarily mean that to use caching you must use tracing, or vice versa, but you do have to provide your project with references to both resources in order to use this extra tool we have provided for convenience. If you do not want to use this tool, you can also generate the necessary code by hand according to Jarek’s instructions here. To install the extension, double-click the “ExtendedContext.vsix” file you downloaded to your desktop. Then click “Install.” Click "Close" after the installation completes successfully. Now open your project in Visual Studio. If you would like a sample project to get started, you can use the same one I am using, which I created in a previous walkthrough the Absolute Beginner’s Guide to Entity Framework. For this particular sample, I am using the same models as in that walkthrough but a simpler version of the executable code which also demonstrates the benefits of caching more obviously. Here is the code in the file Program.cs that I am starting with this time. using System; using System.Linq; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { using (Model1Container context = new Model1Container()) { //Add an entity context.Users.AddObject(new User { Username = "User1", Password = "password" }); context.SaveChanges(); User findUser = context.Users.FirstOrDefault(user => user.Username == "User1"); Console.WriteLine("Found user: " + findUser.Username); Console.WriteLine("User is attending " + findUser.ConfirmedEvents.Count() + " events, including: "); } using (Model1Container newContext = new Model1Container()) User findUser = newContext.Users.FirstOrDefault(user => user.Username == "User1"); Console.Read(); //Pause execution } } } Now we need to add the proper references to Jarek’s code. To do this, from the File menu of Visual Studio click “Add” >> “Existing Project…” First, add the project named EFProviderWrapperToolkit.csproj which is in the EFProviderWrapperToolkit folder of Jarek’s download. Now, add the reference to that project from the project in which we are enabling caching. To do this, right-click on “References” for your project in Solution Explorer, and then select “Add Reference…” Under the “Projects” tab select the EFProviderWrapperToolkit and click “OK” to add a reference for this code into your project. The EFProviderWrapperToolkit is a common dependency for both caching and tracing, so regardless of whether you wish to use one or both of those features, this is a necessary inclusion. To add tracing functionality, follow the same steps as above to add the EFTracingProvider.csproj file which is located in the EFTracingProvider folder within the downloaded code. After you have added the project, right-click on “References” in the Solution Explorer and click “Add Reference…” to add the necessary reference for the EFTracingProvider components. If you would like to follow along with this walkthrough and use the Extended Context generator, which depends on also adding the EFCachingProvider code, repeat that same procedure once more to add the “EFCachingProvider” project, and then add a reference to that project as above. This is required to satisfy a dependency of the class the Extended Context generator writes for you, since that class is designed to work with both caching and tracing and therefore depends on both. Now we will make use of that convenient extended context generator that came in the VSIX file. Right-click on the design surface of your project’s .edmx file and click “Add Code Generation Item.” You should see “EF Caching and Tracing Content Code Generator” as an option. Select that generator and click “Add.” You will also need to come back to this screen to add the “ADO.NET Entity Object Generator,” but you can only add one code generator at a time. You will likely see a security warning as below and perhaps a few other times while using this add-on code. Click “OK” to proceed whenever this warning appears. This will add the ExtendedContext file to your project, like this: Here is an example of what this generator automatically writes for you. This is what is contained in the ExtendedContext1.cs file listed above. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> using System.IO; using EFCachingProvider; using EFCachingProvider.Caching; using EFProviderWrapperToolkit; using EFTracingProvider; public partial class ExtendedModel1Container : Model1Container private TextWriter logOutput; public ExtendedModel1Container() : this("name=Model1Container") public ExtendedModel1Container(string connectionString) : base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers( connectionString, "EFTracingProvider", "EFCachingProvider" )) #region Tracing Extensions private EFTracingConnection TracingConnection get { return this.UnwrapConnection<EFTracingConnection>(); } public event EventHandler<CommandExecutionEventArgs> CommandExecuting add { this.TracingConnection.CommandExecuting += value; } remove { this.TracingConnection.CommandExecuting -= value; } public event EventHandler<CommandExecutionEventArgs> CommandFinished add { this.TracingConnection.CommandFinished += value; } remove { this.TracingConnection.CommandFinished -= value; } public event EventHandler<CommandExecutionEventArgs> CommandFailed add { this.TracingConnection.CommandFailed += value; } remove { this.TracingConnection.CommandFailed -= value; } private void AppendToLog(object sender, CommandExecutionEventArgs e) if (this.logOutput != null) this.logOutput.WriteLine(e.ToTraceString().TrimEnd()); this.logOutput.WriteLine(); public TextWriter Log get { return this.logOutput; } set if ((this.logOutput != null) != (value != null)) { if (value == null) { CommandExecuting -= AppendToLog; } else CommandExecuting += AppendToLog; } this.logOutput = value; } #endregion #region Caching Extensions private EFCachingConnection CachingConnection get { return this.UnwrapConnection<EFCachingConnection>(); } public ICache Cache get { return CachingConnection.Cache; } set { CachingConnection.Cache = value; } public CachingPolicy CachingPolicy get { return CachingConnection.CachingPolicy; } set { CachingConnection.CachingPolicy = value; } } Repeat this same procedure for adding a code generation item by right-clicking the design surface and adding the” ADO.NET Entity Object Generator,” a generator that comes as part of the Entity Framework. Now add the necessary “using” directives at the top of the file(s) in which you’ll be using tracing and/or caching. In other words, add them wherever you construct contexts and manipulate your entities. If you are following along, add this to the top of the “Program.cs” file. As with adding the projects and references, the EFProviderWrapperToolkit is required for either tracing or caching. However, here you can add only the references for the features you intend to use. For example, if you only want to use tracing, you could reference only EFProviderWrapperToolkit and EFTracingProvider to just get the resources for tracing. If you only wanted to use caching, reference EFProviderWrapperToolkit and EFCachingProvider. Since I plan to use both caching and tracing in this walkthrough, I will include all three references right now. You also need to register the provider for whichever of the features you wish to use, which is done separately for each the EFTracingProvider and the EFCachingProvider. This is the crucial step of plugging in to the extensibility point at the store provider level. This can be accomplished very conveniently through the RegisterProvider method as demonstrated below. For this walkthrough I will register both, but you could also register just the feature you plan to use. This registration needs to be called only once during execution, so place this configuration code somewhere in your application that will be called only once and at the beginning of execution before you would like to use either caching or tracing. Note the difference between lines below – their identical length and subtle difference can be misleading. EFTracingProviderConfiguration.RegisterProvider(); //Add this line if you plan to use tracing EFCachingProviderConfiguration.RegisterProvider(); //...This one is for caching In the same section of your code where you placed the above provider registration, you can specify the configuration settings. A more complete list of settings can be found online, but for now I will just turn on tracing to see that it is working. Add this line right below the RegisterProvider lines above, potentially within an “if defined” block so you can toggle it on and off easily. If you do use an “if defined” block, don’t forget to add “#define LOGGING” at the top of the file or at compilation time. #if LOGGING EFTracingProviderConfiguration.LogToConsole = true; //Optional: for sending tracing to console #endif Finally, for any context in your application in which you would like to use caching or tracing, prepend “Extended” to the name of the context you construct. For example, my entity container was called “Model1Container” before installing these features, and the extended context code generator named the class it created as “ExtendedModel1Container.” You can automate this replacement by using find and replace. Select from the top menu bar: “Edit” >> “Find and Replace” >> “Quick Replace.” Here is what my code looks like now (things I changed since the beginning of this walkthrough are highlighted in gray): #define LOGGING using EFProviderWrapperToolkit; //Required for caching and/or tracing using EFTracingProvider; //Required for tracing using EFCachingProvider; //Required for caching EFCachingProviderConfiguration.RegisterProvider(); EFTracingProviderConfiguration.RegisterProvider(); using (ExtendedModel1Container context = new ExtendedModel1Container()) context.SaveChanges(); using (ExtendedModel1Container newContext = new ExtendedModel1Container()) } Now you are ready to test if tracing is working. Build and run your application. Whenever the database is queried, you should see output to the console like below. Each logging output consists of the following: First line (white): The query counter, starting at 1 from the beginning of execution.Next lines (gray): The actual query executed against the databaseLast line (green): An indication that the query was complete and the amount of time it took. Now that we have tracing working, let’s enable some the caching functionality. Begin by adding a new directive at the top of the file in which we added the other “using” statements. Then, define the cache (where the items will be stored) and the caching policy (which items will be stored). It makes the most sense to define these beyond the scope of any one context so that multiple contexts can use the same cache, perhaps directly below the registration and configuration lines added earlier. That ability to share the same cache among multiple contexts in your application is one of the primary benefits of a second-level cache. For example, you could use a basic in-memory cache and a policy that caches all of your entities. ICache IMCache = new InMemoryCache(); CachingPolicy cachingPolicy = CachingPolicy.CacheAll; In the above code, ICache is a public interface for a cache store, created by Jarek for his toolkit, and InMemoryCache is a class he provides that implements that interface. Lastly, you have to inform each context explicitly which cache it will use and how it will cache entities. You do this by telling the context about your cache as follows, referencing the cache and policy just created: context.Cache = IMCache; context.CachingPolicy = cachingPolicy; Now the context will use the cache you defined. Here’s how my code looks with the new additions. using EFCachingProvider.Caching; //Required for using the InMemoryCache ICache IMCache = new InMemoryCache(); CachingPolicy cachingPolicy = CachingPolicy.CacheAll; context.Cache = IMCache; //Required at the beginning of the context context.CachingPolicy = cachingPolicy; //Also required at the beginning of the context newContext.Cache = IMCache; //Required at beginning of every context - references ICache from above newContext.CachingPolicy = cachingPolicy; //Also required for every cache - references CachingPolicy from above } Build and run your program again to see what changes. You should be able to see some difference in the number of database calls, likely fewer than before when only tracing was enabled. You might not see any changes in the number of calls if you primarily write to the database or read items only once during execution, since the cache is only useful during repetitive reads. However, in applications with redundant reads from the database, such as this sample I have been constructing, caching can provide some great performance and load benefits. The table below shows a side-by-side comparison that visually demonstrates the result of caching. Notice how when using caching each query is sent to the database only once. Voila! That’s basic caching at work. If you would like to learn more about this toolkit, you can visit Jarek’s blog and read through the blog post where he describes caching in more advanced detail. And if you have any feedback regarding the provider, you can reply in the comments below or reach out to Jarek via his blog contact form.
http://blogs.msdn.com/b/adonet/archive/2010/09/13/ef-caching-with-jarek-kowalski-s-provider.aspx
CC-MAIN-2014-15
en
refinedweb
Aug 4, 2011 Dec 6, 2011 8:20 PM Anyone else having on-going issues with Zenoss or am I missing something? Greetings!! I'm fairly new to using Zenoss, and am wondering (hoping) that I missed some small minor detail. I have been working with Zenoss for a good 5 months, now and just can't seem to iron out the basic features. I have tried to follow instructions from forums (Zenoss and others) and official documentation, but usually find that directions do not match with what I see in the GUI or have no specifications as to whether I make the changes from the console, GUI, or what. I have downloaded the correct documentation using links from Zenoss GUI. Our On-going Issues: hm...not sure where to start. I'm hoping the below makes sense as I will do a brain dump... - incorrect filesystem size reporting (found solution on several forums, issue not resolved) - have to modify snmp configs on all linux servers to report proper capacity of NIC (what are we supposed to do with our NAS's that do not allow for snmp custom config modifications?) - inaccurate, non-human number reporting for network traffic (found solution, partially working?) - inaccurate(?) CPU utilization - sporadic errors with little or no meaningful details Our setup: OS: Ubuntu 11.04 Linux 2.6.38-8-server Zenoss: 3.0 core zenoss-stack: 3.1.0-0 Incorrect FileSystem Reporting: Our FileSystems report incorrect sizes. I have read and understand the 5% variance on Linux systems. At one point the numbers were WAY off, now seem to be a little off which I can live with. Once after I cleared the "event cache" and "all heart beats" all FileSystem values were being reported as zero (except for "total bytes"). A reboot solved this issue. After that reboot plus a couple of days we started receiving this warning: /Perf/Filesystem threshold of high disk usage exceeded: current value 1193927.00 Filesystem threshold exceeded: 892.6% used (-1.01 GB free) I understand (to some extent) the above error, but why now all of a sudden when the FileSystem had this usage for a while now. So far, I have modified our FileSystem settings as follows (not sure what terminology I should even use): 1. Add a new zProperty click: Properties (tab) Add: Name: zFileSystemSizeOffset, Type: float, Value: 1.0 click "add" 2. Create a transform rule for FileSystem Events for f in device.os.filesystems(): if f.name() != evt.component: continue # Extract the percent and free from the summary import re m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message) if not m: continue usedBlocks = float(m.groups()[0]) totalBlocks = f.totalBlocks * getattr(device, "zFileSystemSizeOffset", 1) p = (usedBlocks / totalBlocks) * 100 freeAmtGB = ((totalBlocks - usedBlocks) * f.blockSize) / 1073741824 # Make a nicer summary evt.summary = "Filesystem threshold exceeded: %3.1f%% used (%3.2f GB free)" % (p,freeAmtGB) break 3. Change Threshold double-click: define threshold change value to: + (here.totalBlocks * here.zFileSystemSizeOffset ) * .90 4. Go back and modify the zProperty properties -set zFileSystemSizeOffset: 0.95 Incorrect Bandwidth Reporting: For every Linux server add the below to the snmp config settings locally to address Zenoss misreading Gbps as Mbps: override ifSpeed.1 uinteger 1000000000 override ifSpeed.2 uinteger 1000000000 Then on Zenoss: modify transforms: import re fs_id = device.prepId(evt.component) for f in device.os.interfaces(): if f.id != fs_id: continue # Extract the percent and utilization from the summary m = re.search("threshold of [^:]+: current value ([\d\.]+)", evt.message) if not m: continue currentusage = (float(m.group(1))) * 8 p = (currentusage / f.speed) * 100 evtKey = evt.eventKey # Whether Input or Output Traffic # if evtKey == "ifInOctets_ifInOctets|high utilization": if evtKey == "ifHCInOctets_ifHCInOctets|high utilization": evtNewKey = "Input" # elif evtKey == "ifOutOctets_ifOutOctets|high utilization": elif evtKey == "ifHCOutOctets_ifHCOutOctets|high utilization": evtNewKey = "Output" # Mbps utilization Usage = currentusage / 1000000 evt.summary = "High " + evtNewKey + " Utilization: Currently (%3.2f Mbps) or %3.2f%% is being used." % (Usage, p) break Modify "high utilization": (here.speed or 1e9) / 8 * .1 Inaccurate Non-human Legible CPU Read-outs: We have same issues with CPU read outs. I won't bother pasting the modifications for that here unless asked for. New MySQL Error: As of yesterday, this new warning started: "|mysql|/Status/IpService||5|IP Service mysql is down" - the only change was the installation of PostgreSQL and restarting of the SNMP daemon. I have spent countless hours so far in trying to get Zenoss to report properly or at least in a manner that is at least somewhat useful. Is it normal to spend quite some time customizing each new monitored host? I can understand the filesystem issue which is inherent to Linux systems, but what about the network band width? My modifications are pretty easy to do on Linux systems but what about our NAS and other network devices that need to be added? Is it expected to modify each CPU entry as well? It seems a bit odd that so much customization needs to be done. I read great reviews about Zenoss, and wouldn't mind getting it to work for us. I'm sure I missed something. Is anyone able to shed some light on this? Does anyone else have these issues? I would really like to continue using Zenoss instead of switching to another monitoring application. Your insights are greatly appreciated!! Thanks in advance.
http://community.zenoss.org/message/63207
CC-MAIN-2014-15
en
refinedweb
libMesh::ConvergenceFailure Class Reference #include <libmesh_exceptions.h> Inheritance diagram for libMesh::ConvergenceFailure: Detailed Description 75 of file libmesh_exceptions.h. Constructor & Destructor Documentation Definition at line 78 of file libmesh_exceptions.h. The documentation for this class was generated from the following file:
http://libmesh.sourceforge.net/doxygen/classlibMesh_1_1ConvergenceFailure.php
CC-MAIN-2014-15
en
refinedweb
04 September 2008 16:29 [Source: ICIS news] By Joe Kamalick?xml:namespace> WASHINGTON (?xml:namespace> Indeed, export sales of chemicals and other manufactured goods are fairly credited with saving the “Exports are vital to the “Over the past year - second quarter 2007 to second quarter 2008 - the “Nearly two-thirds of that growth, 61%, came from exports, which increased by 11.2% during that period,” he said. “Strong growth abroad, which has averaged 3.9% over the past three years (on a trade-weighted basis) and a more competitive dollar have made US manufactured exports more competitive globally,” Huether added. That strong global growth has helped sustain the “Exports are very important to American chemistry, accounting for 23% of shipments for overall chemistry - and 25% of chemicals excluding pharmaceuticals,” Swift said. “According to the Bureau of the Census, exports support 16% of the chemical industry’s jobs, with an additional 8% of industry jobs supported by the exports of other industries that depend on the domestic availability and quality of American chemistry,” Swift said. That is 207,000 chemical industry jobs tied directly or indirectly to export trade, said Swift. “Looking at the details of some of the resins,” said Swift, “exports have been very supportive at a time when domestic demand has been soft.” “The July HDPE [high density polyethylene] figures just came out and indicated that while domestic sales thus far this year were down 6.2% for the first seven months compared with the same period in 2007, exports were up 59.6% during the same time,” he said. “Similarly, domestic sales of polystyrene [PS] were down 3.7% for the first seven months this year compared with the same period in 2007, with exports up 2.1%.” “The question is,” Swift said, “how long can this go on?” The International Monetary Fund (IMF) said that “the slowdown in global growth, which started in mid-2007, is expected to continue through the second half of 2008, with only a gradual recovery during 2009”. “Global growth decelerated to 4.5% in the first quarter of 2008, measured over four quarters earlier,” the IMF said in its recent world economic outlook, “down from 5% in the third quarter of 2007, with activity slowing in both advanced and emerging economies.” In addition, “recent indicators suggest a further deceleration of activity in the second half of 2008,” the IMF said. “Accordingly, global growth is projected to moderate from 5% in 2007 to 4.1% in 2008 and 3.9% in 2009,” according to the fund’s forecast. “Expansions in emerging and developing economies are expected to lose steam,” the IMF said. “Growth in these economies is projected to ease to around 7% in 2008-2009 from 8% in 2007.” “In Growth projections for the euro area and Consequently, at least some of the strong foreign growth that has sustained US chemical and other manufacturing over the past year and more can be expected to wane this year and into 2009. As the export market begins to cool, will the The IMF said that But the fund also expected the As August drew to a close, the US Commerce Department revised its estimate of the nation’s GDP in the second quarter to a 3.3% rate of growth, up sharply from the department’s earlier estimate of 1.9% GDP expansion in the quarter. The question is whether the hoped-for Joe Acker, president of the Synthetic Organic Chemical Manufacturers Association (SOCMA), said that there is another factor in the balance between domestic and foreign markets - the quality and dependability of “While there is no question that the weaker US dollar has helped our exports, there are other factors,” Acker said. “As those developing economies begin to cool and as costs are coming up in In other words, even if the domestic “ Bookmark Paul Hodges' Chemicals and the Economy blog
http://www.icis.com/Articles/2008/09/04/9153990/insight-us-producers-face-test-of-export-strength.html
CC-MAIN-2014-15
en
refinedweb
PhyloXML To start working with phyloXML files, use the TreeIO package: from Bio import Tree('phyloxml_examples.xml', 'phyloxml'): ... = TreeIO.parse('phyloxml_examples.xml', 'phyloxml').next() >>> tree.name 'example from Prof. Joe Felsenstein\'s book "Inferring Phylogenies"' Writing phyloXML files TreeIO.write() supports phyloXML in the usual way: it accepts a Phyloxml object (the result of read() or to_phyloxml()) and either a file name or a handle to an open file-like object.') >>> phx_no.other [] If you want direct access to the phyloXML I/O functions without having to specify the file format each time, you can import the PhyloXMLIO interface directly: from Bio.TreeIO import PhyloXMLIO phx = PhyloXMLIO.read('example.xml') The other functions work exactly the same way. This also allows access to a few format-specific utilities, such as dump_tags() for printing all of the XML tags as they are encountered in a phyloXML file. >>> =.PhyloXML, and offer additional methods for converting between phyloXML and standard Biopython types. The PhyloXML.Sequence class contains methods for converting to and from Biopython SeqRecord objects. This includes the molecular sequence (mol_seq) as a Seq object, and the protein domain architecture as list of SeqFeature objects..
http://biopython.org/w/index.php?title=PhyloXML&oldid=2819
CC-MAIN-2014-15
en
refinedweb
Investment Basics - Course 103 - Investing for the Long Run This is the third Course in a series of 38 called "Investment Basics" - created by Professor Steven Bauer, a retired university professor and still a proactive asset manager and consultant / mentor. Course 103 - Investing for the Long Run Introduction In the last lesson, we noticed that the difference of only a few percentage points in investment returns or interest rates can have a huge impact on your future wealth. Therefore, in the long run, the rewards of investing in stocks can outweigh the risks. We'll examine this risk/reward dynamic in this lesson. Volatility of Single Stocks Individual stocks tend to have highly volatile prices, and the returns you might receive on any single stock may vary wildly. If you invest in the right stock, you could make bundles of money. For instance, Eaton Vance (EV), an investment-management company, had one of the best-performing stock for the last 25+ years. If you had invested $10,000 in 1979 in Eaton Vance, assuming you had reinvested all dividends, your investment would have been worth $10.6 million by December 2007. On the downside, since the returns on stock investments are not guaranteed, you risk losing everything on any given investment. There are hundreds of recent examples of dot-com investments that went bankrupt or are trading for a fraction of their former highs. Even established, well-known companies such as Enron, WorldCom, and Kmart filed for bankruptcy, and investors in these companies lost everything. Prof's. Guidance: That's why you are taking this course. There are financial advisors who can identify the winners and there are those who just - can't and don't. You should focus on learning how to understand, when a salesperson or mutual funds says: I can manage your money - - Will you have the right questions to ask or just believe them? In the last decade the later has been very expensive!. In 1965, you could have purchased General Motors GM stock for $50 per share (split adjusted). In the following decades, though, this investment has only spun its wheels. ByJune 2008, your shares of General Motors would be worth only about $10 each. Though dividends would have provided some ease to the pain, General Motors' return has been terrible. You would have been better off if you had invested your money in a bank savings account instead of General Motors stock. Clearly, if you put all of your eggs in a single basket, (diversification) the basket may fail, breaking all the eggs. Other times, that basket will hold the equivalent of a winning lottery ticket. Prof's. Guidance: So, it is really up to you, not the financial salesperson or mutual fund. Don't be "DEPENDANT" - learn how to find the people you can trust and work with them as a team.. Bear Markets and Market Dips are sometimes significant. Prof's. Guidance: By studying and simple paying attention to these on going fluctuations - much of the downside can be avoided. For example, consider the Dow Jones Industrials Index, a basket of 30 of the most popular, and some of the best, companies in America. If during the last 100 years you had held an investment tracking the Dow, there would have been. But don't worry; there is a bright side to this story. Stocks Are Still Best Investment Despite all the short-term risks and volatility, stocks as a group have had the highest long-term returns of any investment type. This is an incredibly important fact! So after the stock market has crashed, the market has always rebounded and gone on to new highs. Stocks have outperformed bonds on a total real return (after inflation) basis, on average. This holds true even after market peaks. Prof's. Guidance: As the song goes: Pick yourself up, dust yourself off and start all over again. That's only after continuing to study. first learning and second. Prof's. Guidance: There are many strategies for investing. Some of them - simple don't work and others do very, very well. Time Is on Your Side Just as compound interest can dramatically grow your wealth over time, the longer you invest in stocks, the better off you will be. With time, your chances of making money increase, and the volatility of your returns decreases. The average annual return for the S&P 500 stock index for a single year has ranged from negative 39% to positive 61%, while averaging 13.2%. After holding stocks for five years, average annualized returns have ranged from negative 4% to positive 30%, while averaging 11.9%. or continuing in stocks.? Quite simply, stocks allow investors to own companies that have the ability to create enormous economic value. Stock investors have full exposure to this upside. For instance, in 1985, would you have rather lent stocks make an attractive investment in the long run, stock returns are not guaranteed and tend to be volatile in the short term. Therefore, I do not recommend that you invest in stocks to achieve your short-term goals. To be effective, you should invest in stocks only to meet long-term objectives that are at least five years away. (After say - two to five years start enjoying (spending) some of those profits. And the longer you invest, the greater your chances of achieving the types of returns that make investing in stocks worthwhile. Quiz 103 There is only one correct answer to each question. - The average yearly difference between the high and low of the typical stock is between: - 30% and 50%. - 10% and 30%. - 50% and 70%. - If you were saving to buy a car in three years, what percentage of your savings for the car should you invest in the stock market? - 50%. - 70%. - 0%. - If you were investing for your retirement, which is more than 10 years away, based on historical returns in the 20th century, what percentage of the time would you have been better off by investing only in stocks versus a combination of stocks, bonds, and cash? - 50%. - 100%. - 0%. - Well known stocks like General Motors: - Always outperform the stock market. - Are too highly priced for the average investor. - Can underperform the stock market. - Which of the following is true? - After adjusting for inflation, bonds outperform stocks. - When you invest in stocks, you will earn 12% interest on your money. - Stock investments should be part of your long-term investment portfolio.
http://www.safehaven.com/article/18199/investment-basics-course-103-investing-for-the-long-run
CC-MAIN-2014-15
en
refinedweb
04 April 2013 22:13 [Source: ICIS news] HOUSTON (ICIS)--Some oil did leak onto the ground after a freight train derailment near ?xml:namespace> Two of the 22 cars in the Wednesday morning accident contained light sweet crude oil that leaked, Ed Greenberg of CP said. One car was identified and secured easily, he said, but the second was difficult to asses due to its position among the derailed equipment. It showed no signs of oil around its base, but as clean up progressed, CP teams discovered that the part of it that was leaking was buried in snow. Oil leaked a short distance under the snow, Greenberg said. The leaked product will be removed as part of the cleanup, and the site will be fully restored, he said. Approximated 400 barrels of oil leaked from the two cars, the railway said. CP, which is conducting soil and ground water sampling around and below the site, said there was no indication from any of the sampling sites that the product has migrated beyond the containment berms. No injuries were reported in the accident. CP is working with the Transportation Safety Board of Canada and the Ontario Ministry of Environment on the derailment investigation and remediation, Greenberg said. Train operations through the area are expected to resume early Thursday
http://www.icis.com/Articles/2013/04/04/9656047/some-oil-did-leak-onto-ground-after-canada-train-derailment.html
CC-MAIN-2014-15
en
refinedweb
$26.00 By Jared Diamond $36.00 $18 By. Advertisement The shift in results is encouraging, but state politicians are not yet rushing to Kopplin’s cause in sufficient numbers. The religious lobby, which is aligned with such national groups as Focus on the Family, has the power to elect and defeat political candidates. “Republican politicians are under pressure to vote with the religious right,” Kopplin said in a telephone interview with Truthdig on Friday. “If one of these politicians supports legislation that opposes creationism, they’ll be faced with someone who is further to the right than them in the next primary.” Louisiana lawmakers and other state officials don’t just have the voting public to fear. Gov. Bobby Jindal has developed a reputation for punishing those who oppose him. According to New Orleans-based nonprofit news provider The Lens, this year Jindal removed Martha Manuel, the executive director of the Governor’s Office of Elderly Affairs, less than 24 hours after she publicly questioned one of his decisions. He appears to have pressed the resignation of Cynthia Bridges, a longtime secretary at the Department of Revenue, after she produced a tax report that contradicted his plans. And Jindal engineered the removal of several top officials at Louisiana State University who were “all seen as obstacles to privatizing the university’s hospital system.” But Louisiana is not without officials willing to endure the pressure of well-funded interest groups and a vindictive governor. On Tuesday, the Orleans Parish School Board voted unanimously to ban the teaching of creationism and intelligent design in its schools, and included a direct rejection of the Texas Board of Education’s 2010 decision to tailor textbooks to conservative tastes. “No history textbook shall be approved which has been adjusted in accordance with the State of Texas revisionist guidelines,” the parish board wrote in its decision, “nor shall any science textbook be approved which presents creationism or intelligent design as science or scientific theories.” The outcome affects six schools that operate within the parish. Along with the New Orleans City Council’s decision to reject the Louisiana Science Education Act, the city has now fully banned creationism from public classrooms. Kopplin, now a history student in his second year at Rice University in Houston, has already received two honors for his efforts. He won a National Center for Science Education 2012 Friend of Darwin Award and was granted the 2012 Hugh M. Hefner First Amendment Award in Education. “This is a big victory for reason,” wrote Truthdig Editor-in-Chief Robert Scheer—who was on the jury for the Hefner award—of Tuesday’s result in New Orleans. When asked why he believed that he, a mere high school student, could bring about such major change at the state and local level, Kopplin said: “I just thought it was right. I didn’t think about the opposition. I’m used to my attempts at things not working. I may lose nine out of 10 times, but eventually we will win this.” Kopplin has been praised and reviled for his work. Skeptics and scientific groups applaud his endeavors, while some on the other side blame him for Hurricane Katrina. For building such stellar momentum in the direction of reason and progress, and for his commitment to carry on, we honor Zack Kopplin as our Truthdigger of the Week. Zack Kopplin: GateKeeper50hotmail: Get truth delivered to your inbox every week. Previous item: What Americans Should Learn From the ‘Republican Apocalypse’ Next item: Where Are We Heading—Bedford Falls or Pottersville? If you have trouble leaving a comment, review this help page. Still having problems? Let us know. If you find yourself moderated, take a moment to review our comment policy. Newsletter Like Us Get Our Feed Like Truthdig on Facebook
http://www.truthdig.com/report/item/truthdigger_of_the_week_zack_kopplin_20121222?ln
CC-MAIN-2014-15
en
refinedweb
This package is dedicated to support the OGC Common Query Language, version 2.0.1, as a query predicate language inside GeoTools. The rest of this document describe the syntax rules and the parser design. Contents BN analysis the CQL language. Syntax Rules Existence Predicate Comparison Predicate Text Predicate (or Like Predicate) NULL Predicate Between Predicate Temporal Predicate INCLUDE/EXCLUDE Predicate Expression Georutine and Relational Geooperations Geometry Literal Lexical Rules Numeric Delimiter Character String Literal Identifier The following section is intended to give context for identifier and namespaces. It assumes that the default namespace is specified in the query request and does not allow any overrides of the namepace CQL Model CQL Interface This diagram presents the package interface. In parser's protocol methods performs the parsing of CQL and builds the the filter. CQL Implementation The figure shows the principal class in the parser and build process. CQLParser does a top down analysis of the input string and makes the parsing tree. Each time CQLParser builds a node, it makes a call to CQLCompiler, that implements the semantic actions related and builds the product or subproduct required to make the Filter at the end of the parsing process
http://docs.codehaus.org/pages/diffpages.action?pageId=233049612&originalId=228169801
CC-MAIN-2014-15
en
refinedweb
Current Web technologies have an increased demand placed on them. They must be able to manage user accounts, upload content, and stream video. This demand requires RIA developers to seek technologies that streamline development workflow while at the same time providing commonly sought-after features. The challenge to developers is picking the right set of technologies to provide these services. Adobe Flex is a client-side technology that provides developers with a rich set of API calls for creating GUIs, drawing graphics, playing and streaming media, and connecting to Web services. On the server side, Java technology provides abilities such as connecting to relational database management systems (RDBMSs), multi-threaded processing of service requests, and optimum scaling with increased demand. Using these two technologies together offers a powerful technology stack that satisfies the demand of RIA applications. This article demonstrates how to write a simple, yet powerful RIA that utilizes Flex for the client, Java technology for the server, and MySQL for the back-end database. The sample application The sample application (available from the Download section below) provides a rich UI that supports creating, reading, updating, and deleting (CRUD) contact information through an Adobe Flash® (SWF) application. This three-tiered Web architecture is depicted in Figure 1, where the client is represented by the SWF file embedded within a Web page, the server application is run within a Java servlet container (in this case, Apache Tomcat), and the database is MySQL. Combined, these three tiers create a power-distributed application. Figure 1. The Contacts application For communication between the Flash application and the Java servlet container, the Adobe BlazeDS framework provides object remoting—a form of RPC that allows Adobe ActionScript™ objects to call Java objects and vice versa. Communication between the Java server application and the relational database is handled by the Hibernate Object Relational Mapping (ORM) framework. Hibernate allows Java objects to be transformed to SQL code and vice versa. The application: server tier The first step is to create a Java class that encompasses the information required to store contact information. The sample application contains a simple model with basic information. The attributes and the data types required for Contact objects are: - String emailAddress - String firstName - long id - String lastName - String phoneNumber - long serialVersionUID + Contact(String first, String last, String email, String number) + String getEmailAddress() + String getFirstName() + long getId() + String getLastName() + String getPhoneNumber() + void setEmailAddress(String address) + void setFirstName(String first) + void setId(long newId) + void setLastName(String last) + void setPhoneNumber(String number) + StringtoString() Annotating the business object The Java Contact class is considered a POJO (Plain old Java object) that acts as a business object, meaning that it represents business domain characteristics and behaviors. The data inside objects needs to be persisted to the database. The solution is to use an ORM framework such as Hibernate, which performs much of the work in mapping objects to records within database tables and back again. If Java Persistence API (JPA) annotations are used, very little coding is required to fulfill ORM. Listing 1 demonstrates the annotated Java class Listing 1. The Java Contact class package bcit.contacts;; @Entity @Table(name="contact") @NamedQueries( { @NamedQuery(name = "contact.findAll", query = "from Contact"), @NamedQuery(name = "contact.getById", query = "select c from Contact c where c.id = :id") } ) public class Contact { private static final long serialVersionUID = 123456789L; public Contact() { firstName = "N/A"; lastName = "N/A"; emailAddress = "N/A"; phoneNumber = "N/A"; } public Contact(String first, String last, String email, String number) { firstName = first; lastName = last; emailAddress = email; phoneNumber = number; } @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", nullable = false, updatable=false) private long id; @Column(name = "lastName", nullable = false, unique = false) private String lastName; @Column(name = "firstName", nullable = false, unique = false) private String firstName; @Column(name = "emailAddress", nullable = false, unique = false) private String emailAddress; @Column(name = "phoneNumber", nullable = false, unique = false) private String phoneNumber; public void setPhoneNumber(String number) { phoneNumber = number; } public String getPhoneNumber() { return phoneNumber; } public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String address) { emailAddress = address; } public String getFirstName() { return firstName; } public void setFirstName(String first) { firstName = first; } public String getLastName() { return lastName; } public void setLastName(String last) { lastName = last; } public long getId() { return id; } public void setId(long newId) { id = newId; } @Override public String toString() { return id + " " + firstName + " " + lastName + " " + emailAddress + " " + phoneNumber; } } The class is simple, but there is a lot going on with annotations: @Column: Labels the property as a column within the database, with choices including the name of the column, whether it's unique, and whether a column is nullable @Entity: Declares the class as an entity bean, meaning that it is a POJO slated for persistence @GeneratedValue: Specifies the strategy for generating primary keys; choices are AUTO, IDENTITY, SEQUENCE, and TABLE @Id: States that the property is the unique identifier (that is, primary key) for each Java object @NamedQueries: Lists a group of named queries @NamedQuery: Declares a predefined query as a string literal that can later be referenced for execution @Table: Designates the Java class as a table within the database Each time an in-memory Java object is required to be persisted, Hibernate transforms the state information of any Java objects into an SQL update. Likewise, SQL statements with result sets are used to populate Java objects. The result is that all objects can be saved as records within the database, and all records can be retrieved and transformed back into Java objects. The annotations inform Hibernate what within a class should be considered persistent. But they are only part of the picture. The business service: database connectivity A service class is required to perform the calls to Hibernate in order to execute ORM. Listing 2 displays the ContactsService class, which acts as the application service. Listing 2. The ContactsService class public class ContactsService { private static Logger logger = Logger.getLogger(ContactsService.class); private static final String PERSISTENCE_UNIT = "contacts"; private static EntityManagerFactory emf = null; static { logger.info("LOADING CONTACTSSERVICE CLASS."); emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); } public ContactsService() { super(); } public void addContact(Contact c) { if(c == null) { return; } EntityManager em = emf.createEntityManager(); logger.info("PERSISTENCE ENTITYMANAGER ACQUIRED."); logger.info("ABOUT TO ADD CONTACT: fName: " + c.getFirstName() + ", lName: " + c.getLastName() + ", email:" + c.getEmailAddress() + ", phone: " + c.getPhoneNumber()); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.merge(c); tx.commit(); } catch (Exception e) { logger.error("CONTACT APP PERSISTING ERROR: " + e.getMessage()); tx.rollback(); } finally { logger.info("CONTACT APP CLOSING ENTITY MANAGER."); em.close(); } } public void editContact(Contact c) { logger.info("CONTACT TO UPDATE: " + c); addContact(c); } public void deleteContact(Long id) { logger.info("ABOUT TO DELETE CONTACT"); EntityManager em = emf.createEntityManager(); logger.info("PERSISTENCE ENTITYMANAGER ACQUIRED."); Query contactByIdQuery = em.createNamedQuery("contact.getById"); contactByIdQuery.setParameter("id", id); Contact c = (Contact) contactByIdQuery.getSingleResult(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.remove(c); tx.commit(); } catch (Exception e) { logger.error("CONTACT APP PERSISTING ERROR: " + e.getMessage()); tx.rollback(); } finally { logger.info("CONTACT APP CLOSING ENTITY MANAGER."); em.close(); } } public List<Contact> getContacts() { logger.info("ABOUT TO RETRIEVE CONTACTS"); EntityManager em = emf.createEntityManager(); logger.info("PERSISTENCE ENTITYMANAGER ACQUIRED."); Query findAllContactsQuery = em.createNamedQuery("contact.findAll"); List<Contact> contacts = findAllContactsQuery.getResultList(); if (contacts != null) { logger.debug("CONTACT APP RETRIEVED: " + contacts.size() + " CONTACT(S)"); } return contacts; } } Each method gains a reference to an EntityManager, which represents the in-memory cache. Caching is a powerful feature that ensures efficiency, because sending and receiving data from a database can be an expensive operation. You have only to ensure that every cache created is committed to the database or rolled back if not wanted. In JPA, the term given to the cache is persistence context, and it is represented by the EntityManager class. Each persistence context manages a set of entities, which are Java objects that have been annotated with the @Entity annotation. The EntityManagerFactory class represents a persistence unit, which is responsible for configuring connections to a data store (for example, a relational database), managing entity types (that is, all the classes within a given context that you need to map to a data store), and finally providing instances of a persistence context (that is, an EntityManager). Although the process of creating a persistence context is inexpensive time-wise, the process of creating a persistence unit is costly. Setting up connectivity to a data store, finding all classes annotated as entities, and configuring the persistence logic to bind these classes to entities in the data store is not a quick operation. Therefore, you should create an EntityManagerFactory instance once at application start-up. As for persistence contexts, take care to ensure that an EntityManager is destroyed before another one is created. Another important rule to follow is the entitymanager-per-request pattern. This pattern groups database calls (for example, requests and updates) so that they can all be sent at once. Doing so ensures full advantage of JPA's caching mechanism. The next requirement is the client side. The application: client tier The Flex framework allows you to create applications that users can play in Adobe Flash Player. Flex consists of: - A declarative XML UI language known as MXML - The ActionScript programming language - Run time libraries for creating UIs, Web connectivity, and many other features - Developer tools for compiling applications into SWF files The client application referenced in this article uses Flex version 4. Before approaching the client-side application, it is important to understand how Flex applications are created and how they exist as executables within Flash Player. First, you can create applications using a combination of MXML markup and ActionScript code. A common workflow is to create much of the GUI (presentation) using the MXML format, and then use ActionScript code for event handling and business logic. Because both MXML and ActionScript are text-based, a standard text editor and the Flex SDK are all you need to create Flash applications. Second, once you've written a Flex application, you compile the code using the MXML compiler. The MXML compiler creates SWF files that can then be run inside a Web browser (via the Flash Player browser plug-in). Finally, Flash applications run within the ActionScript Virtual Machine 2 (AVM2), which uses the timeline paradigm. This paradigm breaks execution up into frames—much like a movie. You specify the number of frames per second in a Flash application at compile time. Additionally, Flash Player breaks execution up into the following ordered tasks: - Flash Player events such as the timer and mouse events - User code - Pre-rendering logic, where Flash Player attempts to determine whether the GUI needs to be updated because of data value changes - User code that was bound to the data value changes - Flash Player rendering If there are few frames per second to render, then much of the user code can be executed. If, however, the frame rate is high (for example, 60 frames per second), then Flash Player may not be able to execute much of the user code, because the user code may take more time than what can be granted. It's important to keep this in mind when writing for Flash Player. MXML MXML is a powerful declarative XML format that helps: - Minimize the amount of code required to build a GUI because of the declarative nature of the XML format - Reduce the complexity of GUI code by allowing for a clear separation of presentation logic and interaction logic - Promote use of design patterns when approaching software development Listing 3 displays the MXML Application class. Listing 3. The ContactsApp class <mx:Application xmlns: <mx:Style> .mainBoxStyle { borderStyle: solid; paddingTop: 5px; paddingBottom: 5px; paddingLeft: 5px; paddingRight: 5px; } .textMessages { fontWeight: bold; } </mx:Style> <mx:RemoteObject <mx:Script> <![CDATA[ import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.collections.ArrayCollection; import bcit.contacts.dto.Contact; [Bindable] private var contacts:ArrayCollection = new ArrayCollection(); // For more on the Bindable metadata tag, see the devguide_flex3.pdf // document, page 1249 (1257 in PDF page numbering) [Bindable] private var message: <mx:Text <contact:ContactsDataGrid <contact:EditContactForm <mx:ControlBar <mx:Button <mx:Button <mx:Button <mx:Button <mx:Button </mx:ControlBar> <mx:TextArea </mx:VBox> </mx:Application> Here are a few more points pertaining to Listing 3: - The root element of an MXML document is a subclass of the Applicationclass. - The mx:Styleelement allows for CSS properties to define local styling to UI components. Styling can be done using local style definitions (as in Listing 3), references to external style sheets, inlining styles within the components, and using the setStylemethod in ActionScript. - The RemoteObjectclass represents an HTTP service object that performs remoting operations with a server. - The mx:Scriptelement includes ActionScript code blocks in a CDATAsection. - There is one layout (that is, the VBoxclass). - Each time a UI component is declared in the application (for example, a TextArea), an instance variable is generated that can be referenced later within the application using the component's idattribute. - Data binding is performed using braces (for example, the TextAreaelement's textattribute is bound to the ActionScript messageinstance variable). ActionScript While MXML defines the GUI, ActionScript offers the behavior for handling events, binding data (through the [Bindable] metadata tag), and the ability to call a remote service. In Listing 3, the methods createContact, editContact, deleteContact, and getAllContacts all call remote methods on the server side. When a remote method is called, ActionScript is offered the opportunity to handle the result and any fault by declaring callback functions. In Listing 3, the handleResult function receives the result as an Object and casts it to an ArrayCollection. BlazeDS converted the List into an ArrayCollection on the server side. Listing 4 presents the ActionScript class which you create to represent contact objects on the Flash side. Listing 4. The ActionScript Contact class package bcit.contacts.dto { [RemoteClass(alias="bcit.contacts.Contact")] public class Contact { public function Contact() { id = -1; } public var id:Number; public var lastName:String; public var firstName:String; public var emailAddress:String; public var phoneNumber:String; public function toString():String { return id + ", " + firstName + " " + lastName + " " + emailAddress + " " + phoneNumber; } } } These ActionScript objects are sent to the server side, where BlazeDS performs its magic and converts the ActionScript objects into Java objects. The ActionScript Contact class is considered a Data Transfer Object (DTO). Configuring the application The application also relies on configuration files that state setting specifics for the server. The two main areas of configuration within this application are Hibernate and BlazeDS. Configuring Hibernate You can configure Hibernate by using the standard JPA configuration file, persistence.xml, which is shown in Listing 5. Listing 5. A subset of the persistence.xml configuration file <persistence version="1.0" xmlns="" xmlns: <persistence-unit <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.default_schema" value="contacts" /> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/contacts" /> <property name="hibernate.archive.autodetection" value="class, hbm"/> <property name="hibernate.connection.username" value="root"/> <property name="hibernate.connection.password" value="root"/> </properties> </persistence-unit> </persistence> The persistence.xml file must go into the Web application's WEB-INF/classes/META-INF folder for Hibernate to read it. With that in place, Hibernate requires the following information: - Database dialect (that is, which database it is talking to, because many databases have slightly different SQL dialects) - Table space via the default schema - The database driver used to connect to the database - The database URL - What auto-detection should detect (for example, annotated classes, Hibernate mapping XML files, and so on) - User name and password Other information can help the performance of Hibernate but is not required. Configuring BlazeDS BlazeDS has four configuration files: - messaging-config.xml: Defines publish-subscribe messaging information - proxy-config.xml: Offers proxy service information for HTTP and Web services - remoting-config.xml: Defines information for remoting services such as the one in the article application - services-config.xml: The top-level configuration file that references the other configuration files and also provides security constraints, channels, and logging Listing 6 demonstrates the services-config.xml file. Note that for the article application, only the remoting-config.xml file is relevant because the application is only using the BlazeDS remoting service. Listing 6. A subset of the services-config.xml configuration file <?xml version="1.0" encoding="UTF-8"?> <services-config> <services> <service-include <service-include <service-include <default-channels> <channel ref="contacts-amf"/> </default-channels> </services> <channels> <channel-definition <endpoint url="" class="flex.messaging.endpoints.AMFEndpoint"/> <properties> <polling-enabled>false</polling-enabled> </properties> </channel-definition> </channels> <logging> <target class="flex.messaging.log.ConsoleTarget" level="Error"> <properties> <prefix>[BlazeDS] </prefix> <includeDate>false</includeDate> <includeTime>false</includeTime> <includeLevel>false</includeLevel> <includeCategory>false</includeCategory> </properties> <filters> <pattern>Endpoint.*</pattern> <pattern>Service.*</pattern> <pattern>Configuration</pattern> </filters> </target> </logging> </services-config> The services-config.xml configuration file references the other configuration files (which have to exist), configures BlazeDS logging, and sets up any channels. A channel is an abstraction for the protocol that is used for the client to communicate with the server. The article application uses the standard AMF protocol with no polling. Polling means that the client continually communicates with the server to ensure that the connection is still established—something not needed in this application. The channel end point specifies the server URL. This end point is required for compiling the project; the client Flash application uses it as a hard-coded value so that it knows the server to connect to. You can actually define the end point URL right in the MXML or ActionScript code, instead. Finally, the remoting-config.xml configuration file (shown in Listing 7) specifies the adapter class required to handle the remoting operations as well as the actual classes that respond to the remoting calls. (In this case, the bcit.contacts.ContactsService class was given as the responder to remote requests.) Listing 7. A subset of the remoting-config.xml configuration file <?xml version="1.0" encoding="UTF-8"?> <service id="remoting-service" class="flex.messaging.services.RemotingService"> <adapters> <adapter-definition </adapters> <default-channels> <channel ref="contacts-amf"/> </default-channels> <destination id="contacts"> <properties> <source>bcit.contacts.ContactsService</source> <!--<scope>application</scope>--> </properties> </destination> </service> Conclusion This article showed you how to write a Java server-side Web application that runs within Tomcat and answers requests for contact information. You also learned how to write a Flex application using both MXML and ActionScript to create a client-side Flash application. MySQL acted as the data store, and Hibernate—an ORM framework—was used to transform the Java objects into SQL statements that could query and update the MySQL database. Finally, the BlazeDS framework allowed the Flash application to make remote procedure calls and perform remoting on the Java server-side Web application. Download Note - This zip file contains all of the source code (Java, ActionScript 3, MXML) for this project, the Ant build file to generate the WAR, configuration files, and third-party libraries (in the form of JAR files) that this article references and uses. Resources Learn - JPA Concepts: Learn more at the Apache Software Foundation. - Managing Entities: Learn how to work with entities. Take this Java EE tutorial. - Hibernate EntityManager User Guide: Find the information your need to work with the Hibernate EntityManager. - Understanding the Flex 3 Component and Framework Lifecycle (James Polanco and Aaron Pedersen, DevelopmentArc): Learn how to work in the Flex platform more efficiently. - Updated "Elastic Racetrack" for Flash 9 and AVM2 (Sean Christmann): Learn more about this frame execution model within Flash Player. - Explicitly mapping ActionScript and Java objects: Read more from the Adobe LiveCycle® Data Services Developer's Guide. - Creating a declarative XML UI language (Arron Ferguson, developerWorks, September 2009): Learn more about declarative XML UIs. - Create a Flex component (Sandeep Malik, developerWorks, July 2009): Learn how to create new Flex functionality from scratch. - Flex 4 features for creating Software as a Service (Dan Orlando, developerWorks, July 2009): Learn how to use Flex 4 to enhance RIA user experience. - developerWorks Web development zone: The Web development zone is packed with tools and information for Web 2.0 development. - IBM technical events and webcasts: Stay current with developerWorks' technical events and webcasts. - Attend a free developerWorks Live! briefing: Get up to speed quickly on IBM products and tools as well as IT industry trends. - developerWorks on-demand demos: Watch demos ranging from product installation and setup - My developerWorks: Connect with other developerWorks users while exploring the developer-driven blogs, forums, groups, and wikis. More downloads - MySQL (An open source RDBMS required for use with the example project in this article) - Apache Ant (A Java-based build tool for building the example project) - JDK (The Java SDK (JDK) version 6, required for compiling Java source code within the example project ) - Adobe Flex SDK (The Flex 4 SDK for compiling MXML and ActionScript source code within the example project ) - Apache Tomcat (The Apache Software Foundation servlet container that provides a Java HTTP Web server environment for running the example project ) - Adobe BlazeDS (The Adobe framework for connecting Flex technology to Java Platform, Enterprise Edition (Java EE). This software is only for reference, as it is already included in the project download for this article.) - Red Hat Middleware Hibernate (Red Hat ORM framework for Java EE container middleware. This software is only for reference, as it is already included in the project download for this article.).
http://www.ibm.com/developerworks/opensource/library/wa-flex4javaapps/index.html?ca=dgr-lnxw9dFlex4-RIAdth-WD
CC-MAIN-2014-15
en
refinedweb
>>. 51 Reader Comments Really? So you're saying if I'm implementing a network service, and I'm reading a data stream where the first byte in the header is the command type, rather than converting the byte to an enumeration and using a switch to handle dispatching, its better to instead use polymorphisms here? How do you plan on determining which object type to instantiate without using a switch?. You're not listening. A wrapper won't work if the right plumbing isn't exposed by your encapsulated object. If the object doesnt expose the underlying ID because the ID is abstracted by the object model, then you can't expose a new ID without source to the underlying library being linked to. If the 3rd party framework doesn't expose the functionality you need you can't use it in a case block just as much as you can't call it in a handler function, there's absolutely no difference there. ProtocolHandler - ABCShared - A, B, C ProtocolHandler - DEFShared - D, E, F works perfectly fine. No need to ever need MI here Again, you're not listening. Several is not the same as 2. Show me how to have this relationship without multiple inheritance: Handler - ABCShared - A, B, C Handler - DEFShared - D, E, F Handler - AFShared - A, F A and F cannot derive two different classes. Well exactly the same way you solve the absence of MI in such languages for every other problem, less decomposition, composition instead of inheritance, mixins,.. Worst case you end up with a class that does more work than it ought to semantically. On the other hand a switch makes sure all the work is in one place so in the worst case it's just as bad as that. Again, you're not listening. First of all, as long as something is modular and you break your tasks into smaller manageable tasks its easy to test. Whether it uses polymorphism or not is irrelevant. Absolutely true, modular makes testing much easier.. and a giant switch is the perfect example of non-modular code. Return <self> if nothing else is returned? That is what Smalltalk does, and it makes the language easier to work with. There is always something returned; if nothing else, then <self>. :-) - Jesper Return <self> if nothing else is returned? That is what Smalltalk does, and it makes the language easier to work with. There is always something returned; if nothing else, then <self>. :-) - Jesper Smalltalk also typically uses Nil for error conditions - so if something goes wrong the result should be nil Regards, A 13 year Smalltalk veteran. Exceptions are not hard to work with if took the time to understand object oriented programming and the particular language implementation of the paradigm. Who catches an exception? Really, you have to ask this? The answer is your code catches it and deal with it. Your annoying question can be forgiven if you happen to use a language that does not believe in checked excpetions.. What about methods that return an output like an int or string (or any type really), how will you communicate error information to the caller?. If all you are doing is instantiating a class, using a switch or a hashmap are basically the same. A switch uses an integral indexer under the hood, just like a hashmap, except a hashmap runs a hash function over the key before indexing it, so you won't gain any performance boost by using a hashmap. Granted, the hashmap can be strongly typed, but that really doesn't matter if all we're doing is instantiating an object. This is a good solution,but doesn't address my main point about unnecessary complexity. Also, you'll need more than the interface specification, you need to have access to the class factory. That's how most of the libraries are set up in Java and C#. Of course you can get around this if you want to take advantage of reflection. But like I said, one of my previous points, was about maintainability. When you go back in after the fact, or someone else has to look at your code, it's very easy to walk a switch statement to see which object types are instantiated for which enumerations, etc. If you use a HashMap, you have to inspect every class to see its declared ID. Now don't take it as me saying that switches are awesome, and they make everything more maintainable I'm talking about a very narrow use case. Thank you captain obvious. If you have a guy that wrote a library that uses enumerations to identify operations, (which is what I was talking about this entire time), since the conversation started about things that didn't have abstracted object model, then of course the API is exposing this, since that's what I said at the very beginning. I was never arguing that you should go and design everything from the ground up using enumerations. I was talking about "possibility", since the original thread started when someone was talking about there being an impossibility of one solution being necessary, so I gave an example... To back up, and give you a higher level picture, I was talking about scenarios where the person you inherited the code from, didn't think their design all the way through... If you design your code well, then YES, you can make VERY good OO code. I was saying that I found it common, (especially with greenhorns or outsourced code), for people to improperly design their object model. For example, the HashMap solution you mentioned. That's a very good solution, and is how lots of things in .NET/JAVA already work. However, I see few people actually think their designs through and actually design their code this way. All too often, I see people thinking of ways to abstract anything and everything, instead of thinking their architecture through deciding what actually needs to be abstracted and how/why it should be abstracted. Typically you want to abstract things to reduce the error plane, or to simplify things. But then you need to take into account if you would actually reduce the error plane in the particular scenario, and/or are you simplifying things in the right manner, and for the right purposes/reasons. For the particular example we were talking about, you aren't reducing the error plane by introducing abstraction, and for the particular problem that was being solved, you'd be adding a small amount of complexity. No it's not. You can write test cases to test each branch individually, and you make sure each branch has tasks that are broken down into smaller tasks, that can also not only be tested individually, but can be reused. Last edited by a_v_s on Mon Oct 21, 2013 12:11 pm A common thing that is done, similar to COM/DCOM, is to return error status, and pass all your outputs by reference. Some people return status enumerations, others return a boolean, etc... When you have an exception, you can then specify the return type as either and you'll get a Left or a Right. Great so how does this make a programmers life easier. Most modern langs include lambdas. Once you have a lambda you can use this either type as follows: On Either declare an abstract method called map. For the concrete Left type, do nothing and return a Left then the concrete Right type, define a function called map that takes the type parameter for Right and then performs some action and then rewraps it in an either. So, now you can do something like: def foo: Either = {..} def bar(a: Either): Either = {..} foo.map( (wrappedType => bar(wrappedType)) and this would produce an Either. The nice part about this is that it abstracts all of the exception handling and just lets you do the stuff that's specific to your app. This seems to be a case of "When all you have is a hammer, everything looks like a nail." I'm glad to learn you can express exception-like behavior using ADTs. But can you honestly say you think this is clearer than languages with explicit support for exceptions? And what are the performance implications of implementing exception behavior in this way? (This makes the assumption that there is a language implementing these features). A common thing that is done, similar to COM/DCOM, is to return error status, and pass all your outputs by reference. Yeah, I've never liked that too much. For one, it does not facilitate the sensible use of method chaining. You must login or create an account to comment.
http://arstechnica.com/information-technology/2013/10/are-there-reasons-for-returning-exception-objects-instead-of-throwing-them/?comments=1&start=40
CC-MAIN-2014-15
en
refinedweb
public class MouseDragEvent extends MouseEvent MouseEvent. Full press-drag-release gesture can be started by calling startFullDrag() (on a node or scene) inside of a DRAG_DETECTED event handler. This call activates delivering of MouseDragEvents to the nodes that are under cursor during the dragging gesture. When you drag a node, it's still under cursor, so it is considered being a potential gesture target during the whole gesture. If you need to drag a node to a different node and let the other node know about it, you need to ensure that the nodes under the dragged node are picked as the potential gesture targets. You can achieve this by calling setMouseTransparent(true) on the dragged node in a MOUSE_PRESSED handler and returning it back to false in a MOUSE_RELEASED handler. This way the nodes under the dragged node will receive the MouseDragEvents, while all the MouseEvents will still be delivered to the (currently mouse transparent) gesture source. The entered/exited events behave similarly to mouse entered/exited events, please see MouseEvent overview. DRAG_DETECTED, MOUSE_CLICKED, MOUSE_DRAGGED, MOUSE_ENTERED, MOUSE_ENTERED_TARGET, MOUSE_EXITED, MOUSE_EXITED_TARGET, MOUSE_MOVED, MOUSE_PRESSED, MOUSE_RELEASED consumed, eventType, NULL_SOURCE_TARGET, target source copyFor, getButton, getClickCount, getSceneX, getSceneY, getScreenX, getScreenY, getX, getY, isAltDown, isControlDown, isDragDetect, isMetaDown, isMiddleButtonDown, isPrimaryButtonDown, isSecondaryButtonDown, isShiftDown, isShortcutDown, isStillSincePress, isSynthesized, setDragDetect, toString clone, consume, fireEvent, getEventType, getTarget, isConsumed getSource equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait public static final EventType<MouseDragEvent> ANY public static final EventType<MouseDragEvent> MOUSE_DRAG_OVER public static final EventType<MouseDragEvent> MOUSE_DRAG_RELEASED public static final EventType<MouseDragEvent> MOUSE_DRAG_ENTERED_TARGET MOUSE_DRAG_ENTEREDevent handler should be used. MouseEvent for more information about mouse entered/exited handling which is similar public static final EventType<MouseDragEvent> MOUSE_DRAG_ENTERED MOUSE_DRAG_ENTERED_TARGET. MouseEvent for more information about mouse entered/exited handling which is similar public static final EventType<MouseDragEvent> MOUSE_DRAG_EXITED_TARGET MOUSE_DRAG_EXITEDevent handler should be used. MouseEvent for more information about mouse entered/exited handling which is similar public static final EventType<MouseDragEvent> MOUSE_DRAG_EXITED MOUSE_DRAG_EXITED_TARGET. MouseEvent for more information about mouse entered/exited handling which is similar public java.lang.Object getGestureSource() startFullDragmethod being called on it). Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
http://docs.oracle.com/javafx/2/api/javafx/scene/input/MouseDragEvent.html
CC-MAIN-2014-15
en
refinedweb
Timeline 01/07/13: - 20:39 Ticket #19576 (Use `six.with_metaclass` uniformously accross code base) created by - Sometimes object is inherited twice when it's not needed. Simple patch … - 19:17 Changeset [b6119a6]stable/1.5.x by - [1.5.x] Fixed typo in 1.5 release notes; thanks Jonas Obrist. Backport of … - 19:16 Changeset [bb7f34d]stable/1.6.xstable/1.7.x by - Fixed typo in 1.5 release notes; thanks Jonas Obrist. - 19:12 Ticket #19565 (FloatField object returns string when it's value is set from string) closed by - invalid: This is much like #12401, only for a different type of field. When a model … - 17:31 Ticket #19575 (1.5rc breaks custom querysets (at least in my case)) closed by - invalid - 16:14 Ticket #19574 (Tutorial query date should be updated) closed by - duplicate: Thanks, this has already been reported in #19555. - 15:08 Ticket #19575 (1.5rc breaks custom querysets (at least in my case)) created by - A custom queryset that was working through 1.5b2 breaks under rc1. I keep … - 14:34 Ticket #19574 (Tutorial query date should be updated) created by - The tutorial includes the following: # Get the poll whose year is 2012. … - 13:22 Ticket #19573 (It is not possible to overwrite field label in AuthenticationForm) created by - If I inherit "django.contrib.auth.forms.AuthenticationForm" and specify my … - 12:02 Changeset [01222991]stable/1.5.x by - [1.5.x] Created special PostgreSQL text indexes when unique is True Refs … - 08:54 Changeset [c698c55]stable/1.6.xstable/1.7.x by - Created special PostgreSQL text indexes when unique is True Refs #19441. - 05:08 Ticket #19073 (strange behaviour of select_related) closed by - worksforme: We are not going to fix this in 1.4. Our backporting policy is such that … - 02:30 Ticket #19572 (Unused argument in staticfiles.views.serve) created by - The view 'django.contrib.staticfiles.views.serve' has the optional … 01/06/13: - 14:00 Changeset [7ca9b716]stable/1.5.x by - [1.5.x] Fixed #19571 -- Updated runserver output in the tutorial Backport … - 13:59 Ticket #19571 (Django 1.5 Tutorial Need to update Version on First page) closed by - fixed: In a890469d3bffe267aed0260fd267e44e53b14c5e: […] - 13:59 Changeset [a890469d]stable/1.6.xstable/1.7.x by - Fixed #19571 -- Updated runserver output in the tutorial - 13:47 Ticket #19571 (Django 1.5 Tutorial Need to update Version on First page) closed by - invalid: If it says 1.4, that does mean that the Django version you are running is … - 13:18 Ticket #19571 (Django 1.5 Tutorial Need to update Version on First page) created by - … - 09:26 Tickets #15959,17271,17712 batch updated by - fixed: In 69a46c5ca7d4e6819096af88cd8d51174efd46df: […] - 09:18 Changeset [69a46c5c]stable/1.6.xstable/1.7.x by - Tests for various emptyqs tickets The tickets are either about different … - 09:18 Changeset [a2396a4]stable/1.6.xstable/1.7.x by - Fixed #19173 -- Made EmptyQuerySet a marker class only The guarantee that … - 02:56 Ticket #19570 (call_command options) created by - when used with call_command, certain management commands use keywords … - 00:54 Ticket #19569 (Add "widgets" argument to function's modelformset_factory inputs) created by - Function modelformset_factory doesn't have widgets=None in it's input … 01/05/13: - 09:20 Ticket #14040 (Python syntax errors in module loading propagate up) closed by - needsinfo: We would need a real use case to demonstrate the problem. - 09:04 Ticket #12914 (Use yaml faster C implementation when available) closed by - fixed: In a843539af2f557e9bdc71b9b5ef66eabe0e39e3c: […] - 09:04 Changeset [a843539]stable/1.6.xstable/1.7.x by - Fixed #12914 -- Use yaml faster C implementation when available Thanks … - 05:28 Ticket #19567 (Make javascript i18n view as CBV and more extensible.) closed by - needsinfo: I'm not sure I see what you're proposing here, or why you're proposing it. … - 03:37 Ticket #19568 (2012 is so last year!) closed by - duplicate: Thanks, but this has already been reported in #19555. - 03:17 Ticket #19568 (2012 is so last year!) created by - I was reading through the excellent tutorial for 1.4 (and let me just say … - 02:01 Ticket #19567 (Make javascript i18n view as CBV and more extensible.) created by - The current view populates a global namespace (see … - 00:53 Ticket #19566 (update website for retina display) closed by - wontfix: There's a team working on a rebuild of the Django website at the moment. … - 00:44 Ticket #15146 (Reverse relations for unsaved objects include objects with NULL foreign ...) closed by - duplicate: Closing this one as a duplicate of #17541. It doesn't really matter which … 01/04/13: - 18:07 Ticket #19562 (Documentation: How Django stores passwords out of date) closed by - fixed: In f02e1167d788280e33de3df68fa41e89cb083619: […] - 18:04 Changeset [f02e116]stable/1.5.x by - [1.5.x] Fixed #19562 -- cleaned up password storage docs Conflicts: … - 18:02 Changeset [c8eff0d]stable/1.6.xstable/1.7.x by - Fixed #19562 -- cleaned up password storage docs - 13:04 Ticket #19566 (update website for retina display) created by - Just noticed some images on djangoproject.com website need to be updated … - 13:02 Ticket #19565 (FloatField object returns string when it's value is set from string) created by - When float field is set from string value representing float, it is … - 10:49 Changeset [f23d3ce]stable/1.5.x by - [1.5.x] Bump version numbers for 1.5 RC 1. - 10:30 FazendoSessaoExpirarAoFecharNavegador edited by - (diff) - 08:56 Ticket #19561 (Through-table model attributes are not available) closed by - invalid: In your sample code, prop is an instance of the Property model. and … - 05:03 Changeset [96301d2]stable/1.5.x by - [1.5.x] Fixed #19192 -- Allowed running tests with dummy db backend … - 05:03 Ticket #19192 (DjangoTestSuiteRunner cannot run with dummy database backend) closed by - fixed: In b740da3504ea3b9c841f5a9eb14191a0b5410565: […] - 04:55 Changeset [b740da35]stable/1.6.xstable/1.7.x by - Fixed #19192 -- Allowed running tests with dummy db backend Thanks Simon … - 04:24 Ticket #19564 (Little fix in the tutorial part 1) closed by - duplicate: Already reported in #19555 - 03:17 Ticket #19564 (Little fix in the tutorial part 1) created by - In the Tutorial Part 1 of the documentation, in version 1.5 and dev there … - 02:33 Ticket #19563 (SECRET_KEY ampersands get escaped on startproject) closed by - duplicate: Fixed in 1.5, see #18634 - 02:11 Ticket #19563 (SECRET_KEY ampersands get escaped on startproject) created by - Just noticed this in 1.4.3. When you run: […] The resulting … Note: See TracTimeline for information about the timeline view.
https://code.djangoproject.com/timeline?from=2013-01-07T20%3A24%3A32-08%3A00&precision=second
CC-MAIN-2014-15
en
refinedweb
Hendrik, I was able to get a working 2.4.28 kernel today, and even got sound with alsa 1.0.7 and the dbri code. I applied the patch below to the ALSA code, but as Takashi indicated this is probably not essential for the driver to work. Takashi, Jaroslav, please see if the patch below has your approval and can be included. Hendrik, can you confirm that 'aplay -vv' shows continuous output being send? If so, could you try the following: 1) Try not to load the snd-sun-amd7930 module. There may be an interaction issue between the two drivers, causing both not to work. 2) Add the dbi_debug parameter when loading the module: modprobe snd-sun-dbri dbri_debug=7 and post the data dumped in /var/log/syslog. When playing a file more data will be dumped here. Sorry for the delay in responding. I ended up on sparc64 machines last week, which don't have this chipset. Martin On Tue, Dec 07, 2004 at 05:54:41PM +0100, Hendrik Sattler wrote: > Am --------- Not all machines have a PCI bus. Pre-2.6 kernels on those machines fail to load the snd-page-alloc.o module. This patch fixes this for SPARC machines that have an SBUS. Signed-off-by: Martin Habets <errandir_news@mph.eclipse.co.uk> --- alsa-driver-1.0.7/acore/memalloc.c.orig2 2004-12-19 00:22:08.000000000 +0000 +++ alsa-driver-1.0.7/acore/memalloc.c 2004-12-19 13:41:29.662624656 +0000 @@ -123,8 +123,15 @@ #else /* for 2.2/2.4 kernels */ +#ifdef CONFIG_PCI #define dma_alloc_coherent(dev,size,addr,flags) pci_alloc_consistent((struct pci_dev *)(dev),size,addr) #define dma_free_coherent(dev,size,ptr,addr) pci_free_consistent((struct pci_dev *)(dev),size,ptr,addr) +#elif CONFIG_SBUS +#define dma_alloc_coherent(dev,size,addr,flags) sbus_alloc_consistent((struct sbus_dev *)(dev),size,addr) +#define dma_free_coherent(dev,size,ptr,addr) sbus_free_consistent((struct sbus_dev *)(dev),size,ptr,addr) +#else +#error "Need a bus for dma_alloc_coherent()" +#endif #endif /* >= 2.6.0 */
https://lists.debian.org/debian-sparc/2004/12/msg00150.html
CC-MAIN-2014-15
en
refinedweb
Net8 includes an application program interface (API) called Net8 OPEN allowing programmers to develop both database and non-database applications. In addition, Net8 contains several new benefits for programmers, including UNIX client programming, signal handler and alarm programming, Bequeath protocol, and child process termination. This chapter contains the following sections: Net8 includes an application program interface (API) called Net8 OPEN, which enables programmers to: Net8 OPEN provides applications a single common interface to all industry standard network protocols. The relationship of Net8 OPEN to other products is shown in Figure 10-1. Using Net8 OPEN, you can solve a number of problems, such as: In contrast to a remote procedure call interface, Net8 OPEN provides a byte stream-oriented API that can be used to develop basic applications which send and receive data. Applications developed with Net8 OPEN must ensure that values sent across the network are interpreted correctly at the receiving end. The Net8 OPEN API consists of five function calls: The applications program interface is provided as part of the standard Net8 installation. To use it, you need the following: $ORACLE_HOME/network/publicon UNIX and ORACLE_HOME \network\tnsapi\includeon Windows NT. $ORACLE_HOME/network/libdirectory and is named LIBTNSAPI.A. On Windows platforms, the ORACLE_HOME /network/tnsapi/libcontain the files TNSAPI.DLL and TNSAPI.LIB. Modules which make reference to Net8 OPEN functions should include TNSAPI.H, as follows: #include <tnsapi.h> Your makefile (or other location for your build command) should ensure that the include path is set properly so that it can find TNSAPI.H. Refer to the sample makefiles provided in your installation. To configure Net8 to recognize your Net8 OPEN application, proceed as follows: To do this, choose a system identifier (SID) name for your service similar to that of an Oracle database. Do not pick the same SID as your database. For example, if you are configuring a "chat" program, you could call the SID "chatsid". Place the program into the same place as the Oracle server executable, which is normally $ORACLE_HOME/bin on UNIX and ORACLE_HOME \bin on Windows NT. You would place the following entry in a listener configuration file as follows: sid_list_listener =(sid_list =(sid_desc =(sid_name = chatsid)/*your SID name*/ (oracle_home = /usr/oracle)/*$ORACLE_HOME bin directory*/ (program = chatsvr)/*the name of your server program*/) You need to restart the listener, so it will recognize the new service. For example, if your listener is listening on the following address: (description=(address=(protocol=tcp)(host=unixhost)(port=1521))) And you want people to refer to the service you created above as "chat". You would add the following parameter to your local naming configuration file for release 8.1 configuration: chat= (description=(address=(protocol=tcp)(host=unixhost)(port=1521) ) (connect_data=(service_name=chatsid))) You would add the following parameter to your local naming configuration file for pre-release 8.1 configuration: chat= (description=(address=(protocol=tcp)(host=unixhost)(port=1521) ) (connect_data=(sid=chatsid))) Note that the address contains the SID you configured in the LISTENER.ORA file above. Also note that the second line started with at least one space character, which indicates that it is a continuation line. If you have domains in your network, you need to name your service accordingly. For instance, use chat.acme.com if the domain is acme.com. Again, use the TNSNAMES.ORA file as a template -- if all the other net service names end in a domain, you need to name your service similarly. If needed on your operating system, you also must ensure that you have permission to execute your program. Two sample applications are provided with Net8 OPEN: This section lists the error numbers which can be returned if one of the above function calls fails. Note that in some cases, connection-related errors may come back from a send or receive call, if the connection has not yet been established at that time. 20002 - SDFAIL_TNSAPIE - The underlying "send" command failed in tnssend(). 20003 - RECVFAIL_TNSAPIE - The underlying "receive" command failed in tnsrecv(). 20004 - INVSVROP_TNSAPIE - Operation is invalid as the server. 20005 - INVCLIOP_TNSAPIE - Operation is invalid as the client. 20006 - HDLUNINI_TNSAPIE - The connection should be initialized by calling tnsopen(). 20007 - INHFAIL_TNSAPIE - Server failed in inheriting the connection from the listener. 20008 - ACPTFAIL_TNSAPIE - Server failed in accepting the connection request from the client. 20009 - NULHDL_TNSAPIE - A null handle was passed into the call, which is not allowed. 20010 - INVOP_TNSAPIE - An invalid operation called was passed into the call. 20011 - MALFAIL_TNSAPIE - A malloc failed in TNS API call. 20012 - NLINIFAIL_TNSAPIE - Failed in NL initialization. 20013 - NMTOOLONG_TNSAPIE - Service name is too long. 20014 - CONFAIL_TNSAPIE - Client connect request failed. 20015 - LSNFAIL_TNSAPIE - Server failed to listen for connect request. 20016 - ANSFAIL_TNSAPIE - Server failed to answer connect request. 20017 - NMRESFAIL_TNSAPIE - Failed to resolve service name. 20018 - WOULDBLOCK_TNSAPIE - Operation would block. 20019 - CTLFAIL_TNSAPIE - Control call failed. 20020 - TNSAPIE_ERROR - TNS error occurred. 20021 - INVCTL_TNSAPIE - Invalid operation request in control call. Event programming in UNIX requires the use of a UNIX signal. When an event occurs, a signal flags a process. The process executes code that is relevant to the particular signal generated. UNIX does not allow a single process to set more than one signal handler or alarm for a particular signal call. If a process sets a second signal handler or alarm request on a signal like SIGCHLD (signal on a child process' status change), UNIX nullifies and loses the previous request for the SIGCHLD. If any part of your application issues one of these requests, signal handling or alarms may cause the system to lose and never respond to that particular request. Depending on the signal requested, the system may not clean up defunct processes properly because of a signal handler problem. Net8 provides two solutions to allow for the use of signal handling and alarms in tandem with Oracle's usage of those requests: Net8 provides an operating system dependent (OSD) call that keeps a table of all signal handler or alarm requests for each signal. Any program that uses the signal handler or alarm is now required to use the Oracle OSD calls. This provides a solution for programmers in UNIX who are not allowed to set more than one signal handler or alarm for a particular call. Any program that uses the signal handler or alarm must use the Oracle OSD calls. This is however, currently available only for internal use. In the near future, an externalized version of the OSD calls for client application usage will be released. Until then, if you set all of the client's signal handlers before making any database connections, the OSD call will remember the last signal handler set for the signal and will add it to the signal handler table. Note that by doing this, you cannot disable the signal handler. To use the table-driven shared OSD signal handler for all SIGCHLD calls, you must observe the following rules: This section is for UNIX application programmers who use both the UNIX signal handler for tracking child process status changes with the SIGCHLD call and Net8 for the networking portion of their application. When a client application is directed to communicate with an Oracle database on the same machine, it uses the Bequeath protocol to establish the connection. The Bequeath protocol enables the client to retrieve information from the database without using the listener. The Bequeath protocol internally spawns a server process for each client application. In a sense, it performs locally the same operation that a remote listener does for your connection. Since the client application spawns a server process internally through the Bequeath protocol as a child process, the client application becomes responsible for cleaning up the child process when it completes. When the server process completes its connection responsibilities, it becomes a defunct process. Signal handlers are responsible for cleaning up these defunct processes. Alternatively, you may configure your client SQLNET.ORA file to pass this process to the UNIX init process by disabling signal handlers. Use the Net8 Assistant to configure a client to disable the UNIX signal handler. The SQLNET.ORA parameter set to disable is as follows: bequeath_detach=yes This parameter causes all child processes to be passed over to the UNIX init process (pid = 1). The init process automatically checks for "defunct" child processes and terminates them. Bequeath automatically chooses to use a signal handler in tracking child process status changes. If your application does not use any signal handling, then this default does not affect you.
http://docs.oracle.com/cd/F49540_01/DOC/network.815/a67440/ch10.htm
CC-MAIN-2014-15
en
refinedweb
README ¶ pidusage Cross-platform process cpu % and memory usage of a PID for golang Ideas from but just use Golang API import ( "os" "github.com/struCoder/pidusage" ) func printStat() { sysInfo, err := pidusage.GetStat(os.Process.Pid) } How it works A check on the runtime.GOOS is done to determine the method to use. Linux We use /proc/{pid}/stat in addition to the the PAGE_SIZE and the CLK_TCK direclty from getconf() command. Uptime comes from proc/uptime Cpu usage is computed by following those instructions. It keeps an history of the current processor time for the given pid so that the computed value gets more and more accurate. Don't forget to do unmonitor(pid) so that history gets cleared. Cpu usage does not check the child process tree! Memory result is representing the RSS (resident set size) only by doing rss*pagesize, where pagesize is the result of getconf PAGE_SIZE. On darwin, freebsd, solaris We use a fallback with the ps -o pcpu,rss -p PID command to get the same informations. Memory usage will also display the RSS only, process cpu usage might differ from a distribution to another. Please check the correspoding man ps for more insights on the subject. On AIX AIX is tricky because I have no AIX test environement, at the moment we use: ps -o pcpu,rssize -p PID but /proc results should be more accurate! If you're familiar with the AIX environment and know how to get the same results as we've got with Linux systems. Windows Next version will support Documentation ¶ Index ¶ Constants ¶ This section is empty. Variables ¶ This section is empty. Functions ¶ This section is empty. Types ¶ type Stat ¶ type Stat struct { // contains filtered or unexported fields } Stat will store CPU time struct
https://pkg.go.dev/github.com/struCoder/pidusage
CC-MAIN-2022-27
en
refinedweb
openfile 0.1.2 Opening std.stdio.File using a set of symbolic constants as a file access mode To use this package, run the following command in your project's root directory: Manual usage Put the following dependency into your project's dependences section: OpenFile OpenFile library provides functions for opening std.stdio.File using a set of symbolic constants instead of C-style string as a file access mode. This approach allows setting a file access mode which is not possible or non-portable to express via string literals. E.g. an exclusive mode which atomically ensures that the file does not exist upon creating. Also someone might just prefer symbolic constants over string literals. import openfile; // Open a file in write mod and ensure that this is a new file with such name // avoiding an accidental change of data written by some other process and ensuring that no other file with such name exists at the time of opening. File f = openFile("test.txt", OpenMode.createNew); - Registered by Roman Chistokhodov - 0.1.2 released 2 years ago - FreeSlave/openfile - BSL-1.0 - Authors: - - Dependencies: - none - Versions: - Show all 4 versions - Download Stats: 0 downloads today 0 downloads this week 0 downloads this month 6 downloads total - Score: - 0.4 - Short URL: - openfile.dub.pm
https://code.dlang.org/packages/openfile
CC-MAIN-2022-27
en
refinedweb
Regret curves¶ Hint Conveys how quickly the algorithm found the best hyperparameters. The regret is the difference between the achieved objective and the optimal objective. Plotted as a time series, it shows how fast an optimization algorithm approaches the best objective. An equivalent way to visualize it is using the cumulative minimums instead of the differences. Oríon plots the cumulative minimums so that the objective can easily be read from the y-axis. - orion.plotting.base.regret(experiment, with_evc_tree=True, order_by='suggested', verbose_hover=True, **kwargs)[source] Make a plot to visualize the performance of the hyper-optimization process. The x-axis contain the trials and the y-axis their respective best performance. - Parameters - experiment: ExperimentClient or Experiment The orion object containing the experiment data - with_evc_tree: bool, optional Fetch all trials from the EVC tree. Default: True - order_by: str Indicates how the trials should be ordered. Acceptable options are below. See attributes of Trialfor more details. ‘suggested’: Sort by trial suggested time (default). ‘reserved’: Sort by trial reserved time. ‘completed’: Sort by trial completed time. - verbose_hover: bool Indicates whether to display the hyperparameter in hover tooltips. True by default. - kwargs: dict All other plotting keyword arguments to be passed to plotly.express.line. - Returns - plotly.graph_objects.Figure - Raises - ValueError If no experiment is provided. The regret plot can be executed directly from the experiment with plot.regret() as shown in the example below. from orion.client import get_experiment # Specify the database where the experiments are stored. We use a local PickleDB here. storage = dict(type="legacy", database=dict(type="pickleddb", host="../db.pkl")) # Load the data for the specified experiment experiment = get_experiment("random-rosenbrock", storage=storage) fig = experiment.plot.regret() fig Out: `strategy` option is not supported anymore. It should be set in algorithm configuration directly. The objective of the trials is overlayed as a scatter plot under the regret curve. Thanks to this we can see whether the algorithm focused its optimization close to the optimum (if all points are close to the regret curve near the end) or if it explored far from it (if many points are far from the regret curve near the end). We can see in this example with random search that the algorithm unsurpringly randomly explored the space. If we plot the results from the algorithm TPE applied on the same task, we will see a very different pattern (see how the results were generated in tutorial Python API basics). Out: `strategy` option is not supported anymore. It should be set in algorithm configuration directly. You can hover your mouse over the trials to see the configuration of the corresponding trials. The configuration of the trials is following this format: ID: <trial id> value: <objective> time: <time x-axis is ordered by> parameters <name>: <value> For now, the only option to customize the regret plot is order_by, the sorting order of the trials on the x-axis. Contributions are more than welcome to increase the customizability of the plot! By default the sorting order is suggested, the order the trials were suggested by the optimization algorithm. Other options are reserved, the time the trials started being executed and completed, the time the trials were completed. In this example, the order by suggested or by completed is the same, but parallelized experiments can lead to different order of completed trials. # TODO: Add documentation for `regrets()` Finally we save the image to serve as a thumbnail for this example. See the guide How to save for more information on image saving. fig.write_image("../../docs/src/_static/regret_thumbnail.png") Total running time of the script: ( 0 minutes 6.718 seconds) Gallery generated by Sphinx-Gallery
https://orion.readthedocs.io/en/latest/auto_examples/plot_1_regret.html
CC-MAIN-2022-27
en
refinedweb
A snapshot strategy for testing your VoiceOvers support in UIKit, using the SnapshotTesting library by PointFree. This strategy uses a textual representation of the view hierarchy, focusing on just the information that is relevant for VoiceOver. (Related work: AccessibilitySnapshot is a visual snapshot-test tool for a similar use case.) import SnapshotTesting import AccessibilityTextSnapshot assertSnapshot( // SnapshotTesting gives you this... matching: someView, as: .recursiveA11yDescription) // ... but AccessibilityTextSnapshot gives you this This generates a recursive (textual) description of all voiceover-relevant information, suitable for snapshot testing. The string shows |to emphasise that they are not involved in VoiceOver It does not show UIImageViews, which we maybe should reconsider at some point. Example: * UIView // non-a11y view but has a11y-relevant descendant * UIScrollView // (same) * UIView // (same) * UIStackView // ... * MDViewLayer.ElementView * UIStackView * MDViewModels.Label // | hanging from this view means it has a11y-relevant stuff | -label: Relaxation exercises // a11y property | -traits: .staticText // a11y property * UIStackView * MDViewLayer.MultilineButton | -label: Yes | -hint: Unselected option | -traits: .button * MDViewLayer.MultilineButton | -label: No | -hint: Unselected option | -traits: .button * MDViewLayer.ConversationListItemView // hanging | means a11y-relevant view | -label: Only you. No messages yet // a11y property | -hint: Open conversation // a11y property | * UIStackView // subviews that would be a11y-relevant | * UIStackView // BUT are not read by VoiceOver because | * UIStackView // the parent view overrides, note leading | | * MDViewModels.Label | | -label: Only you | * UIStackView | * MDViewModels.Label | | -label: No messages yet. | * MDViewLayer.Button | * UIView | * MDViewModels.Label | | -label: Ongoing video call o MDViewLayer.StepValidationView // o means isHidden=true (on self or a parent) o -label: Please correct the errors above. Actions available o -action: Go to first error // We still show it because we want to o * MDViewLayer.MultilineButton // be reminded that there *could* be something! o | -label: Please correct the errors above target 'MyAppTests' do pod 'AccessibilityTextSnapshot' end Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/minddistrict/ios-accessibility-text-snapshot
CC-MAIN-2022-27
en
refinedweb
We have good WebSocket libraries for Apple platforms, but we need it on Linux too. This library based on Apple Swift NIO framework, which allows it to be cross-platform. Add the following dependency to your Package.swift: .package(url: "", from: "0.2.0") Run swift build and build your app. Add the following to your Podfile: pod 'TesseractWebSocket.swift', '~> 0.2' Then run pod install import Foundation import WebSocket let socket = WebSocket() socket.onConnected = { ws in ws.send("hello") } socket.onData = { data, ws in print("Received", data) assert(data.text! == "hello") ws.disconnect() } socket.connect(url: URL(string: "wss://echo.websocket.org")!) WebSocket.swift is available under the Apache 2.0 license. See the LICENSE file for more information. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/tesseract-one/WebSocket.swift
CC-MAIN-2022-27
en
refinedweb
Fibonacci sequence: The Fibonacci sequence is a sequence type in which the sum of the previous two numbers is each consecutive number. First few Fibonacci numbers are 0 1 1 2 3 5 8 …..etc. Fibonacci sequence without recursion: Let us now write code to display this sequence without recursion. Because recursion is simple, i.e. just use the concept, Fib(i) = Fib(i-1) + Fib(i-2) However, because of the repeated calculations in recursion, large numbers take a long time. So, without recursion, let’s do it. - Python Program to Find the Fibonacci Series Using Recursion - Python Program to Print nth Iteration of Lucas Sequence - C Program to Print Fibonacci Series using Recursion Approach: - Create two variables to hold the values of the previous and second previous numbers. - Set both variables to 0 to begin. - Begin a loop until N is reached, and for each i-th index - Print the sum of the previous and second most previous i.e sum= previous + second previous - Assign previous to second previous i.e. second previous= previous - Assign sum to previous i.e previous=sum Below is the implementation: 1)C++ implementation of above approach. #include <iostream> using namespace std; int main() { // given number int n = 10; // initializing previous and second previous to 0 int previous = 0; int secondprevious = 0; int i; // loop till n for (i = 0; i < n; i++) { // initializing sum to previous + second previous int sum = previous + secondprevious; cout << sum << " "; if (!sum) previous = 1; secondprevious = previous; previous = sum; } return 0; } 2)Python implementation of above approach. # given number n = 10 # initializing previous and second previous to 0 previous = 0 secondprevious = 0 # loop till n for i in range(n): sum = previous + secondprevious print(sum, end=" ") if (not sum): previous = 1 # initializing value to previous to second previous secondprevious = previous previous = sum Output: 0 1 1 2 3 5 8 13 21 34 Related Programs: - object oriented approach to display a sequence of numbers without any for loop or recursion in cpp - python program to print numbers in a range 1upper without using any loops or by using recursion - python program to print all permutations of a string in lexicographic order without recursion - python program to find the fibonacci series using recursion - software engineering notes for mca - accounting and finance for bankers notes - big data notes for cse
https://btechgeeks.com/designing-code-for-fibonacci-sequence-without-recursion/
CC-MAIN-2022-27
en
refinedweb
Welcome to Quickstart 3 for Duende IdentityServer! The previous quickstarts introduced API access and user authentication. This quickstart will bring the two together. OpenID Connect and OAuth combine elegantly; you can achieve both user authentication and api access in a single exchange with the token service. In Quickstart 2, the token request in the login process asked for only identity resources, that is, only scopes such as profile and openid. In this quickstart, you will add scopes for API resources to that request. IdentityServer will respond with two tokens: We recommend you do the quickstarts in order, but if you’d like to start here, begin from a copy of Quickstart 2’s source code. You will also need to install the IdentityServer templates. The client configuration in IdentityServer requires two straightforward updates. Update the Client in IdentityServer/Config.cs as follows:" } } Now configure the client to ask for access to api1 and for a refresh token by requesting the api1 and offline_access scopes. This is done in the OpenID Connect handler configuration in WebClient/Program.cs: builder.Services.AddAuthentication(options => { options.DefaultScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect("oidc", options => { options.Authority = ""; options.ClientId = "web"; options.ClientSecret = "secret"; options.ResponseType = "code"; options.SaveTokens = true; options.Scope.Clear(); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("api1"); options.Scope.Add("offline_access"); options.GetClaimsFromUserInfoEndpoint = true; }); Since SaveTokens is enabled, ASP.NET Core will automatically store the id, access, and refresh tokens in the properties of the authentication cookie. If you run the solution and authenticate, you will see the tokens on the page that displays the cookie claims and properties created in quickstart 2. Now you will use the access token to authorize requests from the WebClient to the Api. Create a page that will Create the Page by running the following command from the WebClient\Pages directory: dotnet new page -n CallApi Update WebClient\Pages\CallApi.cshtml.cs as follows: public class CallApiModel : PageModel { public string Json = string.Empty; public async Task OnGet() { var accessToken = await HttpContext.GetTokenAsync("access_token"); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var content = await client.GetStringAsync(""); var parsed = JsonDocument.Parse(content); var formatted = JsonSerializer.Serialize(parsed, new JsonSerializerOptions { WriteIndented = true }); Json = formatted; } } And update WebClient\Pages\CallApi.cshtml as follows: @page @model MyApp.Namespace.CallApiModel <pre>@Model.Json</pre> Make sure the IdentityServer and Api projects are running, start the WebClient and request /CallApi after authentication. By far the most complex task for a typical client is to manage the access token. You typically want to ASP.NET Core has built-in facilities that can help you with some of those tasks (like caching or sessions), but there is still quite some work left to do. Consider using the IdentityModel library for help with access token lifetime management. It provides abstractions for storing tokens, automatic refresh of expired tokens, etc.
https://docs.duendesoftware.com/identityserver/v6/quickstarts/3_api_access/
CC-MAIN-2022-27
en
refinedweb
Back to: ASP.NET MVC Tutorial For Beginners and Professionals Role-Based Authentication in ASP.NET MVC In this article, I am going to discuss how to implement Role-Based Authentication in the ASP.NET MVC application. I strongly recommended reading our previous article before proceeding to this article as it is a continuation part of our previous article. In our previous article, we discussed how to implement Forms Authentication in ASP.NET MVC as well as we also created the required database tables. As part of this article, we are going to discuss the following things in detail. - What are the Roles? - What is the need for Role-Based Authentication? - How to implement Role-Based Authentication? What are the Roles? Roles are nothing but the permissions given to a particular user to access some resources. So in some other words, we can say that, once a user is authenticated then what are the resources the user can access are determined by his roles. A single user can have multiple roles and Roles plays an important part in providing security to the system. For example, Admin, Customer, Accountant, etc. SQL Script: In order to understand the Roles, let add some data into the tables. Please use the below SQL Script to insert some test data to Employee, Users, RoleMaster, and UserRolesMapping table. -- Inserting data into Employee table INSERT INTO Employee VALUES('Anurag', 'Software Engineer', 10000) INSERT INTO Employee VALUES('Preety', 'Tester', 20000) INSERT INTO Employee VALUES('Priyanka', 'Software Engineer', 20000) INSERT INTO Employee VALUES('Ramesh', 'Team Lead', 10000) INSERT INTO Employee VALUES('Santosh', 'Tester', 15000) -- Inserting data into Users table INSERT INTO Users VALUES('Admin','admin') INSERT INTO Users VALUES('User','user') INSERT INTO Users VALUES('Customer','customer') -- Inserting data into Role Master table INSERT INTO RoleMaster VALUES('Admin') INSERT INTO RoleMaster VALUES('User') INSERT INTO RoleMaster VALUES('Customer') -- Inserting data into User Roll Mapping table INSERT INTO UserRolesMapping VALUES(1, 1, 1) INSERT INTO UserRolesMapping VALUES(2, 1, 2) INSERT INTO UserRolesMapping VALUES(3, 1, 3) INSERT INTO UserRolesMapping VALUES(4, 2, 2) INSERT INTO UserRolesMapping VALUES(5, 3, 3) As you can see, the user with id 1 having three roles whiles the user with id 2 and 3 having only one role. Creating the Role Provider: Create a class file with the name UsersRoleProvider within the Models folder and then copy and paste the following code. This class implements the RoleProvider class. If you go to the definition of RoleProvider class then you can see it is an abstract class. As it is an abstract class we need to implement all the methods of that class. The RoleProvider class belongs to System.Web.Security namespace. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; namespace SecurityDemoMVC.Models { public class UsersRoleProvider : RoleProvider { string[] GetAllRoles() { throw new NotImplementedException(); } public override string[] GetRolesForUser(string username) { using (EmployeeDBContext context = new EmployeeDBContext()) { var userRoles = (from user in context.Users join roleMapping in context.UserRolesMappings on user.ID equals roleMapping.UserID join role in context.RoleMasters on roleMapping.RoleID equals role.ID where user.UserName == username select role.RollName).ToArray(); return userRoles; } }(); } } } In the above class, we only modify the implementation of the GetRolesForUser method. This method takes the Username as an input parameter and based on the username we need to fetch the User Roles as an array and return that array. Configuring Role Provider in the web.config file: Add the following code within the system.web section of your web.config file. <roleManager defaultProvider="usersRoleProvider" enabled="true" > <providers> <clear/> <add name="usersRoleProvider" type="SecurityDemoMVC.Models.UsersRoleProvider"/> </providers> </roleManager> Basically here we are adding our Role Providers. Before adding the Role Providers first we clear all roles. The name you can give anything but the type value is going to be the full name of your Role Provider i.e. including the namespace. Here you can add any number of Role Providers. You have to provide the default provider which is going to be used as default in the default provider parameter of role manager and you need to enable it by setting the value to true of enabled property. Modifying the Employees Controller: Please modify the Authorize attribute to include Roles as shown below. First, we remove the Authorize attribute from the Controller Level and applied it at the action method level. Here you can pass multiple roles separated by a comma. As per your business requirement set the Roles and test by yourself. In the next article, I am going to discuss how to implement Role-Based Menus in the MVC applications. Here, in this article, I try to explain the Role-Based Authentication in ASP.NET MVC application. I hope you understood what is and how to implement Role-Based Authentication in the ASP.NET MVC application. 4 thoughts on “Role-Based Authentication in ASP.NET MVC” how to use GetRolesForUser() Method What is the table structure Refer to previous article role-based not working
https://dotnettutorials.net/lesson/role-based-authentication-in-mvc/
CC-MAIN-2022-27
en
refinedweb
Preface The previous blog summarized the contents of CountDownLatch and Cyclic Barrier. The underlying concurrency control of these contents can not be separated from AQS (AbstractQueuedSynchronizer). Personally, there are fewer scenarios in which AQS is directly used to write concurrency tools in your work, and you won't go deep into the detailed source level of AQS to explore its contents. Only its practical scenarios and simple principles will be summarized. In fact, the tool classes summarized earlier for inter-thread collaboration, such as CountDownLatch, Semaphore, ReentrantLock, all seem to share a common feature, with an internal seemingly uniform gate to control the number of accessible threads and when they are accessible. All Sync Internal Classes So we go into the source structure of these tools and see the following CyclicBarrier is an interthread collaboration implemented through ReentrantLock. The internal class Sync, which exists in all three, actually inherits from AbstractQueuedSynchronizer. Simple principles of AQS We will not analyze the source code of AQS line by line, but simply comb out the principle of AQS. Three Cores There are three main core contents in AQS, which are the key to understanding the principles of AQS. state variable /** * The synchronization state. */ private volatile int state; A volatile-modified variable that is the key to controlling concurrency. In different implementation classes, the meaning of this state does not pass. For example, in Smarphore, state means "the number of licenses remaining"; In CountDownLatch, a state means "a reciprocal number is required"; In ReentrantLock, a state represents the number of locks occupied, and a state value of 0 indicates that the current lock is not occupied by any thread. Since this variable is volatile-modified, thread safety is required each time a state is modified, so the abstract class of AQS provides some ways to modify this variable via CAS /** * Atomically sets synchronization state to the given updated * value if the current state value equals the expected value. * This operation has memory semantics of a {@code volatile} read * and write. * * @param expect the expected value * @param update the new value * @return {@code true} if successful. False return indicates that the actual * value was not equal to the expected value. */ protected final boolean compareAndSetState(int expect, int update) { // See below for intrinsics setup to support this return unsafe.compareAndSwapInt(this, stateOffset, expect, update); } FIFO queue A queue is maintained in AQS to hold "threads waiting to acquire locks". When a lock is released, AQS needs to fetch an appropriate thread from the FIFO queue to acquire locks. There is an internal class called Node in AQS, which actually maintains a double-line chain table. static final class Node { /** Marker to indicate a node is waiting in shared mode */ static final Node SHARED = new Node(); /** Marker to indicate a node is waiting in exclusive mode */ static final Node EXCLUSIVE = null; /** waitStatus value to indicate thread has cancelled */ static final int CANCELLED = 1; /** waitStatus value to indicate successor's thread needs unparking */ static final int SIGNAL = -1; /** waitStatus value to indicate thread is waiting on condition */ static final int CONDITION = -2; /** * waitStatus value to indicate the next acquireShared should * unconditionally propagate */ static final int PROPAGATE = -3; /** * Status field, taking on only the values: * SIGNAL: The successor of this node is (or will soon be) * blocked (via park), so the current node must * unpark its successor when it releases or * cancels. * nodes. This is set (for head node only) in * doReleaseShared to ensure propagation * continues, even if other operations have * since intervened. * 0: None of the above * * The values are arranged numerically to simplify use. * Non-negative values mean that a node doesn't need to * signal. So, most code doesn't need to check for particular * values, just for sign. * * The field is initialized to 0 for normal sync nodes, and * CONDITION for condition nodes. It is modified using CAS * (or when possible, unconditional volatile writes). */ volatile int waitStatus; /** * Link to predecessor node that current node/thread relies on * for checking waitStatus. Assigned during enqueuing, and nulled * out (for sake of GC) only upon dequeuing. Also, upon * cancellation of a predecessor, we short-circuit while * finding a non-cancelled one, which will always exist * because the head node is never cancelled: A node becomes * head only as a result of successful acquire. A * cancelled thread never succeeds in acquiring, and a thread only * cancels itself, not any other node. */ volatile Node prev; /** * Link to the successor node that the current node/thread * unparks upon release. Assigned during enqueuing, adjusted * when bypassing cancelled predecessors, and nulled out (for * sake of GC). The next field of cancelled nodes is set to * point to the node itself instead of null, to make life * easier for isOnSyncQueue. */ volatile Node next; /** * The thread that enqueued this node. Initialized on * construction and nulled out after use. */ volatile; /** * Returns true if node is waiting in shared mode. */ final boolean isShared() { return nextWaiter == SHARED; } /** * Returns previous node, or throws NullPointerException if null. * Use when predecessor cannot be null. The null check could * be elided, but is present to help the VM. * * @return the predecessor of this node */ final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; } Node() { // Used to establish initial head or SHARED marker } Node(Thread thread, Node mode) { // Used by addWaiter this.nextWaiter = mode; this.thread = thread; } Node(Thread thread, int waitStatus) { // Used by Condition this.waitStatus = waitStatus; this.thread = thread; } } The specific diagram is shown below (the picture is from the javadoop website) Methods to acquire and release locks The key remaining content is the methods for acquiring and releasing locks, which depend on the state variable and have different logic for acquiring and releasing locks in different JUC process control tool classes. For example, in Smarphore, the acquire method acquires licenses. The logic is to determine if the state is greater than 0, and if it is greater than 0, to reduce the number specified on the state. The release method is to release the licenses, that is, to add the number specified on the basis of the state. In CountDownLatch, the await method is used to determine the value of the state, and if it is not zero, the thread is blocked. The countDown method is the last number, minus one based on the state. Therefore, the logic for acquiring and releasing locks is different for different tool classes. There are several methods in AQS that can be implemented by subclasses Use of AQS in CountDownLatch sync in CountDownLatch The constructor for CountDownLatch is as follows /** * Constructs a {@code CountDownLatch} initialized with the given count. * * @param count the number of times {@link #countDown} must be invoked * before threads can pass through {@link #await} * @throws IllegalArgumentException if {@code count} is negative */ public CountDownLatch(int count) { if (count < 0) throw new IllegalArgumentException("count < 0"); //Initialization function of internal column was called, and corresponding count value was passed in this.sync = new Sync(count); } In the constructor, the initializer for the internal column is called, and the corresponding count value is passed in In CountDownLatch, Sync's internal class source is shown below private static final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 4982264981922014374L; //Initialize, set the value of state Sync(int count) { setState(count); } int getCount() { return getState(); } //The sync inside CountDownLatch implements the tryAcquireShared method in AQS //You can see that the logic of CountDownLatch is that if the state does not change to zero, the thread enters the waiting queue protected int tryAcquireShared(int acquires) { return (getState() == 0) ? 1 : -1; } //Copy tryReleaseShared in AQS yourself in CountDownLatch protected boolean tryReleaseShared(int releases) { // Decrement count; signal when transition to zero //for loop, like spin for (;;) { //Get the current state int c = getState(); if (c == 0) return false; int nextc = c-1;//state-1 if (compareAndSetState(c, nextc))//Update the value of state by cas return nextc == 0;//If the state becomes 0 after updating, it returns true } } } await in CountDownLatch The await method for CountDownLatch is as follows /** CountDownLatch The await method in calls tryAcquireSharedNanos for internal AQS When this method is called in CountDownLatch, the thread enters the wait queue and waits for the state in CountDownLatch to become zero */ public void await() throws InterruptedException { sync.acquireSharedInterruptibly(1); } Direct calls to the acquireSharedInterruptibly method in sync, which is already implemented in AQS and does not require the related subclasses to implement themselves. The acquireSharedInterruptibly source code in AQS is as follows /** AQS acquireSharedInterruptibly in */ public final void acquireSharedInterruptibly(int arg) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); if (tryAcquireShared(arg) < 0)//CountDownLatch implements this method and returns -1 if the value of state is not equal to 0. doAcquireSharedInterruptibly(arg);//The underlying call to doAcquireSharedInterruptibly will wait for the thread to queue } /** The underlying layer of doAcquireSharedInterruptibly above calls this method This method does not need to be looked at carefully, the waiting threads will be queued */ private void doAcquireSharedInterruptibly(int arg) throws InterruptedException { final Node node = addWaiter(Node.SHARED); boolean failed = true; try { for (;;) { final Node p = node.predecessor(); if (p == head) { int r = tryAcquireShared(arg); if (r >= 0) { setHeadAndPropagate(node, r); p.next = null; // help GC failed = false; return; } } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt())//The underlying suspends threads through LockSupport's lock method throw new InterruptedException(); } } finally { if (failed) cancelAcquire(node); } } You can see that the operation of waiting for a thread to join the queue is implemented in AQS, but when to join the queue, it is handed over to a subclass that first uses AQS as a tool. The same idea can be seen in Smarphore and ReentrantLock. countDown method in CountDownLatch public void countDown() { sync.releaseShared(1); } releaseShared method in AQS public final boolean releaseShared(int arg) { //CountDownLatch's own implementation of tryReleaseShared is called in the if judgment to see the comment for the code above if (tryReleaseShared(arg)) { doReleaseShared();//AQS has an implementation that wakes up all waiting threads directly. return true; } return false; } Use of AQS in Smarphore Later on, the relevant code in AQS will not be posted. In introducing Semaphore, we said that this specifies fairness and unfairness, so we implemented NonfairSync (unfair lock) and FairSync (fair lock) for AQS in Semaphore, similar to CountDownLatch. acquire in Semaphore public void acquire() throws InterruptedException { sync.acquireSharedInterruptibly(1);//The underlying layer also calls the tryAcquireShared method of the Sync implementation in Semaphore } There are two implementations of fair and unfair locks in Semaphore. First, take the unfair lock implementation as an example //java.util.concurrent.Semaphore.NonfairSync#tryAcquireShared protected int tryAcquireShared(int acquires) { //The underlying layer calls the nonfairTryAcquireShared method of the internal class Sync in Semaphore return nonfairTryAcquireShared(acquires); } final int nonfairTryAcquireShared(int acquires) { //spin for (;;) { int available = getState(); //Use cas to reduce the number of locks that need to be acquired based on state int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } release in Semaphore The source code in Semaphore is as follows, because fair and unfair locks release locks in the same way, Semaphore places its implementation in the internal class Sync //java.util.concurrent.Semaphore#release(int) public void release(int permits) { if (permits < 0) throw new IllegalArgumentException(); //This calls releaseShared in AQS, and the underlying calls tryReleaseShared in Semaphore sync.releaseShared(permits); } //java.util.concurrent.Semaphore.Sync#tryReleaseShared //As you can see, this is a simple spin+cas operation, set state = state+release protected final boolean tryReleaseShared(int releases) { for (;;) { int current = getState(); int next = current + releases; if (next < current) // overflow throw new Error("Maximum permit count exceeded"); if (compareAndSetState(current, next)) return true; } } AQS implements its own collaborator Internal inheritance of AbstractQueuedSynchronizer implements an internal Sync /** * autor:liman * createtime:2021/11/30 * comment:AQS A simple example * I use AQS to implement a simple collaborator, beggar version */ @Slf4j public class SelfCountDownLatchDemo { private final Sync sync = new Sync(); public void await() { sync.acquireShared(0); } public void signal() { sync.releaseShared(0); } /** * 1,Inherit the AQS method for acquisition and release, basic operations */ private class Sync extends AbstractQueuedSynchronizer { @Override protected int tryAcquireShared(int arg) { return (getState() == 1) ? 1 : -1; } @Override protected boolean tryReleaseShared(int arg) { setState(1); return true; } } public static void main(String[] args) throws InterruptedException { SelfCountDownLatchDemo selfCountDownLatchDemo = new SelfCountDownLatchDemo(); for (int i = 0; i < 10; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"Try to get customized latch in......"); selfCountDownLatchDemo.await(); System.out.println(Thread.currentThread().getName()+"Continue running"); }).start(); } //Main thread sleeps for 5 seconds Thread.sleep(5000); selfCountDownLatchDemo.signal();//Wake up all threads //This thread does not need to be blocked and will run directly new Thread(()->{ System.out.println(Thread.currentThread().getName()+"Try to get customized latch......"); selfCountDownLatchDemo.await(); System.out.println(Thread.currentThread().getName()+"Continue running"); },"main-sub-thread").start(); } } Run Results summary Core components of AQS, subclasses achieve custom thread collaboration control logic by implementing specified methods. The next article summarizes the contents of Future and Callable Reference material javadoop - Source line by line analysis clearly AbstractQueuedSynchronizer (1) javadoop - Source line by line analysis clearly AbstractQueuedSynchronizer (2) javadoop - Source line by line analysis clearly AbstractQueuedSynchronizer (3)
https://programmer.group/java-concurrency-tool-learning-a-brief-talk-about-aqs.html
CC-MAIN-2022-27
en
refinedweb
Array in C++ Introduction:Let us start with an example- suppose you have to write a program to accept 10 integers and sort it in ascending order. Now in the program if you take 10 individual variables as a, b, c etc. Then can you think of a logic to sort the numbers? It would be a very trublesome job. The problem is that the variables are not related by any relation, as they are created in the memory (RAM) in different locations controlled by other programs. You can not use any loop as you can not generalized the process. In this situation we have to use Array which can store the numbers and all the numbers are stored in successive memory locations. If we know any one of the numbers then we can find the others, so we can use loop. Array:Technically an array is a collection of similar data which share same name. Each data item is identified by its location (index number) in the array. Syntax of declaration : datatype name_of_array[ no_of_elements]; e.g int a[10], it will create an array of 10 integers whose single name is "a". Actually in this array "a" we have 10 integer variables they are - a[0], a[1], a[2]...a[9]. Therefore we can accept numbers in each of them using "cin" statemet, we can assign any number to them e.g a[0]=10. Same way we can declare array of type float, double, char. See the figure below- When we declare an array as int a[10] and compile the program then it creates a table having 10 cells and each of them can store an integer value. In the figure see that the index values at the top of each cell starts from 0 and ranges till 9, which specifies the position of each cell in the array. As I said that all the cells are created in successive memory locations. We can access each cell by just specifying the array name and the index number. e.g a[0], a[1] and so on. We can store numbers in each cells by using a "for" loop. See below- inta[10], i; for(i=0; i<=9; i++){ cout<<"Enter the element :"<<i+1<<":"; cin>>a[i]; }The program segment will store 10 numbers in the array as given below-. Enter the element : 1: 10 Enter the element : 2: 8 Enter the element : 3: 3 Enter the element : 4: 20 Enter the element : 5: 12 Enter the element : 6: 18 Enter the element : 7: 25 Enter the element : 8: 30 Enter the element : 9: 24 Enter the element : 10: 45 The array will be filled up with the entered numbers 10, 8, 3, 20, 12, 18, 25, 30, 24, and 45. Internally the array would be as below- See that only changing the index number we mean different variable here as a[0], a[1] and so on. Hence it is possible to use the loop to accept the numbers. In case of individual variable can we do it? Things to remember: - While declaring an array the number of cells must be constant e.g int b[10], you can not define as int k=10; then int a[k]; - Array can be initialized while declaring not any other place. e.g int a[]={3, 4, 10, 20}; here see that number of cells kept blank, you can give the number of cells here but better practice not to give it as computer gives it automatically. Q46.Write a program to store 10 numbers in an array then find the sum of the numbers. Q47.Write a program to store 10 numbers in an array then display the greatest number. Q48.Write a program to store 10 numbers in an array then search for a user given number Q49.Write a program to store 10 numbers in an array then count number of even numbers in it. Q50.Write a program to store 10 numbers in an array then add 1 with all even numbers and ans subtract 1 from all the odd numbers in it, then display the resulting array. Program-46 #include <iostream.h> void main(){ int ar[10], i, sum=0; for(i=0; i<= 9; i++){ cout<<"Enter the number:"<<i+1<<":"; cin>>ar[i]; } for(i=0; i<= 9; i++){ sum=sum+ar[i]; } cout<<"The Sum="<<sum; }In this program the array is define as "ar[10]" with 10 cells, the first for loop accepting the numbers from the user into the array. The second for loop reading the content of the array and adding it with "sum". Lastly the sum is displayed. The output of the above program is as below. Program-47 #include <iostream.h> void main(){ int ar[10], i, g; for(i=0; i<= 9; i++){ cout<<"Enter the number :"<<i+1<<":"; cin>>ar[i]; } g=ar[0]; for(i=1; i<= 9; i++){ if(ar[i]>g){ g=ar[i]; } } cout<<"The greatest number is ="<<g; }In this program see that the first number is taken a greatest as "g=ar[0]" then in the second loop each number at index number 1 to 9 is comapred with present greatest (g), if it is smaller it is replaced by "ar[i] so it becomes present greatest. At the end of the loop "g" gives the greatest numbers which is displayed. Program-48 #include <iostream.h> void main(){ int ar[10], i, k, found=0; for(i=0; i<= 9; i++){ cout<<"Enter the number :"<<i+1<<":"; cin>>ar[i]; } cout<<"Enter the number to be searched :"; cin>>k; for(i=0; i<= 9; i++){ if(ar[i]==k){ found=1; break; } } if(found==1){ cout<<"Number is found"; } else{ cout<<"Number is not found"; } }In this program see the given number "k" is comparing with each number in the array if equal the the variable "found" which was assign to zero at the begining now becomes 1 and exit the loop by the "break" statement. Outside the loop we are checking the value of "found" if it is 1 then the number is found otherwise it is not found. Program-49 #include <iostream.h> void main(){ int ar[10], i, c=0; for(i=0; i<= 9; i++){ cout<<"Enter the number :"<<i+1<<":"; cin>>ar[i]; } for(i=0; i<= 9; i++){ if(ar[i]%2==0){ c++; } } cout<<"Number of even nos="<<c; }In this program "c" is the accumulator increasing by one when the number is even. Program-50 #include <iostream.h> void main(){ int ar[10], i; for(i=0; i<= 9; i++){ cout<<"Enter the number :"<<i+1<<":"; cin>>ar[i]; } cout<<"The content of the array:\n" for(i=0; i<= 9; i++){ cout<<ar[i]<<" "; } for(i=0; i<= 9; i++){ if(ar[i]%2==0){ ar[i]=ar[i]=1; } esle{ ar[i]=ar[i]-1; } } cout<<"The content of the array after the operation:\n" for(i=0; i<= 9; i++){ cout<<ar[i]<<" "; } } In this program the original array is displayed first. Then the required operation is done on the array and the changed content of the array is displayed
https://www.mcqtoday.com/CPP/array/Array.html
CC-MAIN-2022-27
en
refinedweb
#include <Standard_PrimitiveTypes.hxx> Indicates the outcome of a construction, i.e. whether it is successful or not, as explained below. gce_Done: Construction was successful. gce_ConfusedPoints: Two points are coincident. gce_NegativeRadius: Radius value is negative. gce_ColinearPoints: Three points are collinear. gce_IntersectionError: Intersection cannot be computed. gce_NullAxis: Axis is undefined. gce_NullAngle: Angle value is invalid (usually null). gce_NullRadius: Radius is null. gce_InvertAxis: Axis value is invalid. gce_BadAngle: Angle value is invalid. gce_InvertRadius: Radius value is incorrect (usually with respect to another radius). gce_NullFocusLength: Focal distance is null. gce_NullVector: Vector is null. gce_BadEquation: Coefficients are incorrect (applies to the equation of a geometric object).
https://dev.opencascade.org/doc/occt-6.9.0/refman/html/gce___error_type_8hxx.html
CC-MAIN-2022-27
en
refinedweb
Summary Saves a copy of processed images in a mosaic dataset to a specified folder and raster file format. There are two common workflows that use this tool: - Export each item of a mosaic dataset to a new file. This allows you to have each processed item as a stand-alone file. You must set the appropriate NoData value for the exported items so there are no black borders. - Export each image within a time series mosaic dataset based on an area of interest. This allows you to only export the area of interest from each time slice. Usage By default, all items will be exported to the specified folder. Use the Query Definition parameter or interactively select specific records in the mosaic dataset to export a subset of the images. The images will be exported with all the processing from the function chains applied. Only the function chains at the item level are applied; function chains at the mosaic dataset level are ignored. This tool does not export the raw source images. Parameters arcpy.management.ExportMosaicDatasetItems(in_mosaic_dataset, out_folder, {out_base_name}, {where_clause}, {format}, {nodata_value}, {clip_type}, {template_dataset}, {cell_size}, {image_space}) Derived Output Code sample This is a Python sample for the ExportMosaicDatasetItems function. import arcpy arcpy.ExportMosaicDatasetItems_management( "c:/workspace/exportmditems.gdb/export_all_items", "c:/workspace/export_all_items_out", "allitems", "", "TIFF", "", "NONE", "", "") This is a Python script sample for the ExportMosaicDatasetItems function. #Export Mosaic Dataset items import arcpy arcpy.env.workspace = "c:/workspace" #export mosaic dataset items using feature class as clipping extent imdname = "exportmditem.gdb/exportmd" outfolder = "c:/workspace/outfolder" basename = "Landsat8" query = "OBJECTID = 1" out_format = "TIFF" nodata_value = "#" cliptype = "FEATURE_CLASS" clip_featureclass = "c:/workspace/featureclassdb.gdb/clip_FC" cell_size = "#" arcpy.ExportMosaicDatasetItems_management(imdname, outfolder, basename, query, out_format, nodata_value, cliptype, clip_featureclass, cell_size) Environments Licensing information - Basic: No - Standard: Yes - Advanced: Yes
https://pro.arcgis.com/en/pro-app/latest/tool-reference/data-management/export-mosaic-dataset-items.htm
CC-MAIN-2022-27
en
refinedweb
public class | source import {TakePhotosOfFailures} from '@serenity-js/webdriverio/lib/stage/crew/photographer/strategies' TakePhotosOfFailures Configures the Photographer to take photos (a.k.a. screenshots) when the Interaction performed by the Actor in the spotlight results in an error. This strategy works best when you are interested in the screenshots only when a scenario fails. Extends: PhotoTakingStrategy → TakePhotosOfFailures
https://serenity-js.org/modules/webdriverio/class/src/stage/crew/photographer/strategies/TakePhotosOfFailures.ts~TakePhotosOfFailures.html
CC-MAIN-2022-27
en
refinedweb
Cobrowse.io is 100% free and easy to try out in your own apps. Please see full documentation at. Try our online demo at the bottom of our homepage at. We recommend installing the Cobrowse.io SDK using Cocoapods. Add this to your Podfile: pod 'CobrowseIO', '~>2' Don't forget to run pod repo update then pod install after you've edited your Podfile. import CobrowseIO func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { CobrowseIO.instance().license = "put your license key here" CobrowseIO.instance().start() return true } @import CobrowseIO; - (BOOL)application:(UIApplication*) application didFinishLaunchingWithOptions:(NSDictionary*) launchOptions { CobrowseIO.instance.license = @"put your license key here"; [CobrowseIO.instance start]; return YES; } Important: Do this in your application:didFinishLaunchingWithOptions: implementation to make sure your device shows up in your dashboard right away. Please register an account and generate your free License Key at. This will associate sessions from your mobile app with your Cobrowse account. Once you have your app running in the iOS Simulator or on a physical device, navigate to to see your device listed. You can click the "Connect" button to initiate a Cobrowse session! Initiate sessions with push Any questions at all? Please email us directly at hello@cobrowse.io. v2.20.1 Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/cobrowseio/cobrowse-sdk-ios-binary
CC-MAIN-2022-27
en
refinedweb
This is part 7 of our full-stack GraphQL + React Tutorial that guides you through creating a messaging application. Each part is self-contained and focuses on a few new topics, so you can jump directly into a part that interests you or do the whole series. Here’s what we have covered so far: - Part 1: Setting up a simple client - Part 2: Setting up a simple server - Part 3: Writing mutations and keeping the client in sync - Part 4: Optimistic UI and client side store updates - Part 5: Input Types and Custom Resolvers - Part 6: GraphQL Subscriptions on the Server - Part 7: Client subscriptions (This part!) - Part 8: Pagination In part 6, we implemented the server-side portion of GraphQL Subscriptions for our message channels. Clients can use these subscriptions to be notified whenever a specific event happens — in this case the creation of a message in a specified channel. In this tutorial, we will add GraphQL Subscriptions to our client so that instances of the client can see live updates to messages in a channel. Let’s get started by cloning the Git repo and installing the dependencies: git clone cd graphql-tutorial git checkout t7-start cd server && npm install cd ../client && npm install First, let’s make sure everything works by starting the server and client. In one terminal session we launch the server, which will run on port 4000: cd server npm start And in another session we launch the client, which will run on port 3000: cd client npm start When you navigate your browser to, you should enter the homepage of our messaging app, which has a list of channels that the user has created. Click on one of the channels, and you’ll be taken to the detail view that we created in Part 5, where you can add new messages in the channel. You’ll notice that if you open the same channel in multiple windows, messages added in one window don’t show up in the other. By the end of this tutorial, client syncing will allow multiple users to see each-other’s changes! GraphQL Subscriptions TransportGraphQL Subscriptions Transport. First, let’s add the necessary imports at the top of client/src/App.js import { SubscriptionClient, addGraphQLSubscriptions } from 'subscriptions-transport-ws'; Next, we construct the WebSocket-based subscription client and merge it with our existing network interface const networkInterface = createNetworkInterface({ uri: '' });networkInterface.use([{ applyMiddleware(req, next) { setTimeout(next, 500); }, }]);const wsClient = new SubscriptionClient(`ws://localhost:4000/subscriptions`, { reconnect: true, });const networkInterfaceWithSubscriptions = addGraphQLSubscriptions( networkInterface, wsClient, ); Now all we have to do to enable subscriptions throughout our application is use networkInterfaceWithSubscriptions as the Apollo Client’s network interface const client = new ApolloClient({ networkInterface: networkInterfaceWithSubscriptions, ... }); If you load up the client and look in the “Network” tab of the developer tools (right-click and “Inspect element”), you should see that the client has established a WebSocket connection to the server. Listening for MessagesListening for Messages Now that we can use GraphQL Subscriptions in our client, the next step is to use subscriptions to detect the creation of messages. Our goal here is to use subscriptions to update our React views to see new messages in a channel as they are added. Before we start, we have to refactor our client/src/components/ChannelDetails.js component to be a full ES6 class component instead of just a function, so that we can use the React lifecycle events to set up the subscription. First, we update our import statement to include the Component class. import React, { Component } from 'react'; Then, we refactor our function component into an ES6 class class ChannelDetails extends Component { render() { const { data: {loading, error, channel }, match } = this.props; if (loading) { return <ChannelPreview channelId={match.params.channelId}/>; } if (error) { return <p>{error.message}</p>; } if(channel === null){ return <NotFound /> } return ( <div> <div className="channelName"> {channel.name} </div> <MessageList messages={channel.messages}/> </div>); } } Now that our component is ready to handle subscriptions, we can write out the subscriptions query: const messagesSubscription = gql` subscription messageAdded($channelId: ID!) { messageAdded(channelId: $channelId) { id text } } ` To make the subscription request, we will use Apollo Client’s subscribeToMore function, which lets us update the store when we receive new data. First, we define a componentWillMount in our component, which is where we will start the subscription. class ChannelDetails extends Component { componentWillMount() { } render() { ... } } Inside this React lifecycle function, we set up our subscription to listen for new messages and add them to our local store as they come. Because the updateQuery function is supposed to produce a new instance of a store state based on prev, the previous store state, we use the Object.assign method to create a copy of the store with modifications to add the new message. Also, because we are manually managing our store of messages, it is possible to have duplicate messages. A message can be added once as the result of performing the mutation and again when we receive the subscription notification. To prevent duplicates, we add an extra check to verify that we did not already add the message to our store with a previous mutation. componentWillMount() { this.props.data.subscribeToMore({ document: messagesSubscription, variables: { channelId: this.props.match.params.channelId, }, updateQuery: (prev, {subscriptionData}) => { if (!subscriptionData.data) { return prev; } const newMessage = subscriptionData.data.messageAdded; // don't double add the message if (!prev.channel.messages.find((msg) => msg.id === newMessage.id)) { return Object.assign({}, prev, { channel: Object.assign({}, prev.channel, { messages: [...prev.channel.messages, newMessage], }) }); } else { return prev; } } }); } We’re almost done now! All we have to do is perform the same de-duplication check in the AddMessage component, because when we create a new message we might be notified of creation through the WebSocket before the query returns data. In client/src/components/AddMessage.js , replace data.channel.messages.push(addMessage); with the same statement wrapped in a condition that checks for duplication if (!data.channel.messages.find((msg) => msg.id === addMessage.id)) { // Add our Message from the mutation to the end. data.channel.messages.push(addMessage); } Now we’re ready to test out our subscription-based live updating messages view! Open two windows of the client and select the same channel in both. When you add a message in one client, you should see the same message show up in the other client! ConclusionConclusion Congrats! You’ve now wired up the server-side implementation of GraphQL Subscriptions to your client through Apollo so that users can see live updates of message additions from other clients. With a couple more changes such as pagination, covered in the next tutorial, and auth your application will be ready for real use! If you liked this tutorial and want to keep learning about Apollo and GraphQL, make sure to click the “Follow” button below, and follow us on Twitter at @apollographql and the author at @ShadajL. Thanks to my mentor, Jonas Helfer, for his support as I wrote.
https://www.apollographql.com/blog/apollo-client/subscriptions/tutorial-graphql-subscriptions-client-side
CC-MAIN-2022-27
en
refinedweb
Introduction A while ago, Tomasz introduced Kotlin development on Android. To remind you: Kotlin is a new programming language developed by Jetbrains, the company behind one of the most popular Java IDEs, IntelliJ IDEA. Like Java, Kotlin is a general-purpose language. Since it complies to the Java Virtual Machine (JVM) bytecode, it can be used side-by-side with Java, and it doesn’t come with a performance overhead. In this article, I will cover the top 10 useful features to boost your Android development. Note: at the time of writing this article, actual versions were Android Studio 2.1.1. and Kotlin 1.0.2. Kotlin Setup Since Kotlin is developed by JetBrains, it is well-supported in both Android Studio and IntelliJ. The first step is to install Kotlin plugin. After successfully doing so, new actions will be available for converting your Java to Kotlin. Two new options are: - Create a new Android project and setup Kotlin in the project. - Add Kotlin support to an existing Android project. To learn how to create a new Android project, check the official step by step guide. To add Kotlin support to a newly created or an existing project, open the find action dialog using Command + Shift + A on Mac or Ctrl + Shift + A on Windows/Linux, and invoke the Configure Kotlin in Project action. To create a new Kotlin class, select: File> New> Kotlin file/class, or File> New> Kotlin activity Alternatively, you can create a Java class and convert it to Kotlin using the action mentioned above. Remember, you can use it to convert any class, interface, enum or annotation, and this can be used to compare Java easily to Kotlin code. Another useful element that saves a lot of typing are Kotlin extensions. To use them you have to apply another plugin in your module build.gradle file: apply plugin: 'kotlin-android-extensions' Caveat: if you are using the Kotlin plugin action to set up your project, it will put the following code in your top level build.gradle file: buildscript { ext.kotlin_version = '1.0.2' repositories { jcenter() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } This will cause the extension not to work. To fix that, simply copy that code to each of the project modules in which you wish to use Kotlin. If you setup everything correctly, you should be able to run and test your application the same way you would in a standard Android project, but now using Kotlin. Saving Time with Kotlin So, let’s start with describing some key aspects of Kotlin language and by providing tips on how you can save time by using it instead of Java. Feature #1: Static Layout Import One of the most common boilerplate codes in Android is using the findViewById() function to obtain references to your views in Activities or Fragments. There are solutions, such as the Butterknife library, that save some typing, but Kotlin takes this another step by allowing you to import all references to views from the layout with one import. For example, consider the following activity XML layout: <="co.ikust.kotlintest.MainActivity"> <TextView android: </RelativeLayout> And the accompanying activity code: package co.ikust.kotlintest) helloWorldTextView.text = "Hello World!" } } To get the references for all the views in the layout with a defined ID, use the Android Kotlin extension Anko. Remember to type in this import statement: import kotlinx.android.synthetic.main.activity_main.* Note you don’t need to write semicolons at the end of the lines in Kotlin because they are optional. The TextView from layout is imported as a TextView instance with the name equal to the ID of the view. Don’t be confused by the syntax, which is used to set the label: helloWorldTextView.text = "Hello World!" We will cover that shortly. Caveats: - Make sure you import the correct layout, otherwise imported View references will have a nullvalue. - When using fragments, make sure imported View references are used after the onCreateView()function call. Import the layout in onCreateView()function and use the View references to setup the UI in onViewCreated(). The references won’t be assigned before the onCreateView()method has finished. Feature #2: Writing POJO Classes with Kotlin Something that will save the most time with Kotlin is writing the POJO (Plain Old Java Object) classes used to hold data. For example, in the request and response body of a RESTful API. In applications that rely on RESTful API, there will be many classes like that. In Kotlin, much is done for you, and the syntax is concise. For example, consider the following class in Java:; } } When working with Kotlin, you don’t have to write public keyword again. By default, everything is of public scope. For example, if you want to declare a class, you simply write: class MyClass { } The equivalent of the Java code above in Kotlin: class User { var firstName: String? = null var lastName: String? = null } Well, that saves a lot of typing, doesn’t it? Let’s walk through the Kotlin code. When defining variables in Kotlin, there are two options: - Mutable variables, defined by varkeyword. - Immutable variables, defined by valkeyword. The next thing to note is the syntax differs a bit from Java; first, you declare the variable name and then follow with type. Also, by default, properties are non-null types, meaning that they can’t accept null value. To define a variable to accept a null value, a question mark must be added after the type. We will talk about this and null-safety in Kotlin later. Another important thing to note is that Kotlin doesn’t have the ability to declare fields for the class; only properties can be defined. So, in this case, firstName and lastName are properties that have been assigned default getter/setter methods. As mentioned, in Kotlin, they are both public by default. Custom accessors can be written, for example: class User { var firstName: String? = null var lastName: String? = null val fullName: String? get() firstName + " " + lastName } From the outside, when it comes to syntax, properties behave like public fields in Java: val userName = user.firstName user.firstName = "John" Note that the new property fullName is read only (defined by val keyword) and has a custom getter; it simply appends first and last name. All properties in Kotlin must be assigned when declared or are in a constructor. There are some cases when that isn’t convenient; for example, for properties that will be initialized via dependency injection. In that case, a lateinit modifier can be used. Here is an example: class MyClass { lateinit var firstName : String; fun inject() { firstName = "John"; } } More details about properties can be found in the official documentation. Feature #3: Class Inheritance and Constructors Kotlin has a more concise syntax when it comes to constructors, as well. Constructors Kotlin classes have a primary constructor and one or more secondary constructors. An example of defining a primary constructor: class User constructor(firstName: String, lastName: String) { } The primary constructor goes after the class name in the class definition. If the primary constructor doesn’t have any annotations or visibility modifiers, the constructor keyword can be omitted: class Person(firstName: String) { } Note that a primary constructor cannot have any code; any initialization must be done in the init code block: class Person(firstName: String) { init { //perform primary constructor initialization here } } Furthermore, a primary constructor can be used to define and initialize properties: class User(var firstName: String, var lastName: String) { // ... } Just like regular ones, properties defined from a primary constructor can be immutable ( val) or mutable ( var). Classes may have secondary constructors as well; the syntax for defining one is as follows: class User(var firstName: String, var lastName) { constructor(name: String, parent: Person) : this(name) { parent.children.add(this) } } Note that every secondary constructor must delegate to a primary constructor. This is similar to Java, which uses this keyword: class User(val firstName: String, val lastName: String) { constructor(firstName: String) : this(firstName, "") { //... } } When instantiating classes, note that Kotlin doesn’t have new keywords, as does Java. To instantiate the aforementioned User class, use: val user = User("John", "Doe) Introducing Inheritance In Kotlin, all classes extend from Any, which is similar to Object in Java. By default, classes are closed, like final classes in Java. So, in order to extend a class, it has to be declared as open or abstract: open class User(val firstName, val lastName) class Administrator(val firstName, val lastName) : User(firstName, lastName) Note that you have to delegate to the default constructor of the extended class, which is similar to calling super() method in the constructor of a new class in Java. For more details about classes, check the official documentation. Feature #4: Lambda Expressions Lambda expressions, introduced with Java 8, are one its favorite features. However, things are not so bright on Android, as it still only supports Java 7, and looks like Java 8 won’t be supported anytime soon. So, workarounds, such as Retrolambda, bring lambda expressions to Android. With Kotlin, no additional libraries or workarounds are required. Functions in Kotlin Let’s start by quickly going over the function syntax in Kotlin: fun add(x: Int, y: Int) : Int { return x + y } The return value of the function can be omitted, and in that case, the function will return Int. It’s worth repeating that everything in Kotlin is an object, extended from Any, and there are no primitive types. An argument of the function can have a default value, for example: fun add(x: Int, y: Int = 1) : Int { return x + y; } In that case, the add() function can be invoked by passing only the x argument. The equivalent Java code would be: int add(int x) { Return add(x, 1); } int add(int x, int y) { return x + y; } Another nice thing when calling a function is that named arguments can be used. For example: add(y = 12, x = 5) For more details about functions, check the official documentation. Using Lambda Expressions in Kotlin Lambda expressions in Kotlin can be viewed as anonymous functions in Java, but with a more concise syntax. As an example, let’s show how to implement click listener in Java and Kotlin. In Java: view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(v.getContext(), "Clicked on view", Toast.LENGTH_SHORT).show(); } }; In Kotlin: view.setOnClickListener({ view -> toast("Click") }) Wow! Just one line of code! We can see that the lambda expression is surrounded by curly braces. Parameters are declared first, and the body goes after the -> sign. With click listener, type for the view parameter isn’t specified since it can be inferred. The body is simply a call to toast() function for showing toast, which Kotlin provides. Also, if parameters aren’t used, we can leave them out: view.setOnClickListener({ toast("Click") }) Kotlin has optimized Java libraries, and any function that receives an interface with one method for an argument can be called with a function argument (instead of Interface). Furthermore, if the function is the last parameter, it can be moved out of the parentheses: view.setOnClickListener() { toast("Click") } Finally, if the function has only one parameter that is a function, parentheses can be left out: view.setOnClickListener { toast("Click") } For more information, check Kotlin for Android developers book by Antonio Leiva and the official documentation. Extension Functions Kotlin, similar to C#, provides the ability to extend existing classes with new functionality by using extension functions. For example, an extension method that would calculate the MD5 hash of a String: fun String.md5(): ByteArray { val digester = MessageDigest.getInstance("MD5") digester.update(this.toByteArray(Charset.defaultCharset())) return digester.digest() } Note that the function name is preceded by the name of the extended class (in this case, String), and that the instance of the extended class is available via this keyword. Extension functions are the equivalent of Java utility functions. The example function in Java would look like: public static int toNumber(String instance) { return Integer.valueOf(instance); } The example function must be placed in a Utility class. What that means is that extension functions don’t modify the original extended class, but are a convenient way of writing utility methods. Feature #5: Null-safety One of the things you hustle the most in Java is probably NullPointerException. Null-safety is a feature that has been integrated into the Kotlin language and is so implicit you usually won’t have to worry about. The official documentation states that the only possible causes of NullPointerExceptions are: - An explicit call to throw NullPointerException. - Using the !!operator (which I will explain later). - External Java code. - If the lateinitproperty is accessed in the constructor before it is initialized, an UninitializedPropertyAccessExceptionwill be thrown. By default, all variables and properties in Kotlin are considered non-null (unable to hold a null value) if they are not explicitly declared as nullable. As already mentioned, to define a variable to accept a null value, a question mark must be added after the type. For example: val number: Int? = null However, note that the following code won’t compile: val number: Int? = null number.toString() This is because the compiler performs null checks. To compile, a null check must be added: val number: Int? = null if(number != null) { number.toString(); } This code will compile successfully. What Kotlin does in the background, in this case, is that number becomes nun-null ( Int instead of Int?) inside the if block. The null check can be simplified using safe call operator ( ?.): val number: Int? = null number?.toString() The second line will be executed only if the number is not null. You can even use the famous Elvis operator ( ?:): val number Int? = null val stringNumber = number?.toString() ?: "Number is null" If the expression on the left of ?: is not null, it is evaluated and returned. Otherwise, the result of the expression on the right is returned. Another neat thing is that you can use throw or return on the right-hand side of the Elvis operator since they are expressions in Kotlin. For example: fun sendMailToUser(user: User) { val email = user?.email ?: throw new IllegalArgumentException("User email is null") //... } The !! Operator If you want a NullPointerException thrown the same way as in Java, you can do that with the !! operator. The following code will throw a NullPointerException: val number: Int? = null number!!.toString() Casting Casting in done by using an as keyword: val x: String = y as String This is considered “Unsafe” casting, as it will throw ClassCastException if the cast is not possible, as Java does. There is a “Safe” cast operator that returns the null value instead of throwing an exception: val x: String = y as? String For more details on casting, check the Type Casts and Casts section of the official documentation, and for more details on null safety check the Null-Safety section. lateinit properties There is a case in which using lateinit properties can cause an exception similar to NullPointerException. Consider the following class: class InitTest { lateinit var s: String; init { val len = this.s.length } } This code will compile without warning. However, as soon as an instance of TestClass is created, an UninitializedPropertyAccessException will be thrown because property s is accessed before it is initialized. Feature #6: Function with() Function with() is useful and comes with the Kotlin standard library. It can be used to save some typing if you need to access many properties of an object. For example: with(helloWorldTextView) { text = "Hello World!" visibility = View.VISIBLE } It receives an object and an extension function as parameters. The code block (in the curly braces) is a lambda expression for the extension function of the object specified as the first parameter. Feature #7: Operator Overloading With Kotlin, custom implementations can be provided for a predefined set of operators. To implement an operator, a member function or an extension function with the given name must be provided. For example, to implement the multiplication operator, a member function or extension function, with the name times(argument), must be provided: operator fun String.times(b: Int): String { val buffer = StringBuffer() for (i in 1..b) { buffer.append(this) } return buffer.toString() } The example above shows an implementation of binary * operator on the String. For example, the following expression will assign value “TestTestTestTest” to a newString variable: val newString = "Test" * 4 Since extension functions can be used, it means the default behavior of the operators for all the objects can be changed. This is a double-edged sword and should be used with caution. For a list of function names for all operators that can be overloaded, check the official documentation. Another big difference compared to Java are == and != operators. Operator == translates to: a?.equals(b) ?: b === null While operator != translates to: !(a?.equals(b) ?: What that means, is that using == doesn’t make an identity check as in Java (compare if instances of an object are the same), but behaves the same way as equals() method along with null checks. To perform identity check, operators === and !== must be used in Kotlin. Feature #8: Delegated Properties Certain properties share some common behaviors. For instance: - Lazy-initialized properties that are initialized upon first access. - Properties that implement Observable in Observer pattern. - Properties that are stored in a map instead as separate fields. To make cases like this easier to implement, Kotlin supports Delegated Properties: class SomeClass { var p: String by Delegate() } This means that getter and setter functions for the property p are handled by an instance of another class, Delegate. An example of a delegate for the String property: class Delegate { operator fun getValue(thisRef: Any?, property: KProperty<*>): String { return "$thisRef, thank you for delegating '${property.name}' to me!" } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println("$value has been assigned to '${property.name} in $thisRef.'") } } The example above prints a message when a property is assigned or read. Delegates can be created for both mutable ( var) and read-only ( val) properties. For a read-only property, getValue method must be implemented. It takes two parameters (taken from the offical documentation): - receiver - must be the same or a supertype of the property owner (for extension properties, it is the type being extended). - metadata - must be of type KProperty<*>or its supertype. This function must return the same type as property, or its subtype. For a mutable property, a delegate has to provide additionally a function named setValue that takes the following parameters: - receiver - same as for getValue(). - metadata - same as for getValue(). - new value - must be of the same type as a property or its supertype. There are a few standard delegates that come with Kotlin that cover the most common situations: - Lazy - Observable - Vetoable Lazy Lazy is a standard delegate that takes a lambda expression as a parameter. The lambda expression passed is executed the first time getValue() method is called. By default, the evaluation of lazy properties is synchronized. If you are not concerned with multi-threading, you can use lazy(LazyThreadSafetyMode.NONE) { … } to get extra performance. Observable The Delegates.observable() is for properties that should behave as Observables in Observer pattern. It accepts two parameters, the initial value and a function that has three arguments (property, old value, and new value). The given lambda expression will be executed every time setValue() method is called: class User { var email: String by Delegates.observable("") { prop, old, new -> //handle the change from old to new value } } Vetoable This standard delegate is a special kind of Observable that lets you decide whether a new value assigned to a property will be stored or not. It can be used to check some conditions before assigning a value. As with Delegates.observable(), it accepts two parameters: the initial value, and a function. The difference is that the function returns a Boolean value. If it returns true, the new value assigned to the property will be stored, or otherwise discarded. var positiveNumber = Delegates.vetoable(0) { d, old, new -> new >= 0 } The given example will store only positive numbers that are assigned to the property. For more details, check the official documentation. Feature #9: Mapping an Object to a Map A common use case is to store values of the properties inside a map. This often happens in applications that work with RESTful APIs and parses JSON objects. In this case, a map instance can be used as a delegate for a delegated property. An example from the official documentation: class User(val map: Map<String, Any?>) { val name: String by map val age: Int by map } In this example, User has a primary constructor that takes a map. The two properties will take the values from the map that are mapped under keys that are equal to property names: val user = User(mapOf( "name" to "John Doe", "age" to 25 )) The name property of the new user instance will be assigned the value of “John Doe” and age property the value 25. This works for var properties in combination with MutableMap as well: class MutableUser(val map: MutableMap<String, Any?>) { var name: String by map var age: Int by map } Feature #10: Collections and Functional Operations With the support for lambdas in Kotlin, collections can be leveraged to a new level. First of all, Kotlin distinguishes between mutable and immutable collections. For example, there are two versions of Iterable interface: - Iterable - MutableIterable The same goes for Collection, List, Set and Map interfaces. For example, this any operation returns true if at least one element matches the given predicate: val list = listOf(1, 2, 3, 4, 5, 6) assertTrue(list.any { it % 2 == 0 }) For an extensive list of functional operations that can be done on collections, check this blog post. Conclusion We have just scratched the surface of what Kotlin offers. For those interested in further reading and learning more, check: - Antonio Leiva’s Kotlin blog posts and book. - Official documentation and tutorials from JetBrains. To sum up, Kotlin offers you the ability to save time when writing native Android applications by using an intuitive and concise syntax. It is still a young programming language, but in my opinion, it is now stable enough to be used for building production apps. The benefits of using Kotlin: - Support by Android Studio is seamless and excellent. - It is easy to convert an existing Java project to Kotlin. - Java and Kotlin code may coexist in the same project. - There is no speed overhead in the application. The downsides: - Kotlin will add its libraries to the generated .apk, so the final .apksize will be about 300KB larger. - If abused, operator overloading can lead to unreadable code. - IDE and Autocomplete behaves a little slower when working with Kotlin than it does with pure Java Android projects. - Compilation times can be a bit longer.
https://www.toptal.com/android/kotlin-boost-android-development
CC-MAIN-2022-27
en
refinedweb
Hi, I recently wrote a small script that takes all the layer sourcing in the currently open map (ArcPro 2.5.1) over to a new database contained in enterprise. I have several team members that also need to use this tool as we migrate from one db to another and republish our templates in the new enterprise portal. I thought a webtool would be the best way to share this tool rather than emailing the code out and showing each member how to set up the ArcPro Script tool. The publishing of the tool worked great, but when I pull it in I keep getting an error when I try to reference the following: aprx = arcpy.mp.ArcGISProject('CURRENT') map_ = aprx.activeMap This code works if the script tool is run locally without error but when the gp tool is pulled into pro from portal and run from there, I get the following error: Do I have to explicitly request for a project as a parameter as well as a map document? Or is there something I am missing between running a script tool locally vs over portal? Full code is below: import arcpy aprx = arcpy.mp.ArcGISProject('CURRENT') map_ = aprx.activeMap for layer in map_.listLayers(): conProps = layer.connectionProperties conProps['connection_info']['db_connection_properties'] = '<mydatabase>' conProps['connection_info']['instance'] = 'sde:postgresql:<mydatabase>' conProps['connection_info']['server'] = '<mydatabase>' layer.updateConnectionProperties(layer.connectionProperties, conProps) aprx.save()
https://community.esri.com/t5/python-questions/referencing-the-current-open-map-document-from-a/td-p/1007729
CC-MAIN-2022-27
en
refinedweb
Having recently adapted targets for my model to follow a distribution pattern I am using KLDivLoss as my loss function. I know that for stability the PyTorch KLDivLoss implementation uses log-probabilities as input and hence the output of my final layer is transformed using log_softmax. My 2 questions are: Am I correct in assuming that to convert the output of log_softmaxback to normal softmax (i.e. a vector of probabilities representing a probability distribution) I would take the natural exponent of the output? Hence if the model output is output = log_softmax(dense, dim=1)then I could do np.exp(output)to get the vector back to the range of my y_targets?? Upon doing the above and training my model the output is 5 orders of magnitude smaller than the y_targets! I know the model as a whole usually works (I was using more discrete y_targets before with this model and MSE loss which worked very well). The abbreviated code is below: Model Class: def build_model(self): ''' Main model build code... ''' self.dense = nn.Linear(self.c['hidden_size'], self.c['y_distribution_size']) self.loss = nn.KLDivLoss() self.optimizer = optim.AdamW(self.parameters(), lr=self.c['optim_lr']) def forward(self): ''' Main model forward code... ''' dense = self.dense(self.dropout(self.sigmoid(x_out))) return log_softmax(dense, dim=1) def fit(self): ''' Main model fit code... ''' self.optimizer.zero_grad() model_out = self(x) loss = self.loss(model_out, y) loss.backward() self.optimizer.step() Y_target Tensor Shape: (N, 5) Where each N has a vector such as [0.2, 0.4, 0.4, 0, 0] (sum of probabilities = 1) Mode Output Tensor y_pred = model(x) where y_pred example is: [-12.440563, -12.761744, -13.408863, -12.697731, -12.389305] and I am converting it to y_p_pred = np.exp(y_pred) which gives an example result of: [3.9548686e-06, 2.8684360e-06, 1.5017746e-06, 3.0580563e-06, 4.1628732e-06] (sum of probabilities = 1.554601e-05 for that particular example)! So I am trying to get the model to fit the resultant y_p_pred to y_target.
https://discuss.pytorch.org/t/kldivloss-and-transforming-back-to-probabilities/114700
CC-MAIN-2022-27
en
refinedweb
Perceiver IO for vision (convolutional processing) Perceiver IO model pre-trained on ImageNet (14 million images, 1,000 classes) at resolution 224x224. It was introduced in the paper Perceiver IO: A General Architecture for Structured Inputs & Outputs by Jaegle et al. and first released in this repository. Disclaimer: The team releasing Perceiver IO did not write a model card for this model so this model card has been written by the Hugging Face team. Model description Perceiver IO is a transformer encoder model that can be applied on any modality (text, images, audio, video, ...). The core idea is to employ the self-attention mechanism on a not-too-large set of latent vectors (e.g. 256 or 512), and only use the inputs to perform cross-attention with the latents. This allows for the time and memory requirements of the self-attention mechanism to not depend on the size of the inputs. To decode, the authors employ so-called decoder queries, which allow to flexibly decode the final hidden states of the latents to produce outputs of arbitrary size and semantics. For image classification, the output is a tensor containing the logits, of shape (batch_size, num_labels). Perceiver IO architecture. As the time and memory requirements of the self-attention mechanism don't depend on the size of the inputs, the Perceiver IO authors can train the model directly on raw pixel values, rather than on patches as is done in ViT. This particular model employs a simple 2D conv+maxpool preprocessing network on the pixel values, before using the inputs for cross-attention with the latents. By pre-training the model, it learns an inner representation of images that can then be used to extract features useful for downstream tasks: if you have a dataset of labeled images for instance, you can train a standard classifier by replacing the classification decoder. Intended uses & limitations You can use the raw model for image classification. See the model hub to look for other fine-tuned versions on a task that may interest you. How to use Here is how to use this model in PyTorch: from transformers import PerceiverFeatureExtractor, PerceiverForImageClassificationConvProcessing import requests from PIL import Image feature_extractor = PerceiverFeatureExtractor.from_pretrained("deepmind/vision-perceiver-conv") model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv") url = "" image = Image.open(requests.get(url, stream=True).raw) # prepare input inputs = feature_extractor(image, return_tensors="pt").pixel_values # forward pass outputs = model(inputs) logits = outputs.logits print("Predicted class:", model.config.id2label[logits.argmax(-1).item()]) should print Predicted class: tabby, tabby cat Training data This model was pretrained on ImageNet, a dataset consisting of 14 million images and 1k classes. Training procedure Preprocessing Images are center cropped and resized to a resolution of 224x224 and normalized across the RGB channels. Note that data augmentation was used during pre-training, as explained in Appendix H of the paper. Pretraining Hyperparameter details can be found in Appendix H of the paper. Evaluation results This model is able to achieve a top-1 accuracy of 82.1 on ImageNet-1k. BibTeX entry and citation info @article{DBLP:journals/corr/abs-2107-14795, author = {Andrew Jaegle and Sebastian Borgeaud and Jean{-}Baptiste Alayrac and Carl Doersch and Catalin Ionescu and David Ding and Skanda Koppula and Daniel Zoran and Andrew Brock and Evan Shelhamer and Olivier J. H{\'{e}}naff and Matthew M. Botvinick and Andrew Zisserman and Oriol Vinyals and Jo{\~{a}}o Carreira}, title = {Perceiver {IO:} {A} General Architecture for Structured Inputs {\&} Outputs}, journal = {CoRR}, volume = {abs/2107.14795}, year = {2021}, url = {}, eprinttype = {arXiv}, eprint = {2107.14795}, timestamp = {Tue, 03 Aug 2021 14:53:34 +0200}, biburl = {}, bibsource = {dblp computer science bibliography,} } - Downloads last month - 1,093
https://huggingface.co/deepmind/vision-perceiver-conv
CC-MAIN-2022-27
en
refinedweb
SYNOPSIS #include <pslib.h> PSDoc * PS_new2((void (*errorhandler)(PSDoc *p, int type, const char *msg), void* (*allocproc)(PSDoc *p, size_t size, const char *caller), void* (*reallocproc)(PSDoc *p, void *mem, size_t size, const char *caller), void (*freeproc)(PSDoc *p, void *mem), void *opaque) DESCRIPTION Creates a new document instance. It does not create the file on disk or in memory. It just sets up everything. You may pass your own error handler and memory management functions. If you pass NULL values the internal default handler and functions will be used. In such case you may as well call PS_new(3). RETURN VALUE Pointer to new instance of PostScript document or NULL on failure. AUTHOR This manual page was written by Uwe Steinmann [email protected]
https://manpages.org/ps_new2/3
CC-MAIN-2022-27
en
refinedweb
Tutorial: Develop and plan provisioning for a SCIM endpoint in Azure Active Directory As an application developer, you can use the System for Cross-Domain Identity Management (SCIM) user management API to enable automatic provisioning of users and groups between your application and Azure AD. This article describes how to build a SCIM endpoint and integrate with the Azure AD provisioning service. The SCIM specification provides a common user schema for provisioning. When used in conjunction with federation standards like SAML or OpenID Connect, SCIM gives administrators an end-to-end, standards-based solution for access management. SCIM is a standardized definition of two endpoints: a /Users endpoint and a /Groups endpoint. It uses. Instead of needing a slightly different API for the same basic actions, apps that conform to the SCIM standard a SCIM endpoint can integrate with any SCIM-compliant client without having to do custom work. To automate provisioning to an application will require building and integrating a SCIM endpoint with the Azure AD SCIM client. Use the following steps to start provisioning users and groups into your application. Design your user and group schema Identify the application's objects and attributes to determine how they map to the user and group schema supported by the Azure AD SCIM implementation. Understand the Azure AD SCIM implementation Understand how the Azure AD SCIM client is implemented to model your SCIM protocol request handling and responses. Build a SCIM endpoint An endpoint must be SCIM 2.0-compatible to integrate with the Azure AD provisioning service. As an option, use Microsoft Common Language Infrastructure (CLI) libraries and code samples to build your endpoint. These samples are for reference and testing only; we recommend against using them as dependencies in your production app. Integrate your SCIM endpoint with the Azure AD SCIM client If your organization uses a third-party application to implement a profile of SCIM 2.0 that Azure AD supports, you can quickly automate both provisioning and deprovisioning of users and groups. Publish your application to the Azure AD application gallery Make it easy for customers to discover your application and easily configure provisioning. Design your user and group schema Each application requires different attributes to create a user or group. Start your integration by identifying the required objects (users, groups) and attributes (name, manager, job title, etc.) that your application needs. The SCIM standard defines a schema for managing users and groups. The core user schema only requires three attributes (all other attributes are optional): id, service provider defined identifier userName, a unique identifier for the user (generally maps to the Azure AD user principal name) meta, read-only metadata maintained by the service provider In addition to the core user schema, the SCIM standard defines an enterprise user extension with a model for extending the user schema to meet your application’s needs. For example, if your application requires both a user's email and user’s manager, use the core schema to collect the user’s email and the enterprise user schema to collect the user’s manager. To design your schema, follow these steps: List the attributes your application requires, then categorize as attributes needed for authentication (e.g. loginName and email), attributes needed to manage the user lifecycle (e.g. status / active), and all other attributes needed for the application to work (e.g. manager, tag). Check if the attributes are already defined in the core user schema or enterprise user schema. If not, you must define an extension to the user schema that covers the missing attributes. See example below for an extension to the user to allow provisioning a user tag. Map SCIM attributes to the user attributes in Azure AD. If one of the attributes you have defined in your SCIM endpoint does not have a clear counterpart on the Azure AD user schema, guide the tenant administrator to extend their schema or use an extension attribute as shown below for the tagsproperty. Example list of required attributes { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User", "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", "urn:ietf:params:scim:schemas:extension:CustomExtensionName:2.0:User"], "userName":"bjensen@testuser.com", "id": "48af03ac28ad4fb88478", "externalId":"bjensen", "name":{ "familyName":"Jensen", "givenName":"Barbara" }, "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User": { "Manager": "123456" }, "urn:ietf:params:scim:schemas:extension:CustomExtensionName:2.0:User": { "tag": "701984", }, "meta": { "resourceType": "User", "created": "2010-01-23T04:56:22Z", "lastModified": "2011-05-13T04:42:34Z", "version": "W\/\"3694e05e9dff591\"", "location": "" } } Example schema defined by a JSON payload Note In addition to the attributes required for the application, the JSON representation also includes the required id, externalId, and meta attributes. It helps to categorize between /User and /Group to map any default user attributes in Azure AD to the SCIM RFC, see how customize attributes are mapped between Azure AD and your SCIM endpoint. Example list of user and group attributes Example list of group attributes Note You are not required to support both users and groups, or all the attributes shown here, it's only a reference on how attributes in Azure AD are often mapped to properties in the SCIM protocol. There are several endpoints defined in the SCIM RFC. You can start with the /User endpoint and then expand from there. Example list of endpoints Note Use the /Schemas endpoint to support custom attributes or if your schema changes frequently as it enables a client to retrieve the most up-to-date schema automatically. Use the /Bulk endpoint to support groups. Understand the Azure AD SCIM implementation To support a SCIM 2.0 user management API, this section describes how the Azure AD SCIM client is implemented and shows how to model your SCIM protocol request handling and responses. Important The behavior of the Azure AD SCIM implementation was last updated on December 18, 2018. For information on what changed, see SCIM 2.0 protocol compliance of the Azure AD User Provisioning service. Within the SCIM 2.0 protocol specification, your application must support these requirements: Use the general guidelines when implementing a SCIM endpoint to ensure compatibility with Azure AD: General: idis a required property for all resources. Every response that returns a resource should ensure each resource has this property, except for ListResponsewith zero members. - Values sent should be stored in the same format as what they were sent in. Invalid values should be rejected with a descriptive, actionable error message. Transformations of data should not happen between data being sent by Azure AD and data being stored in the SCIM application. (e.g. A phone number sent as 55555555555 should not be saved/returned as +5 (555) 555-5555) - It isn't necessary to include the entire resource in the PATCH response. - Don't require a case-sensitive match on structural elements in SCIM, in particular PATCH opoperation values, as defined in section 3.5.2. Azure AD emits the values of opas Add, Replace, and Remove. - Microsoft Azure AD makes requests to fetch a random user and group to ensure that the endpoint and the credentials are valid. It's also done as a part of the Test Connection flow in the Azure portal. - Support HTTPS on your SCIM endpoint. - Custom complex and multivalued attributes are supported but Azure AD does not have many complex data structures to pull data from in these cases. Simple paired name/value type complex attributes can be mapped to easily, but flowing data to complex attributes with three or more subattributes are not well supported at this time. - The "type" sub-attribute values of multivalued complex attributes must be unique. For example, there cannot be two different email addresses with the "work" sub-type. Retrieving Resources: - Response to a query/filter request should always be a ListResponse. - Microsoft Azure AD only uses the following operators: eq, and - The attribute that the resources can be queried on should be set as a matching attribute on the application in the Azure portal, see Customizing User Provisioning Attribute Mappings. /Users: - The entitlements attribute is not supported. - Any attributes that are considered for user uniqueness must be usable as part of a filtered query. (e.g. if user uniqueness is evaluated for both userName and emails[type eq "work"], a GET to /Users with a filter must allow for both userName eq "user@contoso.com" and emails[type eq "work"].value eq "user@contoso.com" queries. /Groups: - Groups are optional, but only supported if the SCIM implementation supports PATCH requests. - Groups must have uniqueness on the 'displayName' value for the purpose of matching between Azure Active Directory and the SCIM application. This is not a requirement of the SCIM protocol, but is a requirement for integrating a SCIM service with Azure Active Directory. /Schemas (Schema discovery): - Sample request/response - Schema discovery is not currently supported on the custom non-gallery SCIM application, but it is being used on certain gallery applications. Going forward, schema discovery will be used as the sole method to add additional attributes to the schema of an existing gallery SCIM application. - If a value is not present, do not send null values. - Property values should be camel cased (e.g. readWrite). - Must return a list response. - The /schemas request will be made by the Azure AD SCIM client every time someone saves the provisioning configuration in the Azure portal or every time a user lands on the edit provisioning page in the Azure portal. Any additional attributes discovered will be surfaced to customers in the attribute mappings under the target attribute list. Schema discovery only leads to additional target attributes being added. It will not result in attributes being removed. User provisioning and deprovisioning The following illustration shows the messages that Azure AD sends to a SCIM service to manage the lifecycle of a user in your application's identity store. User provisioning and deprovisioning sequence Group provisioning and deprovisioning Group provisioning and deprovisioning are optional. When implemented and enabled, the following illustration shows the messages that Azure AD sends to a SCIM service to manage the lifecycle of a group in your application's identity store. Those messages differ from the messages about users in two ways: - Requests to retrieve groups specify that the members attribute is to be excluded from any resource provided in response to the request. - Requests to determine whether a reference attribute has a certain value are requests about the members attribute. Group provisioning and deprovisioning sequence SCIM protocol requests and responses This section provides example SCIM requests emitted by the Azure AD SCIM client and example expected responses. For best results, you should code your app to handle these requests in this format and emit the expected responses. Important To understand how and when the Azure AD user provisioning service emits the operations described below, see the section Provisioning cycles: Initial and incremental in How provisioning works. - Create User (Request / Response) - Get User (Request / Response) - Get User by query (Request / Response) - Get User by query - Zero results (Request / Response) - Update User [Multi-valued properties] (Request / Response) - Update User [Single-valued properties] (Request / Response) - Disable User (Request / Response) - Delete User (Request / Response) - Create Group (Request / Response) - Get Group (Request / Response) - Get Group by displayName (Request / Response) - Update Group [Non-member attributes] (Request / Response) - Update Group [Add Members] (Request / Response) - Update Group [Remove Members] (Request / Response) - Delete Group (Request / Response) User Operations - Users can be queried by userNameor Create User": [] } Response HTTP }] } Get User Request GET /Users/5d48a0a8e9f04aa38008 Response (User found) GET /Users/5171a35d82074e068ce2 Response (User not found. Note that the detail is not required, only status.) { "schemas": [ "urn:ietf:params:scim:api:messages:2.0:Error" ], "status": "404", "detail": "Resource 23B51B0E5D7AE9110A49411D@7cca31655d49f3640a494224 not found" } Get User by query Request GET /Users?filter=userName eq "Test_User_dfeef4c5-5681-4387-b016-bdf221e82081" Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 1, "Resources": [{ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "id": "2441309d85324e7793ae", "externalId": "7fce0092-d52e-4f76-b727-3955bd72c939", "meta": { "resourceType": "User", "created": "2018-03-27T19:59:26.000Z", "lastModified": "2018-03-27T19:59:26.000Z" }, "userName": "Test_User_dfeef4c5-5681-4387-b016-bdf221e82081", "name": { "familyName": "familyName", "givenName": "givenName" }, "active": true, "emails": [{ "value": "Test_User_91b67701-697b-46de-b864-bd0bbe4f99c1@testuser.com", "type": "work", "primary": true }] }], "startIndex": 1, "itemsPerPage": 20 } Get User by query - Zero results Request GET /Users?filter=userName eq "non-existent user" Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 0, "Resources": [], "startIndex": 1, "itemsPerPage": 20 } Update User [Multi-valued properties] Request PATCH /Users/6764549bef60420686bc HTTP/1.1 { "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [ { "op": "Replace", "path": "emails[type eq \"work\"].value", "value": "updatedEmail@microsoft.com" }, { "op": "Replace", "path": "name.familyName", "value": "updatedFamilyName" } ] } Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "id": "6764549bef60420686bc", "externalId": "6c75de36-30fa-4d2d-a196-6bdcdb6b6539", "meta": { "resourceType": "User", "created": "2018-03-27T19:59:26.000Z", "lastModified": "2018-03-27T19:59:26.000Z" }, "userName": "Test_User_fbb9dda4-fcde-4f98-a68b-6c5599e17c27", "name": { "formatted": "givenName updatedFamilyName", "familyName": "updatedFamilyName", "givenName": "givenName" }, "active": true, "emails": [{ "value": "updatedEmail@microsoft.com", "type": "work", "primary": true }] } Update User [Single-valued properties] Request PATCH /Users/5171a35d82074e068ce2 HTTP/1.1 { "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "userName", "value": "5b50642d-79fc-4410-9e90-4c077cdd1a59@testuser.com" }] } Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], "id": "5171a35d82074e068ce2", "externalId": "aa1eca08-7179-4eeb-a0be-a519f7e5cd1a", "meta": { "resourceType": "User", "created": "2018-03-27T19:59:26.000Z", "lastModified": "2018-03-27T19:59:26.000Z" }, "userName": "5b50642d-79fc-4410-9e90-4c077cdd1a59@testuser.com", "name": { "formatted": "givenName familyName", "familyName": "familyName", "givenName": "givenName", }, "active": true, "emails": [{ "value": "Test_User_49dc1090-aada-4657-8434-4995c25a00f7@testuser.com", "type": "work", "primary": true }] } Disable User Request PATCH /Users/5171a35d82074e068ce2 HTTP/1.1 { "Operations": [ { "op": "Replace", "path": "active", "value": false } ], "schemas": [ "urn:ietf:params:scim:api:messages:2.0:PatchOp" ] } Response { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User" ], "id": "CEC50F275D83C4530A495FCF@834d0e1e5d8235f90a495fda", "userName": "deanruiz@testuser.com", "name": { "familyName": "Harris", "givenName": "Larry" }, "active": false, "emails": [ { "value": "gloversuzanne@testuser.com", "type": "work", "primary": true } ], "addresses": [ { "country": "ML", "type": "work", "primary": true } ], "meta": { "resourceType": "Users", "location": "/scim/5171a35d82074e068ce2/Users/CEC50F265D83B4530B495FCF@5171a35d82074e068ce2" } } Delete User Request DELETE /Users/5171a35d82074e068ce2 HTTP/1.1 Response HTTP/1.1 204 No Content Group Operations - Groups shall always be created with an empty members list. - Groups can be queried by the displayNameattribute. - Update to the group PATCH request should yield an HTTP 204 No Content in the response. Returning a body with a list of all the members isn't advisable. - It isn't necessary to support returning all the members of the group. Create Group Request POST /Groups HTTP/1.1 { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group", ""], "externalId": "8aa1a0c0-c4c3-4bc0-b4a5-2ef676900159", "displayName": "displayName", "meta": { "resourceType": "Group" } } Response HTTP/1.1 201 Created { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "id": "927fa2c08dcb4a7fae9e", "externalId": "8aa1a0c0-c4c3-4bc0-b4a5-2ef676900159", "meta": { "resourceType": "Group", "created": "2018-03-27T19:59:26.000Z", "lastModified": "2018-03-27T19:59:26.000Z" }, "displayName": "displayName", "members": [] } Get Group Request GET /Groups/40734ae655284ad3abcc?excludedAttributes=members HTTP/1.1 Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "id": "40734ae655284ad3abcc", "externalId": "60f1bb27-2e1e-402d-bcc4-ec999564a194", "meta": { "resourceType": "Group", "created": "2018-03-27T19:59:26.000Z", "lastModified": "2018-03-27T19:59:26.000Z" }, "displayName": "displayName", } Get Group by displayName Request GET /Groups?excludedAttributes=members&filter=displayName eq "displayName" HTTP/1.1 Response HTTP/1.1 200 OK { "schemas": ["urn:ietf:params:scim:api:messages:2.0:ListResponse"], "totalResults": 1, "Resources": [{ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "id": "8c601452cc934a9ebef9", "externalId": "0db508eb-91e2-46e4-809c-30dcbda0c685", "meta": { "resourceType": "Group", "created": "2018-03-27T22:02:32.000Z", "lastModified": "2018-03-27T22:02:32.000Z", }, "displayName": "displayName", }], "startIndex": 1, "itemsPerPage": 20 } Update Group [Non-member attributes] Request PATCH /Groups/fa2ce26709934589afc5 HTTP/1.1 { "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Replace", "path": "displayName", "value": "1879db59-3bdf-4490-ad68-ab880a269474updatedDisplayName" }] } Response HTTP/1.1 204 No Content Update Group [Add Members] Request PATCH /Groups/a99962b9f99d4c4fac67 HTTP/1.1 { "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Add", "path": "members", "value": [{ "$ref": null, "value": "f648f8d5ea4e4cd38e9c" }] }] } Response HTTP/1.1 204 No Content Update Group [Remove Members] Request PATCH /Groups/a99962b9f99d4c4fac67 HTTP/1.1 { "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [{ "op": "Remove", "path": "members", "value": [{ "$ref": null, "value": "f648f8d5ea4e4cd38e9c" }] }] } Response HTTP/1.1 204 No Content Delete Group Request DELETE /Groups/cdb1ce18f65944079d37 HTTP/1.1 Response HTTP/1.1 204 No Content Schema discovery Discover schema Request GET /Schemas Response HTTP/1.1 200 OK { "schemas": [ "urn:ietf:params:scim:api:messages:2.0:ListResponse" ], "itemsPerPage": 50, "startIndex": 1, "totalResults": 3, "Resources": [ { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Schema"], "id" : "urn:ietf:params:scim:schemas:core:2.0:User", "name" : "User", "description" : "User Account", "attributes" : [ { "name" : "userName", "type" : "string", "multiValued" : false, "description" : "Unique identifier for the User, typically used by the user to directly authenticate to the service provider. Each User MUST include a non-empty userName value. This identifier MUST be unique across the service provider's entire set of Users. REQUIRED.", "required" : true, "caseExact" : false, "mutability" : "readWrite", "returned" : "default", "uniqueness" : "server" }, ], "meta" : { "resourceType" : "Schema", "location" : "/v2/Schemas/urn:ietf:params:scim:schemas:core:2.0:User" } }, { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Schema"], "id" : "urn:ietf:params:scim:schemas:core:2.0:Group", "name" : "Group", "description" : "Group", "attributes" : [ { "name" : "displayName", "type" : "string", "multiValued" : false, "description" : "A human-readable name for the Group. REQUIRED.", "required" : false, "caseExact" : false, "mutability" : "readWrite", "returned" : "default", "uniqueness" : "none" }, ], "meta" : { "resourceType" : "Schema", "location" : "/v2/Schemas/urn:ietf:params:scim:schemas:core:2.0:Group" } }, { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Schema"], "id" : "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User", "name" : "EnterpriseUser", "description" : "Enterprise User", "attributes" : [ { "name" : "employeeNumber", "type" : "string", "multiValued" : false, "description" : "Numeric or alphanumeric identifier assigned to a person, typically based on order of hire or association with an organization.", "required" : false, "caseExact" : false, "mutability" : "readWrite", "returned" : "default", "uniqueness" : "none" }, ], "meta" : { "resourceType" : "Schema", "location" : "/v2/Schemas/urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" } } ] } Security requirements TLS Protocol Versions The only acceptable TLS protocol versions are TLS 1.2 and TLS 1.3. No other versions of TLS are permitted. No version of SSL is permitted. - RSA keys must be at least 2,048 bits. - ECC keys must be at least 256 bits, generated using an approved elliptic curve Key Lengths All services must use X.509 certificates generated using cryptographic keys of sufficient length, meaning: Cipher Suites All services must be configured to use the following cipher suites, in the exact order specified below. Note that if you only have an RSA certificate, installed the ECDSA cipher suites do not have any effect. TLS 1.2 Cipher Suites minimum bar: - IP Ranges The Azure AD provisioning service currently operates under the IP Ranges for AzureActiveDirectory as listed here. You can add the IP ranges listed under the AzureActiveDirectory tag to allow traffic from the Azure AD provisioning service into your application. Note that you will need to review the IP range list carefully for computed addresses. An address such as '40.126.25.32' could be represented in the IP range list as '40.126.0.0/18'. You can also programmatically retrieve the IP range list using the following API. Azure AD also supports an agent based solution to provide connectivity to applications in private networks (on-premises, hosted in Azure, hosted in AWS, etc.). Customers can deploy a lightweight agent, which provides connectivity to Azure AD without opening any inbound ports, on a server in their private network. Learn more here. Build a SCIM endpoint Now that you have designed your schema and understood the Azure AD SCIM implementation, you can get started developing your SCIM endpoint. Rather than starting from scratch and building the implementation completely on your own, you can rely on a number of open source SCIM libraries published by the SCIM community. For guidance on how to build a SCIM endpoint including examples, see Develop a sample SCIM endpoint. The open source .NET Core reference code example published by the Azure AD provisioning team is one such resource that can jump start your development. Once you have built your SCIM endpoint, you will want to test it out. You can use the collection of postman tests provided as part of the reference code or run through the sample requests / responses provided above. Note The reference code is intended to help you get started building your SCIM endpoint and is provided "AS IS." Contributions from the community are welcome to help build and maintain the code. The solution is composed of two projects, Microsoft.SCIM and Microsoft.SCIM.WebHostSample. The Microsoft.SCIM project is the library that defines the components of the web service that conforms to the SCIM specification. It declares the interface Microsoft.SCIM.IProvider, requests are translated into calls to the provider’s methods, which would be programmed to operate on an identity store. The Microsoft.SCIM.WebHostSample project is a Visual Studio ASP.NET Core Web Application, based on the Empty template. This allows the sample code to be deployed as standalone, hosted in containers or within Internet Information Services. It also implements the Microsoft.SCIM.IProvider interface keeping classes in memory as a sample identity store. public class Startup { ... public IMonitor MonitoringBehavior { get; set; } public IProvider ProviderBehavior { get; set; } public Startup(IWebHostEnvironment env, IConfiguration configuration) { ... this.MonitoringBehavior = new ConsoleMonitor(); this.ProviderBehavior = new InMemoryProvider(); } ... Building a custom SCIM endpoint The SCIM service must have an HTTP address and server authentication certificate of which the root certification authority is one of the following names: - CNNIC - Comodo - CyberTrust - DigiCert - GeoTrust - GlobalSign - Go Daddy - VeriSign - WoSign - DST Root CA X3 The .NET Core SDK includes an HTTPS development certificate that can be used during development, the certificate is installed as part of the first-run experience. Depending on how you run the ASP.NET Core Web Application it will listen to a different port: - Microsoft.SCIM.WebHostSample: - IIS Express: For more information on HTTPS in ASP.NET Core use the following link: Enforce HTTPS in ASP.NET Core Handling endpoint authentication Requests from Azure Active Directory include an OAuth 2.0 bearer token. Any service receiving the request should authenticate the issuer as being Azure Active Directory for the expected Azure Active Directory tenant. In the token, the issuer is identified by an iss claim, like "iss":"". In this example, the base address of the claim value,, identifies Azure Active Directory as the issuer, while the relative address segment, cbb1a5ac-f33b-45fa-9bf5-f37db0fed422, is a unique identifier of the Azure Active Directory tenant for which the token was issued. The audience for the token will be the application template ID for the application in the gallery, each of the applications registered in a single tenant may receive the same iss claim with SCIM requests. The application template ID for all custom apps is 8adf8e6e-67b2-4cf2-a259-e3dc5476c621. The token generated by the Azure AD provisioning service should only be used for testing. It should not be used in production environments. In the sample code, requests are authenticated using the Microsoft.AspNetCore.Authentication.JwtBearer package. The following code enforces that requests to any of the service’s endpoints are authenticated using the bearer token issued by Azure Active Directory for a specified tenant: public void ConfigureServices(IServiceCollection services) { if (_env.IsDevelopment()) { ... } else { services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = ""; options.Audience = "8adf8e6e-67b2-4cf2-a259-e3dc5476c621"; ... }); } ... } public void Configure(IApplicationBuilder app) { ... app.UseAuthentication(); app.UseAuthorization(); ... } A bearer token is also required to use of the provided postman tests and perform local debugging using localhost. The sample code uses ASP.NET Core environments to change the authentication options during development stage and enable the use a self-signed token. For more information on multiple environments in ASP.NET Core, see Use multiple environments in ASP.NET Core. The following code enforces that requests to any of the service’s endpoints are authenticated using a bearer token signed with a custom key: public void ConfigureServices(IServiceCollection services) { if (_env.IsDevelopment()) { TokenValidationParameters { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, ValidateIssuerSigningKey = false, ValidIssuer = "Microsoft.Security.Bearer", ValidAudience = "Microsoft.Security.Bearer", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("A1B2C3D4E5F6A1B2C3D4E5F6")) }; }); } ... Send a GET request to the Token controller to get a valid bearer token, the method GenerateJSONWebToken is responsible to create a token matching the parameters configured for development: private string GenerateJSONWebToken() { // Create token key SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("A1B2C3D4E5F6A1B2C3D4E5F6")); SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); // Set token expiration DateTime startTime = DateTime.UtcNow; DateTime expiryTime = startTime.AddMinutes(120); // Generate the token JwtSecurityToken token = new JwtSecurityToken( "Microsoft.Security.Bearer", "Microsoft.Security.Bearer", null, notBefore: startTime, expires: expiryTime, signingCredentials: credentials); string result = new JwtSecurityTokenHandler().WriteToken(token); return result; } Handling provisioning and deprovisioning of users Example 1. Query the service for a matching user Azure Active Directory queries the service for a user with an externalId attribute value matching the mailNickname attribute value of a user in Azure AD. The query is expressed as a Hypertext Transfer Protocol (HTTP) request such as this example, wherein jyoung is a sample of a mailNickname of a user in Azure Active Directory. Note This is an example only. Not all users will have a mailNickname attribute, and the value a user has may not be unique in the directory. Also, the attribute used for matching (which in this case is externalId) is configurable in the Azure AD attribute mappings. GET eq jyoung HTTP/1.1 Authorization: Bearer ... In the sample code the request is translated into a call to the Query. // Microsoft.SCIM.IQueryParameters is defined in // Microsoft.SCIM.Protocol. Task<Resource[]> QueryAsync(IRequest<IQueryParameters> request); In the sample query, for a user with a given value for the externalId attribute, values of the arguments passed to the QueryAsync method are: - parameters.AlternateFilters.Count: 1 - parameters.AlternateFilters.ElementAt(0).AttributePath: "externalId" - parameters.AlternateFilters.ElementAt(0).ComparisonOperator: ComparisonOperator.Equals - parameters.AlternateFilter.ElementAt(0).ComparisonValue: "jyoung" Example 2. Provision a user If the response to a query to the web service for a user with an externalId attribute value that matches the mailNickname attribute value of a user doesn't return any users, then Azure AD requests that the service provision a user corresponding to the one in Azure AD. Here is an example of such a request: POST HTTP/1.1 Authorization: Bearer ... Content-type: application/scim+json { "schemas": [ "urn:ietf:params:scim:schemas:core:2.0:User", "urn:ietf:params:scim:schemas:extension:enterprise:2.0User"], "externalId":"jyoung", "userName":"jyoung@testuser.com", "active":true, "addresses":null, "displayName":"Joy Young", "emails": [ { "type":"work", "value":"jyoung@Contoso.com", "primary":true}], "meta": { "resourceType":"User"}, "name":{ "familyName":"Young", "givenName":"Joy"}, "phoneNumbers":null, "preferredLanguage":null, "title":null, "department":null, "manager":null} In the sample code the request is translated into a call to the Create. Task<Resource> CreateAsync(IRequest<Resource> request); In a request to provision a user, the value of the resource argument is an instance of the Microsoft.SCIM.Core2EnterpriseUser class, defined in the Microsoft.SCIM.Schemas library. If the request to provision the user succeeds, then the implementation of the method is expected to return an instance of the Microsoft.SCIM.Core2EnterpriseUser class, with the value of the Identifier property set to the unique identifier of the newly provisioned user. Example 3. Query the current state of a user To update a user known to exist in an identity store fronted by an SCIM, Azure Active Directory proceeds by requesting the current state of that user from the service with a request such as: GET ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1 Authorization: Bearer ... In the sample code the request is translated into a call to the RetrieveAsync method of the service’s provider. Here is the signature of that method: // System.Threading.Tasks.Tasks is defined in mscorlib.dll. // Microsoft.SCIM.IRequest is defined in // Microsoft.SCIM.Service. // Microsoft.SCIM.Resource and // Microsoft.SCIM.IResourceRetrievalParameters // are defined in Microsoft.SCIM.Schemas Task<Resource> RetrieveAsync(IRequest<IResourceRetrievalParameters> request); In the example of a request to retrieve the current state of a user, the values of the properties of the object provided as the value of the parameters argument are as follows: - Identifier: "54D382A4-2050-4C03-94D1-E769F1D15682" - SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" Example 4. Query the value of a reference attribute to be updated If a reference attribute is to be updated, then Azure Active Directory queries the service to determine whether the current value of the reference attribute in the identity store fronted by the service already matches the value of that attribute in Azure Active Directory. For users, the only attribute of which the current value is queried in this way is the manager attribute. Here is an example of a request to determine whether the manager attribute of a user object currently has a certain value: In the sample code the request is translated into a call to the QueryAsync method of the service’s provider. The value of the properties of the object provided as the value of the parameters argument are as follows: - parameters.AlternateFilters.Count: 2 - parameters.AlternateFilters.ElementAt(x).AttributePath: "ID" - parameters.AlternateFilters.ElementAt(x).ComparisonOperator: ComparisonOperator.Equals - parameters.AlternateFilter.ElementAt(x).ComparisonValue: "54D382A4-2050-4C03-94D1-E769F1D15682" - parameters.AlternateFilters.ElementAt(y).AttributePath: "manager" - parameters.AlternateFilters.ElementAt(y).ComparisonOperator: ComparisonOperator.Equals - parameters.AlternateFilter.ElementAt(y).ComparisonValue: "2819c223-7f76-453a-919d-413861904646" - parameters.RequestedAttributePaths.ElementAt(0): "ID" - parameters.SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" Here, the value of the index x can be 0 and the value of the index y can be 1, or the value of x can be 1 and the value of y can be 0, depending on the order of the expressions of the filter query parameter. Example 5. Request from Azure AD to an SCIM service to update a user Here is an example of a request from Azure Active Directory to an SCIM service to update a user: PATCH ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1 Authorization: Bearer ... Content-type: application/scim+json { "schemas": [ "urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [ { "op":"Add", "path":"manager", "value": [ { "$ref":"", "value":"2819c223-7f76-453a-919d-413861904646"}]}]} In the sample code the request is translated into a call to the UpdateAsync method of the service’s provider. Here is the signature of that method: // System.Threading.Tasks.Tasks and // System.Collections.Generic.IReadOnlyCollection<T> // are defined in mscorlib.dll. // Microsoft.SCIM.IRequest is defined in // Microsoft.SCIM.Service. // Microsoft.SCIM.IPatch, // is defined in Microsoft.SCIM.Protocol. Task UpdateAsync(IRequest<IPatch> request); In the example of a request to update a user, the object provided as the value of the patch argument has these property values: Example 6. Deprovision a user To deprovision a user from an identity store fronted by an SCIM service, Azure AD sends a request such as: DELETE ~/scim/Users/54D382A4-2050-4C03-94D1-E769F1D15682 HTTP/1.1 Authorization: Bearer ... In the sample code the request is translated into a call to the DeleteAsync method of the service’s provider. Here is the signature of that method: // System.Threading.Tasks.Tasks is defined in mscorlib.dll. // Microsoft.SCIM.IRequest is defined in // Microsoft.SCIM.Service. // Microsoft.SCIM.IResourceIdentifier, // is defined in Microsoft.SCIM.Protocol. Task DeleteAsync(IRequest<IResourceIdentifier> request); The object provided as the value of the resourceIdentifier argument has these property values in the example of a request to deprovision a user: - ResourceIdentifier.Identifier: "54D382A4-2050-4C03-94D1-E769F1D15682" - ResourceIdentifier.SchemaIdentifier: "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" Integrate your SCIM endpoint with the Azure AD SCIM client Azure AD can be configured to automatically provision assigned users and groups to applications that implement a specific profile of the SCIM 2.0 protocol. The specifics of the profile are documented in Understand the Azure AD SCIM implementation. Check with your application provider, or your application provider's documentation for statements of compatibility with these requirements. Important The Azure AD SCIM implementation is built on top of the Azure AD user provisioning service, which is designed to constantly keep users in sync between Azure AD and the target application, and implements a very specific set of standard operations. It's important to understand these behaviors to understand the behavior of the Azure AD SCIM client. For more information, see the section Provisioning cycles: Initial and incremental in How provisioning works. Getting started Applications that support the SCIM profile described in this article can be connected to Azure Active Directory using the "non-gallery application" feature in the Azure AD application gallery. Once connected, Azure AD runs a synchronization process every 40 minutes where it queries the application's SCIM endpoint for assigned users and groups, and creates or modifies them according to the assignment details. To connect an application that supports SCIM: Sign in to the Azure AD portal. Note that you can get access a free trial for Azure Active Directory with P2 licenses by signing up for the developer program Select Enterprise applications from the left pane. A list of all configured apps is shown, including apps that were added from the gallery. Select + New application > + Create your own application. Enter a name for your application, choose the option "integrate any other application you don't find in the gallery" and select Add to create an app object. The new app is added to the list of enterprise applications and opens to its app management screen. Azure AD application gallery Note If you are using the old app gallery experience, follow the screen guide below. Azure AD old app gallery experience In the app management screen, select Provisioning in the left panel. In the Provisioning Mode menu, select Automatic. Configuring provisioning in the Azure portal In the Tenant URL field, enter the URL of the application's SCIM endpoint. Example: If the SCIM endpoint requires an OAuth bearer token from an issuer other than Azure AD, then copy the required OAuth bearer token into the optional Secret Token field. If this field is left blank, Azure AD includes an OAuth bearer token issued from Azure AD with each request. Apps that use Azure AD as an identity provider can validate this Azure AD-issued token. Note It's not recommended to leave this field blank and rely on a token generated by Azure AD. This option is primarily available for testing purposes. Select Test Connection to have Azure Active Directory attempt to connect to the SCIM endpoint. If the attempt fails, error information is displayed. Note Test Connection queries the SCIM endpoint for a user that doesn't exist, using a random GUID as the matching property selected in the Azure AD configuration. The expected correct response is HTTP 200 OK with an empty SCIM ListResponse message. If the attempts to connect to the application succeed, then select Save to save the admin credentials. In the Mappings section, there are two selectable sets of attribute mappings: one for user objects and one for group objects. Select each one to review the attributes that are synchronized from Azure Active Directory to your app. The attributes selected as Matching properties are used to match the users and groups in your app for update operations. Select Save to commit any changes. Note You can optionally disable syncing of group objects by disabling the "groups" mapping. Under Settings, the Scope field defines which users and groups are synchronized. Select Sync only assigned users and groups (recommended) to only sync users and groups assigned in the Users and groups tab. Once your configuration is complete, set the Provisioning Status to On. Select Save to start the Azure AD provisioning service. If syncing only assigned users and groups (recommended), be sure to select the Users and groups tab and assign the users or groups you want to sync. Once the initial cycle has started, you can select Provisioning logs in the left panel to monitor progress, which shows all actions done by the provisioning service on your app. For more information on how to read the Azure AD provisioning logs, see Reporting on automatic user account provisioning. Note The initial cycle takes longer to perform than later syncs, which occur approximately every 40 minutes as long as the service is running. Publish your application to the Azure AD application gallery If you're building an application that will be used by more than one tenant, you can make it available in the Azure AD application gallery. This will make it easy for organizations to discover the application and configure provisioning. Publishing your app in the Azure AD gallery and making provisioning available to others is easy. Check out the steps here. Microsoft will work with you to integrate your application into our gallery, test your endpoint, and release onboarding documentation for customers to use. Gallery onboarding checklist Use the checklist to onboard your application quickly and customers have a smooth deployment experience. The information will be gathered from you when onboarding to the gallery. - Support a SCIM 2.0 user and group endpoint (Only one is required but both are recommended) - Support at least 25 requests per second per tenant to ensure that users and groups are provisioned and deprovisioned without delay (Required) - Establish engineering and support contacts to guide customers post gallery onboarding (Required) - 3 Non-expiring test credentials for your application (Required) - Support the OAuth authorization code grant or a long lived token as described below (Required) - Establish an engineering and support point of contact to support customers post gallery onboarding (Required) - Support schema discovery (required) - Support updating multiple group memberships with a single PATCH - Document your SCIM endpoint publicly Authorization to provisioning connectors in the application gallery The SCIM spec doesn't define a SCIM-specific scheme for authentication and authorization and relies on the use of existing industry standards. Note It's not recommended to leave the token field blank in the Azure AD provisioning configuration custom app UI. The token generated is primarily available for testing purposes. OAuth code grant flow The provisioning service supports the authorization code grant and after submitting your request for publishing your app in the gallery, our team will work with you to collect the following information: Authorization URL, a URL by the client to obtain authorization from the resource owner via user-agent redirection. The user is redirected to this URL to authorize access. Token exchange URL, a URL by the client to exchange an authorization grant for an access token, typically with client authentication. Client ID, the authorization server issues the registered client a client identifier, which is a unique string representing the registration information provided by the client. The client identifier is not a secret; it is exposed to the resource owner and must not be used alone for client authentication. Client secret, a secret generated by the authorization server that should be a unique value known only to the authorization server. Note The Authorization URL and Token exchange URL are currently not configurable per tenant. Note OAuth v1 is not supported due to exposure of the client secret. OAuth v2 is supported. Best practices (recommended, but not required): - Support multiple redirect URLs. Administrators can configure provisioning from both "portal.azure.com" and "aad.portal.azure.com". Supporting multiple redirect URLs will ensure that users can authorize access from either portal. - Support multiple secrets for easy renewal, without downtime. How to setup OAuth code grant flow Sign in to the Azure portal, go to Enterprise applications > Application > Provisioning and select Authorize. Azure portal redirects user to the Authorization URL (sign in page for the third party app). Admin provides credentials to the third party application. Third party app redirects user back to Azure portal and provides the grant code Azure AD provisioning services calls the token URL and provides the grant code. The third party application responds with the access token, refresh token, and expiry date When the provisioning cycle begins, the service checks if the current access token is valid and exchanges it for a new token if needed. The access token is provided in each request made to the app and the validity of the request is checked before each request. Note While it's not possible to setup OAuth on the non-gallery applications, you can manually generate an access token from your authorization server and input it as the secret token to a non-gallery application. This allows you to verify compatibility of your SCIM server with the Azure AD SCIM client before onboarding to the app gallery, which does support the OAuth code grant. Long-lived OAuth bearer tokens: If your application doesn't support the OAuth authorization code grant flow, instead generate a long lived OAuth bearer token that an administrator can use to setup the provisioning integration. The token should be perpetual, or else the provisioning job will be quarantined when the token expires. For additional authentication and authorization methods, let us know on UserVoice. Gallery go-to-market launch check list To help drive awareness and demand of our joint integration, we recommend you update your existing documentation and amplify the integration in your marketing channels. The below is a set of checklist activities we recommend you complete to support the launch - Ensure your sales and customer support teams are aware, ready, and can speak to the integration capabilities. Brief your teams, provide them with FAQs and include the integration into your sales materials. - Craft a blog post or press release that describes the joint integration, the benefits and how to get started. Example: Imprivata and Azure Active Directory Press Release - Leverage your social media like Twitter, Facebook or LinkedIn to promote the integration to your customers. Be sure to include @AzureAD so we can retweet your post. Example: Imprivata Twitter Post - Create or update your marketing pages/website (e.g. integration page, partner page, pricing page, etc.) to include the availability of the joint integration. Example: Pingboard integration Page, Smartsheet integration page, Monday.com pricing page - Create a help center article or technical documentation on how customers can get started. Example: Envoy + Microsoft Azure Active Directory integration. - Alert customers of the new integration through your customer communication (monthly newsletters, email campaigns, product release notes). Next steps Develop a sample SCIM endpoint Automate user provisioning and deprovisioning to SaaS apps Customize attribute mappings for user provisioning Writing expressions for attribute mappings Scoping filters for user provisioning Account provisioning notifications List of tutorials on how to integrate SaaS apps Feedback Submit and view feedback for
https://docs.microsoft.com/en-gb/azure/active-directory/app-provisioning/use-scim-to-provision-users-and-groups
CC-MAIN-2022-27
en
refinedweb
Changing text color in Table View Cell Is there any way to change the text color in Table View Cell? A TableViewCell's text_labelis a regular Labeland can thus have its text_colorchanged: class MyDataSource(object): def tableview_cell_for_row(self, tv, section, row): cell = ui.TableViewCell() cell.text_label.text_color = (1.0, 0.0, 0.0, 0.0) cell.text_label.text = "I am red" return cell This creates a new cell, I want to modify an existing one. - polymerchm Here's a snippet of code in my flashcard program. highlight is a global that corresponds to the row needing highlighting in the items for the tableview. def tableview_cell_for_row(self, tableview, section, row): # Create and return a cell for the given section/row cell = ui.TableViewCell() cell.text_label.text = self.items[row]['title'] if row == highlight: cell.text_label.text_color = 'red' cell.accessory_type = self.items[row]['accessory_type'] return cell I also set a checkmark on this cell. Remember, this is called every time cell appears on the screen. As when it scrolls into view. Is there a tutorial on how to create custom TableViewCells (with multiple subviews like labels, images, etc.) and then populate them with data? Ah - - seems to be a good starting point!
https://forum.omz-software.com/topic/1244/changing-text-color-in-table-view-cell
CC-MAIN-2022-27
en
refinedweb
Migration from the lab MUI date and time pickers are now available on MUI X! Introduction This is a reference for migrating your site's pickers from @mui/lab to @mui/x-date-pickers or @mui/x-date-pickers-pro. This migration only concerns packages and should do not affect the behavior of the components in your app. We explored the reasons of this migration in a blog post License Most of our components remains MIT and are accessible for free in @mui/x-date-pickers. The range-picker components: DateRangePicker, DateRangePickerDay, DesktopDateRangePicker, MobileDateRangePicker and StaticDateRangePicker were marked as "intended for MUI X Pro" in our documentation and are now part of MUI X Pro. If you are using one of these components, you will have to take a Pro license in order to migrate to @mui/x-date-pickers-pro (see the Pricing page for more information). Migration steps 1. Install MUI X packages Community Plan // with npm npm install @mui/x-date-pickers // with yarn yarn add @mui/x-date-pickers Pro Plan // with npm npm install @mui/x-date-pickers-pro @mui/x-license-pro // with yarn yarn add @mui/x-date-pickers-pro @mui/x-license-pro When you purchase a commercial license, you'll receive a license key by email. You must set the license key before rendering the first component. import { LicenseInfo } from '@mui/x-license-pro'; LicenseInfo.setLicenseKey('YOUR_LICENSE_KEY'); 2. Run the code mod We have prepared a codemod to help you migrate your codebase npx @mui/codemod v5.0.0/date-pickers-moved-to-x <path> Which will transform the imports like this: -import DatePicker from '@mui/lab/DatePicker'; +import { DatePicker } from '@mui/x-date-pickers/DatePicker'; -import DateRangePicker from '@mui/lab/DateRangePicker'; +import { DateRangePicker } from '@mui/x-date-pickers-pro/DateRangePicker'; -import { DatePicker, DateRangePicker } from '@mui/lab'; +import { DatePicker } from '@mui/x-date-pickers'; // DatePicker is also available in `@mui/x-date-pickers-pro` +import { DateRangePicker } from '@mui/x-date-pickers-pro'; Components of the Community Plan such as <DatePicker /> can be imported from both @mui/x-date-pickers-pro and @mui/x-date-pickers. Only date adapters such as AdapterDayjs can only be imported from @mui/x-date-pickers/[adapterName].
https://mui.com/zh/x/react-date-pickers/migration-lab/
CC-MAIN-2022-27
en
refinedweb
aknath Gunathilake1,860 Points Dictionary Members can't seem to pass this challenge. says expected 2 but got 0 def members(my_dict, my_list): count =0 for item in my_dict: if item in my_dict == item in my_list: count+= 1 return count 1 Answer Kourosh Raeen23,732 Points Hi Laknath - Try looping over the list of keys: for key in my_list: Then check to see if the current key is a key in the dictionary: if key in my_dict: Also, make sure the return statement has the right indentation. It shouldn't be in the if or for block.
https://teamtreehouse.com/community/dictionary-members
CC-MAIN-2022-27
en
refinedweb
annonhall12,247 Points How do you Import flash from Flask? Oh dear I think I'm asking a stupid question But if someone helps me that would REALLY help Thanks! :D from flask import Flask, redirect, url_for, render_template app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/fishy') def fishy(): return redirect(url_for('index')) import flash 1 Answer William LiCourses Plus Student 26,865 Points To do that, just add flash to the end of the import statement from flask import Flask, redirect, url_for, render_template, flash channonhall12,247 Points channonhall12,247 Points Thanks Again william! It's always the Tiny stuff that I get stuck on.
https://teamtreehouse.com/community/how-do-you-import-flash-from-flask
CC-MAIN-2022-27
en
refinedweb
rishna aryal6,897 Points public static void main(String[] args) I use sublime 2 and it says Exception in thread "main" java.lang.NullPointerException at TreeStory.main(TreeStory.java:17) Thanks import java.io.Console; public class TreeStory { public static void main(String[] args) { Console console = System.console(); String name = console.readLine("Enter your Name: "); String adjective = console.readLine("Enter an adjective: "); console.printf("%s is very %s", name, adjective); } } ``` Boban Talevski24,793 Points Boban Talevski24,793 Points I think we need to see more code as the problem is reportedly on line 17, which doesn't seem to be shown here (I count up to 13 lines in the code above) :).
https://teamtreehouse.com/community/public-static-void-mainstring-args
CC-MAIN-2022-27
en
refinedweb
Ignácio Brito1,201 Points Reviewing lines Are the comments that I've put about the code correct?: class PezDispenser{ /* public = Public variable static = It can be initialized without instanciating an object final = It can only be defined once int = Variable of integer tipe MAX_PEZ ==> Shows that it's a constant value;Capital letters and words spread by underline */ public static final int MAX_PEZ = 12;//Maximum number of pez final private String characterName;//Name of the character private int pezCount;//Number of pez inside public PezDispenser(String characterName) { this.characterName = characterName; pezCount = 0; }//Class with name of the character and quantity of pez when It's created public String getCharacterName() { return characterName; }//Returns private variable without allowing the user to modify it public class Example { /* public:acces level modifier void:It does not return anything static:It can be initialized without instanciating an object */ public static void main(String[] args) { // Your amazing code goes here... System.out.println("We're making a new PEZ Dispenser"); System.out.printf("FUN FACT: There are %d PEZ allowed in every dispenser %n", PezDispenser.MAX_PEZ);//Inictializing variable without instanciate the object PezDispenser dispenser = new PezDispenser("Yoda");//Instanciating object System.out.printf("The dispenser is %s %n", dispenser.getCharacterName() ); } } 2 Answers Mike D2,784 Points Everything looks pretty good, but public PezDispenser(String characterName) { this.characterName = characterName; pezCount = 0; }//Class with name of the character and quantity of pez when It's created this is not actually a class it's the constructor. A constructor is similar to a method, but yeilds no return. The constructor is just initializing those member variables for an object of the class. Constructors always have the same name as the class.
https://teamtreehouse.com/community/reviewing-lines
CC-MAIN-2022-27
en
refinedweb
onse Cuccurullo2,513 Points So im trying to grip def functions, Mind helping me with my syntax. def times_five puts" Five of these" 5.times do |item| puts item end end puts times_five() Im having trouble understanding def. Like if is it there so i dont keep typing the same code over and over? How often is it used? Also mind correcting my syntax? The goal there was to access the def whenever i wanted to type something down 5 times. 2 Answers Luke Glazebrook13,563 Points Hi Alphonse! What you are doing in the code above is making, what is called, a method. A method is basically just a piece of code that you would like to re-use again and again so you have given a name to it. Just like how if you want to use a certain value again and again you store it in a variable. When you go ahead and 'call' the times_five function you have set. It will run through the code inside of the function which is defined using the 'def' keyword. Here is an example of a function below and beneath the function is it's call. def this_is_a_function() #This is where the function is declared. puts 'This is a function and every time its called this will print.' end this_is_a_function() #This is the call to the function. I hope that I managed to help you out here. If you do have any more questions, however, then don't hesitate to ask them! -Luke Luke Glazebrook13,563 Points Yeah sure. So if we take a look at your method below: def times_five() puts "Five of these" 5.times do |item| puts item end end times_five() Give that a go, you shouldn't need to put 'puts' before you are calling your function because, as you can see inside your function, you are already using 'puts' to print out the values. Also, you can't really do what you are wanting with the variable iteration in that way. However, there is a really great thing that you will learn about shortly called parameters which will allow you to do this! -Luke Luke Glazebrook13,563 Points No problem, glad I could help you out Alphonse! Don't forget to mark a 'Best Answer' so the other members of the community know that your problem has been solved! Alphonse Cuccurullo2,513 Points Alphonse Cuccurullo2,513 Points Ohhhh ok that does make sense thank you. As far as another question ummm if you can help me with my syntax that i posted earlier. Because my method wont print. Also lets say i make a variable after the def function then can i iterate the variable with the method like this......... variable = 5 puts variable[times_five()]
https://teamtreehouse.com/community/so-im-trying-to-grip-def-functions-mind-helping-me-with-my-syntax
CC-MAIN-2022-27
en
refinedweb
Plotting vectors Plotting vectors is handled by pygmt.Figure.plot. import numpy as np import pygmt Plot Cartesian Vectors Create a simple Cartesian vector using a starting point through x, y, and direction parameters. On the shown figure, the plot is projected on a 10cm X 10cm region, which is specified by the projection parameter. The direction is specified by a list of two 1d arrays structured as [[angle_in_degrees], [length]]. The angle is measured in degrees and moves counter-clockwise from the horizontal. The length of the vector uses centimeters by default but could be changed using pygmt.config (Check the next examples for unit changes). Notice that the v in the style parameter stands for vector; it distinguishes it from regular lines and allows for different customization. 0c is used to specify the size of the arrow head which explains why there is no arrow on either side of the vector. Out: <IPython.core.display.Image object> In this example, we apply the same concept shown previously to plot multiple vectors. Notice that instead of passing int/float to x and y, a list of all x and y coordinates will be passed. Similarly, the length of direction list will increase accordingly. Additionally, we change the style of the vector to include a red arrow head at the end (+e) of the vector and increase the thickness ( pen="2p") of the vector stem. A list of different styling attributes can be found in Vector heads and tails. Out: <IPython.core.display.Image object> The default unit of vector length is centimeters, however, this can be changed to inches or points. Note that, in PyGMT, one point is defined as 1/72 inch. In this example, the graphed region is 5in X 5in, but the length of the first vector is still graphed in centimeters. Using pygmt.config(PROJ_LENGTH_UNIT="i"), the default unit can be changed to inches in the second plotted vector. fig = pygmt.Figure() # Vector 1 with default unit as cm fig.plot( region=[0, 10, 0, 10], projection="X5i/5i", frame="ag", x=2, y=8, style="v1c+e", direction=[[0], [3]], pen="2p", color="red3", ) # Vector 2 after changing default unit to inch with pygmt.config(PROJ_LENGTH_UNIT="i"): fig.plot( x=2, y=7, direction=[[0], [3]], style="v1c+e", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> Vectors can also be plotted by including all the information about a vector in a single list. However, this requires creating a 2D list or numpy array containing all vectors. Each vector list contains the information structured as: [x_start, y_start, direction_degrees, length]. If this approach is chosen, the data parameter must be used instead of x, y and direction. Out: <IPython.core.display.Image object> Using the functionality mentioned in the previous example, multiple vectors can be plotted at the same time. Another vector could be simply added to the 2D list or numpy array object and passed using data parameter. # Vector specifications structured as: # [x_start, y_start, direction_degrees, length] vector_1 = [2, 3, 45, 4] vector_2 = [7.5, 8.3, -120.5, 7.2] # Create a list of lists that include each vector information vectors = [vector_1, vector_2] # Vectors structure: [[2, 3, 45, 4], [7.5, 8.3, -120.5, 7.2]] fig = pygmt.Figure() fig.plot( region=[0, 10, 0, 10], projection="X10c/10c", frame="ag", data=vectors, style="v0.6c+e", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> In this example, cartesian vectors are plotted over a Mercator projection of the continental US. The x values represent the longitude and y values represent the latitude where the vector starts. This example also shows some of the styles a vector supports. The beginning point of the vector (+b) should take the shape of a circle (c). Similarly, the end point of the vector (+e) should have an arrow shape (a) (to draw a plain arrow, use A instead). Lastly, the +a specifies the angle of the vector head apex (30 degrees in this example). # Create a plot with coast, Mercator projection (M) over the continental US fig = pygmt.Figure() fig.coast( region=[-127, -64, 24, 53], projection="M10c", frame="ag", borders=1, shorelines="0.25p,black", area_thresh=4000, land="grey", water="lightblue", ) # Plot a vector using the x, y, direction parameters style = "v0.4c+bc+ea+a30" fig.plot( x=-110, y=40, style=style, direction=[[-25], [3]], pen="1p", color="red3", ) # vector specifications structured as: # [x_start, y_start, direction_degrees, length] vector_2 = [-82, 40.5, 138, 2.5] vector_3 = [-71.2, 45, -115.7, 4] # Create a list of lists that include each vector information vectors = [vector_2, vector_3] # Plot vectors using the data parameter. fig.plot( data=vectors, style=style, pen="1p", color="yellow", ) fig.show() Out: <IPython.core.display.Image object> Another example of plotting cartesian vectors over a coast plot. This time a Transverse Mercator projection is used. Additionally, numpy.linspace is used to create 5 vectors with equal stops. x = np.linspace(36, 42, 5) # x values = [36. 37.5 39. 40.5 42. ] y = np.linspace(39, 39, 5) # y values = [39. 39. 39. 39.] direction = np.linspace(-90, -90, 5) # direction values = [-90. -90. -90. -90.] length = np.linspace(1.5, 1.5, 5) # length values = [1.5 1.5 1.5 1.5] # Create a plot with coast, Mercator projection (M) over the continental US fig = pygmt.Figure() fig.coast( region=[20, 50, 30, 45], projection="T35/10c", frame=True, borders=1, shorelines="0.25p,black", area_thresh=4000, land="lightbrown", water="lightblue", ) fig.plot( x=x, y=y, style="v0.4c+ea+bc", direction=[direction, length], pen="0.6p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> Plot Circular Vectors When plotting circular vectors, all of the information for a single vector is to be stored in a list. Each circular vector list is structured as: [x_start, y_start, radius, degree_start, degree_stop]. The first two values in the vector list represent the origin of the circle that will be plotted. The next value is the radius which is represented on the plot in cm. The last two values in the vector list represent the degree at which the plot will start and stop. These values are measured counter-clockwise from the horizontal axis. In this example, the result show is the left half of a circle as the plot starts at 90 degrees and goes until 270. Notice that the m in the style parameter stands for circular vectors. fig = pygmt.Figure() circular_vector_1 = [0, 0, 2, 90, 270] data = [circular_vector_1] fig.plot( region=[-5, 5, -5, 5], projection="X10c", frame="ag", data=data, style="m0.5c+ea", pen="2p", color="red3", ) # Another example using np.array() circular_vector_2 = [0, 0, 4, -90, 90] data = np.array([circular_vector_2]) fig.plot( data=data, style="m0.5c+ea", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> When plotting multiple circular vectors, a two dimensional array or numpy array object should be passed as the data parameter. In this example, numpy.column_stack is used to generate this two dimensional array. Other numpy objects are used to generate linear values for the radius parameter and random values for the degree_stop parameter discussed in the previous example. This is the reason in which each vector has a different appearance on the projection. vector_num = 5 radius = 3 - (0.5 * np.arange(0, vector_num)) startdir = np.full(vector_num, 90) stopdir = 180 + (50 * np.arange(0, vector_num)) data = np.column_stack( [np.full(vector_num, 0), np.full(vector_num, 0), radius, startdir, stopdir] ) fig = pygmt.Figure() fig.plot( region=[-5, 5, -5, 5], projection="X10c", frame="ag", data=data, style="m0.5c+ea", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> Much like when plotting Cartesian vectors, the default unit used is centimeters. When this is changed to inches, the size of the plot appears larger when the projection units do not change. Below is an example of two circular vectors. One is plotted using the default unit, and the second is plotted using inches. Despite using the same list to plot the vectors, a different measurement unit causes one to be larger than the other. circular_vector = [6, 5, 1, 90, 270] fig = pygmt.Figure() fig.plot( region=[0, 10, 0, 10], projection="X10c", frame="ag", data=[circular_vector], style="m0.5c+ea", pen="2p", color="red3", ) with pygmt.config(PROJ_LENGTH_UNIT="i"): fig.plot( data=[circular_vector], style="m0.5c+ea", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> Plot Geographic Vectors On this map, point_1 and point_2 are coordinate pairs used to set the start and end points of the geographic vector. The geographical vector is going from Idaho to Chicago. To style geographic vectors, use = at the beginning of the style parameter. Other styling features such as vector stem thickness and head color can be passed into the pen and color parameters. Note that the +s is added to use a startpoint and an endpoint to represent the vector instead of input angle and length. point_1 = [-114.7420, 44.0682] point_2 = [-87.6298, 41.8781] data = np.array([point_1 + point_2])_10<< Out: <IPython.core.display.Image object> Using the same technique shown in the previous example, multiple vectors can be plotted in a chain where the endpoint of one is the starting point of another. This can be done by adding the coordinate lists together to create this structure: [[start_latitude, start_longitude, end_latitude, end_longitude]]. Each list within the 2D list contains the start and end information for each vector. # Coordinate pairs for all the locations used ME = [-69.4455, 45.2538] CHI = [-87.6298, 41.8781] SEA = [-122.3321, 47.6062] NO = [-90.0715, 29.9511] KC = [-94.5786, 39.0997] CA = [-119.4179, 36.7783] # Add array to piece together the vectors data = [ME + CHI, CHI + SEA, SEA + KC, KC + NO, NO + CA]_11<< Out: <IPython.core.display.Image object> This example plots vectors over a Mercator projection. The starting points are located at SA which is South Africa and going to four different locations. SA = [22.9375, -30.5595] EUR = [15.2551, 54.5260] ME = [-69.4455, 45.2538] AS = [100.6197, 34.0479] NM = [-105.8701, 34.5199] data = np.array([SA + EUR, SA + ME, SA + AS, SA + NM]) fig = pygmt.Figure() fig.coast( region=[-180, 180, -80, 80], projection="M0/0/12c", frame="afg", land="lightbrown", water="lightblue", ) fig.plot( data=data, style="=0.5c+ea+s", pen="2p", color="red3", ) fig.show() Out: <IPython.core.display.Image object> Total running time of the script: ( 0 minutes 16.755 seconds) Gallery generated by Sphinx-Gallery
https://www.pygmt.org/latest/tutorials/advanced/vectors.html
CC-MAIN-2022-27
en
refinedweb
The XPath API supports XML Path Language (XPath) Version 1.0 - 1. XPath Overview - 2. XPath Expressions - 3. XPath Data Types - 4. XPath Context - 5. Using the XPath API 1. XPath Overview. 2. XPath Expressions'] 3. XPath Data Types While XPath expressions select nodes in the XML document, the XPath API allows the selected nodes to be coalesced into one of the following data types: Boolean Number String 3.1 QName typesThe XPath API defines the following QNametypes to represent return types of an XPath evaluation: XPathConstants.NODESET XPathConstants.NODE XPathConstants.STRING XPathConstants.BOOLEAN XPathConstants.NUMBER The return type is specified by a QName parameter in method call used to evaluate the expression, which is either a call to XPathExpression.evalute(...) or XPath.evaluate(...) methods.. 3.2 Class typesIn addition to the QName types, the XPath API supports the use of Class types through the XPathExpression.evaluteExpression(...)or XPath.evaluateExpression(...)methods. The XPath data types are mapped to Class types as follows: Boolean-- Boolean.class Number-- Number.class String-- String.class Nodeset-- XPathNodes.class Node-- Node.class Of the subtypes of Number, only Double, Integer and Long are supported. 3.3 Enum typesEnum types are defined in XPathEvaluationResult.XPathResultTypethat provide mappings between the QName and Class types above. The result of evaluating an expression using the XPathExpression.evaluteExpression(...)or XPath.evaluateExpression(...)methods will be of one of these types. 4. XPath Context XPath location paths may be relative to a particular node in the document, known as the context. A context consists of: - a node (the context node) - a pair of non-zero positive integers (the context position and the context size) - a set of variable bindings - a function library - the set of namespace declarations in scope for the expression It is an XML document tree represented as a hierarchy of nodes, a Node for example, in the JDK implementation. 5. Using the XPath APIConsider the following XML document: <widgets> <widget> <manufacturer/> <dimensions/> </widget> </widgets> The <widget> element can be selected with the following process: // parse the XML as a W3C Document DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File("/widgets.xml")); //Get an XPath object and evaluate the expression XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/widgets/widget"; Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); //or using the evaluateExpression method Node widgetNode = xpath.evaluateExpression(expression, document, Node.class); With a reference to the <widget> element, a relative XPath expression can be written to select the <manufacturer> child element: XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "manufacturer"; Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE); //or using the evaluateExpression method Node manufacturerNode = xpath.evaluateExpression(expression, widgetNode, Node.class); In the above example, the XML file is read into a DOM Document before being passed to the XPath API. The following code demonstrates the use of InputSource to leave it to the XPath implementation to process it: XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/widgets/widget"; InputSource inputSource = new InputSource("widgets.xml"); NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET); //or using the evaluateExpression method XPathNodes nodes = xpath.evaluate(expression, inputSource, XPathNodes.class); In the above cases, the type of the expected results are known. In case where the result type is unknown or any type, the XPathEvaluationResult may be used to determine the return type. The following code demonstrates the usage: XPathEvaluationResult<?> result = xpath.evaluateExpression(expression, document); switch (result.type()) { case NODESET: XPathNodes nodes = (XPathNodes)result.value(); ... break; } The XPath 1.0 Number data type is defined as a double. However, the XPath specification also provides functions that returns Integer type. To facilitate such operations, the XPath API allows Integer and Long to be used in evaluateExpression method such as the following code: int count = xpath.evaluate("count(/widgets/widget)", document, Integer.class); - Since: - 1.5
https://docs.oracle.com/javase/9/docs/api/javax/xml/xpath/package-summary.html
CC-MAIN-2022-27
en
refinedweb
I’m thrilled to finally present attrs 20.1.0 with the following changes: - bug fixes - performance improvements JUST KIDDING! This release is HUGE and I'm stoked we can finally get it to you! It’s the result of more than a year of development and not only does it come with many great features that users desired for a long time, it also lays the foundation for the future evolution of this package. ---- The final push has only been possible thanks to attrs’s Tidelift subscribers () and my generous GitHub Sponsors (). If you want to speed up the development for the forthcoming 20.2.0 release (You do! There’s a lot of great stuff coming up!), please consider supporting my work by either sponsoring me, or convincing your boss to subscribe to my projects on Tidelift (). Hooks on Setting Attributes You could always use validators for when a class is instantiated and you could always make classes immutable. Now you can also freeze specific attributes and validate attribute values on assignment using the new on_setattr argument. It takes a callable and runs it whenever the user tries to assign a new value to the attribute. See #660 (). Automatic Detection of Own Methods If you want to write your own dunder method – say __init__ – you have to remember to tell attrs to not generate an own version (e.g. @attr.s(init=False)) otherwise it will happily overwrite it. Not anymore! If you pass @attr.s(auto_detect=True), attrs will look for your own methods automatically – but only in the current class. In other words: inherited methods don’t count. It’s still a bit of hassle to set it to True, but that will be remedied in the future (see below). See #607 (). Attribute Collection and the MRO attrs’s collection of attributes was slightly wrong in very specific situations involving multiple inheritance (editor’s note: don’t use multiple inheritance). Most people won't notice, but some do () we like to do things the right way. See #635 (). The Road Ahead attrs started out in February 2015. The Python landscape was very different back then and lots of things changed since. We also got some things subtly wrong that need to be fixed by passing arguments. And finally the cute attr.s and attr.ib function names didn't age as attrs gained more and more features over the years. Therefore, we intend to add a new attrs namespace in 20.2.0 later this year, allowing you to import attrs. But there’s more than an extra “s” planned. We want to free people from having to pass all kinds of arguments to get the “good behavior” of attrs and therefore we want to introduce new APIs that have better defaults. Thanks to the new namespace, we don’t have to break backward compatibility and the old APIs aren’t going anywhere: in fact, the new ones build on them. ---- To get the new APIs just right, we’ve added them to attrs 20.1.0 provisionally for you to test and give us with feedback. The APIs are attr.define() which is supposed to become the default way to decorate classes in the future, attr.frozen() that’s the same thing as attr.define(frozen=True) and finally attr.mutable() that is an alias for define() and was wished for by immutability fans. There’s also a new alias for attr.ib() called attr.field() since that seems to be the nomenclature the Python community has agreed on. It carries no changes except that it’s keyword-only. To give you a taste, this is an example for a class defined using the new APIs: import attr @attr.define class C: x: int y: str = attr.field(default="foo") def __repr__(self) -> str: return "attrs will not overwrite this method." If everything goes according to plan, in 20.2.0 you’ll be able to substitute attr with attrs. N.B. All these APIs require at least Python 3.6. While attrs will be Python 2-compatible as long as we can (), the new APIs are not. ---- Check out the API documentation for provisional APIs () and please use issue #668 () for feedback! Relevant discussions happened in #408 (), #487 (), and finally #666 () (yep). Full Changelog The full (looong) changelog with many more features and fixes can be found at. python-announce-list@python.org
https://mail.python.org/archives/list/python-announce-list@python.org/thread/6DE5AQNUIQKJV3Y43M564OUMWL75DTWC/
CC-MAIN-2022-27
en
refinedweb
We are pleased to announce the release of Scala Weather version 0.1.0. Scala Weather is a high-performance Scala library for fetching historical, forecast and current weather data from the OpenWeatherMap API. We are pleased to be working with OpenWeatherMap.org, Snowplow’s third external data provider after MaxMind and Open Exchange Rates. This release post will cover the following topics: 1. Why we wrote this library The Snowplow event analytics platform has a growing collection of configurable event enrichments – from geo-location through custom JavaScript to currency conversions. But the most-requested enrichment still outstanding is a Weather Enrichment: specifically, using the time and geo-location of each event to retrieve the weather and attach it to the event as a context, ready for later analysis. To build this enrichment we needed a couple of things first: - A reliable weather provider with a robust API. After some experimentation with Wunderground and Yahoo! Weather, we settled on OpenWeatherMap as having the most detailed weather reports and extensive historical data - A Scala client for OpenWeatherMap, with sophisticated cache capabilities to minimize the number of API calls when embedded in a Snowplow enrichment process running across millions of events Scala Weather, then, is our idiomatic Scala client for OpenWeatherMap, and the foundation for the new Weather Enrichment in Snowplow, which we hope to release very soon. But Scala Weather, like our Scala Forex project, has a wider scope than just supporting a new Snowplow enrichment: it has an asynchronous as well as synchronous client, and supports current weather lookups and weather forecasts. We hope you find it useful! 2. Basic usage To use Scala Weather you need to sign up to OpenWeatherMap to get your API key. A free key lets you to perform current weather and forecast lookups; for historical data you’ll need paid plan. After obtaining an API key, you can create a client: import com.snowplowanalytics.weather.providers.openweather.OwmAsyncClient val client = OwmAsyncClient(YOURKEY) OwmAsyncClient is the recommended client since it performs all requests asynchronously, using akka-http under the hood and returning its response wrapped in Future. The other client is the synchronous OwmCacheClient, which we’ll cover below. OpenWeatherMap provides several hosts for API with various benefits, which you can pass as the second argument: api.openweathermap.org– free access, recommended, used in OwmAsyncClientby default history.openweathermap.org– paid, history only, used in OwmCacheClientby default pro.openweathermap.org– paid, faster, SSL-enabled Both clients have same basic set of methods, grouping by data they return: These methods were designed to follow OpenWeatherMap’s own API calls as closely as possible. All of these calls receive similar arguments to those described in OpenWeatherMap API documentation. For example, to receive a response equivalent to the API call api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=YOURKEY, run the following code: val weatherInLondon: Future[WeatherError / Current] = asyncClient.currentByCoords(35, 139) / is a scalaz disjunction, which is isomorphic with Scala’s native Either. Depending on the method name, you will get back one of the following case classes: Forecast, Current or History. Neither client attempts to pre-validate your request, so you could pass a start timestamp greater than end, or a negative count or similar. These requests will be sent to API host and handled by OpenWeatherMap, possibly leading to a WeatherError. 3. The cache client Althou gh OwmAsyncClient should be used in most cases, the most interesting functionality – the weather cache – is currently only available in the synchronous OwmCacheClient, which we will be using inside the Snowplow enrichment engine. The OwmCacheClient: - Returns plain WeatherException / OwmResponse, not wrapped in a Future - Stores previously fetched weather data in its internal LRU cache - Check for the requested weather in the cache before making a call to OpenWeatherMap To construct an OwmCacheClient, pass along the API key and API host but also three additional arguments: cacheSize, timeout and geoPrecision: cacheSizedetermines how many daily weather reports for a location can be stored in the cache before entries start getting evicted timeoutis the time in seconds after which the request to OpenWeatherMap is considered unsuccessful geoPrecisiondetermines how precise your cache will be from geospatial perspective. More on this below The geoPrecision essentially rounds the decimal places part of the geo coordinate to the specified part of 1. Some example settings:. 4. Getting help For more details on this release, please check out the Scala Weather 0.1.0 release notes on GitHub. In the meantime, if you have any questions or run into any problems, please raise an issue or get in touch with us through the usual channels. 5. Plans for next release Although Scala Weather is feature-complete as far as the Snowplow Weather Enrichment is concerned, we still have some plans for it. First, we’re exploring ways to improve the cache, to include more dimensions than just basic spatial awareness and time. If there’s a feature you’d like to see, or an alternative weather provider that you’d like to see integrated, then pull requests are very welcome!
https://snowplowanalytics.com/blog/2015/12/13/scala-weather-0-1-0-released/
CC-MAIN-2022-27
en
refinedweb
HIDL requires every interface written in HIDL be versioned. After a HAL interface is published, it is frozen and any further changes must be made to a new version of that interface. While a given published interface may not be modified, it can be extended by another interface. HIDL code structure HIDL code is organized in user-defined types, interfaces, and packages: - User-defined types (UDTs). HIDL provides access to a set of primitive data types that can be used to compose more complex types via structures, unions, and enumerations. UDTs are passed to methods of interfaces, and can be defined at the level of a package (common to all interfaces) or locally to an interface. - Interfaces. As a basic building block of HIDL, an interface consists of UDT and method declarations. Interfaces can also inherit from another interface. - Packages. Organizes related HIDL interfaces and the data types on which they operate. A package is identified by a name and a version and includes the following: - Data-type definition file called types.hal. - Zero or more interfaces, each in their own .halfile. The data-type definition file types.hal contains only UDTs (all package-level UDTs are kept in a single file). Representations in the target language are available to all interfaces in the package. Versioning philosophy A HIDL package (such as android.hardware.nfc), after being published for a given version (such as 1.0), is immutable; it cannot be changed. Modifications to the interfaces in the package or any changes to its UDTs can take place only in another package. In HIDL, versioning applies at the package level, not at the interface level, and all interfaces and UDTs in a package share the same version. Package versions follow semantic versioning without the patch level and build-metadata components. Within a given package, a minor version bump implies the new version of the package is backwards-compatible with the old package and a major version bump implies the new version of the package is not backwards-compatible with the old package. Conceptually, a package can relate to another package in one of several ways: - Not at all. - Package-level backwards-compatible extensibility. This occurs for new minor-version uprevs (next incremented revision) of a package; the new package has the same name and major version as the old package, but a higher minor version. Functionally, the new package is a superset of the old package, meaning: - Top-level interfaces of the parent package are present in the new package, though the interfaces may have new methods, new interface-local UDTs (the interface-level extension described below), and new UDTs in types.hal. - New interfaces may also be added to the new package. - All data types of the parent package are present in the new package and can be handled by the (possibly reimplemented) methods from the old package. - New data types may also be added for use by either new methods of uprev'ed existing interfaces, or by new interfaces. - Interface-level backwards-compatible extensibility. The new package can also extend the original package by consisting of logically separate interfaces that simply provide additional functionality, and not the core one. For this purpose, the following may be desirable: - Interfaces in the new package need recourse to the data types of the old package. - Interfaces in new package may extend interfaces of one or more old packages. - Extend the original backwards-incompatibility. This is a major-version uprev of the package and there need not be any correlation between the two. To the extent that there is, it can be expressed with a combination of types from the older version of the package, and inheritance of a subset of old-package interfaces. Structuring interfaces For a well structured interface, adding new types of functionality that are not part of the original design should require a modification to the HIDL interface. Conversely, if you can or expect to make a change on both sides of the interface that introduces new functionality without changing the interface itself, then the interface is not structured. Treble supports separately-compiled vendor and system components in which the vendor.img on a device and the system.img can be compiled separately. All interactions between vendor.img and system.img must be explicitly and thoroughly defined so they can continue to work for many years. This includes many API surfaces, but a major surface is the IPC mechanism HIDL uses for interprocess communication on the system.img/ vendor.img boundary. Requirements All data passed through HIDL must be explicitly defined. To ensure an implementation and client can continue to work together even when compiled separately or developed on independently, data must adhere to the following requirements: - Can be described in HIDL directly (using structs enums, etc.) with semantic names and meaning. - Can be described by a public standard such as ISO/IEC 7816. - Can be described by a hardware standard or physical layout of hardware. - Can be opaque data (such as public keys, ids, etc.) if necessary. If opaque data is used, it must be read only by one side of the HIDL interface. For example, if vendor.img code gives a component on the system.img a string message or vec<uint8_t> data, that data cannot be parsed by the system.img itself; it can only be passed back to vendor.img to interpret. When passing a value from vendor.img to vendor code on system.img or to another device, the format of the data and how it is to be interpreted must be exactly described and is still part of the interface. Guidelines You should be able to write an implementation or client of a HAL using only the .hal files (i.e. you should not need to look at the Android source or public standards). We recommend specifying the exact required behavior. Statements such as "an implementation may do A or B" encourage implementations to become intertwined with the clients they are developed with. HIDL code layout HIDL includes core and vendor packages. Core HIDL interfaces are those specified by Google. The packages they belong to start with android.hardware. and are named by subsystem, potentially with nested levels of naming. For example, the NFC package is named android.hardware.nfc and the camera package is android.hardware.camera. In general, a core package has the name android.hardware.[ name1].[ name2]…. HIDL packages have a version in addition to their name. For example, the package android.hardware.camera may be at version 3.4; this is important, as the version of a package affects its placement in the source tree. All core packages are placed under hardware/interfaces/ in the build system. The package android.hardware.[ name1].[ name2]… at version $m.$n is under hardware/interfaces/name1/name2/… /$m.$n/; package android.hardware.camera version 3.4 is in directory hardware/interfaces/camera/3.4/. A hard-coded mapping exists between the package prefix android.hardware. and the path hardware/interfaces/. Non-core (vendor) packages are those produced by the SoC vendor or ODM. The prefix for non-core packages is vendor.$(VENDOR).hardware. where $(VENDOR)refers to an SoC vendor or OEM/ODM. This maps to the path vendor/$(VENDOR)/interfaces in the tree (this mapping is also hard-coded). Fully-qualified user-defined-type names In HIDL, every UDT has a fully-qualified name that consists of the UDT name, the package name where the UDT is defined, and the package version. The fully-qualified name is used only when instances of the type are declared and not where the type itself is defined. For example, assume package android.hardware.nfc, version 1.0 defines a struct named NfcData. At the site of the declaration (whether in types.hal or within an interface's declaration), the declaration simply states: struct NfcData { vec<uint8_t> data; }; When declaring an instance of this type (whether within a data structure or as a method parameter), use the fully-qualified type name: android.hardware.nfc@1.0::NfcData The general syntax is PACKAGE@VERSION::UDT, where: PACKAGEis the dot-separated name of a HIDL package (e.g., android.hardware.nfc). VERSIONis the dot-separated major.minor-version format of the package (e.g., 1.0). UDTis the dot-separated name of a HIDL UDT. Since HIDL supports nested UDTs and HIDL interfaces can contain UDTs (a type of nested declaration), dots are used to access the names. For example, if the following nested declaration was defined in the common types file in package android.hardware.example version 1.0: // types.hal package android.hardware.example@1.0; struct Foo { struct Bar { // … }; Bar cheers; }; The fully-qualified name for Bar is android.hardware.example@1.0::Foo.Bar. If, in addition to being in the above package, the nested declaration were in an interface called IQuux: // IQuux.hal package android.hardware.example@1.0; interface IQuux { struct Foo { struct Bar { // … }; Bar cheers; }; doSomething(Foo f) generates (Foo.Bar fb); }; The fully-qualified name for Bar is android.hardware.example@1.0::IQuux.Foo.Bar. In both cases, Bar can be referred to as Bar only within the scope of the declaration of Foo. At the package or interface level, you must refer to Bar via Foo: Foo.Bar, as in the declaration of method doSomething above. Alternatively, you could declare the method more verbosely as: // IQuux.hal doSomething(android.hardware.example@1.0::IQuux.Foo f) generates (android.hardware.example@1.0::IQuux.Foo.Bar fb); Fully-qualified enumeration values If a UDT is an enum type, then each value of the enum type has a fully-qualified name that starts with the fully-qualified name of the enum type, followed by a colon, then followed by the name of the enum value. For example, assume package android.hardware.nfc, version 1.0 defines an enum type NfcStatus: enum NfcStatus { STATUS_OK, STATUS_FAILED }; When referring to STATUS_OK, the fully qualified name is: android.hardware.nfc@1.0::NfcStatus:STATUS_OK The general syntax is PACKAGE@VERSION::UDT:VALUE, where: PACKAGE@VERSION::UDTis the exact same fully qualified name for the enum type. VALUEis the value's name. Auto-inference rules A fully-qualified UDT name does not need to be specified. A UDT name can safely omit the following: - The package, e.g. @1.0::IFoo.Type - Both package and version, e.g. IFoo.Type HIDL attempts to complete the name using auto-interference rules (lower rule number means higher priority). Rule 1 If no package and version is provided, a local name lookup is attempted. Example: interface Nfc { typedef string NfcErrorMessage; send(NfcData d) generates (@1.0::NfcStatus s, NfcErrorMessage m); }; NfcErrorMessage is looked up locally, and the typedef above it is found. NfcData is also looked up locally, but as it is not defined locally, rule 2 and 3 are used. @1.0::NfcStatus provides a version, so rule 1 does not apply. Rule 2 If rule 1 fails and a component of the fully-qualified name is missing (package, version, or package and version), the component is autofilled with information from the current package. The HIDL compiler then looks in the current file (and all imports) to find the autofilled fully-qualified name. Using the example above, assume the declaration of ExtendedNfcData was made in the same package ( android.hardware.nfc) at the same version ( 1.0) as NfcData, as follows: struct ExtendedNfcData { NfcData base; // … additional members }; The HIDL compiler fills out the package name and version name from the current package to produce the fully-qualified UDT name android.hardware.nfc@1.0::NfcData. As the name exists in the current package (assuming it is imported properly), it is used for the declaration. A name in the current package is imported only if one of the following is true: - It is imported explicitly with an importstatement. - It is defined in types.halin the current package The same process is followed if NfcData was qualified by only the version number: struct ExtendedNfcData { // autofill the current package name (android.hardware.nfc) @1.0::NfcData base; // … additional members }; Rule 3 If rule 2 fails to produce a match (the UDT is not defined in the current package), the HIDL compiler scans for a match within all imported packages. Using the above example, assume ExtendedNfcData is declared in version 1.1 of package android.hardware.nfc, 1.1 imports 1.0 as it should (see Package-Level Extensions), and the definition specifies only the UDT name: struct ExtendedNfcData { NfcData base; // … additional members }; The compiler looks for any UDT named NfcData and finds one in android.hardware.nfc at version 1.0, resulting in a fully-qualified UDT of android.hardware.nfc@1.0::NfcData. If more than one match is found for a given partially-qualified UDT, the HIDL compiler throws an error. Example Using rule 2, an imported type defined in the current package is favored over an imported type from another package: // hardware/interfaces/foo/1.0/types.hal package android.hardware.foo@1.0; struct S {}; // hardware/interfaces/foo/1.0/IFooCallback.hal package android.hardware.foo@1.0; interface IFooCallback {}; // hardware/interfaces/bar/1.0/types.hal package android.hardware.bar@1.0; typedef string S; // hardware/interfaces/bar/1.0/IFooCallback.hal package android.hardware.bar@1.0; interface IFooCallback {}; // hardware/interfaces/bar/1.0/IBar.hal package android.hardware.bar@1.0; import android.hardware.foo@1.0; interface IBar { baz1(S s); // android.hardware.bar@1.0::S baz2(IFooCallback s); // android.hardware.foo@1.0::IFooCallback }; Sis interpolated as android.hardware.bar@1.0::S, and is found in bar/1.0/types.hal(because types.halis automatically imported). IFooCallbackis interpolated as android.hardware.bar@1.0::IFooCallbackusing rule 2, but it cannot be found because bar/1.0/IFooCallback.halis not imported automatically (as types.halis). Thus, rule 3 resolves it to android.hardware.foo@1.0::IFooCallbackinstead, which is imported via import android.hardware.foo@1.0;). types.hal Every HIDL package contains a types.hal file containing UDTs that are shared among all interfaces participating in that package. HIDL types are always public; regardless of whether a UDT is declared in types.hal or within an interface declaration, these types are accessible outside of the scope where they are defined. types.hal is not meant to describe the public API of a package, but rather to host UDTs used by all interfaces within the package. Due to the nature of HIDL, all UDTs are a part of the interface. types.hal consists of UDTs and import statements. Because types.hal is made available to every interface of the package (it is an implicit import), these import statements are package-level by definition. UDTs in types.hal may also incorporate UDTs and interfaces thus imported. For example, for an IFoo.hal: package android.hardware.foo@1.0; // whole package import import android.hardware.bar@1.0; // types only import import android.hardware.baz@1.0::types; // partial imports import android.hardware.qux@1.0::IQux.Quux; // partial imports import android.hardware.quuz@1.0::Quuz; The following are imported: android.hidl.base@1.0::IBase(implicitly) android.hardware.foo@1.0::types(implicitly) - Everything in android.hardware.bar@1.0(including all interfaces and its types.hal) types.halfrom android.hardware.baz@1.0::types(interfaces in android.hardware.baz@1.0are not imported) IQux.haland types.halfrom android.hardware.qux@1.0 Quuzfrom android.hardware.quuz@1.0(assuming Quuzis defined in types.hal, the entire types.halfile is parsed, but types other than Quuzare not imported). Interface-level versioning Each interface within a package resides in its own file. The package the interface belongs to is declared at the top of the interface using the package statement. Following the package declaration, zero or more interface-level imports (partial or whole-package) may be listed. For example: package android.hardware.nfc@1.0; In HIDL, interfaces can inherit from other interfaces using the extends keyword. For an interface to extend another interface, it must have access to it via an import statement. The name of the interface being extended (the base interface) follows the rules for type-name qualification explained above. An interface may inherit only from one interface; HIDL does not support multiple inheritance. The uprev versioning examples below use the following package: // types.hal package android.hardware.example@1.0 struct Foo { struct Bar { vec<uint32_t> val; }; }; // IQuux.hal package android.hardware.example@1.0 interface IQuux { fromFooToBar(Foo f) generates (Foo.Bar b); } Uprev rules To define a package package@major.minor, either A or all of B must be true: Because of rule A: - The package can start with any minor version number (for example, android.hardware.biometrics.fingerprintstarts at @2.1.) - The requirement " android.hardware.foo@1.0is not defined" means the directory hardware/interfaces/foo/1.0should not even exist. However, rule A does not affect a package with the same package name but a different major version (for example, android.hardware.camera.device has both @1.0 and @3.2 defined; @3.2 doesn't need to interact with @1.0.) Hence, @3.2::IExtFoo can extend @1.0::IFoo. Provided the package name is different, package@major.minor::IBar may extend from an interface with a different name (for example, android.hardware.bar@1.0::IBar can extend android.hardware.baz@2.2::IBaz). If an interface does not explicitly declare a super type with the extend keyword, it will extend android.hidl.base@1.0::IBase (except IBase itself). B.2 and B.3 must be followed at the same time. For example, even if android.hardware.foo@1.1::IFoo extends android.hardware.foo@1.0::IFoo to pass rule B.2, if an android.hardware.foo@1.1::IExtBar extends android.hardware.foo@1.0::IBar, this is still not a valid uprev. Upreving interfaces To uprev android.hardware.example@1.0 (defined above) to @1.1: // types.hal package android.hardware.example@1.1; import android.hardware.example@1.0; // IQuux.hal package android.hardware.example@1.1 interface IQuux extends @1.0::IQuux { fromBarToFoo(Foo.Bar b) generates (Foo f); } This is a package-level import of version 1.0 of android.hardware.example in types.hal. While no new UDTs are added in version 1.1 of the package, references to UDTs in version 1.0 are still needed, hence the package-level import in types.hal. (The same effect could have been achieved with an interface-level import in IQuux.hal.) In extends @1.0::IQuux in the declaration of IQuux, we specified the version of IQuux that is being inherited (disambiguation is required because IQuux is used to declare an interface and to inherit from an interface). As declarations are simply names that inherit all package and version attributes at the site of the declaration, the disambiguation must be in the name of the base interface; we could have used the fully-qualified UDT as well, but that would have been redundant. The new interface IQuux does not re-declare method fromFooToBar() it inherits from @1.0::IQuux; it simply lists the new method it adds fromBarToFoo(). In HIDL, inherited methods may not be declared again in the child interfaces, so the IQuux interface cannot declare the fromFooToBar() method explicitly. Uprev conventions Sometimes interface names must rename the extending interface. We recommend that enum extensions, structs, and unions have the same name as what they extend unless they are sufficiently different to warrant a new name. Examples: // in parent hal file enum Brightness : uint32_t { NONE, WHITE }; // in child hal file extending the existing set with additional similar values enum Brightness : @1.0::Brightness { AUTOMATIC }; // extending the existing set with values that require a new, more descriptive name: enum Color : @1.0::Brightness { HW_GREEN, RAINBOW }; If a method can have a new semantic name (for instance fooWithLocation) then that is preferred. Otherwise, it should be named similarly to what it is extending. For example, the method foo_1_1 in @1.1::IFoo may replace the functionality of the foo method in @1.0::IFoo if there is no better alternative name. Package-level versioning HIDL versioning occurs at the package level; after a package is published, it is immutable (its set of interfaces and UDTs cannot be changed). Packages can relate to each other in several ways, all of which are expressible via a combination of interface-level inheritance and building of UDTs by composition. However, one type of relationship is strictly-defined and must be enforced: Package-level backwards-compatible inheritance. In this scenario, the parent package is the package being inherited from and the child package is the one extending the parent. Package-level backwards-compatible inheritance rules are as follows: - All top-level interfaces of the parent package are inherited from by interfaces in the child package. - New interfaces may also be added the new package (no restrictions about relationships to other interfaces in other packages). - New data types may also be added for use by either new methods of uprev'ed existing interfaces, or by new interfaces. These rules can be implemented using HIDL interface-level inheritance and UDT composition, but require meta-level knowledge to know these relationships constitute a backwards-compatible package extension. This knowledge is inferred as follows: If a package meets this requirement, hidl-gen enforces backwards-compatibility rules.
https://source.android.com/devices/architecture/hidl/versioning?hl=de
CC-MAIN-2022-27
en
refinedweb
Has anyone seen an error in unit tests that says there is no indented block inside of the test code? I have written many unit tests for my course and they have all worked until today. Now suddenly none of them are working (even ones that previously did), and I am getting this error: I haven’t changed anything in previously working files of unit tests and they are all now getting this error. It could be something in my code, but the code I have in the test is pretty straightforward and just calls a test function I have written: def test_Q4_Test_Grass_Type(self): self.q4.test_grass() It’s frustrating this is occurring now because my students are taking an exam tomorrow, and I like to give them unit tests to use on the programming portion of the exam and now it seems I won’t have that. Please let me know if there is a fix or if anyone else has gotten this error.
https://ask.replit.com/t/new-repl-error-in-unit-testing/264
CC-MAIN-2022-27
en
refinedweb
Big Data Big data is large amount of data. Big Data in normal layman’s term can be described as a huge volume of unstructured data. It is a term used to describe data that is huge in amount and which keeps growing with time. Big Data consists of structured, unstructured and semi-structured data. This data can be used to track and mine information for analysis or research purpose. What is Big Data? Big data in simple terms is a large amount of structured, unstructured, semi-structured data that can be used to for analysis purpose. - Volume: The name Big Data itself suggest it contains large amount of data. The size of the data is very important in determining whether the data is “Big data” or not. Hence, “Volume” is an important characteristic when dealing with Big data. - Velocity: Velocity is the speed at which data is generated. In Big Data the velocity is a measure of determining the efficiency of the data. The more quickly the data is generated and processed will determine the data’s real potential. The flow of data is huge and Velocity is one of the characteristics of Big Data. - Variety: Data comes in various forms, structured, unstructured, numeric, etc. Earlier spreadsheets and database were considered as data. But now pdf’s, emails, audio, etc are considered for analysis. Let us know more about Big Data Big Data has turned out to be really important for businesses who want to maintain their files and huge amount of data. Companies have moved to Big Data technologies in order to maintain data for analysis or business development purposes. Importance of Big Data: Big Data is important not in terms of volume but in terms of what you do with the data and how you utilize it to make analysis in order to benefit your business and organisation. Big Data helps analyse: - Time - Cost - Product Development - Decision Making, etc Big data when teamed up with Analytics help you determine root causes of failure in businesses, analyse sales trends based on analysing the customer buying history. Also help determine fraudulent behaviour and reduce risks that might affect the organisation. Big Data Technology has given us multiple advantages, Out of which we will now discuss a few. - Big Data has enabled predictive analysis which can save organisations from operational risks. - Predictive analysis has helped organisations grow business by analysing customer needs. - Big Data has enabled many multimedia platforms to share data Ex: youtube, Instagram. - Medical and Healthcare sectors can keep patients under constant observations. - Big Data changed the face of customer-based companies and worldwide market Big Data Categories - Structured - Unstructured - Semi-structured Structured Data: Data which is stored in a fixed format is called as Structured Data. In structured data the data is formatted so that it is easily accessible and can be used for analysis. Unstructured Data: Any data whose structure is not classified is known as unstructured data. Unstructured data is very huge in size. Unstructured data usually consists of data that contains combination of text, images, files, etc. They do not use conventional database models. Semi-structured Data: It contains both structured as well as unstructured data. The data is not organized in a repository but has associated information which makes it accessible. Characteristics of Big Data 1-Volume Volume refers to the unimaginable amounts of information generated every second from social media, cell phones, cars, credit cards, M2M sensors, images, video, and whatnot. We are currently using distributed systems, to store data in several locations and brought together by a software Framework like Hadoop. Facebook alone can generate about billion messages, 4.5 billion times that the “like” button is recorded, and over 350 million new posts are uploaded each day. Such a huge amount of data can only be handled by Big Data Technologies. 2-Variety As Discussed before, Big Data is generated in multiple varieties. Compared to the traditional data like phone numbers and addresses, the latest trend of data is in the form of photos, videos, and audios and many more, making about 80% of the data to be completely unstructured Structured data is just the tip of the iceberg. 3-Veracity Veracity basically means the degree of reliability that the data has to offer. Since a major part of the data is unstructured and irrelevant, Big Data needs to find an alternate way to filter them or to translate them out as the data is crucial in business developments 4-Value Value is the major issue that we need to concentrate on. It is not just the amount of data that we store or process. It is actually the amount of valuable, reliable and trustworthy data that needs to be stored, processed, analyzed to find insights. 5-Velocity Last but never least, Velocity plays a major role compared to the others, there is no point in investing so much to end up waiting for the data. So, the major aspect of Big Data is to provide data on demand and at a faster pace. How are the Top MNCs Using Big Data Analytics to their Advantage? 1. 2. 3. 4. 5. Here are some Uses of Big Data and where it is used - Health Care - Detect Frauds - Social Media Analysis - Weather - Public sector. Contribution of Big Data in Health Care The contribution of Big Data in Healthcare domain has grown largely. With medical advances there was need to store large amount of data of the patients. Big data is used extensively to store the patients health history. This data can be used to analyse the patients health condition and to prevent health failures in future. Detect Fraud Fraud detection and prevention is one of the many uses of BIg Data today. Credit card companies face a lot of frauds and big data technologies are used to detect and prevent them. Earlier credit card companies would keep a track on all the transactions and if any suspicious transaction is found they would call the buyer and confirm if that transaction was made. But now the buying patterns are observed and fraud affected areas are analysed using Big Data analytics. This is very useful in preventing and detecting frauds. Social Media Analysis The best use case of big data is the data that keeps flowing on social media networks like, Facebook, Twitter, etc. The data is collected and observed in the form of comments, images, social statuses, etc. Companies use big data techniques to understand the customers requirements and check what they say on social media. This helps companies to analyse and come up strategies that will be beneficial for the companies growth. Weather Big Data technologies are used to predict the weather forecast. Large amount of data is feeded on the climate and an average is taken to predict the weather This can be useful to predict natural calamities such as floods, etc. Examples of how some MNCs are handling Big Data Analytics -. 5-Google Did you know that Google processes about 3.5 billion search queries on single day? Do you know that each request queries about pages numbering 20 billion? Google derives such search results from knowledge graph database, indexed pages and Google bots crawling over a plethora of web pages. The user requests are processed in Google’s application servers. The application server searches results in GFS (Google File System) and logs the search queries in logs cluster for quality testing. Google uses Dremel which is a query execution engine to run almost near real-time, ad-hoc queries from search engines. This kind of advantage is not present in MapReduce. Google launched BigQuery which runs queries based on aggregation over billions row tables in a matter of seconds. Google is really advanced in its implementation of big data technologies. 6-Facebook Did you know that users of Facebook upload 500+ terabytes of data per day? To process such large chunks of data, Facebook uses Hive for parallel map-reduce opertions and Hadoop for its data storage. Would you believe me if I say Facebook uses Hadoop cluster which is the largest in the world? Employees also use Cassandra which is fault-tolerant, distributed storage system aiming to manage large amount of structured data across variety of commodity servers. Facebook also uses Scuba to carry out real-time ad-hoc analysis on massive data sets. Hive is used to store large data in Oracle data warehouse. Prism is used to bring out and manage multiple namespaces instead of a single one managed by Hadoop. Facebook also uses many other big data technologies such as Corona, Peregine, among many others. 7-Oracle There is an explosive growth like 12.5 billion devices which doesn’t include phones, tablets and PCs. This has helped to increase the research and development in the field of Internet-of-Things and in storage requirements which in turn require database management support. Oracle users use Oracle Advanced Analytics which requires Oracle database to be loaded with data. Oracle advanced analytics provides functionalities such as text mining, predictive analytics, statistical analysis and interactive graphics among many others. HDFS data can be loaded into an Oracle data warehouse using Oracle Loader for Hadoop. This feature is used to link data and search query results from Hadoop to Oracle data warehouse. Oracle Exadata Database Machine provides scalable and high-end performance for all database applications. Oracle is leveraging big data to mainly expand its business in Database management systems.
https://abhinavshukla1808.medium.com/big-data-59f93af15c81
CC-MAIN-2022-27
en
refinedweb
Change 272124* introduced a regression in spaceRequiredBetween for left aligned pointers to decltype and typeof expressions. This fix adds logic to fix this. The test added is based on a related test in determineStarAmpUsage. Also add test cases for the regression. LLVM bug tracker: Please use FormatToken::getPreviousNonComment here and add a test like typedef typeof/*comment*/(int(int, int))* MyFuncPtr; This uses FormatToken::getPreviousNonComment and adds a test. This also fixes a bug in token annotation that was breaking the test (by also using getPreviousNonComment instead of Previous) It would be cool if you extract the calls to getPreviousNonComment to a variable, saving the double iteration. Pulled out getPreviousNonComment() into local variable to avoid calling twice. Fix bad formatting Looks good! Please reformat the newly added code blocks with clang-format before submitting. Please reformat this block with clang-format: PrevToken gets indented by two more columns to the right. Pleasereformat this block with clang-format: when I run it, it produces: if (Right.is(TT_PointerOrReference)) { if (Left.is(tok::r_paren) && Line.MightBeFunctionDecl) { if (!Left.MatchingParen) return true; FormatToken *TokenBeforeMatchingParen = Left.MatchingParen->getPreviousNonComment(); if (!TokenBeforeMatchingParen || !TokenBeforeMatchingParen->isOneOf(tok::kw_typeof, tok::kw_decltype)) return true; } return (Left.Tok.isLiteral() || (Left.is(tok::kw_const) && Left.Previous && Left.Previous->is(tok::r_paren)) || (!Left.isOneOf(TT_PointerOrReference, tok::l_paren) && (Style.PointerAlignment != FormatStyle::PAS_Left || (Line.IsMultiVariableDeclStmt && (Left.NestingLevel == 0 || (Left.NestingLevel == 1 && Line.First->is(tok::kw_for))))))); } Ran clang-format over changes and corrected formatting I resolved the formatting issues. I apologize for not paying closer attention to formatting earlier. I don't have commit access, so if this change looks good now, could someone with access please commit?
https://reviews.llvm.org/D35847
CC-MAIN-2022-27
en
refinedweb
AndroidComponentsExtension interface AndroidComponentsExtension<DslExtensionT : CommonExtension<*, *, *, *>?, VariantBuilderT : VariantBuilder?, VariantT : Variant?> : DslLifecycle Generic extension for Android Gradle Plugin related components. Each component has a type, like application or library and will have a dedicated extension with methods that are related to the particular component type. Summary Public functions beforeVariants finalizeD fun beforeVariants( selector: VariantSelector? = selector().all(), callback: Action<VariantBuilderT?>? ): Unit Action based version of beforeVariants above. finalizeDSl fun finalizeDSl(callback: Action<DslExtensionT?>?): Unit Action based version of finalizeDsl above. onVariants fun onVariants( selector: VariantSelector? = selector().all(), callback: Action<VariantT?>? ): Unit Action based version of onVariants above. registerExtension @Incubating). registerSourceType @Incubating fun registerSourceType(name: String?): Unit Register a new source type to all source sets. The name of the source type will be used to create expected directories names in the various source sets. For instance, src/main/ There is no notion of priorities between the build-type, flavor specific directories, all the expected directories will be interpreted as a flat namespace. Therefore, any org.gradle.api.Task that needs access to the entire list of source folders can just use the Sources.extras's SourceDirectories.all method for that source type. However, If you need to have overriding priorities between the expected directories and therefore require a merging activity, you can still use this API but you will need to create a merging task that will have all sources in input and produce a single output folder for the merged sources. selector fun selector(): VariantSelector Creates a VariantSelector instance that can be configured to reduce the set of ComponentBuilder instances participating in the beforeVariants and onVariants callback invocation. Public properties pluginVersion val pluginVersion: AndroidPluginVersion The version of the Android Gradle Plugin currently in use. sdkComponents val sdkComponents: SdkComponents Provides access to underlying Android SDK and build-tools components like adb.
https://developer.android.com/reference/tools/gradle-api/7.2/com/android/build/api/variant/AndroidComponentsExtension?hl=da
CC-MAIN-2022-27
en
refinedweb
Can I resize ui.image pictures in Pythonista? I know I can do resizing with pillow(i.e. reducing the dimensions of the picture), but to start with I have the picture as a ui.imageobject. So can I resize it as that (before I send it over to pillow)? @halloleooo try import ui ui_image = ui.Image.named('test:Lenna') w,h = ui_image.size ui_image.show() print(w,h) wi = 100 hi = wi*h/w with ui.ImageContext(wi,hi) as ctx: ui_image.draw(0,0,wi,hi) ui_resize = ctx.get_image() print(ui_resize.size) ui_resize.show() @halloleooo did you see my little script in your other topic "How to debug crash of image script when it's called as extension"
https://forum.omz-software.com/topic/7011/can-i-resize-ui-image-pictures-in-pythonista/?
CC-MAIN-2022-27
en
refinedweb
#include <fbxsdk/fbxsdk_def.h> #include <fbxsdk/fbxsdk_nsbegin.h> #include <fbxsdk/fbxsdk_nsend.h> Debugging macros and functions. All macros and functions are removed in release builds. To enable asserts, a debug build is required as well as the environment variable "FBXSDK_ASSERT" set to 1 is also required. By default, assertions will pop-up a window. It is possible to disable the pop-up on the Windows platform by calling the following code: Definition in file fbxdebug.h. If this environment variable is set to 1, the FBX SDK will assert in debug builds. Definition at line 30 of file fbxdebug.h. The assertion procedure signature. If a different assertion procedure must be provided, it should have this signature. Definition at line 37 of file fbxdebug.h. Change the procedure used when assertion occurs. Change the procedure back to the default one. Go to the source code of this file.
https://help.autodesk.com/cloudhelp/2018/ENU/FBX-Developer-Help/cpp_ref/fbxdebug_8h.html
CC-MAIN-2022-27
en
refinedweb
Why might you need to customize Liferay services? Perhaps you’ve added a custom field to Liferay’s User object and you want its value to be saved whenever the addUser or updateUser methods of Liferay’s API are called. Or maybe you want to add some additional logging functionality to some of Liferay’s APIs. Whatever your case may be, Liferay’s service wrappers provide easy-to-use extension points for customizing Liferay’s services. To create a module that overrides one of Liferay’s services, follow the Service Wrapper Template reference article to create a servicewrapper project type. As an example, here’s the UserLocalServiceOverride class that’s generated in the Service Wrapper Template tutorial: package com.liferay.docs.serviceoverride; import com.liferay.portal.kernel.service.UserLocalServiceWrapper; import com.liferay.portal.kernel.service.ServiceWrapper; import org.osgi.service.component.annotations.Component; @Component( immediate = true, property = { }, service = ServiceWrapper.class ) public class UserLocalServiceOverride extends UserLocalServiceWrapper { public UserLocalServiceOverride() { super(null); } } Notice that you must specify the fully qualified class name of the service wrapper class that you want to extend. The service argument was used in full in this import statement: import com.liferay.portal.service.UserLocalServiceWrapper This import statement, in turn, allowed the short form of the service wrapper class name to be used in the class declaration of your component class: public class UserLocalServiceOverride extends UserLocalServiceWrapper The bottom line is that when using blade create to create a service wrapper project, you must specify a fully qualified class name as the service argument. (This is also true when using blade create to create a service project.) For information about creating service projects, please see the Service Builder tutorial. The generated UserLocalServiceOverride class does not actually customize any Liferay service. Before you can test that your service wrapper module actually works, you need to override at least one service method. Open your UserLocalServiceOverride class and add the following methods: @Override public int authenticateByEmailAddress(long companyId, String emailAddress, String password, Map<String, String[]> headerMap, Map<String, String[]> parameterMap, Map<String, Object> resultsMap) throws PortalException { System.out.println( "Authenticating user by email address " + emailAddress); return super.authenticateByEmailAddress(companyId, emailAddress, password, headerMap, parameterMap, resultsMap); } @Override public User getUser(long userId) throws PortalException { System.out.println("Getting user by id " + userId); return super.getUser(userId); } Each of these methods overrides a Liferay service method. These implementations merely add a few print statements that are executed before the original service implementations are invoked. Lastly, you must add the following method to the bottom of your service wrapper so it can find the appropriate service it’s overriding on deployment. @Reference(unbind = "-") private void serviceSetter(UserLocalService userLocalService) { setWrappedService(userLocalService); } Now you’re ready to build your project. Navigate to your project’s root folder and run ../../gradlew build. The JAR file representing your portlet module is produced in your project’s build/libs directory. To deploy your project, run this command from your project’s root directory: blade deploy Blade CLI detects your locally running Liferay instance and deploys the specified module to Liferay’s module framework. After running the blade deploy command, you should see a message like this: Installed or updated bundle 334 Use the Gogo shell to confirm that your module was installed: Run blade sh lb at the prompt. If your module was installed, you’ll see an entry like this: 335|Active | 1|com.liferay.docs.serviceoverride (1.0.0.201502122109) Finally, log into your portal as an administrator. Navigate to the Users section of the Control Panel. Confirm that your customizations of Liferay’s user service methods have taken effect by checking Liferay’s log for the print statements that you added. Congratulations! You’ve created and deployed a Liferay DXP 7.0 service wrapper module! Related Topics Upgrading Service Wrappers Creating Modules with Blade CLI
https://help.liferay.com/hc/pt/articles/360018159951-Overriding-Liferay-Services-Service-Wrappers-
CC-MAIN-2022-27
en
refinedweb
README Hive Content ViewersHive Content Viewers Various content viewer web components for displaying different types of content. Supported Content TypesSupported Content Types UsageUsage InstallationInstallation npm i @teamhive/content-viewers Somewhere in your app (e.g. main.ts for Angular): import { defineCustomElements } from '@teamhive/content-viewers/dist/loader'; defineCustomElements(window); Or if you already have another stencil component library, define them separately: import { defineCustomElements as defineHiveContentViewers } from '@teamhive/content-viewers/dist/loader'; defineHiveContentViewers(window); Image ViewerImage Viewer To leverage viewerjs built in styling, you will need to import the global stylesheet into your application (instead of us bundling it with each image-viewer instance). @import '~viewerjs/dist/viewer.min.css';
https://www.skypack.dev/view/@teamhive/content-viewers
CC-MAIN-2022-27
en
refinedweb
Rectangle Selector¶ whether the button from eventpress and eventrelease are the same. from matplotlib.widgets import RectangleSelector import numpy as np import matplotlib.pyplot as plt def line_select_callback(eclick, erelease): """ Callback for line selection. *eclick* and *erelease* are the press and release events. """ x1, y1 = eclick.xdata, eclick.ydata x2, y2 = erelease.xdata, erelease.ydata print(f"({x1:3.2f}, {y1:3.2f}) --> ({x2:3.2f}, {y2:3.2f})") print(f" The buttons you used were: {eclick.button} {erelease.button}") def toggle_selector(event): print(' Key pressed.') if event.key == 't': if toggle_selector.RS.active: print(' RectangleSelector deactivated.') toggle_selector.RS.set_active(False) else: print(' RectangleSelector activated.') toggle_selector.RS.set_active(True) fig, ax = plt.subplots() N = 100000 # If N is large one can see improvement by using blitting. x = np.linspace(0, 10, N) ax.plot(x, np.sin(2*np.pi*x)) # plot something ax.set_title( "Click and drag to draw a rectangle.\n" "Press 't' to toggle the selector on and off.") # drawtype is 'box' or 'line' or 'none' toggle_selector.RS = RectangleSelector(ax, line_select_callback, drawtype='box', useblit=True, button=[1, 3], # disable middle button minspanx=5, minspany=5, spancoords='pixels', interactive=True) fig.canvas.mpl_connect('key_press_event', toggle_selector) plt.show() References The use of the following functions, methods, classes and modules is shown in this example: Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery
https://matplotlib.org/3.4.3/gallery/widgets/rectangle_selector.html
CC-MAIN-2022-27
en
refinedweb
Mozambique: Cashew, Sugar Concessions Date distributed (ymd): 010219 Document reposted by APIC +++++++++++++++++++++Document Profile+++++++++++++++++++++ Region: Southern Africa Issue Areas: +economy/development+ Summary Contents: This posting contains two articles by Joseph Hanlon, as well as several related news reports from the Mozambique News Agency, on new IMF/World Bank concessions on Mozambique's export policies for cashews and sugar, two of the country's principal exports. The cashew issue in particular has long been a subject of dispute and protest (see from 1997 'Can Mozambique Make the World Bank Pay for Its Mistakes?' -, and, recently 'Price of Cashew Nuts Collapses'). International institutions insisted on removing protection from Mozambique's cashew-processing industry, in favor of theoretically available gains from exporting raw cashew nuts. The recent concessions come after years of criticism and protest from Mozambican business, labor, media and government. Nevertheless the new policy does not address the issue of compensation to Mozambique for the damage resulting from the failed policies imposed at creditor insistence. +++++++++++++++++end profile++++++++++++++++++++++++++++++ Mozambique Wins Long Battles over Cashew Nuts and Sugar Mozambique Bans Raw Cashew Exports after IMF Allows Cashew and Sugar Protection articles and clippings by Joseph Hanlon (j.hanlon@open.ac.uk) January 30, 2001 Mozambique has banned the export of unprocessed cashew nuts, ending a five-year battle with the World Bank and International Monetary Fund. Meanwhile, the IMF has allowed Mozambique to protect its expanding sugar industry; IMF directors overrode opposition from their own staff. Allowing Mozambique to protect its two most important agro-industries is a remarkable reversal by the international financial institutions. It results from intense pressure from the Mozambican government, trade unions and business, taken up by international campaign groups. Cashew became a symbol of mindless trade liberalisation when in 1995 the World Bank forced Mozambique to allow the unrestricted export of unprocessed cashew nuts to India. The World Bank argued that peasant producers would gain higher prices from the free market. But it did not happen -- as a monopoly buyer, India pushed down the price; transfer pricing also lowered the price paid to Mozambique; and traders within Mozambique pocketed larger margins. So the peasants lost out, while nearly 10,000 industrial workers (half women) became unemployed. For five years Mozambique has campaigned against the ban. Finally, on 18 December the IMF Executive Board agreed a policy under which some cashew factories will be closed, but the rest will be protected. The protection is two-fold, an 18 percent export duty on unprocessed cashew nuts, plus the local industry given the right of first refusal -- to purchase nuts before they are exported. In light of this, the government banned the export of raw cashew nuts in mid-January. Clippings reproduced below set out the recent events. The long history of the cashew saga was published last year in "Review of African Political Economy" no 83, pages 29-45. The article is also on the web, at Meanwhile, the IMF Executive Board rejected a demand from its own staff, and agreed that Mozambique can protect its sugar industry, which is now being rehabilitated with major foreign investment. IMF staff had argued that since Mozambique could import sugar cheaper than producing it, it should allow duty-free import of sugar. Investors had demanded protection and were backed by the government. On 18 December, the IMF board agreed with the government and not its own staff. Cashew and sugar are both about similar issues: Mozambique wants to create and protect tens of thousands of industrial jobs (cashew and sugar are the country's two largest industries). On the other hand, the international financial institutions (IFIs) argue that free trade and globalisation will bring more long-term benefit, outweighing the cost and disruption of massive unemployment. The IFIs believed they could impose their policies, but the international outcry over cashew made them rethink, and accept that they had to listen more closely to elected national government. IMF Relents on Cashew and Sugar by Joseph Hanlon, 30.01.01 The IMF has quietly accepted a compromise in which some of Mozambique's privatised cashew nut processing factories will be closed and the rest will be protected. This interpretation comes from a close reading of a set of documents issued by the IMF in December and January. The decision to ban exports should be seen in this context. IMF directors also accepted Mozambique's rejection of IMF staff demands on sugar. CASHEW On the surface, the IMF continues to take a hard line on cashew. Notes of the 18 December Executive Board meeting, published 17 January, say: "Directors welcomed the authorities' commitment to trade liberalization. They urged them to stay the course of trade liberalisation, and to resolve the problems of the cashew processing industry." However, the line in the joint IMF/government Memorandum of Economic and Fiscal Policies, published 19 December, is more subtle: ". The government expects to pay Mt 100 billion (about $6 million) to cashew processing companies to pay accumulated back wages to the workers, according to the memorandum. The IMF staff report on Mozambique was published on 17 January 2001, and on cashew it notes that in October 1999 parliament (Assembly of the Republic) "passed a law providing for an increase in the export tax on raw cashew nuts from 14 per cent to 18-22 percent and for a first right to purchase raw nuts for the benefit of indigenous processors. In the wake of this law, the World Bank sponsored an assessment of competitiveness and employment in the cashew-processing industry in Mozambique. This study recommended the liquidation of several non-viable processing plants, with financial support from the government for the settlement of outstanding wage claims. The study also found that newer factories, using a more labor-intensive technology, did not require any special assistance. Following these recommendations, the government decided in September 2000 on a new policy for the cashew sector. It set the export tax at 18 percent for the current crop year, invited the cashew exporters and processors to agree among themselves on possible modalities for the first right to purchase, and accepted in principle the liquidation of unviable processing plants. The government also expressed support for the Mozambican Cashew Institute's efforts, formalised in a master plan, to stimulate farm production of cashew nuts, which, for reasons of inadequate tree maintenance and plants, remains near a historical low. The staff welcomed these decisions, in particular the emphasis on expanding cashew production and solving the problems of the processing industry." I read this to mean that in exchange for closing some factories, the IMF now accepts the concept that the local industry must be given a first right to purchase and that, as has happened, the government can ban the export of raw nuts until the local industry's needs have been satisfied. That was, in practice, what Mozambique has been demanding for five years. SUGAR Sugar has been an issue, with the government wanting to impose an import duty to protect the domestic sugar industry. It argued that virtually all sugar producers do this (including the EU), and that it was essential to protect the tens of millions of dollars in investment planned for the industry. IMF staff had in late 1999 called for Mozambique to be the first big producer not to protect its industry, but Mozambique has now won the battle to maintain protection. The joint Memorandum of Economic and Fiscal Policies says ." The staff study notes that "The government remains determined to support the rebuilding of the sugar industry in Mozambique and has therefore decided to uphold the increase in import surcharges for sugar granted in September 1999. At that time, the staff had viewed the increase in protection as troubling evidence of an inward-oriented industrial police, quite apart from its running counter to the government's commitment not to adopt new, or increase existing, general import surcharges under the programme. In the face of the authorities' wish to maintain the higher import surcharges and raise them further according to a preannounced schedule, the staff suggested that at least the further increases be put on hold, pending the outcome of a cost-benefit analysis of the intended policy, including its impact on the poor. At the invitation of the government, the Food and Agriculture Organization (FAO) undertook this analysis, coming out in support of the government's approach. The staff accepted this position but recommended that the additional protection granted in September 1999 be cut back again over a preannounced period of five years, broadly in line with the time investors thought necessary for the rebuilding of the industry. The government did not accept the staff's recommendation and instead retained discretion to review annual the level of protection based on domestic and international sugar market developments." With FAO support, government has rejected IMF staff views on sugar, and IMF directors have backed this. Notes of the 18 December Executive Board meeting say "A few Directors also stressed the need to avoid increasing protection of the sugar industry". Thus only "a few" directors backed their own staff in opposition to the government. The relevant documents are: Letter of Intent and Memorandum of Economic and Financial Policies of the Government of Mozambique for 200001. Dated 1 Dec 2000, published 19 Dec 2000 following Executive Board meeting of 18 Dec 2000. Mozambique: 2000 Article IV Consultation and Second Review Under the Poverty Reduction and Growth Facility--Staff Report; Staff Statement; Public Information Notice and Press Release on the Executive Board Discussion; and Statement by the Authorities of Mozambique, 17 Jan 2001 IMF Completes Second Review under PRGF for Mozambique and Approves Second Annual PRGF Loan Finally, Raw Cashew Exports Banned Maputo, 26 Jan (AIM) - The Mozambican authorities have slapped an embargo on the export of raw cashew nuts to India, reports Friday's issue of the independent newsheet "Metical"., however, could not believe that the export prices (on which the companies would have to pay the 18 per cent surtax) could be as low as the exporters claimed. They alleged that this season's export price varied from 355 to 440 US dollars a tonne. The government, however, does not want the nuts exported for anything less than an FOB price of 650 dollars dollars a tonne - about twice the price the exporters say the Indian companies are paying them. (AIM) IMF Agrees to Protect Sugar but not Cashew Industry Maputo, 27 Dec (AIM) - Wednesday's issue of the independent newsheet "Metical", in a letter sent to the IMF, the Mozambican government says that following the conclusions of a study conducted by the United Nations Food and Agriculture Organisation has decided to maintain, for next year, the level of protection tax that had been established for September 1999, and adds that this policy will be reviewed every year taking into account the changing prices of sugar. The new positions of the government and the IMF could well be predicted if one takes into account recent statements by IMF director Horst Kohler. In September, Kohler aknowledged, in an interview to the Financial Times, the importance of the protection to the sugar industry in countries such as Mozambique. He said then that the high customs duties applied on imported sugar would end up being covered by the less well off people, but this would not affect the macro-economic stability. "I do not want to have the IMF indirectly being an instrument of the rich countries to maintain the protection of their levels of protection, while we continue saying to the poor countries to speed up their structural adjustment. Recently, Mozambican Prime Minister Pascoal Mocumbi was against any impositions of policies by foreign powers. He thought that the protection on the sugar industry was essential for the sector's recovery. However, the IMF still insists in not changing its policy towards the cashew industry. Because it is going to increase its public expenditure for 2001, the government justified this by saying that money has to be transferred to the cashew industry to compensate the workers who lost their jobs as a consequence led to the closing of nearly all cashew factories. There are about 5000 such workers. The document notes that these are just the social aspect of the debts iuncurred, but one should also take into account all the money the new owners invested to rehabilitate the factories. The government also accepts the IMF principle to liquidate the non-feasible factories, but does explain how this will be done, and this leaves the factory owners apprehensive about whether the government will return about 32 industrialists are owing to the banks. (AIM) More Workers Fall Victim to IMF Structural Policies Maputo, 3 Jan (AIM) - Some 5,930 Mozambican cashew workers lost their jobs in 2000, largely thanks to the International Monetary Fund structural policies being followed by the country. The country's cashew and shoe trade union branches said that the biggest burden fell on the northern Nampula province which saw 3,000 workers be made redundant. Maputo contributed with a further 1,200 workers, while the southern provinces of Gaza and Inhambane collectively came up with 1,730. If added to those who lost their jobs between 1997 to 1999, the figure rises up to 8,800 - meanwhile, the cashew processing industry is completely paralised. Boaventura Mondlane of the cashew trade union branch, SINTIC, blamed the paralisation of the sector on the liberalisation of the export of raw nuts, mainly to India. The farm-gate price has gone down, he said. India has driven the price of raw nuts, and Mozambique is reeling under the impact of low prices - it has no alternative but to sell at whatever price India chooses. (AIM) Most Cashew Workers Now Unemployed Maputo, 20 Jan (AIM) - About 6,000 workers in Mozambique's cashew processing industry lost their jobs in 2000, according to the general secretary of the Cashew Workers Union (SINTIC), Boaventura Mondlane, cited in Saturday's issue of the Maputo daily "Noticias". This brings to 8,500 the number of workers who have definitively lost their jobs since the crisis in the cashew sector began to bite in 1997. In other words, the great majority of workers in this industry are now unemployed. "We have just ended a dark year for the cashew sector", said Mondlane. Prospects for the future looked no better - he said there was no money available to reopen factories that have closed because of the liberalisation of the trade in cashews imposed on Mozambique by the World Bank. Since 1995, the World Bank had insisted that protection be removed from the local processing industry: in effect, this meant that raw cashew nuts were exported to India, for processing by child labourers who shell the nuts by hand, rather than sold to the Mozambican factories. Liberalisation, the World Bank insisted, protected the interests of the peasants who harvest the nuts, who would receive a greater percentage of the cashew price. But as the industrialists predicted, the opposite has happened. With next to no competition from the local factories, the exporters of raw nuts have been able to push prices down. "The result of liberalisation, which we are now witnessing, is a fall in the marketing price", said Mondlane. "The producers are earning less and less, contrary to the arguments of the World Bank and the government. Now that the industry has been put out of action, prices are tumbling". This year's cashew marketing campaign in northern Mozambique looks good, but the bankrupt industries are unable to purchase nuts and reopen their plants. With the fading of all hope for the industry, workers who had been kept on the books even though they were producing nothing, have now been made definitively redundant. The sacked workers are receiving their wage arrears and their redundancy pay. "We are not satisfied at the payment of redundancy money", said Mondlane. "Our objective is employment, and not the laying off of workers". (AIM)
http://www.africaaction.org/docs01/cash0101.htm
crawl-002
en
refinedweb
#include <iostream>int main() {enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};//Now SUNDAY = 0, MONDAY = 1, etc...Days today; //defining a variable based on the above enumerationtoday = MONDAY;if(today == Sunday || today == Saturday) std::cout << "Hooray! The weekend!\n";else std:cout << "Crap back to work\n";return 0;} const int SUNDAY = 0;
http://www.dreamincode.net/forums/showtopic48962.htm
crawl-002
en
refinedweb
lxml has very sophisticated support for custom Element classes. You can provide your own classes for Elements and have lxml use them by default or only for a specific tag name in a specific namespace. Custom Elements must inherit from the lxml.etree.ElementBase class, which provides the Element interface for subclasses: >>> from lxml import etree >>> class HonkElement(etree.ElementBase): ... def honking(self): ... return self.get('honking') == 'true' ... honking = property(honking) This defines a new Element class HonkElement with a property honking. Note that you cannot (or rather must not) instantiate this class yourself. lxml.etree will do that for you through its normal ElementTree API. You can let lxml use your new class for every Element it generates: >>> etree.setDefaultElementClass(HonkElement) >>> el = etree.Element("myelement") >>> print isinstance(el, HonkElement) True >>> el.honking False >>> el = etree.Element("myelement", honking='true') >>> print etree.tostring(el) <myelement honking="true"/> >>> el.honking True To reset lxml.etree to the original element class, pass None or nothing: >>> etree.setDefaultElementClass() >>> el = etree.Element("myelement") >>> print isinstance(el, HonkElement) False lxml allows you to implement namespaces, in a rather literal sense. You can build a new element namespace (or retrieve an existing one) by calling the Namespace class: >>> namespace = etree.Namespace('') and then register the new element type with that namespace, say, under the tag name honk: >>> namespace['honk'] = HonkElement After this, you create and use your XML elements through the normal API of lxml: >>>>> honk_element = etree.XML(xml) >>> print honk_element.honking True The same works when creating elements by hand: >>> honk_element = etree.Element('{. There is one thing to remember. Element classes must not have a constructor, neither must there be any internal state (except for the data stored in the underlying XML tree). Element instances are created and garbage collected at need, so there is no way to predict when and how often a constructor would be called. Even worse, when the __init__ method is called, the object may not even be initialized yet to represent the XML tag, so there is not much use in providing an __init__ method in subclasses. However, there is one possible way to do things on element initialization, if you really need to. ElementBase classes have an _init() method that can be overridden. It can be used to modify the XML tree, e.g. to construct special children or verify and update attributes. The semantics of _init() are as follows: In the Namespace example above, we associated the HonkElement class only with the 'honk' element. If an XML tree contains different elements in the same namespace, they do not pick up the same implementation: >>>>> honk_element = etree.XML(xml) >>> print honk_element.honking True >>> print honk_element[0].honking Traceback (most recent call last): ... AttributeError: >>> class HonkElement(HonkNSElement): ... def honking(self): ... return self.get('honking') == 'true' ... honking = property(honking) >>> namespace['honk'] = HonkElement Now you can rely on lxml to always return objects of type HonkNSElement or its subclasses for elements of this namespace: >>>>> honk_element = etree.XML(xml) >>> print type(honk_element), type(honk_element[0]) <class 'HonkElement'> <class 'HonkNSElement'> >>> print honk_element.honking True >>> print honk_element.honk() HONK >>> print honk_element[0].honk() HONK >>> print honk_element[0].honking Traceback (most recent call last): ... AttributeError: 'HonkNSElement' object has no attribute 'honking' Note that you can also combine this with the global default class. Namespace specific classes will simply override the less specific default.
http://codespeak.net/lxml/namespace_extensions.html
crawl-002
en
refinedweb
Good Robot has been on my mind lately. I keep coming back to the fact that I put a few months into it and didn’t finish it. But then I remember that on top of gameplay concerns I’ve also got a bunch of annoying technology problems to worry about and I lose my enthusiasm. The central part of the technology problems come from [my usage of] GLSL – the OpenGL shader language. The rest of my code – talking to the filesystem, input devices, AI, and gameplay – is basically solid, but the shaders are a mess. On one machine robots would strobe, randomly rendering or not from one frame to the next. Another tester reported that walls didn’t render. Another had the robots and walls render fine, but powerups were invisible. Another person had strange slowdowns that should not have been happening on their given hardware. The center of the problem is that I’m not very knowledgeable regarding GLSL. I’ve only gotten around to messing with it in the last couple of years, and I’ve only learned enough to accomplish the few simple things I need to do. This leaves great big blind spot in my knowledge where problems can hide. It creates situations where I can do something the wrong way and have it work on my machine, and malfunction a dozen different ways elsewhere. But to correct this problem I have to deal with another one: The GLSL resources are an absolute mess. The language has undergone sweeping changes at least twice since its inception. Programs that were once valid are now wrong, which means nearly all of the basic “hello world” tutorials are now broken to the point where they won’t even compile. The docs are filled with side-notes about what’s “new” in a version people stopped using five years ago. The simple stuff is out of date, and the advanced stuff is written with the assumption that you already know what you’re doing and you just need a few pointers on how things have changed. It’s amazing how many pages of documentation fail to explain how things actually work, but instead explain how things differ from how they used to work. It’s like giving someone directions based on scenery that no longer exists. “Drive until you get to the place that used to be a drugstore, turn left onto old main street, and turn left when you see the empty lot where the recycling center used to be.” You’ll probably be be able to find the place eventually, but those layers of ambiguity and uncertainty are a major hindrance. Further exacerbating the problem is that the updated and proper way of doing things is a lot more complex. The entire OpenGL matrix stack has been deprecated. In plain language, this means that the built-in systems for managing tables of numbers and performing the spatial transformations needed to take 3D scenery and draw it on a 2D screen are no longer supposed to be used. You’re supposed to write all of those systems yourself. Now, there are a lot of good reasons for that, but it’s also a massive undertaking when you’re just trying to get a handle on the basics. I’m sure there are open-source tools to do the job, but integrating those is a pain and it adds huge levels of complexity to what should otherwise be simple and straightforward learning exercise. (I already have my own matrix code, although it’s not nearly as well-developed as it could be.) When you get a blank screen you have to wonder: “Am I still not doing this shader properly, or am I mis-applying this new matrix system?” You can fall back to using the old matrix stack, but only if you find the directive to do so and only if you can intuit how it works. (It’s not well documented and I have yet to see it appear in example code.) If you post some short shader code and ask for help you’re likely to get immediate dismissal: “The old matrix stack is deprecated! Don’t use it!” Which is like asking someone why your internal combustion engine doesn’t work and having them give you a hard time because it doesn’t have a gearbox, a catalytic converter, or a starter motor. As if this wasn’t enough of an adventure, the OpenGL pages are somewhat capricious. In the process of working on this project the official docs would vanish for hours or days. You can download the docs as a PDF, but PDFs generally suck and Google can’t help you find what you’re looking for if they’re on your hard drive. And of course snarky RTFM forum posts all become that much less helpful as fallback documentation, since now they’re just insults with dead links. Basically: Learning GLSL is is tough hill to climb, it keeps getting steeper, and the topography keeps changing without anyone updating the maps. The people who reached the top years ago don’t really have a concept of how convoluted the road has gotten and so they often give unhelpful advice. But maybe I’ll have an easier time getting back to Good Robot if I force myself to do something sophisticated with shaders. Right now in Good Robot I’m just using them for simple stuff: I’m drawing basic squares and using the GPU (the graphics card, basically) to rotate them, scale them, and adjust the texture mapping so they draw from the proper section of the sprite sheet. That’s silly easy. My hope is that by doing a bunch of stuff that’s far more complex, I’ll actually get some depth to my GLSL knowledge and be able to spot the mistakes I’m making in Good Robot. Goals: - Aside from the shader work, I want to be really comfortable with what I’m doing. Which means doing something I’ve done before. Which means heightmap-based terrain. That’s easy, it’s familiar, and it looks interesting. (Enough.) - I want to do something that lets me dump a bunch of difficult processing onto the graphics card. Since we’re working with terrain, I figure erosion is a good choice. I’ll make some real-time erosion code and have it run on the GPU. - I want to explore how difficult it is to support Oculus Rift levels of performance. Most games run at 30fps. If the scene gets crowded or if the player stumbles into some scripted event, it’s generally acceptable (or tolerated) if the framerate dips down to 20 or so for a few seconds. But if you’re programming for VR, you need incredible performance. You need 60 frames per second. Worse, you need to render everything twice – one for each eye. If that’s not hard enough, it’s extremely uncomfortable to miss frames, so you can’t ever dip below 60fps unless you want to risk making people sick. So now the program has to render twice as much, twice as fast, with no margin for error. I can’t afford (or justify) getting a Rift dev kit right now, but it should be simple to set up a test to see if my program can keep up with the Rift performance demands. - I’m going to stop being so stubborn and just use the same dang coordinate system everyone else uses. More on this in another post. So those are our goals. I’m calling this “Frontier Rebooted” just because I’m re-hashing a lot of the ideas from Project Frontier, although the code is going to be all new. We’re going to have hills and water and grass and trees like before, but they’ll all be made using new techniques with shaders. Step one: Grab the latest version of my various 3D tools (which come from the Good Robot codebase) and drop them into a new project. I set up an empty scene with a one-meter panel drawn at the origin. Just to make sure I’ve got the axis all pointing the right way, I build a literal axis arrow at the world origin. Red is X, Y is green, blue is Z. Was that worth reading 1,500 words? I hope it was worth reading 1,500 words to see that. Next time we’ll actually accomplish something. Self-Balancing Gameplay There's a wonderful way to balance difficulty in RPGs, and designers try to prevent it. For some reason. This Game is Too Videogame-y What's wrong with a game being "too videogameish"? Programming Language for Games Game developer Jon Blow is making a programming language just for games. Why is he doing this, and what will it mean for game development? Silent Hill 2 Plot Analysis A long-form analysis on one of the greatest horror games ever made. Trekrospective A look back at Star Trek, from the Original Series to the Abrams Reboot. 94 thoughts on “Frontier Rebooted Part 1: Back to School” I’ve been going through this same process recently, with having to learn OpenGL in general on top of it (And learning OpenGL is even worse than GLSL- it has all the same problems of outdated stuff on the web, plus every tutorial uses some third party library to do some of the work, making starting from the very basics really hard). From the sounds of it, you’re moving from using the fixed-pipeline style of rendering to the modern shader-based one. It definitely does put a lot more work on the programmer, in exchange for a ton more flexibility. I too have been learning OpenGL and GLSL recently and given how easy it is to encounter old material on the internet I did run into a lot of the old fixed function pipeline stuff. This might depend on if you knew it before hand but I found it more confusing than doing it the more modern way. Doing it all yourself might not be easier, but I found it simpler. I’m currently in a Computer Graphics class. My teacher basically limited us to using OpenGL 2.0 (a very outdated version) for this very reason. Going much above that would simply take too much time to learn how to use properly. I gave up making 3d games entirely for these reasons. It made me feel like an idiot trying to figure this stuff out, discounted myself as stupid, and I went back to not making anything with code. At least I know I’m not alone, now. “I’m not smart enough” or “I’m stupid” is a bad reason to ever give up on anything. Everything is difficult, until it is easy. “I could spend my time more effectively doing something else” is a good one. “I could spend my time more effectively doing something else” can be a very low bar when the task at hand is sufficiently frustrating. For example, if your honest expectation is that pressing further on graphics programming is going to be a painful slog that never results in you actually building anything that works, you might decide that it’s more rewarding (even in the ‘long term’) to spend that time tickling your pleasure centre by ingesting some nice empty calories. True, but I leave that particular calculation up to the individual to determine. At least it’s less discouraging than “I’m not smart enough.” I taught a middle-school dropout with poor math skills how to convert between binary, decimal, and hexadecimal in 2 hours. And your point is? I have had some wonderful times ingesting empty calories. Mmmm, chocolate. Maybe so, but there are few things more discouraging than being unable to prove to yourself that you’re capable of doing some mental task. I now know that I’m not the problem; the problem is that the information base is held together with toothpicks and gum(not duct tape, that would actually have some substance). But yes, eventually I felt like I was wasting my time because I have artistic obligations, and there are easier ways to make games, so long as those ways aren’t intended to result in a game with 3D graphics, and also not involving using OpenGL to make a 2D game. I’m not gonna sit here and argue that it’s impossible. That’d be blind to the fact that there are those who do accomplish things with these systems. But the barrier for entry is obscene, it seems. It might be easier to learn how to play dwarf fortress over the phone. I can’t help but wonder, from a business standpoint, how many work hours are lost just trying to get the misshapen puzzle pieces to fit together. Well, if your inclinations lean more towards artistic talent than staring at endless lines of text, that’s still useful. Engineers tend to make terrible artists. From what Shamus has said, I’d have to agree that the barriers to entry are rather obscene. It may provide more performance at the end of the day, but at what cost? The result is a system that you can only really learn if you’re a maniac who isn’t willing to ever admit defeat, which is just another reason why so many programmers are crazy. That’s not efficient, that’s just elitist. If you still want to learn the programming side, I would encourage you not to give up. For anything. If you think it’s just not worth the effort… well, nothing to be ashamed of. Emphasize the things you’re good at. If you can’t think of anything you’re good at, find something you want to be good at and practice it until you are. It’s actually entirely worth it once you learn how. And it doesn’t take *that* long in the grand scheme of things- I learned it to a functional level in maybe 2-3 of weeks. It’s just incredibly frustrating because so often you find yourself in a place where making *any* progress is painfully hard because you’re trying to cobble together some sort of guide out of dozens of different sources on the internet. You can spend hours feeling like you’ve accomplished absolutely nothing at all, which makes is really hard to soldier on and continue. Once you get it working, though, there’s no comparison to fixed-pipeline stuff. It’s not just better performance-wise; the fixed pipeline was done away with because it was too limiting. Shaders give you way more options. Just because I’m an artist doesn’t mean I’m not also good at logical deduction. I programmed a working JPS algorithm, at least. :P And I’m an Engineer who also has a lot of artistic talent. There’s always 2D games. With technology these days and the massive amounts of memory, I have always wanted to create a huge 2D world, something procedurally generated to explore, perhaps using isometric graphics. Diablo 2 was a great example of 2D graphics in a large environment. If you look closely, you will see the game doesn’t have any hills at all, it’s all flat terrain, yet it is so nicely done, you never really notice. There’s plenty to do out there. Personally, I think 3D is overdone sometimes, or maybe it’s just the same old games, oh look, another WW2 shooter… I haven’t seen that for a while! ;) Also, with all the handheld devices around these days, it is breathed new life into 2D games which has been quite refreshing to see. With that said, I do like Frontier and am happy to see something on here again as I love the idea of this, and exploring it. I would like to see some ruins randomly placed in it, maybe some old roads etc… something to explore. I love exploring, not really much of a killer. ;) Ugh, yes, I have the very same problem in one of my FLOSS projects, xoreos (a reimplementation of the BioWare 3D games; think ScummVM for Neverwinter Nights and later). In short, my OpenGL knowledge is stuck somewhere in OpenGL 1.2, and that too only from old tutorials. The code I wrote works…somewhat. It’s slow, missing a lot of features, and my 3D engine code in general is a mess. I tried learning the recent OpenGL API, only to be bogged down in conflicting information. What I have gleamed, and some infodumps by nice individuals with knowledge, just tought me how much I don’t know. I basically gave up on trying to learn all that. I have tried cramming the Ogre3D engine into it, with middling success. Again, it kinda works, but I have to work around several Ogre3D peculiarities, and I lack the knowledge to judge whether I made the right choices. In fact, I know I didn’t, because a screen full of text drops the FPS into single digits. Right now, I’m kinda hoping I’ll find a person willing to work with me on xoreos, a person with OpenGL knowledge and some time to spare. Hope dies last, and all that. EDIT: Okay, two links is already enough to trigger the spam moderation queue? :) My approach has been to create a Renderer class that contains all of the actual OpenGl calls. It helps keep the messy OpenGL stuff in one place, while everything else in the engine can have the interfaces I want them to have. Every renderable object is basically just sent to the Renderer in an array each frame. That’s what I did, too. Built a draw manager that was able to organize everything to suit all the features I wanted, then every frame, I send it any updated objects, and say “Update, draw.” It’s a much more rewarding system when you get a handle on it – allowing you to do fancier things like deffered shading to allow practically unlimited lights to render accurately. I followed this tutorial a few months ago and it really helped to get to know everything and seems to be up to date. I hadn’t seen that one before, it seems reasonable – but skip the first three tutorials! They’re fixed-function pipeline, and won’t actually work on a lot of hardware as the fixed-function is only guaranteed to exist in OpenGL 2.x and older contexts. – They made me think the whole thing was deprecated, but it quickly jumps up to OpenGL 3.3. It is also very important to specify the exact OpenGL context you want – the various underlying toolkits offer ways to specify this, and you really must do as otherwise you get whatever’s default. (And most tutorials don’t say how. Which sucks.) – Minor hint, nVidia may be slightly slower in pure Core Profile, so develop in Core, release in Compatibility. Yes, the OpenGL tutorials are awful, and most of the tutorials that pop up at the top of Google are deprecated! The best tutorial site I’ve found so far is this one: My recommendation is to target pure OpenGL 3.3 Core Profile. If you stick to the core profile and don’t use any extensions or anything marked as deprecated, it should run correctly on all hardware and reasonable drivers from the last few years. Extensions are where the trouble starts, and mixing shaders with fixed-function (eg OpenGL 1.1) is asking for trouble. (OSX is particularly hairy, and has broken almost every time Apple released an update.) You’ll need OpenGL 3.2 or newer if you want to do geometry shaders, which are a wonderful way to do sprites and procedural geometry, as you can offload almost everything to the GPU. I’ve had a lot of fun with these! I agree with all of the above, apart from the fact that I really should learn geometry shaders but am too thick to do so. It’s fairly easy to get your hands on a set of matrix classes these days – I stuck the one I use together from bits of online tutorials and my own diseased imaginings, but I’m pretty sure one was included with, for example, the OpenGL Superbible. Shamus, maybe you’d get more useful advice on GLSL if you posted about your particular problems here; I have personally found it easier to deal with GLSL’s quirks because it does at least do vector and matrix operations natively very much in the way that C doesn’t. However it’s often not clear from your column exactly which operations you’re having trouble with, and a basic lighting model isn’t more than a few lines in GLSL so between your commenters it should be pretty easy to get you moving in the right direction! I don’t know anything about GLSL, OpenGL or shaders at all, and I have no intention of using them. But it was absolutely worth reading 1500 words, because it’s still an interesting topic. Thanks. I always love reading your programming posts, Shamus. Now, I ain’t a programmer, nor do I play one on TV, but it is still a lot of fun to be a spectator in watching you build something. Now, what is meant by ‘deprecated’ in this context? I can guess a lot by context, but I’d like to know more precisely. It means old and shouldn’t be used, but hasn’t been removed as not to break old code. OK, that’s basically what I thought. Still, that feels like handing a new mechanic at a shop a tool box and pointing to some of the tools and saying ‘Don’t use those tools, we only use those when fixing older cars.’ I think a better analogy is if you’re building a car, and you have a choice between part A and part B. While you can use part A, it’s no longer manufactured, so you won’t be able to replace it if it breaks. It’s still not a perfect analogy, but it’s closer. I would flip the analogy around – a deprecated car part is not used in new vehicles, but is still made for spares in older ones. To modify your anology, I think it’s more like saying “here’s your tools, these ones aren’t that useful any more but we keep them around because they’re required to work on older machines.” It wouldn’t surprise me if it CAN be like that at some mechanic shops, though I can’t say. I know almost as much about cars as I do about programming. Me too! – everything I know about motoring I learnt from reading car analogies on Twenty Sided… XD Anyway, this post talks a little bit more (if only a little bit!) about deprecation: Or maybe it’s like how thousands of businesses have computers still running xp, 98 or hell, even MS-DOS just in case they need to use a piece of ancient hardware or software that refuses to talk to anything newer? When a function is depreciated, that basically is warning you that it will eventually be removed entirely and no longer be available. It can also mean something better exists to do the same task. They leave the function in to give you a chance to learn the new way to do things while still having the old one available. You can basically count on a depreciated function eventually no longer being available. It gives you some time to adjust anyhow. Small typo in the paragraph before “Step one”: “We're going to have jills and water and grass and trees like before…” As far as getting help, have you tried StackExchange? I don’t know if they have a community for OpenGL/GLSL, or how good it is if it exists, but it’s been a great resource for any math or programming topic I’ve needed help on. The GameDev portion of Stack Exchange might be a good place to start. Especially since they’re less strict about the “good” questions rule than StackOverflow is. Like, you’ll get more questions which are less focused, but you’ll also get answers which are genuinely useful for people trying to figure stuff out. SO often has questions locked as “not useful”, or “too broad” or whatever, but which are exactly the same thing I was about to ask… ^^; I had the same thought. Any time I run into a poorly documented language, feature set, API, or whatever, StackExchange/StackOverflow is where I look first. (Well, usually I google it and look for the stack exchange links, since google does a better job finding stuff) This is almost always the most effective way forward, since the site is populated by people who are both a) very knowledgeable in whatever niche you might need, b) motivated to provide helpful advice, because helpful advice is what gets modded up and gives you “points” Here’s a link to the top voted questions tagged GLSL in stackoverflow, one could probably learn a ton by just browsing through these questions and becoming familiar with the answers: I read all 1500 words with a tinge of guilt, and I don’t think I ever apologised for breaking everything, so let me officially apologise for breaking everything. And if it turns out the problem is because I’m using three-year-old drivers, you have permission to slap me. (Seriously, though, even though I haven’t done programming since leaving school, I still love these posts of yours. A lot of your complaints about documentation apply to the support/server side of things too.) Documentation sucks for pretty much anything more complicated than a toaster. Software, hardware, textbooks…everything. :S Relevant: Making tools that accomplish a task in an obvious way is difficult. Documenting the in-obvious ways in which tasks can be accomplished with poorly designed tools is equally difficult. It really comes down to how much effort you’re willing to invest up-front, and how much you’re willing to offload onto the user-base. If the tools are only going to be used by a few specialists, it might make sense to document them poorly and simply pass the knowledge along as needed, or require that the experts derive usage from first principles. Ideally, of course, you’d have elegant tools AND thorough documentation… but that gets really expensive. When you’re paying “free on the internet” it’s hard to take complaints about quality of both tools and documentation very seriously. The paid tools I’ve used have had documentation that was barely better than the free stuff on the internet. (Many free projects are actually better.) So, where’s all that money going? XD I totally agree that purchased goods carry an expectation of comprehensibility. That so many free tools are better than professional ones is a reversal for sure (and a happy one at that). I just think it’s a bit unfair to hold free tools to the same standards that we expect from ones for which the developers are being compensated. My one complaint with the article: I wanted more words! :O I have really really missed your programming posts. So glad they are coming back! Seconding! In a way, programming stories are like the ancient Heinlein mode of science fiction adventure: weird and unexpected problems, overcome by daring heroes with knowledge and ingenuity. :) For a few years I’d been trying to learn OpenGL without success. What finally made modern OpenGL and GLSL actually click for me last year was restricting myself to OpenGL ES (for WebGL). It allowed me to focus on a much, much smaller API, a simpler shader language, and very little historical cruft. I could do searches for “OpenGL ES” specifically and get better results. I also found the WebGL specification to be a good, quick reference: except for GLSL, everything I needed was on that one page. There are also a couple of good OpenGL ES books out there. I got an error here: “This page has moved” So is not valid… should be used instead. And do note that the url is not the same as Which has a higher revision but is actually a older standard (how the hell did they mess up that numbering this way?). The truly great thing about standards is how badly documented they are. I linked “/registry/webgl/specs/latest/” because I assumed that would always redirect to the latest version. Somehow I’m not surprised to see Khronos screw this up. They’ve been a tad messy over the years yeah. The redirect works but threw an error/message here. A better url would be and then just click the “WebGL current draft specification” link. The extension registry is also linked from this page. Yes, this; so very much this. :-) Focusing on webgl, which outright prevents the use of any of the older deprecated stuff because it’s built on ES, and also outright prevents the use of any extension unless you explicitly ask for it, turned out to be amazingly helpful when trying to port the original Frontier to a browser. (Not that I’ve gotten very far. But trees render, at least, and it’s doing order-independent transparency! Which I think I’ve talked about before, at length.) Turns out the OpenGL thick client setup allows you to call any particular extension function that the GL library includes, whether you negotiate it or not, as long as you have a function prototype. (In one sense it doesn’t have a choice, since wglGetProcAddress / glxGetProcAddress have to work the same as the native GetProcAddress / dlsym functions, which look at the DLL’s / shared-object-file’s public symbol table. Doing the symbol lookup at program-link time instead of runtime has to work, but it means you can accidentally mess up extension requirements or whatever.) Since webgl doesn’t let you use a symbol until you’ve asked for the extension that contains it — the extensions are each registered in their own namespace so your code can’t just refer to them — it can’t run into the same issues. Of course, after saying all that, it *does* mean moving from C++ to javascript, and from thick client code to a browser. So that might be another whole learning curve for you (==Shamus), which luckily I didn’t have to climb since I did it a few years before. I wonder if it’s possible to do OpenGL ES in a windows program. Hmm. SDL might make it hard though… GLFW3 seems to be able to open OpenGL ES contexts (I don’t use ES myself, but their “New features” page claim you can do it). For me, moving from SDL to GLFW3 was quite easy. Unfortunately, that means that I’ll need to look elsewhere for playing sounds. I would be interested in reading about your order-independant transparency. Where have you written about it? It is – that’s what ANGLE does under Windows Qt5.x currently has two available builds on Windows desktop (as well as the compiler – ANGLE (default) and OpenGL. In the ‘ANGLE’ build, you have the OpenGL ES API, and ANGLE translates this into DirectX. While this probably comes at a performance cost, I haven’t tried it so couldn’t say whether it’s significant. In the OpenGL build, you’ve got normal desktop OpenGL. I’ve only been using the OpenGL builds so far, with OpenGL 3.3 or 4.x depending on the project. This is very reassuring to hear as I have been wanting to use 3D graphics in Javascript programs and have in the past tried and failed to understand OpenGL. It is good to know that WebGL simplifies things somewhat, thanks for the link to the specification. Shamus, among all the things I come to Twenty Sided for these programming articles are some of my favourite. More words spent on the intricacies of coding please! Shamus can you update your Projects page to include the Good Robot stuff (and other stuff not on there)? I think they’re all in ‘Programming’ rather than ‘Projects.’ That’s what I meant, and no they’re not. You don’t see them via the link below – starting five or six posts down? (Perhaps after a page refresh?) (Please do not share that link with any clone troopers you may know.) I think the above might refer to the page reached by clicking the big button that says “Programming” in the right column. Reckon you might be right, there! Never even noticed that; d’oh. Yes. That however (as Packbat notes) is not reachable via the Programming button. I have no idea where you found your link, it’s not anywhere I can find, but thanks for it. It’ll make going back and reading those articles far easier than trying to go back blog post by blog post. I fiddled with the sidebar some weeks ago and managed to remove the category selector. It’s been on my list of stuff to fix for a while now. Cool. I await it’s return! There are publishers out there that appear to specialize in cheap books that turn opaque documentations into actual how-to books. With the predictable reaction by some that: “LOL, this is just selling free docs to the clueless”, but, you know, whatever. Sure enough, I can find at least one such book on GLSL from such a publisher. Is it good? Accurate? UP to date? Couldn’t possibly tell you, but even if this specific one is not what you need, there must be other titles out there, and a few bucks may save you hours of headaches. Boy do you hit the nail on the head about the OpenGL docs. I originally learnt OpenGL through uni when using 2.1, but for my projects now I like to use OpenGL 3.3. At first it was an absolute pain getting info on 3.3, which had completely overhauled all the function calls and of course the matrix stack. But finding a tutorial for 3.3 was impossible, all I kept getting was 2.1 or even immediate mode tutorials…. I eventually stumbled upon which is a superb list of tutorials that go through how to code with 3.3 and has examples (Just skip the first three, they basically just explain how it “used to be done”). On 3.3: I love the new matrix stack, it vastly improves how you can set up your rendering pipeline. For my project I needed to do lighting calculations done by vertex, rather then by pixel, with 3.3 it makes it really easy to do my lighting calculations in the vertex shader before the perspective matrix is applied. It is also much cleaner to both send variables to the shaders and then sending variables between shaders, and simply by looking at the names, you can tell what variable is an input and an output for the shader. I am so glad I decided to learn SFML instead of putzing around with all that OpenGL code. I actually got somewhere quickly without too much trouble. It’s a solid library. I would have loved to use SFML, but it does (did?) not seem to be able to open sRGB contexts. How do you do your sRGB encoding? By hand, or does SFML do it now? The words were absolutely worth reading; I love your programming posts as I get huge motivation hurdles of my own and your blog lets me experience the programming vicariously. … I should really dive back into that last project of mine … I always hate the ‘snark’ as you call it when you want to learn new things like these. A sad fact is that it is both boring and hard to write good documentation that can be read by someone who actually needs it, so it hardly ever gets done. This problem appears to be worse in open source projects, I assume because of the boring part. My favourite example is all the Microsoft documentation on for instance C# (but it is universal for everything they do). The official pages can only be read if you have a degree in that language it seems and I’ve never actually met anyone that can use them effectively. It is like they go out of their way to make it look more complex than it is. Even as a reference in case you just want to remember how it works it doesn’t seem to work. Thousands (millions?) of lines of documentation that are useless to most people. I understand it can get frustrating to see the same question over and over, but if people keep asking it over and over it is likely something is wrong with the documentation and not those people… Oh so agree with this. I work in document solutions and my new job has had me shift from a purpose built WYSIWYG program with GUI to dabbling in C# instead. There are loads of web based resources for the beginner but the Microsoft library is an unwelcoming maze of self referencing jargon. I generally end up on StackOverflow sifting through the snark trying to find the one toungue-in-cheek ‘gag’ response which actualy answers my ridiculously simple noob question. I’ve found MS’s docs to be pretty good, actually. They’re references, not tutorials. You aren’t supposed to be going to them to learn the language itself, they’re for learning the libraries. I know this might be even less helpful than RTFM posts, but have you considered using Cg instead? I know nobody really uses it, unless he is programming for PS3, but it can output both DirectX and OpenGL shader programs and the syntax is (obviously wuite similar to C and other derivatives). So here’s what I did. Do some of the basic tutorials like NeHe at to understand all the concepts. Then throw away all that sample code and start again. Download the OpenGL 3.3 language and shader reference manuals: Now either use SDL to get everything initialized, or do it yourself (painful.) As you write your new code, use the reference manuals to find the features you want, then Google for uses of those features, checking to make sure the uses are version 3.3. StackOverflow has lots of good stuff. Because you are starting with the reference manuals, you won’t be using the wrong functions. But do make *very* sure when you Google that the examples are the right version. You can switch to earlier versions (2.1 is close to WebGL) or later versions (4.0), and the principle is the same. Anchor yourself with reference manuals and then Google for working code. OpenGL is a funny thing to write in. My experience a few semesters ago, writing a flow visualization, was that you REALLY need to test on multiple platforms. Some platforms (Windows/NVIDIA) are more lenient than others. I had what I thought was a working program because it ran on my primary development machine (my MacBook in Windows). Then I tried to test it in Linux and Mac on the same machine and got garbage out, ditto for my much more powerful AMD-based desktop. I had to strip the GL-based stuff down to 1.2 level stuff to get it to work everywhere before the deadline. I skimmed the comments and bookmarked one of the tutorial sites listed — hopefully that will be helpful. I look forward to this series, no matter what happens. Yay, new programming project! I’m always so interested by these. Every pedantic little detail is fascinating to me, don’t worry. Also, I really enjoyed Frontier the first time around, so Frontier Rebooted should be interesting. Are you still planning to just leave it as a proof of concept sort of thing for the terrain, or are you going to do more on the “how to make this an actual game” side of things? A game all about erosion would be kind of weird, but at least it hasn’t been done to death. You have probably already come across this one, but I thought I’d still drop this one here: It’s an OpenGL 4.0 tutorial series, covering some of the basics up to simple lighting. I have no clue on about how good it is, but his(her?) DirectX tutorials are pretty good. How ubiquitous are OpenGL 4 machines these days? I know that my five-years old laptop stops at 3.3. I’ll get a new laptop soon, but I am wondering if I should continue with 3.3 or if pretty much everybody can run 4.0 by now. Whenever you have this kind of question, about the install base of different things, I strongly recommend you check Steam’s hardware survey. Here: Annoyingly, they don’t say anything about OpenGL, but you can deduce that from the graphics card’s statistics. After a bit of research, it would seem that OpenGL 3.2 is about the sweet spot for modern OpenGL and cross platform compatibility (has Apple updated their drivers yet?) Thank you for the tip, this is very useful. Is there a way to convert a DirectX version into a OpenGL version? Like “DirectX 9 shader model 2” into “OpenGL 2.1”? I understand that I am violently mixing software and hardware here, but there may be such a correspondance table somewhere. only 1500 words? was hoping for so many more :) Absolutely adore your programming posts and I am glad you are back at it :) I find it a little odd when I see people mention they are having trouble with certain things about this or that GL stuff because I never had much trouble getting into it. Then I remember my programming course is focused on how to make games and get you a job doing it, so graphical programming is rather important in my education but its not something easy to locate online, nor is it something other fields seem to care about (also I tend to assume everyone knows more than I do about everything). If you have any maths troubles I’d recommend looking into OpenGL Mathematics as I’ve found it solid to use, much better than my own maths library. So maybe when Shamus is finished doing this he can write a book about how to do this stuff which is comprehensible and useful, and make $$$. I mean, the market is doubtless not that large, but to say the least it does not seem to be saturated. Possible odd marketing trick: His loyal followers (us) could go around to all those places Google searches take you to, where people are asking questions about this stuff, and recommend Shamus’ excellent book. Then everyone looking for answers and going to look in those places will see that their prayers can be answered for a couple of bucks and a quick download from Amazon. An idea for the title of the book! The F***ing Manual by Shamus Young +1 That would be hilarious. Oh, yes! +1 I’m really pleased to see that you’re getting back to this Shamus. I’m planning to get into the GLSL myself when I get some free time again over the summer, but I know how tricky this stuff is having tinkered with it on mobile phones and Linux..! My advice, if you’re serious about learning OpenGL and GLSL, invest in the OpenGL SuperBible (get the version for whichever OpenGL version you mean to target). It doesn’t assume you know anything, and walks you through the basics without referencing the old ways. It also has a ton of example code, which you can also download for free if you want just examples of the shaders. You can get those here: It goes from the most basic (drawing a single triangle) to some pretty advanced stuff, so even just reading the code should be helpful. The Superbible seems to rely a lot on a library written by the authors themselves. I guess that’s fine(ish) when you program in C++, but I don’t (I code in go these days). If their sb6 library abstracts too much, then the book won’t be that useful to me. Indeed, I don’t want to learn THEIR OpenGL, I want to learn the ‘real’ one. This is why I have not purchased it yet. Do you think that their sb6 library is light enough for people like me? I used SB5, since that’s the one I bought a while ago. That said, they simply used the library to handle things after explaining why they did it that way, or to hide things until they can get around to explaining it. Since you have the source to the library anyway, you can dive in and see how things work in as much detail as you want. You can even modify the library and see how it works. For example, even though the examples in SB5 used GLUT, I never bothered with it and instead I used their library with SFML to handle the windowing. SB6 seems to have done away with GLUT and provides a framework for the application better suited to their purpose. Take the simplest example I was able to find in the SB6 source bundle: singletri. If what you want is to learn GLSL, none of that is abstracted by the library. The shader code is right there for you to see (in this case, a vertex shader that creates a triangle and a fragment shader that colors it). For someone like Shamus, that says he’d like to see examples of modern shader code, these are perfect. So, to answer your actual question: Do I think the library abstracts too much? The library abstracts all the boilerplate code to create a window and an OpenGL context, with an object oriented approach. That’s all the “not OpenGL” stuff you don’t care about. At least for the 5th edition (I can’t speak about the 6th edition), the book explained how OpenGL is modeled, and why you need to take each step. I’ve found it very helpful to understand OpenGL (though I’m not an expert by any stretch, and I haven’t used anything more complex than textured triangles in my own work). Thank you for taking the time to clarify this. I am relieved :). It will be nice to have an `exhaustive’ and consistent documentation other than the Reference Pages for once. It was well worth reading the 1500 words. It’s not the end result I enjoy, it’s the journey getting there. Your thought processes and sense of humor I personally enjoy more than the end product usually. Ooooh, how exciting! I loved reading the Project Frontier entries, they made me want to learn how to do programming. Don’t have time for that unfortunately, so I’ll just have to live vicariously through these posts. Ok, this is OT and may even considered to be a troll — but it is not intended as such. In general, I probably wouldn’t play stuff (on a PC) that works at 30 FPS. I can easily see the difference between 30 and 60 FPS and 30 just isn’t smooth at all. 20 is borderline unplayable, imo. In other words — why do you say that most games run at 30 FPS (on a PC)? I can’t truly remember the last game I’ve played that was intended to run at this FPS — possibly Atlantica Online — and it was annoying as hell. I strongly believe that ‘the world’ has moved away from ’30 FPS is enough’ long ago. 60 is the new 30 :) Sadly, the opposite seems to be the case in some places (read: Not PC). Time was, you could reasonably expect consoles to attain 60 (or 50) consistently, but I’ve read that these days, consoles are completely failing to keep up with new graphics technology, and many games choose to sacrifice 60fps in favour of “more shineys” at 30. And of course, if you complain about this, you get called a Nazi. (I’m not even kidding) The reason that console players at least have the option now is because the complaining about it was so numerous and so vocal.So while there were many idiots that called people nazi for it,they>
https://www.shamusyoung.com/twentysidedtale/?p=22825
CC-MAIN-2020-10
en
refinedweb
tag:blogger.com,1999:blog-6988918715704433860.comments2013-03-27T09:16:34.159+01:00Ludovic Rousseau's blogLudovic Rousseau's blog<br /><br /><br /><br /> Rousseau's blog can I download the pcsc-perl latest version?...Where can I download the pcsc-perl latest version?Huey is stupid. You should always use the header...Oracle is stupid. You should always use the header files provided by the target system.Ludovic Rousseau's blog Ludovic Rousseau, I have post an question at Ap...Hi Ludovic Rousseau,<br />I have post an question at Apple support (). Could you please take a look at the answer? <br />Regards , Valentin IvanovAnonymous?Anonymous framework is 32 and 64 bits on Mac OS X. It s...PCSC framework is 32 and 64 bits on Mac OS X. It should not be the problem.<br /><br />Open a bug report at Rousseau's blogAnonymous pcsc-perl to version 1.4.11 to solve the P...Upgrade pcsc-perl to version 1.4.11 to solve the PCSC error.Ludovic Rousseau's blog use use to reports bugs and limitations.Ludovic Rousseau's blog ludovic i am having a strange issue running pcs...Hi ludovic i am having a strange issue running pcsc-lite in ubuntu-server 10.04 LTS version 64bits<br /><br />system works good, but it has limited number of readers connected when i reach device 16 connected when i try to plug in device 17 it wont work and it will show up the following log message.<br /><br />PC/SC device scanner<br />V 1.4.16 (c) 2001-2009, Ludovic Rousseau <br />Compiled with PC/SC lite version: 1.5.3<br />Scanning present readers...<br />0: OmniKey CardMan 3121 00 00<br />1: OmniKey CardMan 3121 01 00<br />2: OmniKey CardMan 3121 02 00<br />3: OmniKey CardMan 3121 03 00<br />4: OmniKey CardMan 3121 04 00<br />5: OmniKey CardMan 3121 05 00<br />6: Gemplus GemPC Twin 06 00<br />7: OmniKey CardMan 3121 07 00<br />8: OmniKey CardMan 3121 08 00<br />9: OmniKey CardMan 3121 09 00<br />10: OmniKey CardMan 3121 0A 00<br />11: OmniKey CardMan 3121 0B 00<br />12: OmniKey CardMan 3121 0C 00<br />13: OmniKey CardMan 3121 0D 00<br />14: OmniKey CardMan 3121 0E 00<br />15: OmniKey CardMan 3121 0F 00<br />SCardGetStatusChange: Invalid parameter given.<br /><br /><br /><br />And after that if i plug more readers to machine it wont simply recognize..<br /><br />any ideas on how i can fix this i am using old version of pcsc-lite which works ok.<br /><br />Also some readers after running 3 weeks or so plugged, some readers just simply disconnect and in log will show Status card disconected/unplugged<br /><br />how can i fix this also:<br />Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-6988918715704433860.post-15687726847544295432013-01-28T17:03:52.046+01:002013-01-28T17:03:52.046+01:00pcsc-lite do not provide any Info.plist. The smart...pcsc-lite do not provide any Info.plist. The smart card reader drivers do.Ludovic Rousseau's blog you please precise where is located Info.pli...Could you please precise where is located Info.plist in the sources?Anonymous follow follow Rousseau's blog Ludovic I'm noticing my pcsc-lite-1.8.6 is...Hi Ludovic<br /><br />I'm noticing my pcsc-lite-1.8.6 is capable of getting itself into a state where it will spam the log endlessly if card reader is unplugged. I'm wondering if 1.8.7 improves anything?<br /><br />Repeating block is:<br />Jan 24 13:11:23 laasu pcscd: ccid_usb.c:660:WriteUSB() write failed (2/2): -4 No such device<br />Jan 24 13:11:23 laasu pcscd: ifdwrapper.c:348:IFDStatusICC() Card not transacted: 617<br />Jan 24 13:11:24 laasu pcscd: eventhandler.c:303:EHStatusHandlerThread() Error communicating to: OMNIKEY CardMan 1021 00 00<br /><br />Couldn't the daemon just give up on the transaction after a while?Leho Kraav you have luck with your requirement?Did you have luck with your requirement?PCSC Developer! exact. Now fixed.Oops! exact. Now fixed.Ludovic Rousseau's blog think you forgot to update the ChangeLog in the ...I think you forgot to update the ChangeLog in the tarball.arved idea. I contact you by email.Good idea. I contact you by email.Ludovic Rousseau's blog about... Node.js ? I've seen only one pro...What about... Node.js ?<br />I've seen only one project that could handle smartcard/rfid stuff, it's called node-hid (available on GitHub)... I think it would be interested to port pcsc to Node.js, making some gyp bindings.<br />You can mail me at main [arobase] jokester.fr if you are interested to talk about it.Anonymous Apple support. Or maybe ask on a Apple support. Or maybe ask on a list.Ludovic Rousseau's blogJan Schermer fixed. Thanks.Bugs fixed. Thanks.Ludovic Rousseau's blog Ludovic, Long time no speak. Just wanted to po...Hi Ludovic,<br /><br />Long time no speak. Just wanted to point out two corrections for your code above otherwise it will not compile on Mac OS:<br /><br />Line 9: The include shows empty, I guess because Blogger thought it was a tag, should be <br />#include <PCSC/winscard.h><br /><br />Line 13: Should be deleted, so the #endif is not after a blank line<br /><br />But this is a great post to get started with PC/SC in other platforms. Thanks for that!Adrian C idea. I found idea. I found<br /><br />I don't know how easy it would be to add Free Pascal support.Ludovic Rousseau's blog about Free Pascal ?How about Free Pascal ?Anonymous
https://ludovicrousseau.blogspot.com/feeds/comments/default
CC-MAIN-2020-10
en
refinedweb
Sets the width at which child elements will break into columns. Pass a number for pixel values or a string for any other valid CSS length. Sets the gutter (grid-gap) between columns. Pass a number for pixel values or a string for any other valid CSS length. A tiny (~2kb) CSS grid layout for React, built with styled-components 💅. See the website.react grid css styled-components The react-flexbox-grid is a set of React components that implement flexboxgrid.css. It even has an optional support for CSS Modules with some extra configuration.react-flexbox-grid imports the styles from flexboxgrid, that's why we're configuring the loader for it.css-modules flexbox-grid react-components flexbox grid react react-component Primitive for controlling width, margin, padding and more. Both <Flex /> and <Box /> share the same props.react flexbox grid react-component css-in-js grid-component layout Pinterest like layout components for React.js. You can install the react-stack-grid from npm.react pinterest animation react-component grid-layout layout grid masonry Example of a two column, responsive, centered grid. All grid layout classes and responsive width classes are modifiers. $av-namespace Global prefix for layout and cell class names. Default: grid.css sass scss bem grid-layout grid oocss Inspired by Flexbugs this list aims to be a community curated list of CSS Grid Layout bugs, incomplete implementations and interop issues. Grid shipped into browsers in a highly interoperable state, however there are a few issues - let's document any we find here. While I'd like to focus on issues relating to the Grid Specification here, it is likely that related specs such as Box Alignment will need to be referenced. If you think you have spotted an issue and it seems to relate to Grid, post it. We can work out the details together and make sure browser or spec issues get logged in the right place.css css-grid-layout Auto responsive grid layout library for React.See our CONTRIBUTING.md for information on how to contribute.react layout react-components data-grid table data-table "Bricks" Bootstrap's responsive grid and responsive utility classes only, without any extras. Lightweight yet still powerful. Style to taste. Include one of the precompiled grids (grid12.css, grid24.css, grid30.css, grid100.css) in your site, or customize and compile grid.css.less with command line lessc or LessPHP (no extends are used).bootstrap grid layout css less What you ASCII is what you get. Build layout through ASCII art in Sass (and more).sass grid grid-layout grid-system ascii-art Less Framework is a CSS grid system for designing adaptive web sites. It contains 4 layouts and 3 sets of typography presets, all based on a single grid. Solid knowledge of HTML and CSS is recommended. You'll find the dimensions for each layout noted down in comments within the CSS files. A CSS grid framework using Flexbox. Flexible Box Layout Module and calc() as CSS unit value used in Grd are available on modern browsers (Chrome, Firefox, Safari, Opera, Edge and IE11).css grid framework flexbox We have large collection of open source products. Follow the tags from Tag Cloud >> Open source products are scattered around the web. Please provide information about the open source projects you own / you use. Add Projects.
https://www.findbestopensource.com/product/jxnblk-react-css-grid
CC-MAIN-2020-10
en
refinedweb
DtWsmSetCurrentWorkspace(library call)DtWsmSetCurrentWorkspace(library call) NAME [Toc] [Back] DtWsmSetCurrentWorkspace - set the current workspace SYNOPSIS [Toc] [Back] #include <Dt/Wsm.h> int DtWsmSetCurrentWorkspace( Widget widget, Atom aWorkspace); DESCRIPTION [Toc] [Back] The DtWsmSetCurrentWorkspace function works with the CDE workspace manager, [Toc] [Back] Upon successful completion, the DtWsmSetCurrentWorkspace function returns Success; otherwise, it returns a value not equal to Success. APPLICATION USAGE [Toc] [Back] If the DtWsmSetCurrentWorkspace function is not successful, the most likely reason for failure is that the CDE workspace manager, dtwm(1), is not running. The DtWsmSetCurrentWorkspace function requires a widget. [Toc] [Back] Dt/Wsm.h - DtWsm(5), dtwm(1), DtWsmGetCurrentWorkspace(3). - 1 - Formatted: January 24, 2005
http://nixdoc.net/man-pages/HP-UX/man3/DtWsmSetCurrentWorkspace.3.html
CC-MAIN-2020-10
en
refinedweb
Class JavaSourceLocator - java.lang.Object - org.eclipse.jdt.launching.sourcelookup.JavaSourceLocator - All Implemented Interfaces: IPersistableSourceLocator, ISourceLocator @Deprecated public class JavaSourceLocator extends Object implements IPersistableSourceLocatorDeprecated.In 3.0, the debug platform provides source lookup facilities that should be used in place of the Java source lookup support provided in 2.0. The new facilities provide a source lookup director that coordinates source lookup among a set of participants, searching a set of source containers. See the following packages: org.eclipse.debug.core.sourcelookupand org.eclipse.debug.core.sourcelookup.containers. This class has been replaced by.Locates source for a Java debug session by searching a configurable set of source locations. This class may be instantiated. - Since: - 2.0 - See Also: ISourceLocator - Restriction: - This class is not intended to be sub-classed by clients. Constructor Detail JavaSourceLocator public JavaSourceLocator()Deprecated.Constructs a new empty JavaSourceLocator. JavaSourceLocator public JavaSourceLocator(IJavaProject[] projects, boolean includeRequired) throws CoreExceptionDeprecated.Constructs a new Java source locator that looks in the specified project for source, and required projects, if includeRequiredis true. - Parameters: projects- the projects in which to look for source includeRequired- whether to look in required projects as well - Throws: CoreException- if a new locator fails to be created JavaSourceLocator public JavaSourceLocator(IJavaSourceLocation[] locations)Deprecated.Constructs a new JavaSourceLocator that searches the specified set of source locations for source elements. - Parameters: locations- the source locations to search for source, in the order they should be searched JavaSourceLocator public JavaSourceLocator(IJavaProject project) throws CoreExceptionDeprecated.Constructs a new JavaSourceLocator that searches the default set of source locations for the given Java project. - Parameters: project- Java project - Throws: CoreException- if an exception occurs reading the classpath of the given or any required project Method Detail setSourceLocations public void setSourceLocations(IJavaSourceLocation[] locations)Deprecated.Sets the locations that will be searched, in the order to be searched. - Parameters: locations- the locations that will be searched, in the order to be searched getSourceElements public Object[] getSourceElements(IStackFrame stackFrame)Deprecated.Returns all source elements that correspond to the type associated with the given stack frame, or nullif none. - Parameters: stackFrame- stack frame - Returns: - all source elements that correspond to the type associated with the given stack frame, or nullif none - Since: - 2.1 getSourceElement public Object getSourceElement(IStackFrame stackFrame)Deprecated. - Specified by: getSourceElementin interface ISourceLocator collectRequiredProjects protected static void collectRequiredProjects(IJavaProject proj, ArrayList<IJavaProject> res) throws JavaModelExceptionDeprecated.Adds all projects required by projto the list res - Parameters: proj- the project for which to compute required projects res- the list to add all required projects too - Throws: JavaModelException- if there is a problem with the backing Java model getDefaultSourceLocations public static IJavaSourceLocation[] getDefaultSourceLocations(IJavaProject project) throws CoreExceptionDeprecated.Returns a default collection of source locations for the given Java project. Default source locations consist of the given project and all of its required projects . - Parameters: project- Java project - Returns: - a collection of source locations for all required projects - Throws: CoreException- if an exception occurs reading computing the default locations getMemento public String getMemento() throws CoreExceptionDeprecated. - Specified by: getMementoin interface IPersistableSourceLocator - Throws: CoreException initializeDefaults public void initializeDefaults(ILaunchConfiguration configuration) throws CoreExceptionDeprecated. - Specified by: initializeDefaultsin interface IPersistableSourceLocator - Throws: CoreException initializeFromMemento public void initializeFromMemento(String memento) throws CoreExceptionDeprecated. - Specified by: initializeFromMementoin interface IPersistableSourceLocator - Throws: CoreException
https://help.eclipse.org/2019-06/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/launching/sourcelookup/JavaSourceLocator.html
CC-MAIN-2020-10
en
refinedweb
Add CSS for tab components and color schemes. Review Request #10387 — Created Jan. 22, 2019 and submitted — Latest diff uploaded This introduces common CSS for defining tab navigation for content. It's meant to be generic enough to be used in a variety of cases, but also to be extendable for additional presentation modes going forward. Tabs are defined by creating a ul.rb-c-tabselement, with li.rb-c-tabs__tabelements inside of it. Each has a label, which can optionally have a short version for mobile devices. On mobile devices, tabs are also horizontally scrollable, keeping the tabs from wrapping around awkwardly. Mixin functions are available to customize tab presentation. .set-color-scheme()defines the colors used by the tabs, and .set-flush-with-border()makes the tabs flush with a border of a content container. Tabs make use of another new CSS addition, color schemes. We constantly define colors throughout our UI, rarely making use of centralized variables for them. In an effort to both standardize colors and to make it easy to apply them, the beginnings of a set of namespaced color definitions and pre-defined color schemes (grouping together backgrounds, borders, etc.) now exist in colors.less. Color schemes can be passed currently to .set-color_scheme(), and other functions down the road, to give a standard way of customizing components. Made use of this with the Issue Summary Table. Tested the full and short labels in mobile/desktop modes, and tested the horizontal scrolling in mobile mode. Tested the mixins in different conditions.
https://reviews.reviewboard.org/r/10387/diff/?expand=1
CC-MAIN-2020-10
en
refinedweb
okular #include <sourcereference.h> Detailed Description Defines a source reference. A source reference is a reference to one of the source(s) of the loaded document. Definition at line 25 of file sourcereference.h. Constructor & Destructor Documentation Creates a reference to the row row and column column of the source fileName. Definition at line 32 of file sourcereference.cpp. Destroys the source reference. Definition at line 40 of file sourcereference.cpp. Member Function Documentation Returns the column of the position in the source file. Definition at line 55 of file sourcereference.cpp. Returns the filename of the source. Definition at line 45 of file sourcereference.cpp. Returns the row of the position in the source file. Definition at line 50 of file sourcereference.cpp. The documentation for this class was generated from the following files: Documentation copyright © 1996-2020 The KDE developers. Generated on Sun Feb 16 2020 04:30:02 by doxygen 1.8.7 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/4.x-api/kdegraphics-apidocs/okular/html/classOkular_1_1SourceReference.html
CC-MAIN-2020-10
en
refinedweb
#include <storagedrive.h> Detailed Description This device interface is available on storage devices. A storage is anything that can contain a set of volumes (card reader, hard disk, cdrom drive...). It's a particular kind of block device. Definition at line 37 of file ifaces/storagedrive.h. Constructor & Destructor Documentation Destroys a StorageDrive object. Definition at line 23 of file ifaces/storagedrive.cpp. Member Function Documentation Retrieves the type of physical interface this storage device is connected to. - Returns - the bus type - See also - Solid::StorageDrive::Bus Retrieves the type of this storage drive. - Returns - the drive type - See also - Solid::StorageDrive::DriveType Indicates if this storage device can be plugged or unplugged while the computer is running. - Returns - true if this storage supports hotplug, false otherwise Indicates if the media contained by this drive can be removed. For example memory card can be removed from the drive by the user, while partitions can't be removed from hard disks. - Returns - true if media can be removed, false otherwise. Retrieves this drives size in bytes. - Returns - the size of this drive The documentation for this class was generated from the following files: Documentation copyright © 1996-2020 The KDE developers. Generated on Sun Feb 16 2020 04:43:47 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006 KDE's Doxygen guidelines are available online.
https://api.kde.org/frameworks/solid/html/classSolid_1_1Ifaces_1_1StorageDrive.html
CC-MAIN-2020-10
en
refinedweb
. POLITICS Translated byC.D.C. REEVEARISTOTLE PoliticsARIS TOTLE Politics Translated, by C.D.C. Reeve 09 08 07 06 4 5 6 7 8 9 Aristotle [Politics. English] Politics/ Aristotle; translated, with introduction and notes, by C.D.C. Reeve. p. em. Includes bibliographical references and indexes. ISBN 0-87220-389-1 (cloth). ISBN 0-87220-388-3 (pbk.) 1. Political science-Early works to 1800. I. Reeve, C.D.C., 1 948-- . II. Title. JC7l .A41R44 1998 97-46398 320'.01'1-dc2 1 CIP Acknowledgments Xlll Introduction XVll §3 Perfectionism XXV §6 Theorizers xliii §7 Political Animals xlviii §8 Rulers and Subjects lix §9 Constitutions lxv § 1 0 The Ideal Constitution lxxii §1 1 Conclusion lxxviiiMap lxxx BooK I Chapter 1 The City-State and Its Rule 1 Chapter 2 The Emergence and Naturalness of the City-State 2 Chapter 3 Parts of the City-State: Household; Master, and Slave 5 Chapter 4 The Nature of Slaves 6 Chapter 5 Natural Slaves 7 Chapter 6 Are There Natural Slaves? 9 Chapter 7 Mastership and Slave-Craft 12 Chapter 8 Property Acquisition and Household Management 12 Chapter 9 Wealth Acquisition and the Nature of Wealth 15 Chapter 10 Wealth Acquisition and Household Management; Usury 18 VIIVlll Contents BooK II Chapter 1 Ideal Constitutions Proposed by Others 26 Chapter 2 Plato's Republic: Unity of the City-State 26 Chapter 3 Plato's Republic: Communal Possession of Women and Children ( 1 ) 28 Chapter 4 Plato's Republic: Communal Possession of Women and Children (2) 30 Chapter 5 Plato's Republic: Communal Ownership of Property 32 Chapter 6 Plato's Laws 36 Chapter 7 The Constitution of Phaleas of Chalcedon 41 Chapter 8 The Constitution of Hippodamus of Miletus 45 Chapter 9 The Spartan Constitution 49 Chapter 1 0 The Cretan Constitution 55 Chapter 1 1 The Carthaginian Constitution 58 Chapter 1 2 The Constitutions Proposed b y Solon and Other Legislators 61 BOOK III Chapter 1 City-States and Citizens 65 What Is a City-State? What Is a Citizen? Unconditional Citizens Chapter 2 Pragmatic Definitions of Citizens 67 Chapter 3 The Identity of a City-State 68 Chapter 4 Virtues of Men and of Citizens 70 Virtues of Rulers and Subjects Chapter 5 Should Craftsmen Be Citizens? 73 Chapter 6 Correct and Deviant Constitutions 75 Chapter 7 The Classification of Constitutions 77 Chapter 8 Difficulties in Defining Oligarchy and Democracy 78 Chapter 9 Justice and the Goal of a City-State 79 Democratic and Oligarchic Justice Contents IX BooK IV Chapter 1 The Tasks of Statesmanship 101 Chapter 2 Ranking Deviant Constitutions 103 The Tasks of Book IV Chapter 3 Constitutions Differ Because Their Parts Differ 1 04 Chapter 4 Precise Accounts of Democracy and Oligarchy 106 Why Constitutions Differ Democracy and Its Parts Plato on the Parts of a City-State Kinds of Democracy Chapter 5 Kinds of Oligarchy 111 Chapter 6 Kinds of Democracy and Oligarchy 1 12 Chapter 7 Kinds of Aristocracy 1 14 Chapter 8 Polities 1 14 Chapter 9 Kinds of Polities 1 16 Chapter 10 Kinds of Tyranny 1 18 Chapter 1 1 The Middle Class ( 1 ) 1 18 Chapter 12 The Middle Class (2) 121 Chapter 1 3 Devices Used in Constitutions 123 Chapter 14 The Deliberative Part of a Political System 1 24 Chapter 1 5 Offices 1 27 Chapter 1 6 Judiciary 1 32 B ooKV Chapter 1 Changing and Preserving Constitutions 1 34 The General Causes of Faction The Changes Due to Faction Chapter 2 Three Principal Sources of Political Change 136 Chapter 3 Particular Sources of Political Change ( 1 ) 137X Contents BooK VI Chapter 1 Mixed Constitutions 1 75 Kinds of Democracies Chapter 2 Principles and Features of Democracies 1 76 Chapter 3 Democratic Equality 1 78 Chapter 4 Ranking Democracies 1 79 Chapter 5 Preserving Democracies 1 82 Chapter 6 Preserving Oligarchies ( 1 ) 1 84 Chapter 7 Preserving Oligarchies (2) 185 Chapter 8 Kinds of Political Offices 1 87 BooK VII Chapter 1 The Most Choiceworthy Life 191 Chapter 2 The Political Life and the Philosophical Life Compared 193 Chapter 3 The Political and Philosophical Lives Continued 196 Chapter 4 The Size of the Ideal City-State 197 Chapter 5 The Territory of the Ideal City-State 200 Chapter 6 Access to the Sea and Naval Power 200 Chapter 7 Influences of Climate 202 Chapter 8 Necessary Parts of a City-State 203 Chapter 9 Offices and Who Should Hold Them 205 Chapter 1 0 The Division of the Territory 206 Chapter 1 1 The Location of the City-State and Its Fortifications 209 Chapter 1 2 The Location o f Markets, Temples, and Messes 211 Chapter 1 3 Happiness as the Goal of the Ideal City-State 212 The Importance ofVirtue Contents XI BooK VIII Chapter 1 Education Should Be Communal 227 Chapter 2 The Aims of Education 227 Chapter 3 Education and Leisure 228 Music ( 1 ) Chapter 4 Gymnastic Training 23 1 Chapter 5 Music (2) 232 Chapter 6 Music (3): Its Place in the Civilized Life 236 Chapter 7 Music (4): Harmonies and Rhythms 239 Glossary 243 Bibliography 263 Traduttori traditori, translators are traitors. They are also thieves. I haveshamelessly plundered other translations of the Politics, borrowingwhere I could not improve. I hope others will find my own translationworthy of similar treatment. Anyone who has worked with John Cooper knows what a rare privilege it is to benefit from his vast knowledge, extraordinary editorialskills, and sound judgment. I am greatly in his debt for guiding the crucial early stages of this translation, and for characteristically trenchantand detailed comments on parts of Books I and III. His ideals of translation, "correct as humanly possible" and "ordinary English-where necessary, ordinary philosophical English," I have tried to make my own.Anyone who has translated Aristotle (or any other Greek writer, for thatmatter) will know that, though easy to state, they are enormously difficult to achieve. I owe an even larger debt, truly unrepayable, to Trevor Saunders(Books I and II) and Christopher Rowe (III and IV), who late in thegame, and by dint of their wonderfully thorough comments, inspired meto a complete revision of the entire translation. It is now much closer toAristotle than I, who learned Greek regrettably late in life, could everhave made it unaided. I am also very grateful to David Keyt (Books V and VI) and RichardKraut (VII and VIII) for allowing me to see their own forthcoming editions of these books, and for allowing me to benefit from their enviableknowledge of them. Keyt also commented perceptively on the Introduction. Paul Bullen not only arranged to have his Internet discussion list discuss parts of my work, but he himself sent me hundreds of suggestionsfor improvement, many of which I accepted gladly. What is of value here belongs to all these generous Aristotelians. Themistakes alone, of which there must surely still be many, are whollymme. xiiiXIV Acknowledgments XVXVI Note to the Reader XVIIXVlll Introduction As in all other cases, we must set out the phenomena and first of all go through the problems. In this way we must prove the endoxa . . . ideally all the endoxa, but if not all, then most of them and the most compelling. For if the problems are solved and the endoxa are left, it will be an adequate proof. (NE 1 1 4Sh2-7) We must set out the phenomena, go through the problems, and provethe endoxa. But what are these things? And why is proving the mostcompelling of the endoxa an adequate proof of anything? Phenomena are things that appear to someone to be the case, whetherveridically or nonveridically.1 They include, in the first instance, empirical observations or perceptual evidence (APr. 46' 17-27, Gael. 297'2-6,297h23 -25). But they also include items that we might not comfortablycall observations at all, such as propositions that strike people as true orthat are commonly said or believed. For example, the following is a phenomenon: "The weak-willed person knows that his actions are base, butdoes them because of his feelings, while the self-controlled personknows that his appetites are base, but because of reason does not followthem" (NE 1 1 4Shi2-14).2 Phenomena are usually neither proved norsupported by something else. Indeed, they are usually contrasted withthings that are supported by proof or evidence (EE 12I6h26-28). Butthere is no a priori limit to the degree of conceptualization or theoryladenness manifest in them. They need not be, and in Aristotle seemrarely if ever to be, devoid of interpretative content; they are not Baconian observations, raw feels, sense data, or the like. The endoxa, or putative endoxa, are defined in the Topics as "thoseopinions accepted by everyone or by the majority or by the wiseeither by all of them or by most or by the most notable and reputable(endoxois)" (IOOh2I-23). But to count as endoxa these opinions cannotbe paradoxical ( 1 04' 1 0-1 1 ); that is to say, the many cannot disagreewith the wise about them, nor can "one or the other of these two classesdisagree among themselves" (I04h3 1-36). If there is such disagreement, what we have is a problem. Indeed, if just one notable philosopher rejects a proposition that everyone else accepts, that is sufficient to a feature might be, Aristotle thinks, the fact that the sap at the joint between leaf and stem solidifies in colder temperatures. If he is right, theappropriate explanatory demonstration would look something like this(see APo. 98b36 -38): ( 1 ) All plants in which sap solidifies at the joint between leaf and stem in colder temperatures lose their leaves in the fall. (2) All oak trees have sap that solidifies at the joint between leaf and stem in colder temperatures. (3) Therefore, all oak trees lose their leaves in the fall. But there are important conditions that ( 1 ) and (2) must satisfy if thisdemonstration is to yield a genuine scientific explanation: for example,(1) and (2) must be necessary and more fundamental than (3). Why doesAristotle impose these austere conditions? It is sometimes thought thathe does so because he mistakenly assimilates all the sciences to mathematics. There may be some truth in this, but the real reason surely has todo with the ideals of knowledge and explanation. If ( 1 ) and (2) are notnecessary, they will not adequately explain (3). For given that plantswith sap of the kind in question do not have to lose their leaves or thatoak trees do not have to have sap of that kind, why do oak trees none theless still inevitably lose their leaves? On the other hand, if ( 1 ) and (2) arenot biologically more fundamental than (3), they cannot be an adequateexplanation of it either. For in the true and complete biological theorythe more fundamental (3) will be used to explain (I) and (2). Hence inusing them to explain (3) we would be implicitly engaging in circular explanation, and circular explanation is not explanation at all (APo.72b2S-73•20). The nature of our scientific knowledge of derived principles is perhaps clear enough. But what sort of knowledge do we have of first principles, since we cannot possibly demonstrate them (NE1 140b33-1 141' 1)? Aristotle tells two apparently different stories by wayof an answer. The first, in Posterior Analytics 11. 19, runs as follows. Cognitive access to first principles begins with ( 1 ) perception of particulars(99b34-35). In some animals, perception of particulars gives rise to (2)retention of the perceptual content in the soul (99h39-J OO•I). Whenmany such perceptual contents have been retained, some animals (3)"come to have an account from the perception of such things"( 1 00•1-3). The retention of perceptual contents is memory; and a col- Introduction XXlll The problem with this story is to explain what dialectic's way, thephilosopher's way, toward first principles actually is. The philosopher knows that the first principles in question are trueand their negations false. He has this on authority from the scientist,whose own knowledge is based on experience. Yet when the philosopheruses his dialectical skill to draw out the consequences of these princi- §3 PerfectionismWe distinguish politics from the intellectual study of it, which we callpolitical science or political philosophy. The former is a hard-headed,practical matter engaged in by politicians; the latter is often a ratherspeculative and abstract one engaged in by professors and intellectuals.This distinction is alien to Aristotle. On his view, statesmanship or political science (politike episteme) is the practical science that genuine statesmen use in ruling, in much the way that medicine is the science genuinedoctors use in treating the sick. We also distinguish (not always very sharply, to be sure) between political philosophy and ethics or moral philosophy.9 The former dealswith the nature of the just or good society; the latter deals with individual rights and duties, personal good and evil, virtue and vice. This distinction too is foreign to Aristotle. On his view, ethics pretty much just isstatesmanship: ethics aims to define the human good, which is happiness or eudaimonia, so that armed with a dialectically clarified conception of our end in life we can do a better job of achieving it (NE1 094'22-24); statesmanship aims at achieving that same good not j ustfor an individual but for an entire COMMUNITY ( 1 323'14-23, NE1094h7-ll). But because we are by nature social or political animals (§7),we can achieve our ends as individuals only in the context of a political 10. Stephen Engstrom and Jennifer Whiting, eds., Aristotle, Kant, and the Sto ics: Rethinking Duty and Happiness (Cambridge: Cambridge University Press, 1996) includes some useful comparative studies of Aristotle's ethics with Kant's. Introduction XXVII §4 Human NatureOf the various things that exist, "some exist by nature, some from othercauses" (Ph. 192h8-9). Those that exist (or come into existence) by nature have a nature of their own, i.e., an internal source of "change andstaying unchanged, whether in respect of place, growth and decay, or alteration" ( 192h 1 3- 1 5). Thus, for example, a feline embryo has within ita source that explains why it grows into a cat, why that cat moves and alters in the ways it does, and why it eventually decays and dies. A houseor any other artifact, by contrast, has no such source within it; instead"the source is in something else and external," namely, in the soul of thecraftsman who manufactures it ( 192h30- 3 1 , Metdph. 1 032'32-h lO). A natural being's nature, essence, function (ergon), and end (telos), orthat for the sake of which it exists (hou heneka), are intimately related.For its end just is to actualize its nature by performing its function( Cael. 286'8 -9, EN 1 1 68'6-9, EE 1 2 1 9' 1 3 - 1 7), and something thatcannot perform its function ceases to be what it is except in name (Mete.390•10-13, PA 640h33- 64 1'6, Pol. 1 253'23-25). Aristotle's view of natural beings is therefore "teleological": it sees them as defined by an endfor which they are striving, and as needing to have their behavior explained by reference to it. It is this end, essence, or function that fixes what is best for the being, or what its perfections or virtues consist in(NE 1098•7-20, Ph. 195•23-25). Many of the things characterized as existing by nature or as productsof some craft are hylomorphic compounds, compounds of matter (huli)and form (morphe). Statues are examples: their matter is the stone ormetal from which they are made; their form is their shape. Human beings are also examples: their matter is (roughly speaking) their body;their soul is their form. Thus (with a possible exception discussed below)a person's soul is not a substance separate from his body, but is more likethe structural organization responsible for his body's being alive andfunctioning appropriately. Even city-states are examples: their matter istheir inhabitants and their form is their CONSTITUTION (§7). These compounds have natures that owe something to their matter and somethingto their form (Metaph. 1025b26-1 026•6). But "form has a better claimthan matter to be called nature" (Ph. 193b6-7). A human being, for example, can survive through change in its matter (we are constantly metabolizing), but if his form is changed, he ceases to exist (Pol. 1 276bl-1 3).For these reasons an Aristotelian investigation into human perfectionnaturally focuses on human souls rather than on human bodies. According to Aristotle, these souls consist of hierarchically organizedconstituents (NE 1. 1 3). The lowest rung in the hierarchy is nutritivesoul, which is responsible for nutrition and growth, and which is alsofound in plants and other animals. At the next rung up, we find perceptive and desiring soul, which is responsible for perception, imagination,and movement, and so is found in other animals but not in plants. Thisis the nonrational (alogon) part of the soul, which, though it lacks reason, can be influenced by it (Pol. 1 3 3 3• 1 7- 1 8 , NE 1 1 03•1-3,1 1 5 1" 1 5-28). The third part of the soul is the rational part, which hasreason ( 1 3 33• 1 7) and is identified with no us or understanding( 1 254•8 -9, 1 3 34b20, NE 1097b33 -1098•8). This part is further dividedinto the scientific part, which enables us to study or engage in theoretical activity or contemplation (theoria), and the deliberative part, whichenables us to engage in practical, including political, activity ( 1 3 33•25,NE 1 1 39•3-b5). Because the soul has these different parts, a perfectionist has a lot ofplaces to look for the properties that define the human good. He mightthink that the good is defined by properties exemplified by all three ofthe soul's parts; or he might, for one reason or another, focus on properties exemplified by one of the parts. To discover which of these optionsAristotle favors, we need to work through the famous function argu- Introduction XXIX ment from the Nicomachean Ethics (a work whose final chapters lead naturally into the Politics). By doing so we shall be armed with the kind ofunderstanding of Aristotle's views on human nature and the good thathe supposes we will have when we read the Politics (see VII. l-3 ,1333"16-30). The function argument begins as follows: [A] Perhaps we shall find the best good if we first find the function or task (ergon) of a human being. For just as the good-i.e., [doing] well-for a flute-player, a sculptor, and every craftsman, and, in general, for whatever has a function and action, seems to depend on its function, the same seems to be true for a human being, if a human being has some function. 1 3 [B] Then do the carpenter and the leather worker have their functions and actions, while a human being has none and is by nature inactive without any function? Or, just as eye, hand, foot, and in general every [body] part apparently has its functions, may we likewise ascribe to a human being some function over and above all of theirs? (NE 1097b24-33) Just as every instrument is for the sake of something, the parts of the body are also for the sake of something, that is to say, for the sake of some action, so the whole body must evidently be for the sake of some complex action. Similarly, the body too must be for the sake of the soul, and the parts of the body for the sake of those functions for which they are naturally adapted. 14 (PA 64Sb 14-20) Thus the parts of the body are for the sake of the complex action of thebody as a whole, but the body as whole is for the sake of the soul and itsactivities. Even within the soul itself, moreover, the function of one part seemsto be for the sake of the function of another, for example, that of practical wisdom for the sake of that of theoretical wisdom (Pol. 1 333"24-30,1 334b 1 7-28).15 Now theoretical wisdom is the virtue of understanding,and understanding has a somewhat peculiar status. Unlike many othercapacities of the soul, such as memory or perception, its activities arecompletely separate from those of the body: "bodily activity is in no wayassociated with the activity of understanding" (GA 736b28-29). Couldit be, then, that our function or essence is over and above the functionsof all of our body parts, precisely because it lies exclusively in our understanding and consists exclusively in theoretical activity? If the answer is yes, Aristotle's perfectionism seems to be narrowly intellectualist: the good or happy life for humans will consist largely in theoreticalactivity alone. But it is not clear the answer is yes. Aristotle himself occasionally settles for expressing a weaker disjunctive conclusion: thehuman function consists in practical rational activity or theoretical rational activity (Pol. 1 33 3'24-30, NE 1 094'3 -7) . None the less, thestronger conclusion often seems to be in view (§6). For the moment,then, let us simply content ourselves by noticing how close to the function argument the stronger conclusion lies, however controversial or incredible we might initially find it. I said earlier (§3) that it is difficult to gauge the extent of Aristotle'snaturalism, because it is difficult to determine how naturalistic (in ourterms) some parts of his psychology are. Understanding is the majorsource of that difficulty. Human beings have a function, in any case, which is over and abovethe functions of their body parts. The next stage of the argument concerns its identification: [C] What, then, could this be? For living is apparently shared with plants, but what we are looking for is special; hence we should set 14. This doctrine is very much alive in the Politics ( 1 333'1 6-b5).1 5 . Also EE 1 249b9-2 1 , MM 1 198b l 7-20, NE 1 145'6-9; §6. Introduction XXXI aside the life of nutrition and growth. The life next in order is some sort of life of sense-perception; but this too is apparently shared, with horse, ox, and every other animal. The remaining possibility, then, is some sort of action of what has reason. Now this [the part that has reason itself has two parts, each of which has reason in a dif ferent way], one as obeying reason, the other as itself having it and exercising understanding. Moreover, life is also spoken of in two ways, and we must take life as activity, since this seems to be called life to a fuller extent. We have found, then, that the human function is the activity of the soul that expresses reason or is not without rea son. (NE 1 097b33-1 098"8; compare Pol. 1 333" 1 6-bS) 16. Does this entail that the human function cannot be theoretical activity or study? No. For Aristotle allows that study is itself a kind of ACTION (Pol. 1325bl6-21).xxxii Introduction 17. See Ph. 246'10-15, Metaph. 102 J h20-23, Rh. 1 366'36-b l ; Plato, Republic 3 52d-354'.18. In other words, it isn't a conceptual truth that the specifically moral virtues are what perfect our nature. But neither does Aristotle think that it is. Con trast Thomas Hurka, Perfectionism (Oxford: Clarendon Press, 1 993): 1 9-20. Introduction XXXIll After all, (A) explicitly states that if human beings (or anything else)have a function, the good for them depends on their function. And,again, the fact that a human being's function is his end, or his essenceactivated, makes this an intelligible view. For to say that the good forhuman being is to best achieve his end is to say something that is at leasta serious candidate for truth. (F), the conclusion of the function argument, is that the human goodis an activity of the soul expressing virtue. But to that conclusion Aristotle adds a difficult coda: [G] And if there are more virtues than one, the good will express the best and most complete virtue. [H] Further, in a complete life. For one swallow does not make a spring, nor does one day; nor, sim ilarly, does one day or a short time make us blessed and happy. (NE 1 098"1 7-20) expressing virtue. The stronger version more narrowly identifies our nature or essence with theoretically rational activity, and our good with suchactivity when it expresses the virtue of wisdom. The trouble (if that is theright word) is that the function argument is an abstract metaphysical or(maybe) biological argument that seems far removed from life experience,and seems to some degree to be in conflict with it. Certainly, few people,if asked, would say that the good, or the good life, consisted exclusively inbeing active in politics (remember that practical wisdom is pretty muchthe same thing as statesmanship for Aristotle) or in theorizing (contemplating). They are far more likely to think that the good is pleasure or enjoyment, and that the good life is a pleasant or enjoyable one. This is a serious problem, if for no other reason than that people arefar more likely to be guided by their experience in these matters than byphilosophical arguments. Aristotle himself explicitly recognizes this(NE 1 1 72•34-h7, 1 1 79• 1 7-22). But he does not believe that the problemis insurmountable. For he thinks he can show that the various views ofhappiness defended by ordinary people on the basis of their experienceand by philosophers on the basis of experience and argument (NE1098b27-29) are all consistent with the conclusion of the function argument. For example, he thinks that the activities expressing virtue arepleasant, and "do not need pleasure to be added as some sort of ornament" (NE 1099• 1 5-16), so that the popular view that happiness is pleasure is underwritten rather than contradicted. Moreover, he concedesthat were such conflict to occur, it would be the conclusion of the argument that might have to be modified: "We should examine the first principle [i.e., human good or happiness]," he says, "not only from the conclusion and premises of a deductive argument, but from what is saidabout it; for all the facts harmonize with a true account, whereas thetruth soon clashes with a false one" (NE 1 098h9-l l ) . I t would b e misleading, therefore, flatly to describe the function argument as providing the metaphysical or biological foundations of Aristotelian ethics and statesmanship. This suggests too crude an inheritance from metaphysics and biology, too crude a naturalism. Thefunction argument employs concepts such as those of function, essence,and end which, though perhaps biological in origin, belong to Aristotle'smetaphysics. By using these concepts and by showing how they are related to the ethical and political notions of virtue and the good life, thefunction argument establishes the close connections between metaphysics, on the one hand, and ethics and statesmanship, on the other.But the ultimate test of the function argument is not simply the cogency Introduction XXXV §5 Practical AgentsOur nature, essence, or function lies in the rational part of our souls, inany case, and the human good consists in rational activity expressingvirtue. This activity, as we have seen, can be either practical or theoretical or some mix of the two. But what more particularly do these types ofrational activity themselves consist in? We shall discuss practical activityin this section, theoretical activity in the next. Canonical practical ACTION or activity is action that is deliberatelychosen, that expresses deliberate choice (proairesis). Such choice is a desire based on deliberation (bouleusis) that requires a state of characterand is in accord with wish (boulesis), a desire for the good or the apparent good.20 Suppose, for example, that we are faced with a lunch menu.We wish for the good or happiness. We deliberate about which of the actions available to us in the circumstances will best promote it. Should weorder the fish (low fat, high protein) or the lasagna (high fat, high fiber)? 19. For further discussion of the function argument, see my Practices ofReason, 1 23-38; and J. Whiting, "Aristotle's Function Argument: A Defense," An cient Philosophy 8 ( 1 988): 33-48.20. NE 1 1 1 3'9-14 (reading kata ten boulesin), 1 1 39'3 1-bS, 1 1 1 3'3-5.XXXVI Introduction We choose fish with a salad (low fat, high fiber), on the grounds that thiscombines low fat, high protein, and high fiber. For we believe that this isthe kind of food that best promotes health, and that being healthy promotes our happiness. If our appetite is then for fish and salad, we chooseit, and our action accords with our wish and our desire. If our appetite isconsistently or habitually in accord with our wish, so that it does notoverpower wish and wish does not have to overpower it, Aristotle saysthat (everything else being equal) we have the virtue of temperance(sophrosuni). Suppose we deliberately choose as before, but our appetite is for thelasagna; there are then two further possibilities. First, our appetite isstronger than our wish and overpowers it, so that we choose and eat thelasagna. In this case, we are weak-willed. We know the good but don't doit. Second, our wish is stronger and overpowers our still very insistentappetite. In this case, we are self-controlled. We do what we think best inthe teeth of our insistent and soon-to-be-frustrated appetite. Now thesethree things, weak will, self-control, and virtue are precisely states ofcharacter. And it is in part because our deliberate choices exhibit thesethat they involve such states. This is one way character is involved in deliberate choice, but there isanother. It is revealed by a fourth possibility. Here appetite is in accordwith wish, but wish is only for the apparent and not the genuine humangood (Pol. 133 1 b26-34 ). This possibility is realized by a vicious person(a person who has vices). He wishes for the good, but he mistakenly believes that the good consists (say) in gratifying his appetites. So if his appetite is for a high-fat diet, such as lasagna with extra cheese followed bya large ice cream sundae, that is what he wishes for and orders. Some people (virtuous, self-controlled, and weak-willed ones) havetrue conceptions of the good, then; others (vicious ones) have false conceptions. What explains this fact? Aristotle's answer in a nutshell ishabits, especially those habits developed early in life (NE l09Sb4-8)although nature and reason also have a part to play (Pol. 1 332•38-bS).We come to enjoy fatty foods, for example, by being allowed to eat themfreely when we are children and developing a taste for them (or perhapsby being forbidden them in a way that makes them irresistibly attractive). If we had acquired "good eating habits" instead, we would have adifferent conception of that part of the good that involves diet. Wewould want and would enjoy the fish and salad and not hanker for thelasagna and ice cream at all. Failing that, we would, as weak-willed orself-controlled people, at least not wish for it. Introduction XXXVII 2 1 . This should remind us of the money lovers, honor lovers, and wisdom lovers of Plato's Republic.XXXVlll Introduction But what more precisely are the good habits that correct laws foster?What is it that is true of our feelings, our desires and emotions, whenthey are such as good or bad habits make them? Aristotle's answer is that properly habituated emotions "listen to reason" (NE 1 1 02b28-1 1 03•1), and so are in accord with wish, aiming at thesame thing it does (NE 1 1 1 9h l 5-18). When this happens, the feelings aresaid to be "in a mean" between excess and deficiency: "If, for example,our feeling is too intense or too weak, we are badly off in relation toanger, but if it is in a mean, we are well off; and the same is true in othercases" (NE l i OSh2S-28; also Ph. 247•3 -4) . Some of Aristotle's adviceabout how we might achieve this mean state helps explain its nature: We must also examine what we ourselves drift into easily. For dif ferent people have different natural tendencies toward different ends, and we come to know our own tendencies by the pleasure and pain that arise in us. We must drag ourselves off in the contrary di rection. For if we pull far away from error, as they do in straighten ing bent wood, we shall reach the mean. (NE 1 I 09b l -7) By noticing our natural proclivities, we can correct for them. Over time,with habit and practice, our feelings typically change, becoming moreresponsive or less resistant to wish, more in harmony with it. Providedthat wish embodies a correct conception of the good, we are then farmore likely to achieve the good and be happy than if our feelings successfully oppose wish or have to be overpowered by it. In the formercase, we miss the good altogether; in the latter, we achieve it but only atthe cost of the pain and frustration of our unsatisfied feelings. We eatfish and salad but we remain "hungry" and, in some cases, no doubt, obsessed with the forbidden lasagna and ice cream: an uncomfortable andunstable condition, as we know. In §4 we noticed a problem. It is conceptually guaranteed that if ourrational activities express genuine virtue, they constitute the humangood. But it is not guaranteed that the conventionally recognized ethicalvirtues-justice, temperance, courage, and the rest-are genuine ones.The doctrine of the mean is intended to solve this problem. A genuinevirtue is a state that is in a mean between excess and deficiency. Hence ifthe conventionally recognized virtues are such states, they are genuine Introduction XXXIX virtues. Books III-V of the Nicomachean Ethics are for the most part intended to show that the antecedent of this conditional is true. We shallnot probe their details here, not all of which are entirely persuasive. It isenough for our purposes to see that the doctrine of the mean is intendedto fill what would otherwise be a lacuna in Aristotle's argument.22 Feelings are concerned with external goods; that is to say, with "goodsof competition," which include money, honor, bodily pleasure, and ingeneral goods that people tend to fight over; and with having friends,which "seems to be the greatest external good" (NE 1 1 69b9-l0). Wewould expect, therefore, that the virtues of character would be particularly concerned with external goods. And indeed they are. The vast majority are concerned with the goods of competition. Courage is concerned with painful feelings of fear and pleasant feelings of confidence;temperance, with the pleasures of taste and touch (NE l l l 8•2J-h8);generosity and magnificence, with wealth; magnanimity, with honor;special justice, with ACQUISITIVENESS (pleonexia), with wanting moreand more without limit of the external goods of competition (NE1 1 29h l-4). General justice (NE l l 29h2S-27) is especially concernedwith friendship and community. It is our needs for these goods that leadus to form communities that are characterized as much by mutuality ofinterest as by competition (l. l-2). But it is these same needs that oftenbring us into conflict with one another. The single major cause of political instability, indeed, is competition, especially between the rich andthe poor, for external goods such as wealth and honor (V. l ). The political significance of the virtues is therefore assured; without them no constitution can long be stable. For "the law has no power to secure obedience except habit" ( 1 269•20-21). Imagine that all our feelings, all our emotions and desires are in amean, so that we have all the virtues of character. Our feelings are in accord with our wish, and our wish is for the real and not merely the apparent good. Haven't we got all we need to ensure, as far as any humanbeing can, that we will achieve the good and live happily? Not quite.Until we have engaged in the kind of dialectical clarification of our conception of happiness undertaken in the Nicomachean Ethics, until wehave seen how to solve the problems to which it gives rise, and how to §6 TheorizersThe political life is one of the three most favored types of lives. Anotheris the life of study or contemplation (bios theiiretikos), in which theoretical activity plays a very important role. Our focus now will be on the nature of that activity, the second type of rational activity in which ourgood consists, and on the relationship between it and the practical activity we discussed in §5. Study of any of the various sciences Aristotle recognizes is an exerciseof understanding (nous) and is a theoretical activity of some sort: As we see from this passage, things that are ungenerated and imperishable for the whole of eternity are the best kind to study. Among these, thevery best is God himsel£ Hence the very best theoretical activity consistsin the study of God: theology. That is why only the study of theologyfully expresses wisdom (NE 1 1 412"1 6-20 with APo. 87"3 1-37). One reason Aristotle holds this view about theology is this. 27 TheAristotelian cosmos consists of a series of concentric spheres, with theearth at its center. God is the eternal first mover, or first cause of motionin the universe. But he does not act on the universe to cause it to move.He is not its efficient cause. He moves it in the way that an object of lovecauses motion in the things that love or desire it (DA 415"26-b7). He is 27. The other reasons are these: God is the best or most estimable thing there is, so that theology, the science that studies him, is the most estimable sci ence (Metaph. 983'5-7, 1074h34, 1075'1 1-12). He is also the most intelligi ble or most amenable to study of all things, because he is a pure or matter less form (Metaph. 1026'1 0-32). Introduction xlv The most natural act for any living thing that has developed nor mally . . . is to produce another like itself (an animal producing an animal, a plant, a plant), in order to partake as best it can in the eter nal and divine. That is what all things strive for, and everything they do naturally is for the sake of that. (DA 4 1 5'26-h2) Because all things are in essence trying to be as much like God as possible, we cannot understand them fully unless we see them in that light.And once we do see them in that light we still do not understand themfully until we understand theology, until we understand what God is.Theology is more intelligible, and hence better to study, than the othersciences for just this reason: the other sciences contain an area of darkness that needs to be illuminated by another science; theology can fullyilluminate itself. 28 Human beings participate in the divine in the same way as other animals do by having children. But they can participate in it yet more fullybecause they have understanding. For God, on Aristotle's view, is a pureunderstanding who is contemplating or holding in thought the completescience of himself: theology (Metaph. 983'6-7).29 Hence when humanbeings are actually studying theology they are participating in the veryactivity that is God himself. They thus become much more like Godthan they do by having children, or doing anything else. In the process,Aristotle claims, they achieve the greatest happiness possible (NE1).xlvi Introduction litical life against the philosophical, but not giving decisive precedenceto either. What explains this caginess may not be faint-heartedness on Aristotle's part, however, but a confusion on ours. We need to distinguish thequestion of what happiness is from the question of what the best or happiest life is. Aristotle himself is quite decisive and consistent on the firstquestion: happiness is activity expressing virtue; the contenders arepractical activity and theoretical activity; the palm of victory invariablygoes to theoretical activity, although practical activity is often awardedsecond prize. This is as true in the Politics as it is in the NicomacheanEthics. But it does not tell us what the best life is. Here, as in the case of activities, there are two contenders, the political life and the philosophical or theoretical life (Pol. 1 324'29-3 1 ). Theselives sound like the activities already discussed but must not be confusedwith them. The political life involves taking part in politics with otherpeople and participating in a city-state ( 1 3 24'1 5-16); the philosophicallife is that of "an alien cut off from the political community" Introduction xlvii §7 Political AnimalsAristotle famously claims that a human being is by nature a political animalY Less famously, but perhaps more controversially, he also claimsthat the city-state is itself a natural phenomenon, something that existsby nature (Pol. 1 252h30, 1253'1). These doctrines are closely relatedso closely, indeed, that they are based on the very same argument( 1 252'24-1253'19). We shall analyze that argument below, but before wedo we should look at the doctrines themselves. According to Aristotle, political animals are a subclass of herding orgregarious animals that "have as their task (ergon) some single thing thatthey all do together." Thus bees, wasps, ants, and human beings are allpolitical animals in this sense (HA 487h33-488'10). But human beingsare more political than these others (Pol. 1 253'7-18), because they arenaturally equipped for life in a type of community that is itself morequintessentially political than a beehive or an ant nest, namely, a household or city-state. What equips human beings to live in such communities is the natural capacity for rational speech, which they alone possess.For rational speech "is for making clear what is beneficial or harmful,and hence also what is just or unjust . . . and it is community in thesethat makes a household and a city-state" ( 1 253'14-1 7). It may well be as uncontroversial to say that human beings have a natural capacity to live in communities with others as it is to make parallelclaims about bees and ants. But why should we think that they will bestactualize this capacity in a community of a particular sort, such as anAristotelian household or city-state? Why not think that, unlike bees andants, human beings might realize their natures equally well either in isolation or in some other kind of political or nonpolitical community?32 Weshall return to these questions in due course. We now have some idea at least of what Aristotle means by saying thata human being is a political animal. But what does he mean by the far would need masters, or why the latter would need them. Aristotle's ownview is that masters and slaves form a union "for the sake of their ownsurvival" ( 1 252•30-3 1). But this is very implausible. Animals also lackthe capacity to deliberate, on Aristotle's view, yet they seem to survivequite nicely without human masters who can deliberate;35 freed (supposedly) natural slaves do not simply die like flies. Masters may indeed benefit from having slaves to do the donkey work, while they spend theirleisure on philosophy or politics ( 1 255b36-37), but, since masters havebodies of their own and are capable of working on their own behalf, it isunclear why they need slaves in order to survive. We don't have slaves,and we survive. Not only is Aristotle's conception of the household politically or ethically controversial, then, but it isn't clear that, even if we granted himits controversial elements, he could succeed in showing that it is naturalbecause "naturally constituted to satisfy everyday needs" (1252h12-14). Somewhat similar problems beset the next stage in the emergence ofthe city-state: the village. First, the village is "constituted from severalhouseholds for the sake of satisfying needs other than everyday ones"( 1252h1 5-16). To determine whether these nonroutine needs are natural,we have to be told what they are. But all that Aristotle says is that households have to engage in barter with one another when the need arises( 1 257• 19-25). This does not help very much, because the things they exchange with one another seem to be just the sorts of things that thehousehold itself is supposed to be able to supply, such as wine and wheat( 1 257•2 5-28). Second, to count as a village a community of severalhouseholds must be governed in a characteristic way, namely, by a king( 1 252b20-22). This is natural, Aristotle explains, because villages are offshoots of households, in which the eldest is king ( 1 252b20-22). Theproblem is that on Aristotle's own view households involve various kindsof rule, not just kingly rule. For example, a head of household rules hiswife with political rule (1. 12). We might wonder, therefore, why a villagehas to be governed with kingly rule rather than with political rule, that isto say, with all the heads of households ruling and being ruled in turn. The final stage in the emergence of the city-state, and the conclusionof Aristotle's argument that the city-state exists by nature and that ahuman being is a political animal, is presented in the following terse andconvoluted passage: (A) tells us that the city-state, unlike the village, has reached the goal ofpretty much total SELF-SUFFICIENCY. What does this mean? It seemsfairly clear that enough basic human needs are satisfied outside of thecity-state for human life to be possible there: households and villagesthat are not parts of city-states do manage to persist for considerable periods of time ( 1 252b22-24, 1 2 6 1 '27-29); individuals too can surviveeven in solitude ( 1 253'3 1-33, HA 487b33-488' 14). None the less, moreof these needs seem to be better satisfied in the city-state than outside it(see 1278b 17-30). For it is always need that holds any community together as a single unit (NE 1 1 33b6-7). (B) separates what gives rise to the city-state from what sustains itonce it exists. Fairly basic human needs do the former, but what sustainsa city-state in existence is that we are able to live well and achieve happiness only in it. Thus the city-state is self-sufficient not simply becauseour essential needs are satisfied there but because it is the communitywithin which we perfect our natures ( 1 253'3 1-37). (D) and (E) are the crucial clauses. (D) tells us that household, village,and city-state are like embryo, child, and mature adult: a single nature ispresent at each stage but developed or completed to different degrees.Where is that nature to be located? (E) suggests that it lies within the individuals who constitute the household, village, and city-state: they are political animals because their natural needs lead them to form, first, households, then villages, then city-states. "An impulse toward this sort ofcommunity," we are told, "exists by nature in everyone" ( 1 2 53'29-30). Introduction Iiii 36. Aristotle distinguishes household justice (to oikonomikon dikaion) from city state or political justice at NE 1 334bl 5-18.liv Introduction piness will be correct, and one will possess practical wisdom in its unqualified form (NE 1 144b30 -1 14Sb2). But it is only in the best constitution that the virtues inculcated in a citizen through public education areunqualifiedly virtues of character (111.4, 1 293bJ-7). It follows that in noother constitution will the virtues that suit citizens to the constitutionprovide them with a correct conception of their happiness or with unqualified practical wisdom. Starting with the household, then, what wehave is a series of types of virtue and types of practical wisdom suited todifferent types of communities and constituting a single nature that isrealized or developed to different degrees in these different communities. It is for this reason that Aristotle thinks that human beings are by nature political animals, not just in the sense that, like bees, they are naturally found in communities, but also in the stronger sense that they perfect their natures specifically in political communities of a certain sort.The function argument has shown that human nature consists in rational activity, whether practical (political) or theoretical. Hence to perfecttheir natures human beings must acquire the unqualified virtues ofcharacter. But this they do, Aristotle has argued, only in a city-state;more specifically, in a city-state with the best constitution. The move from household to village or from village to city-state coincides, then, with a development in human virtue and practical w�sdom.How should we conceive of this development as occurring? If humanbeings were nonrational animals, the development would itself be onethat occurred through the operation of nonrational natural causes. Butbecause human beings have a rational nature, their natural development(which is always communal, as we have seen) essentially involves a development in their rational capacities; for example, an increase in the levelof the practical wisdom they possess. Imagine, then, that the householdalready exists. Its adult males possess a level of practical wisdom whichthey bring to bear in solving practical problems. The household is notself-sufficient: it produces a surplus of some needed items, not enoughof others. This presents a practical problem which it is an exercise ofpractical wisdom to solve. And it might be solved, for example, by noticing that other nearby households are in the same boat, and that exchanging goods with them would improve life for everyone involved. But exchange eventually leads to the need for money and with it to the need fornew communal roles (that of merchant, for example), new forms ofcommunal control (laws governing commerce), new virtues of character(such as generosity and magnificence which pertain to wealth), and newopportunities for the exercise of (a further developed) practical wis- Introduction lv 37. This account is modeled on the one Aristotle tells at 1 257' 14-hS.38. That the legislator in question may not have been brought up in the com munity for which he is developing a constitution should not blind us to the fact that the practical wisdom he exercises in developing that constitution is itself a communal achievement-an achievement internal to community.39. See Pol. 1253'30-3 1 , 1268h34-38, 1273h32-33, 1274b18-19, 1282b 14-16, 1 325h40-1 326'5. It is important to be clear, however, that the fact that Aris totle speaks of statesmanship (practical wisdom) as crafting (demiourgein) a city-state or its constitution does not mean that either is a product of craft, like a table, or that statesmanship (practical wisdom) is itself a craft. After all, Aristotle speaks of nature as crafting animals and other things (PA 645'7-10, GA 73 1 '24 ), and analogizes nature to a craft ( GA 73Qb27-32, 743hZ0-25, 789h8-12). But nature is not a craft nor are its products craft products. Statesmanship (practical wisdom) is in fact not a craft, but a virtue of thought (NE VI.4-8).lvi Introduction form has a better claim to being called its nature than does its matter,what we are really asking is whether Aristotle thinks that a city-state'sconstitution is a source of its stability and change in the way that acanonical nature is. And surely he does. A city-state can change its matter (population) over time, but cannot sustain change from one kind ofconstitution to another ( 1 276"34-h l ) , or dissolution of its constitutionaltogether ( l 272h l4-15). Thus its identity over time is determined by itsconstitution. A population constitutes a single city-state if it shares asingle constitution ( 1 276"24-26). Thus its synchronic unity, its identityat a time, is also determined by its constitution. A city-state can grow orshrink in size, but its constitution sets limits to how big or small it can be(VII.4-5). What causes it to decay or to survive is also determined bythe type of constitution it has (Book V discusses these constitution-specific causes in considerable detail). Thus a city-state's constitution is indeed a canonical nature, an inner source of stability and change, and thecity-state meets all of Aristotle's conditions for existing by nature. It isno surprise, therefore, to find Aristotle claiming that the various kinds ofconstitutions, the various kinds of natures that city-states possess, are tobe defined in the same way as the different natures possessed by animalsbelonging to different species ( l 29Qh2S-39). So far we have been discussing the individual human beings in a citystate. But the very same process of nature indexing that occurs in themas they become parts of a city-state also occurs in the various subcommunities that make up that city-state. Consider the village, for example.When it is not yet part of a city-state, a village is a kingship. But when itbecomes part of a democratic city-state (say), though it may perhapshave a village elder of some sort, it is no longer a kingship plain and simple. For in a democracy authority is in the hands of all the free male citizens. Hence though the village elder may exercise kingly rule over villageaffairs, he must do so in a way that fits in with the democratic constitution of which his village is a part. And in that constitution he is under theauthority of others as a real king is not. The same is true of the household. Various types of rule are present in the household, as we saw, butthese are transformed when the household becomes part of a city-state.For the sort of virtue that a head of household possesses and the sort hetries to develop or encourage in its other members must themselves besuited to the larger constitution of which his household is a part (Pol.1. 12-13). Thus households and villages that are parts of a city-state havenatures that are transformed by being indexed to the constitution of thatcity-state. It is this that makes them into genuine parts of it. Introduction !vii they will reject the idea that we perfect our natures or achieve our goodonly as members of it: it is as members of nonpolitical communities thatwe do that. Many people also believe that leading the good life involves followingthe cultural traditions and speaking the language of their own culture orethnic group. Aristotle would agree with them, but this is very largelybecause he assumes that city-states (or at least their citizens) will be ethnically, nationally, and even religiously homogeneous ( 1 1 27b22-36,1 328b l l-1 3): he is no cosmopolitan. Modern states by contrast are increasingly multicultural and polyethnic. If they are to respect the rightsof their citizens, and allow them (within limits) to pursue their own conceptions of the good, they need to be supportive of cultural and ethnicdiversity. They should not use their coercive powers to promote one culture or one ethnicity at the expense of others. Again, this means thatmost people will achieve the good or perfect their natures as members ofdifferent ethnic communities, and not as members of city-states as such. Religion, nationality, and ethnicity aside, it is perhaps more naturalfor us to think of public political life as being like work, something weengage in in order to "be ourselves" in our private lives and leisure time.We are most ourselves, we think, not in any public sphere, but in the private one. Politics, like work, is necessary, but it is valuable primarily forwhat it makes possible, not in itself. These styles of objection can of course be generalized. Many people,including probably most of us, believe that, at least as things stand, thereare many different, equally defensible conceptions of the human goodand the good life. We want to make room in the city-state for many ofthese conceptions. We want to be left free to undertake what John StuartMill calls "experiments in living" in order to discover new conceptions.Consequently, we do not want the city-state to enforce any one conception of the good life but to be largely neutral. We want it to allow different individuals and different communities (religious, ethnic, national) topursue their own conceptions of the good, provided that they do so inways that allow other individuals and communities to do the same. If wehold views of this sort, we will not agree with Aristotle that we perfectour natures or achieve our good as members of the city-state. We willclaim instead that we do so as members of communities that share ourconception of the good, but that lack the various powers, most particularly the coercive powers, definitive of the city-state. Needless to say, it might be responded on Aristotle's behalf that thiscriticism of his argument for the naturalness of the city-state simply ig- Introduction lix nares the function argument, since it implicitly denies (or at least seriously doubts) that the human good just does consist in practical activityor in theorizing. This is a reasonable response so far as it goes. But, as wesaw in §4, the function argument is compelling only to the degree that itis underwritten by the facts of ethical and political experience. And whatis surely true is that those facts no longer underwrite it completely.What experience has taught us is that there are many different humangoods, many different good lives, many different ways to perfect ourselves, and much need for further experimentation and discovery inthese areas. That is one reason we admire somewhat liberal states whichrecognize this fact and give their citizens a lot of liberty to explore various conceptions of the good and to live in the way that they find mostvaluable and worthwhile.40 40. Recent discussions of the topics in this section include D. Keyt, "Three Basic Theorems in Aristotle's Politics," W. Kullmann, "Man as a Political Animal in Aristotle," and F. D. Miller, Nature, Justice, and Rights in Aristo tle 's Politics, 3 - 66. Some recent works on the natural origins of human com munities and virtues include J. H. Barkow, L. Cosmides, and]. Tooby (eds.), The Adapted Mind: Evolutionary Psychology and the Generation of Culture (New York: Oxford University Press, 1 992); M. Ridley, The Origins of Virtue: Human Instincts and the Evolution of Cooperation (New York: Viking, 1997); R. Wright, The Moral Animal (New York: Vintage, 1994).lx Introduction claim were entirely true, it is not clear that it would support the normative ethical and political doctrines Aristotle rests on it. Why should our status as rulers or subjects depend on the degree ofour practical wisdom or virtue? Aristotle does not directly confront thisquestion. And one reason he doesn't is that, like Plato before him, hesees the city-state as analogous to the individual soul. In Politics 1. 5, forexample, he argues as follows: it is best for the body and desire to beruled by the part of the soul that has reason, that is to say, by practicalwisdom acting as the steward of understanding or theoretical reason(§6); the city-state is analogous to the soul; hence it is best for those withunqualified practical wisdom to rule those without it, whether they arewomen, natural slaves, or wild animals ( 1 2 S4b6-20). The psychological side of this analogy is relatively uncontroversial:given Aristotle's characterization of practical wisdom as alone possessing knowledge of the human good and of how best to achieve it, it surelyis best that practical wisdom should have authority over or rule the otherparts of the soul, since that maximizes the chances that the whole souland body, the whole person, will achieve what is best. But the politicalside of the analogy is vastly more problematic. We think that individual freedom or autonomy is a very important political value. We think not only that individuals want to achieve what isin fact best, but that they want to be free to evaluate for themselves whatis best for them, and to act on their own j udgment about it. They want toown their lives and choose their goals and projects for themselves, evenif this means that they sometimes make mistakes and regret theirchoices. We are suspicious of paternalism, especially when it is exercisedby the state, and balk at the idea of having others determine what weshould do with our lives, even when they might be better qualified tomake such determinations than we are. Because autonomy does notreach down below the individual, there is no comparable worry aboutthe parts of the soul. Autonomy is a personal, not a subpersonal, value.Thus in making use of the analogy between the soul and the city-state asa device for justifying rule in the latter, Aristotle conceals from himselfwhat is for us a fundamental political problem.41 42. Notice that this would be a very surprising result if the exercise of states manship in ruling others were the human good (happiness) or the most im portant component of it. For Aristotle thinks that the reason A should rule B is that B is better off or happier being ruled by A than by ruling himself. But B could not be better off being ruled by anyone, if in fact ruling were happiness or its most important component. Introduction lxiii to safeguard the capacity for autonomy by, among other things, providing the kind of public education, and fostering the kind of public debate,that promotes it, and by preparing its citizens precisely to be citizenswho themselves promote and safeguard autonomy. §9 ConstitutionsHuman beings encounter the political either as rulers or as subjects.That is one sort of political diversity. But there is another: the diversityexhibited by constitutions themselves. Hence just what a ruler or subject encounters in encountering the political also depends on the type ofconstitution he encounters it in. Our task in the present section is to understand these different constitutions, and Aristotle's characterizationof them as either correct or deviant. The traditional Greek view is that a constitution can be controlled by"the one, the few, or the many" ( 1 279•26-28): it can be either a monarchy, an oligarchy, or a democracy. Aristotle accepts this view to some extent, but introduces some important innovations. First, he argues thatdifferences in wealth are of greater theoretical importance than difference in numbers. Oligarchy is really control by the wealthy; democracy isreally control by the poor. It just so happens that the wealthy are alwaysfew in number, while the poor are always many ( 1 279b20-1 280•6,1 290b l 7-20). This allows him to see the importance of the middleclasses, those who are neither very rich nor very poor but somewhere inbetween ( 1 29Sb l-3), and to recognize the theoretical significance of aconstitution, a so-called POLITY, in which they play a decisive part( 1 293•40-b l ) . Second, Aristotle departs from tradition in thinking thateach of these three traditional types of rule actually comes in two majorvarieties, one of which is correct and the other deviant ( 1 289bS - l l ) . Ruleby "the one" is either a kingship (correct) or a tyranny (deviant); rule by"the few" is either an aristocracy (correct) or an oligarchy (deviant); ruleby "the many" is either a polity (correct) or a democracy (deviant). One important difference between these constitutions is that theyhave different aims or goals ( 1 289' 1 7-28), different conceptions of happiness: "it is by seeking happiness in different ways and by differentmeans that individual groups of people create different ways of life anddifferent constitutions" ( 1 3 28'41-b2).44 The goal of the ideal constitu- 44. Compare NE 1095'17-1096'10: people agree that the human good is called happiness, but they disagree about what happiness actually is or consists in.lxvi Introduction aim at "the common benefit"; deviant ones at the benefit of the rulers( 1 279'26- 3 1 ) . His explanation is not very helpful, however, because hedoesn't specify the group, G, whose benefit is the common one, and hedoesn't tell us whether the common benefit is that of the individualmembers of G, or that of G taken as some kind of whole. When we try toprovide the missing information, moreover, we run into difficulties. A natural first thought about G, for example, is that it is the group ofunqualified citizens, those who participate in judicial and deliberativeoffice (111. 1-2, 5). But if G is restricted to these citizens, the commonbenefit and the private one coincide, since only the rulers participate inthese offices. Moreover, even the deviant constitutions aim at the benefitof a wider group than that of the unqualified citizens, since they alsoseem to aim at the benefit of the wives and children of such citizens( 1 260h8-20 with 1 3 1 0'34-36). Perhaps, then, G consists of all the free native inhabitants of the constitution. No, that won't do either, because now even some correct constitutions, such as a polity, will count as deviant. For the common benefit in a correct constitution is a matter of having a share in noble orvirtuous living ( 1 278h20-23, NE 1 142h3 1-33). Hence a polity will notaim at the benefit of its native-born artisans, tradesmen, or laborers,since there is "no element of virtue" in these occupations ( 1 3 1 9'26-28). These common characterizations of G all fail, but the last failurepoints in a promising direction. Let us begin with the class, N, of thefree native inhabitants of the constitution. There are two ways to construct the class of unqualified citizens from N. The first is to do so onthe basis of the type of justice internal to the constitution; the second isto do so on the basis of unqualified justice. If we proceed in the first way, "and the constitution is an oligarchy, for example, the unqualified citizens will be the wealthy male members of N. But if we proceed in thesecond way, the unqualified citizens of our oligarchy will be those whohave an unqualifiedly just claim to that status. And Aristotle thinks thatthe virtuous, the rich, and the poor all have such a claim, one that is proportional to their virtue ( 1 283'1 4-26, 1 280h40-128 1 '8, 1 294'1 9-20).Thus they ought to be unqualified citizens of any constitution. In fact,however, they are so only in correct constitutions, not in deviant ones. What I suggest, then, is that we construct G as follows: all the members of N, who have an unqualifiedly just claim to be unqualified citizens of the constitution, are members of G; all the wives and children ofmembers of G are members of G; no one else is a member of G. If a constitution aims at the benefit of G, it aims at the common benefit and is Introduction lxix 47. In 1.13, a similar claim is made about virtue: "the virtue of a part must be determined by looking to the virtue of the whole" ( l 260bJ4-16). Introduction Ixxi The fact that there need be no more than this sort of general congruence between a city-state's happiness and the happiness of the individuals in its G class also explains why Aristotle's doctrine that individualsare parts of a city-state is no threat to his moderate individualism. Ahand can perform its task only as part of a body; there is general congruence between the health of a body and the health of all its parts; butin some circumstances, the closest we can come to preserving this congruence involves sacrificing a part. In this respect, Aristotle thinks, weare like hands. One will find this insufficiently reassuring only if onethinks that general congruence between the aim of a just city-state andthat of an individual in G is not enough, that more is required, that congruence must be guaranteed in all circumstances. Aristotle certainly failsto provide such reassurance, but this is almost certainly a strength ratherthan a weakness of his view. Properly or at least plausibly interpreted, then, Aristotle's treatmentof ostracism and his view that individuals are parts of city-states seem tobe compatible with the sort of moderate individualism he espouses. 48 48. Some of the topics in this section are further discussed in]. Barnes, ''Aristo tle on Political Liberty," and F. D. Miller, Nature, Justice and Rights in Aris totle's Politics, 143-308. Introduction lxxiii tial catastrophe, obviously, but also an ethical one, since injustice in thedistribution of what constitutes the basis for all other distributions infects all those other distributions with injustice as well. Aristotle's ideal constitution thus fails to be just in its own terms; itfails to meet its own standards of justice. This is a major problem. But itpoints the way to a yet more serious one and then to a possible solution.Aristotle believes that unqualified justice must be based on virtue. Healso believes that virtue is not something children possess at birth. Morethan that, he believes that virtue is a social or political output, a consequence of receiving benefits, such as public education, that a constitution itself bestows. But no constitution can distribute all benefits on thebasis of a property, such as virtue, which is itself the result of the distribution of benefits. If justice is going to be based on some feature of individuals, it must be one that individuals do not acquire through a processwhich may itself be either just or unjust. Aristotle's theory fails to meetthis groundedness requirement, and so is strictly unsatisfiable. Yet the fact that Aristotle's theory of justice is unsatisfiable for thissort of reason suggests a way forward. His theory of justice needs to bemodified, so that the means of acquiring virtue are distributed on thebasis, not of virtue, but of a feature, such as being human, that is unproblematically possessed to an equal degree by all the children born inthe constitution, whether male or female, whether born to citizens or tononcitizens. The ideal constitution would have to provide equal opportunities to all the children possessing this feature. Then, at the appropriate stage, it would have to cull out as its future citizens those who hadindeed acquired virtue in this way. If this process were fairly carried out,it would ensure that people acquired their virtue in a just way. Subsequent virtue-based distributions of benefits would then not be unjustlybased. If Aristotle's ideal constitution were constructed in this way, itwould, of course, have to be very different from the constitution he describes, but at least it wouldn't fail to meet its own standards of justice. That problem, perhaps now to some extent solved, has to do with thebasis on which benefits are distributed in the ideal constitution. Thenext problem concerns what gets distributed. If someone is a naturalslave or a non-Greek of one sort or another, Aristotle thinks that he haspretty well no natural potential for virtue. Provided that his lack of suchpotential is determined by a fair process, it will then be unqualifiedlyjust, on Aristotle's view, for the ideal constitution to assign him no shareor a very small share in political benefits or in true happiness. But it doesnot follow that it will be just to assign him a share of political harms. For Introduction lxxv terms themselves, which are far too vague to do the work required ofthem. Let us suppose for the sake of argument, however, that this defect,like the others, could be remedied, so that the ideal constitution was justin its own terms. Would it, then, be the ideal constitution to live in fromthe point of view of happiness, once again granting that happiness is, asAristotle thinks, activity expressing virtue? There are many ways to look at this question. We shall consider justone very important one, private property, which together with proportional equality is the sole guarantee of stability in a constitution( 1 307'26 -27). Property is a necessary component of the happy life:"Why should we not say that someone is happy when his activities express complete virtue and he has an adequate supply of external GOODS,not for some chance period but throughout a complete life?" (NE1 1 0 1 ' 1 4-16). But that does not tell us how the ideal constitution shouldhandle property ownership. Aristotle firmly rejects the idea, defendedby Plato, that private property should be abolished and that the citizensof the ideal constitution should possess their property in common. Hedoes so for three reasons. First, communally owned property is neglected. Second, "it is very pleasant to help one's friends, guests, orcompanions, and do them favors, as one can if one has property of one'sown" ( 1 263bS-7). And, third, without private property one cannot practice the virtue of generosity ( 1 263bl l - 1 4). To avoid these defects inPlato's proposals, as well as those generated by strictly private property,Aristotle designs an intermediate position: some property should becommunally owned and some should be privately owned, but the use ofeven the privately owned property should be communal ( 1 329b3 6-1 3 30'3 1 ) . Is this proposal an improvement on Plato's? Is it one thatshould attract us to a constitution that embodies it? To own property, according to the Rhetoric, is to have the power toalienate or dispose of it through either gift or sale ( 1 3 6 1 '2 1-22). ButAristotle stipulates that each of the unqualified citizens in the ideal constitution (each male head of household) should be given an equal allotment of land, one part of which is near the town, the other near thefrontier ( 1 330' 14-1 8). Moreover, he seems to favor making these allotments inalienable ( 1 266b14-3 1 , 1 270' 1 5 -34).50 But if they are inalienable, so that one cannot sell them or give them away, what does owningthem actually consist in? The natural thought is that it must consist in 50. If they were not inalienable, they could hardly continue to serve the purpose they are introduced to serve at 1330'14-25.Ixxviii Introduction having private or exclusive use of them. But that thought is derailed, because the use of private property is communal. It seems, then, that amajor portion of what is called the private property of a citizen of theideal constitution is not something that he really and truly owns. Another passage from the Rhetoric tells us that ownership of propertyis secure if the use of it is in the owner's power ( 1 36 1" 1 9-21). Privatelyowned but communally used property would therefore seem to be insecurely owned at best. To be sure, this isn't what Aristotle intends to betrue in the ideal constitution. He thinks that the use of private propertyremains in the owner's power but that he will grant it to his fellow citizens out of virtue and friendship and not because the law requires himto do it (Pol. 1 263"21-40). None the less, the expectation on the part ofone citizen that another will do what virtue requires of him is pretty wellbound to make the owner's power seem notional rather than real. So what we have in the ideal constitution is a somewhat notional ownership of not very much (nonlanded) property. This will hardly recommend the constitution to those who think that private property is a goodthing. Indeed, it seems to be not much more than a notational variant ona system of communal ownership. It is scarcely surprising, therefore, thatit does not help much with the problems Aristotle raises for Plato. If communally owned property tends to be neglected, why will privately ownedbut communally used property fare any better? If I can use even what Idon't own, and so don't particularly have to take care of and maintain,ownership seems more like a curse than a blessing. By the same token, togive someone something of which he already has the use and you continue to retain the use is a wishy-washy sort of generosity at best, a palepleasure compared to that of using what one actually owns to do favorsfor one's friends. The system of property adopted in the ideal constitution, then, does not seem to be best from the point of view of maximizingthe citizen's happiness. Many other systems seem much more preferable;for example, fair taxation on private property and income, with the proceeds used to maintain public property and provide public servicesY § 1 1 Conclusion We have been looking at the central argument of the Politics, and atthe way Aristotle's perfectionism plays out there. We have seen the enormous price he pays in terms of political credibility for having too narrowa conception of what human perfection consists in (§§7-1 0): the politicaland philosophical lives are worthwhile but they are not the only onesthat are; virtue is worthwhile but it provides a poor basis for distributivejustice. We have seen the even larger price he pays for making false factual claims that are accretions to his perfectionism: without naturalslaves or women whose nature makes them incapable of ruling, Aristotle's ideal constitution would have to look very different than it does.None the less, if we strip away those accretions and broaden the perfectionism, we have a theory with considerable attractions and possibilities. 52 Arguably it is Aristotle's most important political legacy, both historically speaking and in fact. The central argument is just that, however: a major highway connecting the Politics to the rest of Aristotle's philosophy. But the Politics isn'treducible to its central argument; much fascinating material is to befound on the side roads. The discussion in Books V and VI, for example,of how different constitutions are preserved and destroyed is full of astute observations about people and their motives. In some ways, indeed, the Politics is best thought of not simply as anargument, but rather as an opportunity to think about some of the mostimportant human questions in unparalleled intellectual company. Engaged in the dialectical process of doing politics with Aristotle, one experiences the great seductive power of the philosophical life full force,but one also experiences the rather different power of the political life.To some degree, indeed, one senses that the two are, Aristotelian theoryto the contrary, not all that different, that the give and take of dialectic isvery like the give and take of politics, and that life's problems are no easier to solve in theory than in practice. This is not quite what the Politicstells us, to be sure, but it is, in a way that is mildly subversive of its message, what it dramatizes. 52. Thomas Hurka, Perfectionism, is one of the best general accounts of this sort of modified Aristotelian theory. Parts of it discuss Aristotle explicitly; all of it is relevant to understanding his thought. Am TYRRHENIAN SEA IONIAN SEA c::. . M E D I T E R R A N E A N UBYA 0 100 200 0 100 200 300 Kilometers PHRYGIA enedos A E G E A N "'T{_.rp ASIA Antis�{\_ � D0 �Myilene • Atarneus LESBOS o• " � • �s Cyme e • 'Hestiaea/Oreu () \\� �Ei-l i > Chio� LYDIA et,i•�th� <> <'.. E A Sarf[{. S�Pi>.eu'<> '"'l 0 o s., � , 0� 5 E A B oo K I Chapter 1We see that every CITY-STATE is a COMMUNITY of some sort, and that 1252"every community is established for the sake of some GOOD (for everyoneperforms every ACTION for the sake of what he takes to be good). Clearly,then, while every community aims at some good, the community thathas the most AUTHORITY of all and encompasses all the others aims 5highest, that is to say, at the good that has the most authority of all. Thiscommunity is the one called a city-state, the community that is political.1 Those,Z then, who think that the positions of STATESMAN, KING,HOUSEHOLD MANAGER, and MASTER of slaves are the same, are not correct. For they hold that each of these differs not in kind, but only inwhether the subjects ruled are few or many: that if, for example, someone rules few people, he is a master; if more, a household manager; ifstill more, he has the position of statesman or king-the assumption 10being that there is no difference between a large household and a smallcity-state. As for the positions of statesman and king, they say thatsomeone who is in charge by himself has the position of king, whereassomeone who follows the principles of the appropriate SCIENCE, ruling ISand being ruled in turn, has the position of statesman. But these claimsare not true. What I am saying will be clear, if we examine the matter ac- 1 . kuriotate koinonia: the most sovereign community, the one with the most au thority, is the city-state, because all the other communities are encompassed (periechein) by it or are its parts, so that the goods for whose sake they are formed are pursued in part for the sake of the good for which it is formed (see 1.2). These subcommunities include households, villages, religious societies, etc. The good with the most authority is HAPPINESS, since everything else is pursued in part for its sake, while it is pursued solely for its own sake. The science with the most authority, STATESMANSHIP, directs the entire city-state toward happiness. A more detailed version of this opening argument is given in NE 1. 1-2. Here it is being adapted to define what a city-state is.2. Plato, Statesman 258e-26 l a. Compare Xenophon, Memorabilia III. iv. l 2, III.vi. l 4 . 2 Politics I Chapter 2 If one were to see how these things develop naturally from the begin- 25 ning, one would, in this case as in others, get the best view of them. First, then, those who cannot exist without each other necessarily form a couple, as [ I ] female and male do for the sake of procreation (they do not do so from DELIBERATE CHOICE, but, like other animals and plants, because the urge to leave behind something of the same kind as them- 30 selves is natural), and [2] as a natural ruler and what is naturally ruled do for the sake of survival. For if something is capable of rational foresight, it is a natural ruler and master, whereas whatever can use its body to labor is ruled and is a natural SLAVE. That is why the same thing is ben eficial for both master and slave.4 There is a natural distinction, of course, between what is female and12521 what is servile. For, unlike the blacksmiths who make the Delphian knife, nature produces nothing skimpily, but instead makes a single thing for a single TASK, because every tool will be made best if it serves to perform one task rather than many. 5 Among non-Greeks, however, a 5 WOMAN and a slave occupy the same position. The reason is that they do not have anything that naturally rules; rather their community consists of a male and a female slave. That is why our poets say "it is proper for Greeks to rule non-Greeks,"6 implying that non-Greek and slave are in nature the same. The first thing to emerge from these two communities7 is a house- hold, so that Hesiod is right when he said in his poem, "First and fore- 10most: a house, a wife, and an ox for the plow."8 For an ox is a poor man'sservant. The community naturally constituted to satisfy everyday needs,then, is the household; its members are called "meal-sharers" byCharondas and "manger-sharers" by Epimenides the Cretan.9 But thefirst community constituted out of several households for the sake of 1Ssatisfying needs other than everyday ones is a village. As a COLONY or offshoot from a household, 10 a village seems to be particularly natural, consisting of what some have called "sharers of thesame milk," sons and the sons of sons. 1 1 That is why city-states wereoriginally ruled by kings, as nations still are. For they were constitutedout of people who were under kingships; for in every household the el- 20dest rules as a king. And so the same holds in the offshoots, because thevillagers are blood relatives. 12 This is what Homer is describing when hesays: "Each one lays down the law for his own wives and children."1 3 Forthey were scattered about, and that is how people dwelt in the distantpast. The reason all people say that the gods too are ruled by a king isthat they themselves were ruled by kings in the distant past, and somestill are. Human beings model the shapes of the gods on their own, and 25do the same to their way of life as well. A complete community constituted out of several villages, once itreaches the limit of total SELF-SUFFICIENCY, practically speaking, is acity-state. It comes to be for the sake of living, but it remains in existence for the sake of living well. That is why every city-state exists byNATURE, 14 since the first communities do. For the city-state is their end, 30and nature is an end; for we say that each thing's nature-for example,that of a human being, a horse, or a household-is the character it haswhen its coming-into-being has been completed. Moreover, that for the sake of which something exists, that is to say, its end, is best, and self-1253• sufficiency is both end and best. It is evident from these considerations, then, that a city-state is among the things that exist by nature, that a human being is by nature a political animal, 15 and that anyone who is without a city-state, not by luck but by nature, is either a poor specimen or else superhuman. Like the one Homer condemns, he too is "clanless, lawless, and homeless."16 S For someone with such a nature is at the same time eager for war, like an isolated piece in a board game. 17 It is also clear why a human being is more of a political animal than a bee or any other gregarious animal. Nature makes nothing pointlessly, 18 10 as we say, and no animal has speech except a human being. A voice is a signifier of what is pleasant or painful, which is why it is also possessed by the other animals (for their nature goes this far: they not only per ceive what is pleasant or painful but signify it to each other). But speech is for making clear what is beneficial or harmful, and hence also what is IS just or unjust. For it is peculiar to human beings, in comparison to the other animals, that they alone have perception of what is good or bad, just or unjust, and the rest. And it is community in these that makes a household and a city-state.19 The city-state is also PRIOR in nature to the household and to each of 20 us individually, since the whole is necessarily prior to the part. For if the whole body is dead, there will no longer be a foot or a hand, except homonymously,20 as one might speak of a stone "hand" (for a dead hand will be like that); but everything is defined by its TASK and by its capac ity; so that in such condition they should not be said to be the same things but homonymous ones. Hence that the city-state is natural and 25 prior in nature to the individual is clear. For if an individual is not self sufficient when separated, he will be like all other parts in relation to the whole. Anyone who cannot form a community with others, or who doesnot need to because he is self-sufficient, is no part of a city-state-he iseither a beast or a god. Hence, though an impulse toward this sort of 30community exists by nature in everyone, whoever first established onewas responsible for the greatest of goods. For as a human being is thebest of the animals when perfected, so when separated from LAW andJUSTICE he is worst of all. For injustice is harshest when it has weapons,and a human being grows up with weapons for VIRTUE and PRACTICALWISDOM to use, which are particularly open to being used for oppositepurposes.21 Hence he is the most unrestrained and most savage of ani- 35mals when he lacks virtue, as well as the worst where food and sex areconcerned. But justice is a political matter; for justice is the organizationof a political community, and justice22 decides what is just. Chapter 3Since it is evident from what parts a city-state is constituted, we must 1253hfirst discuss household management, for every city-state is constitutedfrom households. The parts of household management correspond inturn to the parts from which the household is constituted, and a com-plete household consists of slaves and FREE. But we must first examineeach thing in terms of its smallest parts, and the primary and smallest 5parts of a household are master and slave, husband and wife, father andchildren. So we shall have to examine these three things to see what eachof them is and what features it should have. The three in question are [ 1 Jmastership, [2] "marital" science (for we have no word to describe theunion of woman and man), and [3] "procreative" science (this also lacks 10a name of its own). But there is also a part which some believe to beidentical to household management, and others believe to be its largestpart. We shall have to study its nature too. I am speaking of what iscalled WEALTH ACQUISITION. 23 15 But let us first discuss master and slave, partly to see how they stand in relation to our need for necessities, but at the same time with an eye to knowledge about this topic,24 to see whether we can acquire some better ideas than those currently entertained. For, as we said at the beginning, some people believe that mastership is a sort of science, and that master ship, household management, statesmanship, and the science of king ship are all the same. But others25 believe that it is contrary to nature to 20 be a master (for it is by law that one person is a slave and another free, whereas by nature there is no difference between them), which is why it is not just either; for it involves force. Chapter 4 Since property is part of the household, the science of PROPERTY ACQUI SITION is also a part of household management (for we can neither live nor live well without the necessities). Hence, just as the specialized 25 crafts must have their proper tools if they are going to perform their tasks, so too does the household manager. Some tools are inanimate, however, and some are animate. The ship captain's rudder, for example, is an inanimate tool, but his lookout is an animate one; for where crafts 30 are concerned every assistant is classed as a tool. So a piece of property is a tool for maintaining life; property in general is the sum of such tools; a slave is a piece of animate property of a sort; and all assistants are like tools for using tools. For, if each tool could perform its task on com mand or by anticipating instructions, and if like the statues of Daedalus 35 or the tripods of Hephaestus-which the poet describes as having "en tered the assembly of the gods of their own accord"26-shuttles wove cloth by themselves, and picks played the lyre, a master craftsman would not need assistants, and masters would not need slaves.1254" What are commonly called tools are tools for production. A piece of property, on the other hand, is for ACTION. For something comes from a shuttle beyond the use of it, but from a piece of clothing or a bed we getonly the use. Besides, since action and production differ in kind, and Sboth need tools, their tools must differ in the same way as they do. Lifeconsists in action, not production. Therefore, slaves too are assistants inthe class of things having to do with action. 27 Pieces of property are spo-ken of in the same way as parts. A part is not just a part of another thing,but is entirely that thing's. The same is also true of a piece of property. 10That is why a master is just his slave's master, not his simply, while aslave is not just his master's slave, he is entirely his. It is clear from these considerations what the nature and capacity of aslave are. For anyone who, despite being human, is by nature not his ownbut someone else's is a natural slave. And he is someone else's when, de- 1Sspite being human, he is a piece of property; and a piece of property is atool for action that is separate from its owner. 28 Chapter 5But whether anyone is really like that by nature or not, and whether it isbetter or just for anyone to be a slave or not (all slavery being against nature)-these are the things we must investigate next. And it is not difficult either to determine the answer by argument or to learn it from ac-tual events. For ruling and being ruled are not only necessary, they are 20also beneficial, and some things are distinguished right from birth, somesuited to rule and others to being ruled. There are many kinds of rulersand ruled, and the better the ruled are, the better the rule over them always is;29 for example, rule over humans is better than rule over beasts. 25For a task performed by something better is a better task, and where onething rules and another is ruled, they have a certain task. For whenevera number of constituents, whether continuous with one another or discontinuous, are combined into one common thing, a ruling element and 30a subject element appear. These are present in living things, because thisis how nature as a whole works. (Some rule also exists in lifeless things: 30. The reference is to the mese or hegemiin (leader), which is the dominant note in a chord (Pr. 920'21-22, Metaph. 1 0 1 8h26-29). 3 1 . exoterikoteras: see 1 278h3 1 note. 32. The difference between depraved people and those in a depraved condition is unclear. The former are perhaps permanently in the condition that the latter are in temporarily; the former incorrigibly depraved, the latter corri gibly so. In any case, both make poor models. 33. Both statesmen and kings rule willing subjects; in the virtuous desires obey understanding "willingly." See Introduction xxv-xxxviii. 34. Alternatively: "It is better for all of the tame ones to be ruled." But the dis tinction between tame and wild animals is not hard and fast: "All domestic (or tame) animals are at first wild rather than domestic, . . . but physically weaker"; "under certain conditions of locality and time sooner or later all animals can become tame" (Pr. 89Sh23-896' 1 1). Presumably, then, it is bet ter even for wild animals to be ruled by man. 35. For example, it is natural for Greeks to rule non-Greeks. Chapter 6 9 tion-those people are natural slaves. And it is better for them to be sub-ject to this rule, since it is also better for the other things we mentioned. 20For he who can belong to someone else (and that is why he actually doesbelong to someone else), and he who shares in reason to the extent ofunderstanding it, but does not have it himself (for the other animalsobey not reason but feelings), is a natural slave. The difference in the usemade of them is small, since both slaves and domestic animals help pro-vide the necessities with their bodies. 25 Nature tends, then, to make the bodies of slaves and free people different too, the former strong enough to be used for necessities, the latteruseless for that sort of work, but upright in posture and possessing allthe other qualities needed for political life-qualities divided into those 30needed for war and those for peace. But the opposite often happens aswell: some have the bodies of free men; others, the souls. This, at anyrate, is evident: if people were born whose bodies alone were as excellentas those found in the statues of the gods, everyone would say that those JSwho were substandard deserved to be their slaves. And if this is true ofthe body, it is even more justifiable to make such a distinction with re-gard to the soul; but the soul's beauty is not so easy to see as the body's. 12SS• It is evident, then, that there are some people, some of whom are nat-urally free, others naturally slaves, for whom slavery is both just andbeneficial. 36 Chapter 6But it is not difficult to see that those who make the opposite claim37 arealso right, up to a point. For slaves and slavery are spoken of in two ways:for there are also slaves-that is to say, people who are in a state of slavery-by law. The law is a sort of agreement by which what is conquered Sin war is said to belong to the victors. But many of those conversant withthe law challenge the justice of this. They bring a writ of illegality againstit, analogous to that brought against a speaker in the assembly. 38 Their 36. A more complex conclusion than we might expect. The idea is perhaps this: being a slave might not be just or beneficial for a natural slave who has long been legally free; similarly, being legally free might not be just or beneficial for a naturally free person who has long been a legal slave.37. That slavery is unjust.38. A speaker in the Athenian assembly was liable to a writ of illegality or graphe paranoman if he proposed legislation that contravened already existing law; i.e., the "war" rule would not be allowed in a civil context. 10 Politics I 39. Virtue together with the necessary external goods or resources are what en able someone to do something well, including use force. If someone is able to conquer his foes, this at least suggests that he has the virtues needed for success. See 1324hZZ-1325'14. 40. Reading eunoia with Dreizehnter and the mss. 4 1 . The two parties to the dispute share common ground because they both be lieve that "force never lacks virtue." But they disagree in their accounts of justice, and hence about whether the enslavement of conquered populations is unjust. Those who believe that justice is the rule of the more powerful be lieve that such enslavement is just, because justice (by definition) is always on the side of the conqueror, since his victory shows him to have the greater power. Those who believe that justice is benevolence (i.e., that it is the good of another) believe that enslavement is unjust because not beneficial for the slaves. Both accounts are canvassed by Thrasymachus in Book I of Plato's Republic (338c, 343c). Once their accounts are disentangled it is readily ap parent that their contrasting positions do nothing to confute Aristotle's own view that the one who is more virtuous should rule (1. 1 3). 42. Aristotle is assuming that even an unjust war will be undertaken in accor dance with the laws governing declarations of war, and so will be "legal." Thus by admitting that a person enslaved by the victor in an unjust war has been unjustly but legally enslaved, the proponent of the view here in ques tion denies both that enslaving is always just and that what is legal is always just. Chapter 6 11 as the best born would be slaves or the children of slaves, if any of themwere taken captive and sold. That is why indeed they are not willing todescribe them, but only non-Greeks, as slaves. Yet, in saying this, theyare seeking precisely the natural slave we talked about in the beginning. 30For they have to say that some people are slaves everywhere, whereasothers are slaves nowhere. The same holds of noble birth. Nobles regard themselves as well bornwherever they are, not only when they are among their own people, butthey regard non-Greeks as well born only when they are at home. Theyimply a distinction between a good birth and freedom that is unqualifiedand one that is not unqualified. As Theodectes' Helen says: "Sprung JSfrom divine roots on both sides, who would think that I deserve to becalled a slave?"43 But when people say this, they are in fact distinguish-ing slavery from freedom, well born from low born, in terms of virtueand vice alone. For they think that good people come from good people 40in just the way that human comes from human, and beast from beast.But often, though nature does have a tendency to bring this about, it is 12SSbnevertheless unable to do so. 44 It is clear, then, that the objection with which we began has something to be said for it, and that the one lot are not always natural slaves,nor the other naturally free. But it is also clear that in some cases there is Ssuch a distinction--cases where it is beneficial and just45 for the one tobe master and the other to be slave, and where the one ought to be ruledand the other ought to exercise the rule that is natural for him (so that heis in fact a master), and where misrule harms them both. For the samething is beneficial for both part and whole, body and soul; and a slave is 10a sort of part of his master-a sort of living but separate part of his body.Hence, there is a certain mutual benefit and mutual friendship for suchmasters and slaves as deserve to be by nature so related.46 When their relationship is not that way, however, but is based on law, and they havebeen subjected to force, the opposite holds. 1S 43. Nauck 802, fr. 3. Theodectes was a mid-fourth-century tragic poet who studied with Aristotle. Helen is Helen of Troy.44. See 1254b27-33.45. Reading kai dikaion.46. "Every human being seems to have some relations of justice with everyone who is capable of community in law and agreement. Hence there is also friendship between master and slave, to the extent that a slave is a human being" (NE 1 16 1bl-8). 12 Politics I Chapter 7 It is also evident from the foregoing that the rule of a master is not the same as rule of a statesman and that the other kinds of rule are not all the same as one another, though some people say they are. For rule of a statesman is rule over people who are naturally free, whereas that of a master is rule over slaves; rule by a household manager is a monarchy, since every household has one ruler; rule of a statesman is rule over peo- 20 ple who are free and equal. A master is so called not because he possesses a SCIENCE but because he is a certain sort of person. 47 The same is true of slave and free. None the less, there could be such a thing as mastership or slave-craft; for ex ample, the sort that was taught by the man in Syracuse who for a fee 25 used to train slave boys in their routine services. Lessons in such things might well be extended to include cookery and other services of that type. For different slaves have different tasks, some of which are more esteemed, others more concerned with providing the necessities: "slave is superior to slave, master to master,"48 as the proverb says. All such 30 SCIENCEs, then, are the business of slaves. Mastership, on the other hand, is the science of using slaves; for it is not in acquiring slaves but in using them that someone is a master. But there is nothing grand or impressive about this science. The master needs to know how to command the things that the slave needs to know 35 how to do. Hence for those who have the resources not to bother with such things, a steward takes on this office, while they themselves engage in politics or PHILOSOPHY.49 As for the science of acquiring slaves (the just variety of it), it is different from both of these,50 and is a kind of warfare or hunting. These, then, are the distinctions to be made regarding slave and master. Chapter 8 Since a slave has turned out to be part of property, let us now study1256• property and wealth acquisition generally, in accordance with our guid- ing method. 5 1 The first problem one might raise is this: Is wealth acquisition the same as household management, or a part of it, or an assistantto it? If it is an assistant, is it in the way that shuttle making is assistant 5to weaving, or in the way that bronze smelting is assistant to statue making? For these do not assist in the same way: the first provides tools,whereas the second provides the matter. (By the matter I mean the substrate, that out of which the product is made-for example, wool for theweaver and copper for the bronze smelter.) 10 It is clear that household management is not the same as wealth acquisition, since the former uses resources, while the latter providesthem; for what science besides household management uses what is inthe household? But whether wealth acquisition is a part of householdmanagement or a science of a different kind is a matter of dispute. For ifsomeone engaged in wealth acquisition has to study the various sourcesof wealth and property, and52 property and wealth have many different 15parts, we shall first have to investigate whether farming is a part ofhousehold management53 or some different type of thing, and likewisethe supervision and acquisition of food generally. But there are many kinds of food too. Hence the lives of both animalsand human beings are also of many kinds. For it is impossible to live 20without food, so that differences in diet have produced different ways oflife among the animals. For some beasts live in herds and others livescattered about, whichever is of benefit for getting their food, becausesome of them are carnivorous, some herbivorous, and some omnivorous. 25So, in order to make it easier for them to get hold of these foods, naturehas made their ways of life different. And since the same things are notnaturally pleasant to each, but rather different things to different ones,among the carnivores and herbivores themselves the ways of life are different. Similarly, among human beings too; for their ways of life differ agreat deal. The idlest are nomads; for they live a leisurely life, because 30they get their food effortlessly from their domestic animals. But whentheir herds have to change pasture, they too have to move around withthem, as if they were farming a living farm. Others hunt for a living, differing from one another in the sort of hunting they do. Some live by 35 raiding; some-those who live near lakes, marshes, rivers, or a sea con taining fish-live from fishing; and some from birds or wild beasts. But 40 the most numerous type lives off the land and off cultivated crops. Hence the ways of life, at any rate those whose fruits are natural and do not provide food through EXCHANGE or COMMERCE, are roughly speak-] 256h ing these: nomadic, raiding, fishing, hunting, farming. But some people contrive a pleasant life by combining several of these, supplementing their way of life where it has proven less than self-sufficient; for exam ple, some live both a nomadic and a raiding life, others, both a farming 5 and a hunting one, and so on, each spending their lives as their needs jointly compel. It is evident that nature itself gives such property to all living things, both right from the beginning, when they are first conceived, and simi larly when they have reached complete maturity. Animals that produce 10 larvae or eggs produce their offspring together with enough food to last them until they can provide for themselves. Animals that give birth to live offspring carry food for their offspring in their own bodies for a cer tain period, namely, the natural substance we call milk. Clearly, then, we 15 must suppose in the case of fully developed things too that plants are for the sake of animals, and that the other animals are for the sake of human beings, domestic ones both for using and eating, and most but not all wild ones for food and other kinds of support, so that clothes and the 20 other tools may be got from them. If then nature makes nothing incom plete or pointless, it must have made all of them for the sake of human beings. That is why even the science of warfare, since hunting is a part of it, will in a way be a natural part of property acquisition. For this science ought to be used not only against wild beasts but also against those 25 human beings who are unwilling to be ruled, but naturally suited for it, as this sort of warfare is naturally just. One kind of property acquisition is a natural part of household man agement,54 then, in that a store of the goods that are necessary for life and useful to the community of city-state or household either must be available to start with, or household management must arrange to make 30 it available. At any rate, true wealth seems to consist in such goods. For the amount of this sort of property that one needs for the self-suffi ciency that promotes the good life is not unlimited, though Solon in his poetry says it is: "No boundary to wealth has been established for human beings."55 But such a limit o r boundary has been established, justas in the other crafts. For none has any tool unlimited in size or num- 35ber,56 and wealth is a collection of tools belonging to statesmen andhousehold managers. It is clear, then, that there is a natural kind of property acquisition forhousehold managers and statesmen, and it is also clear why this is so. Chapter 9But there is another type of property acquisition which is especiallycalled wealth acquisition, and justifiably so. It is the reason wealth and 40property are thought to have no limit. For many people believe that 1257"wealth acquisition is one and the same thing as the kind of property acquisition we have been discussing, because the two are close neighbors.But it is neither the same as the one we discussed nor all that far from it:one of them is natural, whereas the other is not natural, but comes froma sort of experience and craft. 57 Let us begin our discussion of the latter as follows. Every piece of 5property has two uses. Both of these are uses of it as such, 58 but they arenot the same uses of it as such: one is proper to the thing and the otheris not. Take the wearing of a shoe, for example, and its use in exchange.Both are uses to which shoes can be put. For someone who exchanges ashoe, for MONEY or food, with someone else who needs a shoe, is using 10the shoe as a shoe. But this is not its proper use because it does not cometo exist for the sake of exchange. The same is true of other pieces ofproperty as well, since the science of exchange embraces all of them. Itfirst arises out of the natural circumstance of some people having more 15than enough and others less. This also makes it clear that the part ofwealth acquisition which is commerce does not exist by nature: for peo-ple needed to engage in exchange only up to the point at which they hadenough. It is evident, then, that exchange has no task to perform in thefirst community (that is to say, the household), but only when the com- 20 55. Diehl 1.2 1 , fr. 1 . 7 1 . Solon (c. 640-560) was an Athenian statesman and poet, and first architect of the Athenian constitution. The limit to the amount of property needed for the good or happy life is determined by what happiness is. See 1257b28, NE 1 1 28b1 8-25, 1 1 53b21-25, EE 1 249'22-b25 .56. See 1 323h7-10.57. See 1 257'41-b5, 1258'38-bS.58. kath ' hauto: what something is as such or in itself or in its own right is what it is UNQUALIFIEDLY. 16 Politics I munity has become larger. For the members of the household used to share all the same things, whereas those in separate households shared next many different things, which they had to exchange with one an other through barter when the need arose, as many non-Greek peoples 25 still do even to this day. For they exchange useful things for other useful things, but nothing beyond that-for example, wine is exchanged for wheat, and so on with everything else of this kind. This kind of exchange is not contrary to nature, nor is it any kind of wealth acquisition; for its purpose was to fill a lack in a natural self-suf- 30 ficiency. 59 None the less, wealth acquisition arose out of it, and in an in telligible manner. Through importing what they needed and exporting their surplus, people increasingly got their supplies from more distant foreign sources. Since not all the natural necessities are easily trans- JS portable, the use of money had of necessity to be devised. So for the purposes of exchange people agreed to give to and take from each other something that was a useful thing in its own right and that was conve nient for acquiring the necessities of life: iron or silver or anything else of that sort. At first, its value was determined simply by size and weight, 40 but finally people also put a stamp on it, so as to save themselves the trouble of having to measure it. For the stamp was put on to indicate the amount.J2S7b After money was devised, necessary exchange gave rise to the second of the two kinds of wealth acquisition, commerce. At first, commerce was probably a simple affair, but then it became more of a craft as expe rience taught people how and from what sources the greatest profit could be made through exchange. That is why it is held that wealth ac- S quisition is concerned primarily with money, and that its task is to be able to find sources from which a pile of wealth will come. For it is pro ductive of wealth and money, and wealth is often assumed to be a pile of money, on the grounds that this is what wealth acquisition and com merce are concerned to provide. 10 On the other hand, it is also held that money itself is nonsense and wholly conventional, not natural at all. For if those who use money alter it, it has no value and is useless for acquiring necessities; and often someone who has lots of money is unable to get the food he needs. Yet it is absurd for something to be wealth if someone who has lots of it will 59. "Eating indiscriminately or drinking until we are too full is exceeding the quantity that suits nature, since the aim of a natural appetite is to fill a lack" (NE l l l 8 b l 8 -1 9). Chapter 9 17 die of starvation, like Midas in the fable, when everything set before him I5turned to gold in answer to his own greedy prayer. That is why peoplelook for a different kind of wealth and wealth acquisition, and rightly so;for natural wealth and wealth acquisition are different. Natural wealthacquisition is a part of household management, whereas commerce has 20to do with the production of goods, not in the full sense, but throughtheir exchange. It is held to be concerned with money, on the groundsthat money is the unit and limit of exchange.60 The wealth that derives from this kind of wealth acquisition is with-out limit. For medicine aims at unlimited health, and each of the crafts 25aims to achieve its end in an unlimited way, since each tries to achieve itas fully as possible. (But none of the things that promote the end is unlimited, since the end itself constitutes a limit for all crafts.) Similarly,there is no limit to the end of this kind of wealth acquisition, for its endis wealth in that form, that is to say, the possession of money. The kindof wealth acquisition that is a part of household management, on theother hand, does have a limit, since this is not the task of household 30management. In one way, then, it seems that every sort of wealth has to have a limit.Yet, if we look at what actually happens, the opposite seems true, for allwealth acquirers go on increasing their money without limit. The explanation of this is that the two are closely connected. Each of the two 35kinds of wealth acquisition makes use of the same thing, so their usesoverlap, since they are uses of the same property. But they do not use itin accordance with the same principle. For one aims to increase it,whereas the other aims at a different end. So some people believe thatthis is the task of household management, and go on thinking that theyshould maintain their store of money or increase it without limit. 40 The reason they are so disposed, however, is that they are preoccu-pied with living, not with living well.61 And since their appetite for life isunlimited, they also want an unlimited amount of what sustains it. And 1258•those who do aim at living well seek what promotes physical gratifica-tion. So, since this too seems to depend on having property, they spendall their time acquiring wealth. And the second kind of wealth acquisi- 5tion arose because of this. For since their gratification lies in excess, theyseek the craft that produces the excess needed for gratification. If they 60. The unit (stoicheion) for obvious reasons; the limit (peras) because the price of something delimits its exchange value. See Introduction lxxvi.6 1 . See 12S2h29-30, 1280'3 1-32. 18 Politics I Chapter 1 0 Clearly, we have also found the solution to our original problem about whether the craft of wealth acquisition is that of a household manager or20 a statesman, or not-this having rather to be available. For just as states manship does not make human beings, but takes them from nature and uses them, so too nature must provide land or sea or something else as a source of food, and a household manager must manage what comes from25 these sources in the way required. For the task of weaving is not to make wool but to use it, and to know which sorts are useful and suitable or worthless and unsuitable. For one might be puzzled as to why wealth ac quisition is a part of household management but medicine is not, even though the members of a household need health, just as they need life30 and every other necessity. And in fact there is a way in which it is the task of a household manager or ruler to see to health, but in another way it is not his task but a doctor's. So too with wealth: there is a way in which a household manager has to see to it, and another in which he does not, and an assistant craft does. But above all, as we said, nature must ensure that wealth is there to start with. For it is the task of nature35 to provide food for what is born, since the surplus of that from which they come serves as food for every one of them. 62 That is why the craft of acquiring wealth from crops and animals is natural for all people. But, as we said, there are two kinds of wealth acquisition. One has to do with commerce, the other with household management. The latter is necessary and commendable, but the kind that has to do with exchange is justly disparaged, since it i s not natural but is from one another. 63 Hence 12S!Jbusury is very justifiably detested, since it gets wealth from money itself,rather than from the very thing money was devised to facilitate. Formoney was introduced to facilitate exchange, but interest makes moneyitself grow bigger. (That is how it gets its name; for offspring resemble Stheir parents, and interest is money that comes from money.)64 Hence ofall the kinds of wealth acquisition this one is the most unnatural. Chapter 1 1Now that we have adequately determined matters bearing on knowledge,we should go through those bearing on practice. 65 A FREE person hastheoretical knowledge of all of these, but he will gain practical experi- 10ence of them to meet necessary needs.66 The practical parts of [I] wealthacquisition are experience of: [ 1 . 1] livestock, for example, what sorts ofhorses, cattle, sheep, and similarly other animals yield the most profit indifferent places and conditions; for one needs practical experience ofwhich breeds are by comparison with one another the most profitable, 1Sand which breeds yield the most profit in which places, as different onesthrive in different places. [ 1 .2] Farming, which is now divided into landplanted with fruit and land planted with cereals.67 [ 1 .3] Bee keeping andthe rearing of the other creatures, whether fish or fowl, that can be ofsome use. These, then, are the parts of the primary and most appropri-ate kind of wealth acquisition. 20 (2] Exchange's most important part, on the other hand, is (2. 1 ] trad-ing, which has three parts: [2. 1 . 1 ] ship owning, [2. 1 .2] transport, and(2. 1 .3] marketing. These differ from one another in that some are safer,others more profitable. The second part of exchange is (2.2] moneylending; the third is (2.3] wage earning. As for wage earning, some wageearners are (2 . 3 . 1 ] vulgar craftsmen, whereas (2.3.2] others are un- 2Sskilled, useful for manual labor only. [3] A third kind of wealth acquisition comes between this kind and 63. Because for everyone who makes a profit in a commercial transaction, some- one else makes a loss? See Rh. 138 1'21-33, Oec. 1 343'27-30.64. Takas means both "offspring" and "interest." See Plato, Republic 507a.65. See 1253b14-18.66. Alternatively: "but he cannot avoid practical experience of them."67. Ancient farming consisted in the cultivation of wheat and other cereals on flat open plains (psili) and the cultivation of grapes, olives, etc. on more hilly areas (pephuteumeni). 20 Politics I the primary or natural kind, since it contains elements both of the nat ural kind and of exchange. It deals with inedible but useful things from 30 the earth or extracted from the earth. Logging and mining are examples. Mining too is of many types, since many kinds of things are mined from the earth. A general account has now been given of each of them. A detailed and precise account might be useful for practical purposes, but it would be 35 VULGAR to spend one's time developing it.68 (The operations that are most craftlike depend least on luck; the more they damage the body, the more vulgar they are; the most slavish are those in which the body is used the most; the most ignoble are those least in need of virtue.) Be sides, some people have written books on these matters which may be studied by those interested . For example, Chares of Paras and Apol-1259' lodorus of Lemnos69 have written on how to farm both fruit and cereals, and others have written on similar topics. Moreover, the scattered stories about how people have succeeded in acquiring wealth should be collected, since all of them are useful to 5 those who value wealth acquisition. For instance, there is the scheme of Thales of Miletus. 70 This is a scheme for getting wealthy which, though credited to him on account of his wisdom, is in fact quite generally ap plicable. People were reproaching Thales for being poor, claiming that it 10 showed his philosophy was useless. The story goes that he realized through his knowledge of the stars that a good olive harvest was coming. So, while it was still winter, he raised a little money and put a deposit on all the olive presses in Miletus and Chios for future lease. He hired them at a low rate, because no one was bidding against him. When the olive season came and many people suddenly sought olive presses at the same 15 time, he hired them out at whatever rate he chose. He collected a lot of money, showing that philosophers could easily become wealthy if they wished, but that this is not their concern. Thales is said to have demon strated his own wisdom in this way. But, as I said, his scheme involves a 20 generally applicable principle of wealth acquisition: to secure a monop oly if one can. Hence some city-states also adopt this scheme when they are in need of money: they secure a monopoly in goods for sale. There was a man in Sicily who used some money that had been lent tohim to buy up all the iron from the foundries, and later, when the mer- 25chants came from their warehouses to buy iron, he was the only seller.He did not increase his prices exorbitantly and yet he turned his fifty sil-ver talents into one hundred and fifty. When Dionysius71 heard aboutthis, he told the man to take his wealth out, but to remain in Syracuse nolonger, as he had discovered ways of making money that were harmful to 30Dionysius' own affairs. Yet this man's insight was the same as Thales':each contrived to secure a monopoly for himself. It is also useful for statesmen to know about these things, since manycity-states have an even greater need for wealth acquisition and the associated revenues than a private household does. That is why indeed some 35statesmen restrict their political activities entirely to finance. Chapter 1 2Household management has proved to have three parts: [ I ] one is mastership (which we discussed earlier), [2] another that of a father, and [3]a third, marital.72 For a man rules his wife and children both as free peo-ple, but not in the same way: instead, he rules his wife the way a states- 40man does,73 and his children the way a king does. For a male, unless he J251J'is somehow constituted contrary to nature, is naturally more fitted tolead than a female, and someone older and completely developed is nat-urally more fitted to lead than someone younger and incompletely developed. In most cases of rule of a statesman, it is true, people take turns atruling and being ruled, because they tend by nature to be on an equal 5footing and to differ in nothing. Nevertheless, whenever one person isruling and another being ruled, the one ruling tries to distinguish him- self in demeanor, title, or rank from the ruled; witness what Amasis said about his footbath.74 Male is permanently related to female in this way.10 The rule of a father over his children, on the other hand, is that of a king, since a parent rules on the basis of both age and affection, and this is a type of kingly rule. Hence Homer did well to address Zeus, who is the king of them all, as "Father of gods and men.ms For a king should15 have a natural superiority, but be the same in stock as his subjects; and this is the condition of older in relation to younger and father in relation to child. Chapter 1 3 It is evident, then, that household management is more seriously con-20 cerned with human beings than with inanimate property, with their virtue more than with its (which we call wealth), and with the virtue of free people more than with that of slaves. The first problem to raise about slaves, then, is this: Has the slave some other virtue more estimable than those he has as a tool or servant, such as temperance, courage, justice, and other such states of character?25 Or has he none besides those having to do with the physical assistance he provides? Whichever answer one gives, there are problems. If slaves have temperance and the rest, in what respect will they differ from the. free? If they do not, absurdity seems to result, since slaves are human and have a share in reason. Roughly the same problem arises about30 women and children. Do they too have virtues? Should women be tem perate, courageous, and just, or a child be temperate or intemperate? Or not? The problem of natural rulers and natural subjects, and whether their virtue is the same or different, needs to be investigated in general terms. If both of them should share in what is noble-and-good/6 why should one of them rule once and for all and the other be ruled once and for all? 35(It cannot be that the difference between them is one of degree. Rulingand being ruled differ in kind, but things that differ in degree do notdiffer in that way.) On the other hand, if the one shares in what is nobleand-good, and not the other, that would be astonishing. For if the ruleris not going to be temperate and just, how will he rule well? And if thesubject is not going to be, how will he be ruled well? For if he is intern- 40perate and cowardly, he will not perform any of his duties. It is evident, 126()'therefore, that both must share in virtue, but that there are differencesin their virtue (as there are among those who are naturally ruled). 77 Consideration of the soul leads immediately to this view. The soul bynature contains a part that rules and a part that is ruled, and we say that 5each of them has a different virtue, that is to say, one belongs to the partthat has reason and one to the nonrational part. It is clear, then, that thesame holds in the other cases as well, so that most instances of rulingand being ruled are natural. For free rules slaves, male rules female, andman rules child in different ways, because, while the parts of the soul 10are present in all these people, they are present in different ways. Thedeliberative part of the soul is entirely missing from a SLAVE; a WOMANhas it but it lacks authority; a child has it but it is incompletely developed. We must suppose, therefore, that the same necessarily holds of thevirtues of character too: all must share in them, but not in the same way; ISrather, each must have a share sufficient to enable him to perform hisown task. Hence a ruler must have virtue of character complete, sincehis task is unqualifiedly that of a master craftsman, and reason is a mas-ter craftsman, 78 but each of the others must have as much as pertains tohim. It is evident, then, that all those mentioned have virtue of charac-ter, and that temperance, courage, and justice of a man are not the same 20as those of a woman, as Socrates supposed:79 the one courage is that of aruler, the other that of an assistant, and similarly in the case of the othervirtues too. If we investigate this matter in greater detail, it will become clear. Forpeople who talk in generalities, saying that virtue is a good condition of 25the soul, or correct action, or something of that sort, are deceivingthemselves. It is far better to enumerate the virtues, as Gorgias does, 80. See Plato, Meno 7 l d4-72a5, where Meno, following Gorgias, lists the dis tinct virtues of men, women, children, and slaves. 8 1 . Sophocles, Ajax 293. See 1277b22-24, Thucydides II.45. 82. That is to say, the end he will have as a mature adult (happiness), and toward which his father is leading him. 83. A reference to Plato, Laws 777e. 84. No full discussion of these topics appears in the Politics as we have it. 85. See 1253'18-29, 1337'27-30. Chapter 13 25 a city-state that its children be virtuous, and its women too. And it mustmake a difference, since half the free population are women, and fromchildren come those who participate in the constitution. So, since we have determined some matters, and must discuss the rest 20elsewhere, let us regard the present discussion as complete, and make anew beginning. And let us first investigate those who have expressedviews about the best constitution. B ooK I I Chapter 1 Since we propose to study which political community is best of all for people who are able to live as ideally as possible, 1 we must investigate other constitutions too, both some of those used in city-states that are 30 said to be well governed, and any others described by anyone that are held to be good, in order to see what is correct or useful in them, but also to avoid giving the impression that our search for something different from them results from a desire to be clever. Let it be held, instead, that we have undertaken this inquiry because the currently available consti- 35 tutions are not in good condition. We must begin, however, at the natural starting point of this investi gation. For all citizens must share everything, or nothing, or some things but not others. It is evidently impossible for them to share nothing. For 40 a constitution is a sort of community, and so they must, in the first in stance, share their location; for one city-state occupies one location, and126Ja citizens share that one city-state. But is it better for a city-state that is to be well managed to share everything possible? Or is it better to share some things but not others? For the citizens could share children, 5 women, and property with one another, as in Plato's Republic.2 For Socrates claims there that children, women, and property should be communal. So is what we have now better, or what accords with the law described in the Republic? Chapter 2 10 That women should be common to all raises many difficulties. In partic ular, it is not evident from Socrates' arguments why he thinks this legis- 1 . As not many people are; see 1 288b23-24. Ideal conditions are literally those that are answers to our prayers (kat' euchen). 2. See 423e-424a, 449a-466d. 26 Chapter 2 27 lation is needed. Besides, the end he says his city-state should have isimpossible, as in fact described, yet nothing has been settled about howone ought to delimit it. I am talking about the assumption that it is bestfor a city-state to be as far as possible all one unit; for that is the assumption Socrates adopts.3 And yet it is evident that the more of a unity 15a city-state becomes, the less of a city-state it will be. For a city-statenaturally consists of a certain multitude; and as it becomes more of aunity, it will turn from a city-state into a household, and from a house-hold into a human being. For we would surely say that a household ismore of a unity than a city-state and an individual human being than a 20household. Hence, even if someone could achieve this, it should not bedone, since it will destroy the city-state. A city-state consists not only of a number of people, but of people ofdifferent kinds, since a city-state does not come from people who arealike. For a city-state is different from a military alliance. An alliance isuseful because of the weight of numbers, even if they are all of the same 25kind, since the natural aim of a military alliance is the sort of mutual assistance that a heavier weight provides if placed on a scales. A nation willalso differ from a city-state in this sort of way, provided the multitude isnot separated into villages, but is like the Arcadians.4 But things fromwhich a unity must come differ in kind. That is why reciprocal EQUAL-ITY preserves city-states, as we said earlier in the Ethics,5 since this must 30exist even among people who are free and equal. For they cannot all ruleat the same time, but each can rule for a year or some other period. As aresult they all rule, just as all would be shoemakers and carpenters ifthey changed places, instead of the same people always being shoemak- 35ers and the others always carpenters. But since it is better to have the lat-ter also where a political community is concerned, it is clearly better,where possible, for the same people always to rule. But among thosewhere it is not possible, because all are naturally equal, and where it is atthe same time just for all to share the benefits or burdens of ruling, it is 126Jbat least possible to approximate to this if those who are equal take turnsand are similar when out of office. For they rule and are ruled in turn,just as if they had become other people. It is the same way among those 5who are ruling; some hold one office, some another. Chapter 3 But even if it is best for a community to be as much a unity as possible, this does not seem to have been established by the argument that every one says "mine" and "not mine" at the same time (for Socrates takes this as an indication that his city-state is completely one).7 For "all" is am-20 biguous. If it means each individually, perhaps more of what Socrates wants will come about, since each will then call the same woman his wife, the same person his son, the same things his property, and so on for each thing that befalls him. But this is not in fact how those who have25 women and children in common will speak. They will all speak, but not each. And the same goes for property: all, not each. It is evident, then, that there is an equivocation involved in "all say." (For "all," "both," "odd," and "even," are ambiguous, and give rise to contentious argu-30 ments even in discussion.)8 Hence in one sense it would be good if all said the same, but not possible, whereas in the other sense it is in no way conducive to concord. But the phrase is also harmful in another way, since what is held in common by the largest number of people receives the least care. For people give most attention to their own property, less to what is commu- nal, or only as much as falls to them to give.9 For apart from anythingelse, the thought that someone else is attending to it makes them neglect 35it the more (just as a large number of household servants sometimes giveworse service than a few). Each of the citizens acquires a thousand sons,but they do not belong to him as an individual: any of them is equallythe son of any citizen, and so will be equally neglected by them all. Be- 40sides, each says "mine" of whoever among the citizens is doing well or 1262•badly10 in this sense, that he is whatever fraction he happens to be of acertain number. What he really means is "mine or so-and-so's," refer-ring in this way to each of the thousand or however many who constitutethe city-state. And even then he is uncertain, since it is not clear who hashad a child born to him, or one who once born survived. Yet is this way Sof calling the same thing "mine" as practiced by each of two or ten thou-sand people really better than the way they in fact use "mine" in citystates? For the same person is called "my son" by one person, "mybrother" by another, "my cousin" by a third, or something else in virtue 10of some other connection of kinship or marriage, one's own marriage, inthe first instance, or that of one's relatives. Still others call him "my fel-low clansman" or "my fellow tribesman." For it is better to have a cousinof one's own than a son in the way Socrates describes. Moreover, it is impossible to prevent people from having suspicionsabout who their own brothers, sons, fathers, and mothers are. For the re- ISsemblances that occur between parents and children will inevitably betaken as evidence of this. And this is what actually happens, according tothe reports of some of those who write accounts of their world travels.They say that some of the inhabitants of upper Libya have their womenin common, and yet distinguish the children on the basis of their resem- 20blance to their fathers. 11 And there are some women, as well as some females of other species such as mares and cows, that have a strong naturaltendency to produce offspring resembling their sires, like the mare inPharsalus called "Just."12 9. For example, someone might have official responsibility for or a special in terest in some common property.10. See Republic 463e2-5.1 1 . See Herodotus IV. 1 80. At Rh. 1360'33-35, Aristotle comments on the util ity of such travel writings in drafting laws.1 2 . She is called "Just" because in producing offspring like the sire, she made a just return on his investment, and showed herself to be a virtuous and faith ful wife. See HA 586'12-14. Pharsalus was in Thessaly in northern Greece. 30 Politics II Chapter 4 Moreover, there are other difficulties that it is not easy for the establish- 25 ers of this sort of community to avoid, such as voluntary or involuntary homicides, assaults, or slanders. None of these is pious when committed against fathers, mothers, or not too distant relatives (just as none is even against outsiders).13 Yet they are bound to occur even more frequently 30 among those who do not know14 their relatives than among those who do. And when they do occur, the latter can perform the customary expi ation, whereas the former cannot. It is also strange that while making sons communal, he forbids sexual intercourse only between lovers, 15 but does not prohibit sexual love itself or the other practices which, between father and son or a pair of broth- 35 ers, are most indecent, since even the love alone is. It is strange, too, that Socrates forbids such sexual intercourse solely because the pleasure that comes from it is so intense, but regards the fact that the lovers are father 40 and son or brother and brother as making no difference. 16 It would seem more useful to have the farmers rather than the guardians share their women and children . 17 For there will be lessJ262h friendship where women and children are held in common.18 But it is the ruled who should be like that, in order to promote obedience and prevent rebellion. In general, the results of such a law are necessarily the opposite of 5 those of a good law, and the opposite of those that Socrates aims to achieve by organizing the affairs of children and women in this way. For we regard friendship as the greatest of goods for city-states, since in this condition people are least likely to factionalize. And Socrates himself 13. Reading hosper kai pros apothen with the mss. The sentence is ambiguous, even if kai is omitted, as it is by Ross and Dreizehnter. But it cannot mean or imply that homicides, assaults, and slanders are pious when committed against outsiders. The implication is that these acts are particularly impious when committed against relatives, since even against outsiders they are so. See Plato, Laws 868c-873c. 14. Reading gnorizont011 with Dreizehnter and the mss. 1 5 . Homosexual male lovers are meant. 16. See Republic 403a--c. 17. The ideal city-state described in the Republic has three parts, producers (farmers), guardians, and philosopher-kings. The latter two share their women, children, and other property in common. The text is less clear about whether this is also true of the producers. See 1 264'1 1-bS. 18. Perhaps for the sort of reason given at 1 263'8-21. Chapter 4 31 Chapter 5 The next topic to investigate is property, and how those in the best con stitution should arrange it. Should it be owned in common, or not? One could investigate these questions even in isolation from the legislation dealing with women and children. I mean even if women and children1263" belong to separate individuals, which is in fact the practice everywhere, it still might be best for property either to be owned or used commu nally. For example, [ 1 ] the land might be owned separately, while the crops grown on it are communally stored and consumed (as happens in some nations). [2] Or it might be the other way around: the land might 5 be owned and farmed communally, while the crops grown on it are di vided up among individuals for their private use (some non-Greeks are also said to share things in this way). [3) Or both the land and the crops might be communal. If the land is worked by others, the constitution is different and eas ier. But if the citizens do the work for themselves, property arrange- 10 ments will give rise to a lot of discontent. For if the citizens happen to be unequal rather than equal in the work they do and the profits they enjoy, accusations will inevitably be made against those who enjoy or take a lot but do little work by those who take less but do more. It is generally dif- 15 ficult to live together and to share in any human enterprise, particularly in enterprises such as these. Travelers away from home who share a jour ney together show this clearly. For most of them start quarreling because they annoy one another over humdrum matters and little things. More over, we get especially irritated with those servants we employ most reg- 20 ularly for everyday services. These, then, and others are the difficulties involved in the common ownership of property. The present practice, provided it was enhanced by virtuous character22 and a system of correct laws, would be much su perior. For it would have the good of both-by "of both" I mean of the 25 common ownership of property and of private ownership. For while property should be in some way communal, in general it should be pri vate. For when care for property is divided up, it leads not to those mutual accusations, but rather to greater care being given, as each will be attending to what is his own. But where use is concerned, virtue will ensure that it is governed by the proverb "friends share everything in 30 common." evils people will lose through sharing, but also how many good things. The life they would lead seems to be totally impossible. One has to think that the reason Socrates goes astray is that his as- 30 sumption is incorrect. For a household and a city-state must indeed be a unity up to a point, but not totally so. For there is a point at which it will, as it goes on, not be a city-state, and another at which, by being nearly not a city-state, it will be a worse one. It is as if one were to reduce a har- 35 mony to a unison, or a rhythm to a single beat. But a city-state consists of a multitude, as we said before,27 and should be unified and made into a community by means of education. It is strange, at any rate, that the one who aimed to bring in education, and who believed that through it the city-state would be excellent, should think to set it straight by mea sures of this sort, and not by habits, philosophy, and laws28-as in Sparta and Crete, where the legislator aimed to make property communal by 40 means of the MESSES.1 264• And we must not overlook this point, that we should consider the im- mense period of time and the many years during which it would not have gone unnoticed if these measures were any good. For practically speaking all things have been discovered, 29 although some have not been collected, and others are known about but not used. The matter would 5 become particularly evident, however, if one could see such a constitu tion actually being instituted. For it is impossible to construct his city state without separating the parts and dividing it up into common messes or into clans and tribes. Consequently, nothing else will be legis lated except that the guardians should not do any farming, which is the 10 very thing the Spartans are trying to enforce even now. But the fact is that Socrates has not said, nor is it easy to say, what the arrangement of the constitution as a whole is for those who participate in it. The multitude of the other citizens constitute pretty well the entire multitude of his city-state, yet nothing has been determined about them, 27. At 1261•18. 28. Good habits promote the virtues of character; philosophy, here probably to be understood fairly loosely, promotes the virtues of thought, and the good use of LEISURE; laws sustain both. 29. See also 1329h25-35. Two of Aristotle's other views explain this otherwise implausible claim: ( I ) The world and human beings have always existed (Mete. 3 52bl6-17, GA 7 3 J h24-732•3, 742hJ7-743• 1 , DA 4 1 5•2S-h7). (2) Human beings are naturally adapted to form largely reliable beliefs about the world and what conduces to their welfare in it (Metaph. 993•30-hl l , Rh. 1355'1 5-17). Chapter 5 35 whether the farmers too should have communal property or each his 15own private property, or whether their women and children should beprivate or communal. 30 If all is to be common to all in the same way, howwill they differ from the guardians? And how will they benefit from submitting to their rule? Or what on earth will prompt them to submit toit-unless the guardians adopt some clever stratagem like that of theCretans? For the Cretans allow their slaves to have the same other things 20as themselves, and forbid them only the gymnasia and the possession ofweapons. On the other hand, if they31 too are to have such things, as theydo in other city-states, what sort of community will it be? For it will inevitably be two city-states in one, and those opposed to one another. 32 25For he makes the guardians into a sort of garrison, and the farmers,craftsmen, and the others into the citizens. 33 Hence the indictments,lawsuits, and such other bad things as he says exist in other city-stateswill all exist among them. And yet Socrates claims that because of theireducation they will not need many regulations, such as town or market 30ordinances and others of that sort. Yet he gives this education only to theguardians. 34 Besides, he gives the farmers authority over their property,although he requires them to pay a tax.35 But this is likely to make themmuch more difficult and presumptuous than the helots,36 serfs, andslaves that some people have today. 35 But be that as it may, whether these matters are similarly essential ornot, nothing at any rate has been determined about them; neither are therelated questions of what constitution, education, and laws they willhave. The character of these people is not easy to discover, and the difference it makes to the preservation of the community of the guardiansis not small. But if Socrates is going to make their women communaland their property private, who will manage the household in the way 12641 30. Aristotle is justified in thinking that Socrates is vague about this. Farmers initially seem to have a traditional family life and to possess private prop erty. But casual remarks at 433d and 454d--e suggest that this may not be so, that female producers will not necessarily be housewives, but will be trained in the craft for which their natural aptitude is highest.3 1 . The citizens other than the guardians.32. This is a criticism that Socrates brings against other city-states at Republic 422e-423b.33. See Republic 4 1 5a-417b, 4 19a-42l c, 543b--c.34. See Republic 424a-426e.3 5 . See Republic 4 16d--e.36. Helots were the serf population of Sparta. 36 Politics II the men manage things in the fields? Who will manage it, indeed, if the farmers' women and property are communal? It is futile to draw a com parison with wild beasts in order to show that women should have the5 same way of life as men: wild beasts do not go in for household manage ment.37 The way Socrates selects his rulers is also risky. He makes the same people rule all the time, which becomes a cause of conflict even among people with no merit, and all the more so among spirited and warlike10 men. 38 But it is evident that he has to make the same people rulers, since the gold from the god has not been mixed into the souls of one lot of people at one time and another at another, but always into the same ones. He says that the god, immediately at their birth, mixed gold into the souls of some, silver into others, and bronze and iron into those who are15 going to be craftsmen and farmers. Moreover, even though Socrates deprives the guardians of their hap piness, he says that the legislator should make the whole city-state happy.39 But it is impossible for the whole to be happy unless all, most, or some of its parts are happy. For happiness is not made up of the same20 things as evenness, since the latter can be present in the whole without being present in either of the parts,40 whereas happiness cannot. But if the guardians are not happy, who is? Surely not the skilled craftsmen or the multitude of VULGAR CRAFTSMEN. These, then, are the problems raised by the constitution Socrates de-25 scribes, and there are others that are no less great. Chapter 6 Pretty much the same thing holds in the case of the Laws, which was written later, so we had better also briefly examine the constitution there. In fact, Socrates has settled very few topics in the Republic: theway in which women and children should be shared in common; the sys-tem of property; and the organization of the constitution. For he divides 30the multitude of the inhabitants into two parts: the farmers and the defensive soldiers. And from the latter he takes a third, which is the part ofthe city-state that deliberates and is in authorityY But as to whether thefarmers and skilled craftsmen will participate in ruling to some extent ornot at all, and whether or not they are to own weapons and join in bat- JStie-Socrates has settled nothing about these matters.42 He does think,though, that guardian women should join in battle and receive the sameeducation as the other guardians. Otherwise, he has filled out his account with extraneous discussions,43 including those about the sort ofeducation the guardians should receive. 40 Most of the Laws consist, in fact, of laws, and he has said little about 1265"the constitution. He wishes to make it more generally attainable by ac-tual city-states,44 yet he gradually turns it back toward the other constitutionY For, with the exception of the communal possession of womenand property, the other things he puts in both constitutions are the Ssame: the same education,46 the life of freedom from necessary work,47and, on the same principles, the same messes--except that in this constitution he says that there are to be messes for women too;48 andwhereas the other one consisted of one thousand weapon owners, thisone is to consist of five thousand.49 All the Socratic dialogues have some- 10thing extraordinary, sophisticated, innovative, and probing about them;but it is perhaps difficult to do everything well. Consider, for example,the multitude just mentioned. We must not forget that it would need aterritory the size of Babylon or some other unlimitedly large territory to 15 keep five thousand people in idleness, and a crowd of women and ser vants along with them, many times as great. We should assume ideal conditions, to be sure, but nothing that is impossible. It is stated that a legislator should look to just two things in establish- 20 ing his laws: the territory and the people. 5° But it would also be good to add the neighboring regions too, if first, the city-state is to live a politi cal life, 51 not a solitary one; for it must then have the weapons that are useful for waging war not only on its own territory but also against the 25 regions outside it. But if one rejects such a life, both for the individual and for the city-state in common, the need to be formidable to enemies is just as great, both when they are invading its territory and when they are staying away from it. 52 The amount of property should also be looked at, to see whether it would not be better to determine it differently and on a clearer basis. He says that a person should have as much as he needs in order to live tem- 30 perately, which is like saying "as much as he needs to live well." For the formulation is much too general. Besides, it is possible to live a temper ate life but a wretched one. A better definition is "temperately and gen erously"; for when separated, the one will lead to poverty, the other to luxury. For these are the only choiceworthy states that bear on the use of 35 property. One cannot use property either mildly or courageously, for ex ample, but one can use it temperately and generously. Hence, too, the states concerned with its use must be these. It is also strange to equalize property and not to regulate the number 40 of citizens, leaving the birth rate unrestricted in the belief that the exis tence of infertility will keep it sufficiently steady no matter how many births there are, because this seems to be what happens in actual city-1265b states.53 But the same exactness on this matter is not required in actual city-states as in this one. For in actual city-states no one is left destitute, because property can be divided among however great a number. But, in this city-state, property is indivisible,54 so that excess children will nee- 50. This is not said anywhere in our text of the Laws, but Aristotle may be in ferring it from 704a-709a, 747d, 842c-e. His subsequent criticisms overlook 737d, 758c, 949e ff. 5 1 . City-states typically lead a political life in part by interacting with other city-states ( 1 327b3-6), but even isolated city-states can lead such a life pro vided their parts interact appropriately ( 132Sb23-27). 52. Reading apousin with Bender. The mss. have apelthousin: "when they are leaving it." The political life is discussed in the Introduction xlvi-xlvii. 53. Aristotle apparently overlooks Laws 736a, 740b-74 la, 923d. 54. See Laws 740b, 74 lb, 742c, 855a-b, 856d-e. Chapter 6 39 essarily get nothing, no matter whether they are few or many. One might 5well think instead that it is the birth rate that should be limited, ratherthan property, so that no more than a certain number are born. (Oneshould fix this number by looking to the chances that some of those bornwill not survive, and that others will be childless.) To leave the numberunrestricted, as is done in most city-states, inevitably causes poverty 10among the citizens; and poverty produces faction and crime. In fact,Pheidon of Corinth,55 one of the most ancient legislators, thought thatthe number of citizens should be kept the same as the number of house-hold estates, even if initially they all had estates of unequal size. But in 15the Laws, it is just the opposite. 56 Our own view as to how these thingsmight be better arranged, however, will have to be given later.57 Another topic omitted from the Laws concerns the rulers: how theywill differ from the ruled. He says that just as warp and woof come fromdifferent sorts of wool, so should ruler be related to ruled. 58 Further- 20more, since he permits a person's total property to increase up to fivetimes its original value, 59 why should this not also hold of land up to acertain point? The division of homesteads also needs to be examined, incase it is disadvantageous to household management. For he assigns twoof the separate homesteads resulting from the division to each individ-ual; but it is difficult to run two households.60 25 The overall organization tends to be neither a democracy nor an oligarchy but midway between them; it is called a POLITY, since it is madeup of those with HOPLITE weapons.61 If, of the various constitutions, heis establishing this as the one generally most acceptable to actual citystates, his proposal is perhaps good, but if as next best after the first con- 30 stitution, it is not goodY For one might well commend the Spartan con stitution, or some other more aristocratic one. Some people believe, in- 35 deed, that the best constitution is a mixture of all constitutions, which is why they commend the Spartan constitution. For some say that it is made up of oligarchy, monarchy, and democracy; they say the kingship is a monarchy, the office of senators an oligarchy, and that it is governed democratically in virtue of the office of the overseers (because the over seers are selected from the people as a whole). Others of them say that 40 the overseership is a tyranny, and that it is governed democratically be cause of the messes and the rest of daily life.63 But in the Laws it is said1266" that the best constitution should be composed of democracy and tyranny, constitutions one might well consider as not being CONSTITU TIONS at all, or as being the worst ones of all. 64 Therefore, the proposal of those who mix together a larger number is better, because a constitu- 5 tion composed of a larger number is better. 65 Next, the constitution plainly has no monarchical features at all, but only oligarchic and democratic ones, with a tendency to lean more toward oligarchy. This is clear from the method of selecting officials. For to select by lot from a previously elected pool is common to both. But it is oli garchic to require richer people to attend the assembly, to vote for offi- 10 cials, and to perform any other political duties, without requiring these things of the others.66 The same is true of the attempt to ensure that the majority of officials come from among the rich, with the most important ones coming from among those with the highest PROPERTY ASSESSMENTY 62. Plato seems to have chosen his constitution for both reasons (Laws 739a ff., 745e ff., 805b--d, 853c). 63. See 1 294hl 3-40. On senators, kings, and overseers, see 11.9 and notes. 64. Plato describes monarchy (not tyranny) and democracy as the "mothers" of all constitutions (Laws 693d-e). He describes the constitution he is propos ing, which is not the best but the second best, as a mean between monarchy and democracy (756e). In the Republic, where he sets out the best constitu tion, he agrees with Aristotle that democracy and tyranny are the worst con stitutions possible (580a-c). 65. The conclusion hardly follows. But the point is perhaps this: a constitution in which principles drawn from a large number of other constitutions are mixed will serve the interests of more citizens (whatever their own political leanings) and so will be more stable ( 1 270h17-28) and more just ( 1 294' 1 5-25). 66. See Laws 756b-e, 763d-767d, 9 5 1 d-e. 67. This is true of the market and city-state managers but it is not so clearly true of other important officials. See Laws 753b--d , 755b--756b, 766a-c, 946a. Chapter 7 41 Chapter 7There are other constitutions, too, proposed either by private individu-als or by philosophers and statesmen. But all of them are closer to theestablished constitutions under which people are actually governed thaneither of Plato's. For no one else has ever suggested the innovations ofsharing children and women, or of messes for women.71 Rather, they 35begin with the necessities. Some of them hold, indeed, that the most important thing is to have property well organized, for they say that it isover property that everyone creates faction. That is why Phaleas of Chalcedon,72 the first to propose such a constitution, did so; for he says thatthe property of the citizens should be equal. He thought this was not 40difficult to do when city-states were just being founded, but that in those 1 266balready in operation it would be more difficult. Nonetheless, he thoughtthat a leveling could very quickly be achieved by the rich giving but not receiving dowries, and the poor receiving but not giving them. (Plato,5 when writing the Laws, thought that things should be left alone up to a certain point, but that no citizen should have more than five times the smallest amount, as we also said earlier-)13 However, people who make such laws should not forget, as in fact they do, that while regulating the quantity of property they should regulate the quantity of children too.10 For if the number of children exceeds the amount of property, it is cer tainly necessary to abrogate the law. But abrogation aside, it is a bad thing for many to become poor after having been rich, since it is a task to prevent people like that from becoming revolutionaries.15 That leveling property has some influence on political communities was evidently understood even by some people long ago; for example, both by Solon in his laws/4 and the law in force elsewhere which pro hibits anyone from getting as much land as he might wish. Laws likewise prevent the sale of property, as among the Locrians75 where the law for-20 bids it unless an obvious misfortune can be shown to have occurred. In yet other cases it is required that the original allotments be preserved in tact. It was the abrogation of this provision, to cite one example, that made the constitution of Leucas76 too democratic, since as a result men no longer entered office from the designated assessment classes. But25 equality of property may exist and yet the amount may be too high, so that it leads to luxurious living, or too low, so that a penny-pinching life results. It is clear, then, that it is not enough for the legislator to make property equal, he must also aim at the mean. Yet even if one prescribed a moderate amount for everyone, it would be of no use. For one should level desires more than property, and that cannot happen unless people30 have been adequately educated by the laws. 77 Phaleas would perhaps reply that this is actually what he means; for he thinks that city-states should have equality in these two things: prop erty and education. But one also ought to say what the education is going to be. And it is no use for it be one and the same. For it can be one35 and the same, but of the sort that will produce people who deliberately choose to be ACQUISITIVE of money or honor or both. Besides, people re- 73. At 1 26Sb21-23. 74. Discussed at 1273h3S-1 274"2 1 . 7 5 . A Greek settlement in southern Italy. Their legislator Zaleucus (mentioned at 1274'22- 3 1 ) was famous for trying to reduce class conflict, and may have been the author of the law in question. 76. A Corinthian colony founded in the seventh century. 77. See 1337'10-32, NE 1 179'33-1 1 8 1 b23. Chapter 7 43 78. Homer, Iliad IX. 3 1 9. Achilles is complaining that if his war prizes can be taken away by Agamemnon, then noble and base are being honored to the same degree.79. The pleasure of satisfying one's hunger comes in part from alleviating the pains of hunger, but other pleasures need involve no pain. See NE 1 1 73bl 3-20; Plato, Republic 359c, 373a-d, 583b-588a.80. Reading autim with some mss. Alternatively (Ross and Dreizehnter): "if any one should wish to find enjoyment through themselves (hautim). " But this makes Aristotle's proposed cure irrelevant to its target.8 1 . On Aristotle's view there are two relevant candidate pleasures-the pleasure of practical political activity and the pleasure of philosophical contempla tion. The former, however, which involves living a life with other people, in volves pain, while the latter, which is compatible with living a solitary life, does not. The contrast is particularly clear at NE 1 177'22-b26. 44 Politics II 82. A wealthy money-changer who united Atarneus and Assos (two strongholds on the coast of Asia Minor) into a single kingdom, which was attacked by the Persian general Autophradates c. 350, and where Aristotle lived in the late 340s. 83. An obol is one sixth of a drachma. The two-obol payment (diobelia) was in troduced after the fall of the oligarchy of 41 1 I 10. It seems to have been, in effect, a form of poor relief. See Ath. XXVIII. 3. 84. See 1257b40-1258'14. Chapter S 45 Chapter 8Hippodamus of Miletus, the son of Euryphon, invented the division ofcity-states and laid out the street plan for Piraeus. 86 His love of honorcaused him also to adopt a rather extraordinary general lifestyle. Somepeople thought he carried things too far, indeed, with his long hair, ex- 25pensive ornaments, and the same cheap warm clothing worn winter andsummer. He also aspired to understand nature as a whole, and was thefirst person, not actually engaged in politics, to attempt to say somethingabout the best constitution. The city-state he designed had a multitude of ten thousand citizens, 30divided into three parts. He made one part the craftsmen, another thefarmers, and a third the defenders who possess the weapons. He also divided the territory into three parts: sacred, public, and private. Thatwhich provided what is customarily rendered to the gods would be sacred; that off which the defenders would live, public; and the land be- JSlonging to the farmers, private. He thought that there are just threekinds of law, since the things lawsuits arise over are three in number: ARROGANT behavior, damage,87 and death. He also legislated a single courtwith supreme authority, consisting of a certain number of selected elders, to which all lawsuits thought to have not been well decided are tobe referred. He thought that verdicts in law courts should not be ren- 40 85. Epidamnus in the Adriatic was a colony of Corinth and Corcyra founded in the seventh century. The identity of Diophantus is uncertain, and his scheme otherwise unknown.86. Hippodamus was a fifth-century legislator and city-state planner. Around the middle of the fifth century he went as a colonist to Italy, where he laid out the city-state ofThurii. Piraeus is the harbor area near Athens. Aristotle comments on city-state planning at 1330h29-3 1 .87. blabin: covering both personal injury and damage to property. 46 Politics II 1268• dered by casting ballots. Rather, each juror should deposit a tablet: if he convicts unqualifiedly, he should write the penalty on the tablet; if he acquits unqualifiedly, he should leave it blank; if he convicts to some ex tent and acquits to some extent, he should specify that. For he thought S that present legislation is bad in this regard, because it forces jurors to violate their judicial oath by deciding one way or the other. 88 Moreover, he established a law that those who discovered something beneficial to the city-state should be honored, and one another that children of those who died in war should receive support from public funds. He assumed that this had not been legislated elsewhere, whereas in reality such a law 10 existed both in Athens and in some other city-states. All the officials were to be elected by the people, and the people were to be made up of the city-state's three parts. Those elected should take care of commu nity, foreign affairs, and orphans. These, then, are most of the features 1S of Hippodamus' organization, and the ones that most merit discussion. The first problem is the division of the multitude of citizens. The craftsmen, farmers, and those who possess weapons all share in the con stitution. But the fact that the farmers do not possess weapons, and that the craftsmen possess neither land nor weapons, makes them both virtu- 20 ally slaves of those who possess weapons. So it is impossible that every office be shared. For the generals, civic guards, and practically speaking all the officials with the most authority will inevitably be selected from those who possess weapons. But if the farmers and craftsmen cannot participate, how can they possibly have any friendly feelings for the con- 25 stitution? "But those who possess weapons will need to be stronger than both the other parts." Yet that is not easy to arrange unless there are lots of them. And, in that case, is there any need to have the others partici pate in the constitution or have authority over the selection of officials? Besides, what use are the farmers to Hippodamus' city-state? Skilled 30 craftsmen are necessary (every city-state needs them), and they can sup port themselves by their crafts, as in other city-states. It would be rea sonable for the farmers to be a part of the city-state, if they provided 88. In Athenian law juries decided guilt or innocence by casting a ballot. The penalty for some crimes was prescribed by law. For others, the jury had to choose between a penalty proposed by the prosecutor and a counterpenalty proposed by the defendant. In neither case could a juror propose some penalty of his own devising. Hippodamus is proposing to give a juror more discretion in both sorts of cases. Jurors in Athens took a judicial oath to ren der the most just verdict possible. Chapter 8 47 food and sustenance for those who possess weapons. But, as thingsstand, they have private land and farm it privately. Next, consider the public land, which is to feed the defenders. If they 35themselves farm it, the fighting part will not be different from the farm-ing one, as the legislator intends. And if there are going to be some oth-ers to do so, different from those who farm privately and from the warriors, they will constitute a fourth part in the city-state that participatesin nothing and is hostile to the constitution. Yet if one makes those who 40farm the private land and those who farm the public land the same, thequantity of produce from each one's farming will be inadequate for twohouseholds. 89 Why will they not at once feed themselves and the soldiers 1268hfrom the same land and the same allotments? There is a lot of confusionin all this. The law about verdicts is also bad, namely, the requirement that thejuror should become an ARBITRATOR and make distinctions in his decisions, though the charge is written in unqualified terms. This is possible Sin arbitration, even if there are lots of arbitrators, because they confertogether over their verdict. But it is not possible in jury courts; and, indeed, most legislators do the opposite and arrange for the jurors not toconfer with one another.90 How, then, will the verdict fail to be confused 10when a juror thinks the defendant is liable for damages, but not for asmuch as the plaintiff claims? Suppose the plaintiff claims twenty minas,but the juror awards ten (or the former more, the latter less), anotherawards five, and another four. It is clear that some will split the award in 1Sthis way, whereas some will condemn for the whole sum, and others fornothing. How then will the votes be counted? Furthermore, nothingforces the one who just acquits or convicts unqualifiedly to perjure him-self, provided that the indictment prescribes an unqualified penalty. Ajuror who acquits is not deciding that the defendant owes nothing, onlythat he does not owe the twenty minas. A juror who convicts without be- 20lieving that he owes the twenty minas, however, violates his oathstraightway. As for his suggestion that those who discover something beneficial tothe city-state should receive some honor, such legislation is sweet to lis- 89. Presumably, because of the lost efficiency of scale. One can produce less from two farms than from a single farm of the same acreage.90. Athenian juries of five hundred to one thousand members were not unusual. They gave their verdicts directly without conferring. 48 Politics II ten to, but not safe.91 For it would encourage "sychophancy,"92 and 25 might perhaps lead to change in the constitution. But this is part of an other problem and a different inquiry. For some people93 raise the ques tion of whether it is beneficial or harmful to city-states to change their traditional laws, if some other is better. Hence if indeed change is not beneficial, it is not easy to agree right off with Hippodamus' suggestion, though it is possible someone might propose that the laws or the consti- 30 tution be dissolved on the grounds of the common good. Now that we have mentioned this topic, however, we had better ex pand on it a little, since, as we said, there is a problem here, and change may seem better. At any rate, this has certainly proved to be beneficial in the other sciences. For example, medicine has changed from its tradi- 35 tiona! ways, as has physical training, and the crafts and sciences gener ally. So, since statesmanship is held to be one of these, it is clear that something similar must also hold of it. One might claim, indeed, that the facts themselves provide evidence of this. For the laws or customs of the distant past were exceedingly simple and barbaric. For example, 40 the Greeks used to carry weapons and buy their brides from one an other. Moreover, the surviving traces of ancient law are completely1261)' naive; for example, the homicide law in Cyme says that if the prosecutor can provide a number of his own relatives as witnesses, the defendant is guilty of murder. Generally speaking, everyone seeks not what is tradi tional but what is good. But the earliest people, whether they were 5 "earth-born" or the survivors of some cataclysm, were probably like or dinary or foolish people today (and this is precisely what is said about the earth-born indeed}.94 So it would be strange to cling to their opin ions. Moreover, it is not better to leave even written LAWS unchanged. For just as it is impossible in the other crafts to write down everything 10 exactly, the same applies to political organizations. For the universal law must be put in writing, but actions concern particulars. 9 1 . Though Aristotle does favor such legislation in at least one kind of case, see 1309' 1 3-14. 92. By the middle of the fifth century some people in Athens, known as sycho phants, made a profession of bringing suits against others for financial, po litical, or personal reasons. Aristotle worries that Hippodamus' law will en courage sychophancy through giving people an incentive to pose as public benefactors by bringing false charges of sedition and the like against others. 93. See Herodotus 111.80; Plato, Laws 772a-d, Statesman 298c ff.; Thucydides 1.7 1 . 94. The cataclysm view i s expressed i n Plato, Laws 677a ff., Timaeus 22c ff. The earth-born are described at Statesman 272c-d and Laws 677b-678b. Chapter 9 49 Chapter 9There are two things to investigate about the constitution of Sparta, ofCrete, and, in effect, about the other constitutions also. First, is there 30anything legislated in it that is good or bad as compared with the best organization? Second, is there anything legislated in it that is contrary tothe fundamental principle or character of the intended constitution? It is generally agreed that to be well-governed a constitution shouldhave leisure from necessary tasks. But the way to achieve this is not easy 35to discover. For the Thessalian serfs often attacked the Thessalians, justas the helots-always lying in wait, as it were, for their masters' misfortunes-attacked the Spartans. Nothing like this has so far happened inthe case of the Cretans. Perhaps the reason is that, though they war with 40one another, the neighboring city-states never ally themselves with the 1269"rebels: it benefits them to do so, since they also possess SUBJECT PEOPLESthemselves. Sparta's neighbors, on the other hand, the Argives, Messe-nians, and Arcadians, were all hostile. The Thessalians, too, first experi- 5enced revolts because they were still at war with their neighbors, theAchaeans, Perrhaebeans, and Magnesians. If nothing else, it certainlyseems that the management of serfs, the proper way to live together with them, is a troublesome matter. For if they are given license, they become arrogant and claim to merit equality with those in authority, but if they10 live miserably, they hate and conspire. It is clear, then, that those whose system of helotry leads to these results still have not found the best way. 96 Furthermore, the license where their women are concerned is also detrimental both to the deliberately chosen aims of the constitution and to the happiness of the city-state as well. For just as a household has a15 man and a woman as parts, a city-state, too, is clearly to be regarded as being divided almost equally between men and women. So in all consti tutions in which the position of women is bad, half the city-state should be regarded as having no laws. And this is exactly what has happened in Sparta. For the legislator, wishing the whole city-state to have en-20 durance, makes his wish evident where the men are concerned, but has been negligent in the case of the women. For being free of all con straint,97 they live in total intemperance and luxury. The inevitable re sult, in a constitution of this sort, is that wealth is esteemed.98 This is particularly so if the citizens are dominated by their women, like most25 military and warlike races (except for the Celts and some others who openly esteemed male homosexuality). So it is understandable why the original author of the myth of Ares and Aphrodite paired the two;99 for all warlike men seem obsessed with sexual relations with either men or30 women. That is why the same happened to the Spartans, and why in the days of their hegemony, many things were managed by women. And yet what difference is there between women rulers and rulers ruled by women? The result is the same. Audacity is not useful in everyday mat-35 ters, but only, if at all, in war. Yet Spartan women were very harmful even here. They showed this quite clearly during the Theban invasion;100 for they were of no use at all, like women in other city-states, 1 0 1 but caused more confusion than the enemy. spite lengthy wars. Indeed, they say that there were once ten thousand Spartiates.105 Whether this is true or not, a better way to keep high the number of men in a city-state is by leveling property. But the law dealing with the procreation of children militates against this reform. For the127rJ legislator, intending there to be as many Spartiates as possible, encour ages people to have as many children as possible, since there is a law ex empting a father of three sons from military service, and a father of four from all taxes. But it is evident that if many children are born, and the S land is correspondingly divided, many people will inevitably become poor. Matters relating to the board of overseers 106 are also badly organized. For this office has sole authority over the most important matters; but the overseers are drawn from among the entire people, so that often very 10 poor men enter it who, because of their poverty, are107 open to bribery. (This has been shown on many occasions in the past too, and recently among the Andrians; for some, corrupted by bribes, did everything in their power to destroy the entire city-state. 1 08) Moreover, because the of fice is too powerful-in fact, equal in power to a tyranny-even the kings were forced to curry favor with the overseers. And this too has IS harmed the constitution, for from an aristocracy a democracy was emerging. Admittedly, the board of overseers does hold the constitution to gether; for the people remain contented because they participate in the most important office. So, whether it came about because of the legisla- 20 tor or by luck, it benefits Spartan affairs. For if a constitution is to sur vive, every part of the city-state must want it to exist and to remain as it is. 109 And the kings want this because of the honor given to them; the noble-and-good, because of the senate (since this office is a reward of 25 virtue); and the people, because of the board of overseers (since selec- tions for it are made from all). Still, though the overseers should be chosen from all, it should not be by the present method, which is exceedingly childish. 1 1 0 Furthermore, the overseers have authority over the most importantjudicial decisions, though they are ordinary people. Hence it would bebetter if they decided cases not according to their own opinion, but inaccordance with what is written, that is to say, laws. Again, the overseers' 30lifestyle is not in keeping with the aim of the constitution.111 For it involves too much license, whereas in other respects112 it is too austere, sothat they cannot endure it, but secretly escape from the law and enjoythe pleasures of the body. 1 13 35 Matters relating to the senate also do not serve the Spartans well. 1 14 Ifthe senators were decent people, with an adequate general education inmanly virtue, one might well say that this office benefits the city-state.Although, one might dispute about whether they ought to have lifelongauthority in important matters,115 since the mind has its old age as well asthe body. 1 16 But when they are educated in such a way that even the legis 40 1271•lator himself doubts that they are good men, it is not safe. And in fact inmany matters of public concern, those who have participated in this office have been conspicuous in taking bribes and showing favoritism. Thisis precisely why it is better that the senators not be exempt from INSPECTION, as they are at present. It might seem that the overseers should in 5spect every office, but this would give too much to the board of overseers,and is not the way we say inspections should be carried out. The method of electing senators is also defective. Not only is the selection made in a childish way, 117 but it is wrong for someone worthy of 10 1 1 0. The overseers may have been chosen by acclamation, like the senate, but it is also possible that they were chosen by lot. See Plato, Laws 692a.1 1 1 . Reading tes politeias with Scaliger. Alternatively: "not in keeping with the aim of the city-state (tes poleos)."1 12. en de tois a/lois: or "in the case of other people."1 1 3. See Plato, Republic 548b.1 14. The senate (gerousia) had 28 members in addition to the two kings (dis cussed below). All were over 60 years old, and were probably selected from aristocratic families. The senate prepared the agenda of the citizen assem bly, and had other political and judicial functions.1 1 5. The apparent conflict with the characterization of the overseers at 1270b28-29 is perhaps removed by 1 275b9-1 1 .1 1 6. See Rh. 1 389h1 3-1 390•24.1 1 7. Members of the senate were chosen by an elaborate process of acclamation. See 1 306•18-1 9, Plutarch, Lycurgus XXVI. 54 Politics II the office to ask for it: a man worthy of the office should hold it whether he wants to or not. But the fact is that the legislator is evidently doing the same thing here as in the rest of the constitution. He makes the citi zens love honor and then takes advantage of this fact in the election of 15 the senators; for no one would ask for office who did not love honor. Yet the love of honor and of money are the causes of most voluntary wrong doings among human beings. The question of whether or not it is better for city-states to have a kingship must be discussed later;ll8 but it is better to choose each new 20 king, not as now, 119 but on the basis of his own life. (It is clear that even the Spartan legislator himself did not think it possible to make the kings noble-and-good. At any rate he distrusts them, on the grounds that they are not sufficiently good men. That is precisely why they used to send out a king's opponents as fellow ambassadors, and why they regard fac- 25 tion between the kings as a safeguard for the city-state.) Nor were matters relating to the messes (or so-called phiditia) well legislated by the person who first established them. For they ought to be publicly supported, as they are in Crete. 120 But among the Spartans each individual has to contribute, even though some are extremely poor and 30 unable to afford the expense. The result is thus the opposite of the legis lator's deliberately chosen aim. He intended the institution of messes to be democratic, but, legislated as they are now, they are scarcely democ ratic at all, since the very poor cannot easily participate in them. Yet 35 their traditional way of delimiting the Spartan constitution is to exclude from it those who cannot pay this contribution. The law dealing with the admirals has been criticized by others, and rightly so, since it becomes a cause of faction.121 For the office of admiral is established against the kings, who are permanent generals, as pretty 40 much another kingship. One might also criticize the fundamental principle of the legislator as1271b Plato criticized it in the Laws.122 For the entire system of their laws aims at a part of virtue, military virtue, since this is useful for conquest. So, as 1 1 8. At 111. 14-17. 1 19. Sparta had two hereditary kings, each descended from a different royal house, both of whom were members of the senate and ruled for life. They had a military as well as a political and religious function. 1 20. See 1 272' 1 2-27. 1 2 1 . For examples, see 1301h18-2 1 , 1306h3 1-33. 1 22. At 625c-638b. Chapter 10 55 long as they were at war, they remained safe. But once they ruledsupreme, they started to decline, because they did not know how to be atleisure, and had never undertaken any kind of training with more 5AUTHORITY than military training. Another error, no less serious, is thatalthough they think (rightly) that the good things that people competefor are won by virtue rather than by vice, they also suppose (not rightly)that these GOODS are better than virtue itself.123 Matters relating to public funds are also badly organized by the Spar- 10tiates. For they are compelled to fight major wars, yet the public treasuryis empty, and taxes are not properly paid; for, as most of the land belongsto the Spartiates, they do not scrutinize one another's tax payments. 124Thus the result the legislator has produced is the opposite of beneficial: IShe has made his city-state poor and the private individuals into lovers ofmoney. So much for the Spartan constitution. For these are the things onemight particularly criticize in it. Chapter 1 0The Cretan constitution closely resembles that of the Spartans; in some 20small respects it is no worse, but most of it is less finished. For it seems,or at any rate it is said, 125 that the constitution of the Spartans is largelymodeled on the Cretan; and most older things are less fully elaboratedthan newer ones. They say that after Lycurgus relinquished theguardianship of King Charillus126 and went abroad, he spent most of his 25time in Crete, because of the kinship connection. For the Lyctians werecolonists from Sparta, and those who went to the colony adopted the organization of the laws existing among the inhabitants at that time. Henceeven now their subject peoples employ these laws, in the belief that 30Minos127 first established the organization of the laws. The island seems naturally adapted and beautifully situated to rule 123. This criticism of Sparta and other oligarchies is repeated with various elaborations and emphases at 1334'2-h5, 1324h5-1 1 , l 3 33b5-1 l .124. Thucydides 1. 132 tells u s that the regular custom o f the Spartans was "never to act hastily in the case of a Spartan citizen and never to come to any irrevocable decision without indisputable proof."125. See Herodotus 1.65; Plato, Minos 3 18c-d, 320a, b.126. The posthumous son of Lycurgus' elder bother King Polydectes.127. Semimythical Cretan king, husband of Pasiphae, the mother of the Mino taur. 56 Politics II the Greek world since it lies across the entire sea on whose shores most 35 of the Greeks are settled. In one direction it is not far from the Pelopon nese, and in the other from Asia (the part around Cape Triopium) and from Rhodes. That is why Minos established his rule over the sea too, subjugating some islands, establishing settle -:1ents on others, and finally attacking Sicily, where he met his death near Camicus.128 40 The Cretan way of organizing things is analogous to the Spartan. The helots do the farming for the latter, the subject peoples for the former.1272" Both places have messes (in ancient times, the Spartans called these an dreia rather than phiditia, 129 like the Cretans-a clear indication that they came from Crete). Besides, there is the organization of the constitution. For the overseers have the same powers as the order keepers (as they are 5 called in Crete), except that the overseers are five in number and the order keepers ten. The senators correspond to the senators, whom the Cretans call the council. The Cretans at one time had a kingship, but later they did away with it, and the order keepers took over leadership in war. 10 All Cretans participate in the assembly, but its authority is limited to vot ing together for the resolutions of the senators and order keepers. Communal meals are better handled among the Cretans than among the Spartans. In Sparta, as we said earlier, 130 each person must con tribute a fixed amount per capita; if he does not, a law prevents him from 15 participating in the constitution. In Crete, on the other hand, things are done more communally. Out of all the public crops and livestock and the tributes paid by the subject peoples, one part is set aside for the gods 20 and for PUBLIC SERVICES, and another for the messes, so that all women and children and men-are fed at public expense. 131 The legisla tor regarded frugality as beneficial and gave much thought to securing it, and to the segregation of women, so as to prevent them from having many children, and to finding a place for sexual relations between men. There will be another opportunity to examine whether this was badly 25 done or not.132 It is evident, then, that the messes have been better orga nized by the Cretans than by the Spartans. Matters relating to the order keepers, on the other hand, are even lesswell organized than those relating to the overseers. For the board oforder keepers shares the defect of the board of overseers (that it is composed of ordinary people), but the benefit to the constitution there is ab- 30sent here. For there the people participate in the most important office,and so wish the constitution to continue, because the election is fromall.133 But here the order keepers are elected not from all but from cer-tain families, and the senators are elected from those who have beenorder keepers. And the same remarks might be made about the senators 35as about those who become senators in Sparta: their exemption from inspection and their life tenure are greater prerogatives than they merit,and it is dangerous that they rule not in accordance with what is writtenbut according to their own opinion. The fact that the people remain quiescent even though they do notparticipate is no indication that it has been well organized. For unlike 40the overseers, the order keepers have no profit, because they live on anisland, far away, at least, from any who might corrupt them. The remedy !272hthey use for this offense is also strange, not political but characteristic ofa DYNASTY. For the order keepers are frequently expelled by a conspir-acy either of their colleagues themselves or of private individuals. Orderkeepers are also allowed to resign before their term has expired. But Ssurely it is better if all these things should take place according to LAWand not human wish, which is not a safe standard. Worst of all, however, is the suspension of order keepers, 134 oftenbrought about by the powerful, when they are unwilling to submit tojustice. For this makes it clear that whereas the organization has something of a constitution about it, yet it is not a constitution but more of adynasty. Their habit is to divide the people and their own friends, create !0anarchy, 135 form factions, and fight one another. Yet how does this sort ofthing differ from such a city-state ceasing temporarily to be a city-state,and the political community dissolving? A city-state in this condition isin danger, since those who wish to attack it are also able to so. But, as we ISsaid, Crete's location saves it, since its distance has served to keep foreigners out. 136 This is why the institution of subject peoples survives among the Cretans, whereas the helots frequently revolt. For the Cre tans do not rule outside their borders-though a foreign war has recently 20 come to the island, which has made the weakness of its laws evident. 137 So much for this constitution. Chapter 1 1 The Carthaginians also are thought to be well-governed, and in many 25 respects in an extraordinary way (compared to others), though in some respects closely resembling the Spartans. For these three constitutions, the Cretan, Spartan, and, third, the Carthaginian, are all in a way close to one another and very different from others. Many of their arrange ments work well for them, and it is an indication that their constitution 30 is well organized that the people willingly138 stick with the way the con stitution is organized, and that no faction even worth talking about has arisen among them, and no tyrant. Points of similarity to the Spartan constitution are these. The com panions' messes are like the phiditia; the office of the one-hundred- 35 and-four is like that of the overseers, except that it is not worse (for the overseers are drawn from ordinary people, whereas they elect to this of fice on the basis of merit). Their kings and senate are analogous to those of Sparta; but it is better that the kings are neither from the same family nor from a chance one; but if any family distinguishes itself, then the kings are elected from its members, rather than selected on the basis of 40 seniority. For they have authority in important matters, and if they are insignificant people, they do a lot of harm to the city-state (as they al-1273• ready have done to the city-state of the Spartans). Most of the criticisms one might make because of its deviations from the best constitution are actually common to all the constitutions we have discussed. But of those that are deviations from the fundamental principle of an aristocracy or a POLITY,139 some deviate more in the di- S rection of democracy, others more in the direction of oligarchy. For the kings and senators have authority over what to bring and what not to 1 37. Outside dominions involve foreign wars, which are one cause of serf re volts. See 1269bS-7. 1 38. Reading hekousion with Dreizehnter. 139. A polity is a mixed constitution ( 1 26Sb26-28). Aristotle usually uses the term "aristocracy" to refer to a single component of a mixed constitution. But here-as at 1 294bl 0-1 1-he treats it and "polity" as equivalents. Chapter 1 1 59 bring before the people, provided they all agree; but if they do not, thepeople have authority over these matters also. Moreover, when theymake proposals, the people not only are allowed to hear the officials' resolutions, but have the authority to decide them; and anyone who wishes 10may speak against the proposals being made. This does not exist in theother constitutions. On the other hand, it is oligarchic that the boards of five, which haveauthority over many important matters, elect themselves, and elect tothe office of one-hundred, 1 40 which is the most important office. More-over, it is also oligarchic that they hold office longer than the others (for 15they rule before taking office and after they have left it). But we must re-gard it as aristocratic that they are neither paid nor chosen by lot, or anything else of that sort. And also that all legal cases are decided by theboards of five, and not, as in Sparta, some by some and others by others.141 20 But the major deviation of the organization of the Carthaginians awayfrom aristocracy and toward oligarchy is their sharing a view that is heldalso by the many: that rulers should be chosen not solely on the basis oftheir merit but also on the basis of their wealth, since poor people can-not afford the leisure necessary to rule well. Hence, if indeed it is oli- 25garchic to choose rulers on the basis of their wealth, and aristocratic tochoose them on the basis of their merit, then this organization, accord-ing to which the Carthaginians have organized matters relating to theconstitution, will be a third sort. For they elect to office with an eye toboth qualities, especially in the case of the most important officials, thekings and the generals. 30 But this deviation from aristocracy should be regarded as an error onthe part of their legislator. For one of the most important things is to seeto it from the outset that the best people are able to be at leisure and donothing unseemly, not only when in office but in private life. But even ifone must look to wealth too, in order to ensure leisure, still it is bad that 35 the most important offices, those of king and general, should be for sale. For this law gives more esteem to wealth than to virtue, and makes the entire city-state love money. For whatever those in authority esteem, the 40 opinion of the other citizens too inevitably follows theirs. Hence when virtue is not esteemed more than everything else, the constitution can-1 27Jh not be securely governed as an aristocracy. It is reasonable to expect too that those who have bought office will become accustomed to making a profit from it, when they rule by having spent money. For if a poor but decent person will want to profit from office, it would certainly be odd if a worse one, who has already spent money, will not want to. Hence those S who are able to rule best should rule.142 And even if the legislator ne glected the wealth of the decent people, he had better look to their leisure, at least while they are ruling. It would also seem to be bad to allow the same person to hold several offices, a thing held in high esteem among the Carthaginians. For one 10 task is best performed by one person. The legislator should see to it that this happens, and not require the same person to play the flute and make shoes. So, where the city-state is not small, it is more political, 143 and more democratic, if more people participate in the offices. For it is more widely shared, as we said, and each of the offices144 is better carried out IS and more quickly. (This is clear in the case of military and naval affairs, since in both of them ruling and being ruled extend through practically speaking everyone.) But though their constitution is oligarchic, they are very good at es caping faction by from time to time sending some part of the people out to the city-states to get rich.145 In this way they effect a cure, and give 20 stability to their constitution. But this is the result of luck, whereas they ought to be free of faction thanks to their legislator. As things stand, however, if some misfortune occurs and the multitude of those who are ruled revolt, the laws provide no remedy for restoring peace. This, then, is the way things stand with the Spartan, Cretan, and 2S Carthaginian constitutions, which are rightly held in high esteem. Chapter 1 2Some of those who have had something to say about a constitution tookno part in political actions, but always lived privately. About them prettymuch everything worth saying has been said. Others became legislators, 30engaging in politics themselves, some in their own city-states, others inforeign ones as well. Some of these men crafted LAWS only, whereas oth-ers, such as Lycurgus and Solon, crafted a CONSTITUTION too, for theyestablished both laws and constitutions. We have already discussed that of the Spartans.146 As for Solon, some 35think he was an excellent legislator because: he abolished an oligarchywhich had become too unmixed; he put an end to the slavery of the com-mon people; 147 and he established the ancestral democracy, by mixingthe constitution well. For they think the council of the Areopagus is oligarchic;148 the election of officials aristocratic; and the courts democra- 40tic. But it seems that the first two, the council and the election of offi- 1274acials, existed already, and Solon did not abolish them. On the otherhand, by making law courts open to all, he did set up the democracy.That, indeed, is why some people criticize him. They say that when hegave law courts selected by lot authority over all legal cases, he destroyedthe other things. For when this element became powerful, those who 5flattered the common people like a tyrant changed the constitution intothe democracy we have now: Ephialtes and Pericles149 curtailed thepower of the Areopagus, and Pericles introduced payment for jurors.150In this way, each popular leader enhanced the power of the people andled them on to the present democracy. 10 It seems that this did not come about through Solon's deliberatechoice, however, but rather more by accident. For the common peoplewere the cause of Athens's naval supremacy during the Persian wars. As a result, they became arrogant, and chose inferior people as their popu lar leaders when decent people opposed their policies. 151 Solon, at any15 rate, seems to have given the people only the minimum power necessary, that of electing and INSPECTING officials (since if they did not even have authority in these, the people would have been enslaved and hostile). 152 But he drew all the officials from among the notable and rich: the pen-20 takosiomedimnoi, the zeugitai, and the third class, the so-called hippeis. But the fourth class, the thetes, did not participate in any office. 153 Zaleucus became a legislator for the Epizephyrian Locrians, and Charondas of Catana for his own citizens and for the other Chalcidian city-states in Italy and Sicily. (Some people actually try to establish con-25 nections by telling the following story: Onomacritus was the first person to become an expert in legislation. Though a Locrian, he trained in Crete while on a visit connected with his craft of divination. Thales was his companion; Lycurgus and Zaleucus were pupils of Thales; and Charondas was a pupil of Zaleucus. But when they say these things, they30 speak without regard to chronology.)154 There was also Philolaus of Corinth, 155 a member of the Bacchiad family, who became a legislator for the Thebans. He became the lover of Diodes, the victor in the Olympic games. Diodes left Corinth in disgust35 at the lust his mother, Alcyone, had for him, and went off to Thebes, where they both ended their days. Even now people point out their tombs, which are in full view of one another, although one is visible from the land of the Corinthians and the other is not. The story goesthat they arranged to be buried in just this way, Diodes having the landof Corinth not be visible from his burial mound because of his loathingfor what he had experienced there, and Philolaus so that it might be vis- 40ible from his. It was for this sort of reason, then, that the two of themsettled among the Thebans. But Philolaus became legislator both on 1274hother matters and about procreation (which they call "the laws of adop-tion"). This is peculiar to his legislation, its purpose being to keep thenumber of estates fixed. 5 There is nothing peculiar to Charondas except lawsuits for perjury; hewas the first to introduce denunciations for perjury. But in the precisionof his laws, he is more polished than even present-day legislators. Thefeature peculiar to Phaleas is the leveling of property. And to Plato: thesharing of women, children, and property; 156 messes for women; the law 10about drinking, that the sober should preside at drinking parties;157 andthe one requiring ambidextrous training for soldiers, on the grounds thatone of the hands should not be useful and the other useless. There are also Draco's laws, 158 but Draco established his laws for anexisting constitution. There is nothing peculiar to his laws worth talking I5about, except the severity of the punishments. Pittacus too crafted laws,but not a constitution. A law peculiar to him requires a drunken personto be punished more severely for an offense than a sober one. For since 20more drunken people than sober ones commit acts of arrogance, Pitta-cus paid attention not to the greater indulgence one should show tothose who are drunk, but to what is beneficial.159 Androdamus of Rhe- Chapter 1When investigating constitutions, and what each is and is like, prettywell the first subject of investigation concerns a city-state, to see whatthe city-state is. For as things stand now, there are disputes about this.Some people say, for example, that a city-state performed a certain ac-tion, whereas others say that it was not the city-state that performed theaction, but rather the oligarchy or the tyrant did. We see, too, that the 35entire occupation of statesmen and legislators concerns city-states.Moreover, a constitution is itself a certain organization of the inhabitants of a city-state. But since a city-state is a composite, one that is awhole and, like any other whole, constituted out of many parts,1 it isclear that we must first inquire into citizens. For a city-state is some sort 40of multitude of citizens. Hence we must investigate who should be calleda citizen, and who the citizen is. For there is often dispute about the cit- 1275•izen as well, since not everyone agrees that the same person is a citizen.For the sort of person who is a citizen in a democracy is often not one inan oligarchy. We should leave aside those who acquire the title of citizen in someexceptional way; for example, those who are made citizens.2 Nor is a cit- 5izen a citizen through residing in a place, for resident aliens and slavesshare the dwelling place with him. Again, those who participate in thejustice system, to the extent of prosecuting others in the courts or beingjudged there themselves, are not citizens: parties to treaties can also dothat (though in fact in many places the participation of resident aliens in 10the justice system is not even complete, but they need a sponsor, so thattheir participation in this sort of communal relationship is in a way 1 . Composites are always analyzed into their parts ( 1 252' 1 7-20). A whole (holon) is a composite that is a substance possessing an essence or nature (Metaph. 104 l b l l-33). See Introduction xxvii-xxxv.2. Presumably, honorary citizens and the like. 65 66 Politics III incomplete).3 Like minors who are too young to be enrolled in the citi zen lists or old people who have been excused from their civic duties,4I5 they must be said to be citizens of a sort, but not UNQUALIFIED citizens. Instead, a qualification must be added, such as "incomplete" or "super annuated" or something else like that (it does not matter what, since what we are saying is clear). For we are looking for the unqualified citi zen, the one whose claim to citizenship has no defect of this sort that20 needs to be rectified (for one can raise and solve similar problems about those who have been disenfranchised or exiled). The unqualified citizen is defined by nothing else so much as by his participation in judgment and office. But some offices are of limited tenure, so they cannot be held twice by the same person at all, or can be25 held again only after a definite period. Another person, however, holds office indefinitely, such as the juror or assemblyman . Now someone might say that the latter sort are not officials at all, and do not, because of this, 5 participate in any office as such. Yet surely it would be absurd to deprive of office those who have the most authority.6 But let this make no difference, since the argument is only about a word. For what a juror30 and an assemblyman have in common lacks a name that one should call them both. For the sake of definition, let it be indefinite office. We take it, then, that those who participate in office in this way are citizens. And this is pretty much the definition that would best fit all those called citi zens. We must not forget, however, that in case of things in which what un-35 derlies differs in kind (one coming first, another second, and so on), a common element either is not present at all, insofar as these things are such, or only in some attenuated way.7 But we see that constitutions dif- 3. Resident aliens in Athens had to have a citizen "sponsor" (prostates), but they could represent themselves in legal proceedings. Elsewhere, it seems, their sponsor had to do this for them. 4. At the age of 18, young Athenians were enrolled in the citizen list kept by the leader of the deme. Older men were released from having to serve in the mili tary, and perhaps also from jury duty and attendance at meetings of the as sembly. 5 . Because of being jurors, assemblymen, and the like. 6. As jurors and members of the assembly do in certain sorts of democracies ( 1 27Jb4 1-1274" l l ) . 7 . Exercise is healthy, a complexion i s healthy, and a certain physical condition is healthy. Each of them underlies the property of being healthy, or is the sub ject of which that property is predicated. But exercise is healthy because it Chapter 2 67 fer in kind from one another, and that some are posterior and othersprior; for mistaken or deviant constitutions are necessarily posterior tothose that are not mistaken.8 (What we mean by "deviant" will be appar- 1275hent later.)9 Consequently, the citizen in each constitution must also bedifferent. That is precisely why the citizen that we defined is above all a citizenin a democracy, and may possibly be one in other constitutions, but notnecessarily. For some constitutions have no "the people" or assemblies 5they legally recognize, but only specially summoned councils and judi-cial cases decided by different bodies. In Sparta, for example, some casesconcerning contracts are tried by one overseer, others by another,whereas cases of homicide are judged by the senate, and other cases by 10perhaps some other official. It is the same way in Carthage, since therecertain officials decide all cases.10 None the less, our definition of a citi-zen admits of correction. For in the other constitutions, 11 it is not theholder of indefinite office who is assemblyman and juror, but someonewhose office is definite. For it is either to some or to all of the latter thatdeliberation and judgment either about some or about all matters is as- 15signed. It is evident from this who the citizen is. For we can now say thatsomeone who is eligible to participate in deliberative and judicial officeis a citizen in this city-state, and that a city-state, simply speaking, is amultitude of such people, adequate for life's self-sufficiency. 20 Chapter 2But the definition that gets used in practice is that a citizen is someonewho comes from citizens on both sides, and not on one only-for exam- pie, that of father or of mother. Some people look for more here too, going back, for example, two or three or more generations of ancestors. But quick political definitions of this sort lead some people to raise the 25 problem of how these third- or fourth-generation ancestors will be citi zens. So Gorgias of Leontini, half perhaps to raise a real problem and half ironically, said that just as mortars are made by mortar makers, so Lariseans too are made by craftsmen, since some of them are Larisean 30 makersY But this is easy: if the ancestors participated in the constitu tion in the way that accords with the definition just given, 13 they were citizens. For "what comes from a citizen father and mother" cannot be applied to even the first inhabitants or founders. But perhaps a bigger problem is raised by the next case: those who come to participate in a constitution after a revolution, such as the citi- 35 zens created in Athens by Cleisthenes14 after the expulsion of the tyrants (for he enrolled many foreigners and alien slaves in the tribes). But the dispute in relation to these people is not which of them is a citizen, but whether they are rightly or wrongly so. And yet a further question might be raised as to whether one who is not rightly a citizen is a citizen at all,1276• as "wrong" and "false" seem to have the same force. But since we see that there are also some people holding office wrongly, whom we say are holding it though not rightly, and since a citizen is defined as someone who holds a sort of office (for someone who participates in such office is 5 a citizen, as we said), it is clear that these people too must be admitted to be citizens. Chapter 3 The problem of rightly and not rightly is connected to the dispute we mentioned earlier. 15 For some people raise a problem about how to de termine whether a city-state has or has not performed an action, for ex ample, when an oligarchy or a tyranny is replaced by a democracy. At 12. Gorgias was a famous orator and sophist (c. 483-376) who visited Athens in 427. In Larissa, and other place, the word demiourgos, which means "crafts man," is also the title of a certain sort of public official. A Larisean is both a citizen of Larissa and a kind of pot made there. 1 3 . At 1 275b17- 2 1 . 1 4 . Cleisthenes was a sixth century Athenian statesman whose wide-ranging re form of the Athenian constitution was as significant and abiding as that of Solon. 1 5. At 1 274b34-36. Chapter 3 69 these times, some do not want to honor treaties, since it was not the city- 10state but its tyrant who entered into them, nor to do many other thingsof the same sort, on the grounds that some constitutions exist by forceand not for the common benefit.16 Accordingly, if indeed some democ-rats also rule in that way, it must be conceded that the acts of their constitution are the city-state's in just the same way as are those of the oli-garchy or the tyranny. 15 There seems to be a close relation between this argument and theproblem of when we ought to say that a city-state is the same, or not thesame but a different one.17 The most superficial way to investigate thisproblem is by looking to location and people. For a city-state's location 20and people can be split, and some can live in one place and some in another. Hence the problem must be regarded as a rather tame one. For thefact that a thing is said to be a city-state in many different ways makesthe investigation of such problems pretty easy.1 8 Things are similar if one asks when people inhabiting the same loca-tion should be considered a single city-state. Certainly not because it is 25enclosed by walls, since a single wall could be built around the Peloponnese. Perhaps Babylon is like that, or anywhere else that has the dimensions of a nation rather than a city-state. At any rate, they say that whenBabylon was captured, a part of the city-state was unaware of it for threedays. 19 But it will be useful to investigate this problem in another con- 30text. For the size of the city-state, both as regards numbers and as regards whether it is beneficial for it to be one or10 several, should not beoverlooked by the statesman. But when the same people are inhabiting the same place, is the city-state to be called the same as long as the inhabitants remain of the samestock, even though all the time some are dying and others being born 35(just as we are accustomed to say that rivers and springs remain the same, even though all the time some water is flowing out and some flow ing in)? Or are we to say that human beings can remain the same for this 40 sort of reason, but the city-state is different? For if indeed a city-state is1276h a sort of community, a community of citizens sharing a constitution, then, when the constitution changes its form and becomes different, it would seem that the city-state too cannot remain the same. At any rate, a chorus that is at one time in a comedy and at another in a tragedy is said S to be two different choruses, even though the human beings in it are often the same. Similarly, with any other community or composite: we say it is different if the form of the composite is different. 21 For example, we call a melody composed of the same notes a different melody when it is played in the Dorian harmony than when it is played in the Phrygian. 10 But if this is so, it is evident that we must look to the constitution above all when saying that the city-state is the same. But the name to call it may be different or the same one whether its inhabitants are the same or completely different people.22 But whether it is just to honor or not to honor agreements when a 1S city-state changes to a different constitution requires another argument. Chapter 4 The next thing to investigate after what we have j ust discussed is whether the virtue of a good man and of a good citizen should be re garded as the same, or not the same. But surely if we should indeed in vestigate this, the virtue of a citizen must first be grasped in some sort of outline. Just as a sailor is one of a number of members of a community, so, we 20 say, is a citizen. And though sailors differ in their capacities (for one is an oarsman, another a captain, another a lookout, and others have other sorts of titles), it is clear both that the most exact account of the virtue of each sort of sailor will be peculiar to him, and similarly that there will also b e some common account that fits them all. For the safety o f the 25voyage is a task of all of them, since this is what each of the sailors strivesfor. In the same way, then, the citizens too, even though they are dissim-ilar, have the safety of the community as their task. But the communityis the constitution. Hence the virtue of a citizen must be suited to hisconstitution. Consequently, if indeed there are several kinds of constitu- 30tion, it is clear that there cannot be a single virtue that is the virtue-thecomplete virtue--of a good citizen. But the good man, we say, does express a single virtue: the complete one. Evidently, then, it is possible forsomeone to be a good citizen without having acquired the virtue ex-pressed by a good man. 35 By going through problems in a different way, the same argument canbe made about the best constitution. If it is impossible for a city-state toconsist entirely of good people, and if each must at least perform hisown task well, and this requires virtue, and if it is impossible for all thecitizens to be similar, then the virtue of a citizen and that of a good man 40cannot be a single virtue. For that of the good citizen must be had by all 1277•(since this is necessary if the city-state is to be best), but the virtue of agood man cannot be had by all, unless all the citizens of a good city-stateare necessarily good men. Again, since a city-state consists of dissimilarelements (I mean that just as an animal consists in the first instance of 5soul and body, a soul of reason and desire, a household of man andwoman, and property of master and slave, so a city-state, too, consists ofall these, and of other dissimilar kinds in addition), then the citizenscannot all have one virtue, any more than can the leader of a chorus and 10one of its ordinary members. 23 It is evident from these things, therefore, that the virtue of a man andof a citizen cannot be unqualifiedly the same. But will there, then, be anyone whose virtue is the same both as agood citizen and as a good man? We say, indeed, that an excellent ruler isgood and possesses practical wisdom, but that a citizen24 need not pos- 15sess practical wisdom. Some say, too, that the education of a ruler isdifferent right from the beginning, as is evident, indeed, from the sonsof kings being educated in horsemanship and warfare, and from Euripi- 23. The examples given are all of natural ruler-subject pairs. Aristotle has al ready shown in 1 . 1 3 that the virtues of natural rulers and subjects are differ ent.24. Reading politen with Ross and Dreizehnter. Alternatively (mss.): "but that a statesman (politikon) need not be practically-wise." 72 Politics III des saying "No subtleties for me . . . but what the city-state needs,"25 (since this implies that rulers should get a special sort of education). But 20 if the virtue of a good ruler is the same as that of a good man, and if the man who is ruled is also a citizen, then the virtue of a citizen would not be unqualifiedly the same as the virtue of a man (though that of a certain sort of citizen would be), since the virtue of a ruler and that of a citizen would not be the same. Perhaps this is why Jason said that he went hun gry except when he was a tyrant.26 He meant that he did not know how to be a private individual. 25 Yet the capacity to rule and be ruled is at any rate praised, and being able to do both well is held to be the virtue of a citizen. 27 So if we take a good man's virtue to be that of a ruler, but a citizen's to consist in both, then the two virtues would not be equally praiseworthy. Since, then, both these views are sometimes accepted,28 that ruler and 30 ruled should learn different things and not the same ones, and that a cit izen should know and share in both, we may see what follows from that. For there is rule by a master, by which we mean the kind concerned with the necessities. The ruler does not need to know how to produce these, but rather how to make use of those who do. In fact, the former is 35 servile. (By "the former" I mean actually knowing how to perform the actions of a servant.) But there are several kinds of slaves, we say, since their tasks vary. One part consists of those tasks performed by manual laborers. As their very name implies, these are people who work with1 27Jb their hands. VULGAR CRAFTSMEN are included among them. That is why among some peoples in the distant past craftsmen did not participate in office until extreme democracy arose. Accordingly, the tasks performed by people ruled in this way should not be learned by a good person, nor by29 a statesman, nor by a good citizen, except perhaps to satisfy some 5 personal need of his own (for then it is no longer a case of one person becoming master and the other slave).30 But there is also a kind of rule exercised over those who are similar in birth and free. This we call "political" rule. A ruler must learn it by 25. From the lost play Aeolus (Nauck 367 fr. 16. 2-3). King Aeolus is apparently speaking about the education his sons are to receive. 26. Jason was tyrant of Pherae in Thessaly (c. 380-370). 27. See Plato, Laws 643e-644a. 28. Reading dokei amphO hetera with Dreizehnter. 29. Reading oude ton. 30. See 1 34 JbJ0- 1 5 . Chapter 5 73 Chapter 5But one of the problems about the citizen still remains. For is the citizenreally someone who is permitted to participate in office, or should vul-gar craftsmen also be regarded as citizens? If, indeed, those who do not 35share in office should be regarded as citizens, then this sort of virtue34cannot belong to every citizen (for these will then be citizens). On the other hand, if none of this sort is a citizen, in what category should they each be put?-for they are neither resident aliens nor foreigners. Or shall we say that from this argument, at least, nothing absurd fol-1278• lows, since neither slaves nor freed slaves are in the aforementioned classes either? For the truth is that not everyone without whom there would not be a city-state is to be regarded as a citizen. For children are not citizens in the way men are. The latter are unqualified citizens, whereas the former are only citizens given certain assumptions: they are S citizens, but incomplete ones. Vulgar craftsmen were slaves or foreigners in some places long ago, which is why most of them still are even today. The best city-state will not confer citizenship on vulgar craftsmen, how ever; but if they too are citizens, then what we have characterized as a citizen's virtue cannot be ascribed to everyone, or even to all free people, 10 but only to those who are freed from necessary tasks. Those who per form necessary tasks for an individual are slaves; those who perform them for the community are vulgar craftsmen and hired laborers. If we carry our investigation a bit further, it will be evident how things stand in these cases. In fact, it is clear from what we have already said.35 For since there are several constitutions, there must also be sev- 1S eral kinds of citizens, particularly of citizens who are being ruled. Hence in some constitutions vulgar craftsmen and hired laborers must be citi zens, whereas in others it is impossible-for example, in any so-called aristocracy in which offices are awarded on the basis of virtue and merit. 20 For it is impossible to engage in virtuous pursuits while living the life of a vulgar craftsman or a hired laborer. 36 In oligarchies, however, while hired laborers could not be citizens (since participation in office is based on high property assessments), vulgar craftsmen could be, since in fact most craftsmen become rich (though in Thebes there used to be a law that anyone who had not kept 25 away from the market for ten years could not participate in office)Y In many constitutions, however, the law even goes so far as to admit some foreigners as citizens; for in some democracies the descendant of a citizen mother is a citizen, and in many places the same holds of bas tards too. Nevertheless, since it is because of a shortage of legitimate cit- 30 izens that they make such people citizens (for it is because of underpop- 35. At III. I . 36. Explained somewhat at 1 260'38-h l , 1 337h4-21 . 37. Aristotle thinks that oligarchies should impose restrictions of this sort on vulgar craftsmen (1321'26-29). Chapter 6 75 ulation that they employ laws in this way), when they are well suppliedwith a crowd of them, they gradually disqualify, first, those who have aslave as father or mother, then those with citizen mothers, until finallythey make citizens only of those who come from citizens on both sides. It is evident from these considerations, therefore, that there are sev-eral kinds of citizens, and that the one who participates in the offices is 35particularly said to be a citizen, as Homer too implied when he wrote:"like some disenfranchised alien."38 For people who do not participate inthe offices are like resident aliens. When this is concealed, it is for thesake of deceiving coinhabitants.39 As to whether the virtue expressed by a good man is to be regarded as 40the same as that of an excellent citizen or as different, it is clear from 1278"what has been said that in one sort of city-state both are the same per-son, while in another they are different. And that person is not just any-one, but the statesman, who has authority or is capable of exercising au-thority in the supervision of communal matters, either by himself orwith others. 5 Chapter 6Since these issues have been determined, the next thing to investigate iswhether we should suppose that there is just one kind of constitution orseveral, and, if there are several, what they are, how many they are, andhow they differ. A constitution is an organization of a city-state's various offices but,particularly, of the one that has authority over everything. For the governing class has authority in every city-state, and the governing class is 10the constitution.'�{) I mean, for example, that in democratic city-statesthe people have authority, whereas in oligarchic ones, by contrast, thefew have it, and we also say the constitutions of these are different. Andwe shall give the same account of the other constitutions as well. First, then, we must set down what it is that a city-state is constituted 15for, and how many kinds of rule deal with human beings and communallife. In our first discussions, indeed, where conclusions were reached 38. Iliad IX.648, XVI. 59. Achilles is complaining that this is how Agamemnon is treating him.39. See 1264'19-22.40. Aristotle is relying on his doctrine that "a city-state and every other com posite system is most of all the part of it that has the most authority" (NE 1 168h31-33). 76 Politics III about household management and rule by a master, it was also said that a human being is by nature a political animal.41 That is why, even when 20 they do not need one another's help, people no less desire to live to gether, although it is also true that the common benefit brings them to gether, to the extent that it contributes some part of living well to each. This above all is the end, then, whether of everyone in common or of each separatelyY But human beings also join together and maintain po litical communities for the sake of life by itself. For there is perhaps 25 some share of what is NOBLE in life alone, as long as it is not too over burdened with the hardships of life. In any case, it is clear that most human beings are willing to endure much hardship in order to cling to life, as if it had a sort of joy inherent in it and a natural sweetness. But surely it is also easy to distinguish at least the kinds of rule people 30 talk about, since we too often discuss them in our own external works.43 For rule by a master, although in truth the same thing is beneficial for both natural masters and natural slaves, is nevertheless rule exercised 35 for the sake of the master's own benefit, and only coincidentally for that of the slave. 44 For rule by a master cannot be preserved if the slave is de stroyed. But rule over children, wife, and the household generally, which we call household management, is either for the sake of the ruled or for the sake of something common to both. Essentially, it is for the 40 sake of the ruled, as we see medicine, physical training, and the other1279" crafts to be, but coincidentally it might be for the sake of the rulers as well. For nothing prevents the trainer from sometimes being one of the athletes he is training, just as the captain of a ship is always one of the 5 sailors. Thus a trainer or a captain looks to the good of those he rules, but when he becomes one of them himself, he shares coincidentally in the benefit. For the captain is a sailor, and the trainer, though still a trainer, becomes one of the trained. Hence, in the case of political office too, where it has been established on the basis of equality and similarity among the citizens, they think it 10 right to take turns at ruling. In the past, as is natural, they thought it right to perform public service when their turn came, and then to havesomeone look to their good, just as they had earlier looked to his benefitwhen they were in office. Nowadays, however, because of the profits tobe had from public funds and from office, people want to be in officecontinuously, as if they were sick and would be cured by being always inoffice. At any rate, perhaps the latter would pursue office in that way. 15 It is evident, then, that those constitutions that look to the commonbenefit turn out, according to what is unqualifiedly just, to be correct,whereas those which look only to the benefit of the rulers are mistakenand are deviations from the correct constitutions. For they are like rule 20by a master, whereas a city-state is a community of free people. Chapter 7Now that these matters have been determined, we must next investigatehow many kinds of constitutions there are and what they are,45 startingfirst with the correct constitutions. For once they have been defined, thedeviant ones will also be made evident. Since "constitution" and "governing class" signify the same thing,46 25and the governing class is the authoritative element in any city-state, andthe authoritative element must be either one person, or few, or many,then whenever the one, the few, or the many rule for the common bene-fit, these constitutions must be correct. But if they aim at the privatebenefit, whether of the one or the few or the MULTITUDE, they are devi- 30ations (for either the participants47 should not be called citizens, or theyshould share in the benefits). A monarchy that looks to the common benefit we customarily call akingship; and rule by a few but more than one, an aristocracy (either be-cause the best people rule, or because they rule with a view to what is 35best for the city-state and those who share in it). But when the multitudegoverns for the common benefit, it is called by the name common to allCONSTITUTIONS, namely, politeia. Moreover, this happens reasonably.For while it is possible for one or a few to be outstandingly virtuous, it isdifficult for a larger number to be accomplished in every virtue, but it 40can be so in military virtue in particular. That is precisely why the class 12 7CJ' of defensive soldiers, the ones who possess the weapons, has the most authority in this constitution.48 Deviations from these are tyranny from kingship, oligarchy from aris-5 tocracy, and democracy from polity. For tyranny is rule by one person for the benefit of the monarch, oligarchy is for the benefit of the rich, and democracy is for the benefit of the poor. But none is for their com mon profit. Chapter 8I0 We should say a little more about what each of these constitutions is. For certain problems arise, and when one is carrying out any investigation in a philosophical manner, and not merely with a practical purpose in view, it is appropriate not to overlook or omit anything, but to make the truthI5 about each clear. A tyranny, as we said, exists when a monarchy rules the political com munity like a master; in an oligarchy those in authority in the constitu tion are the ones who have property. A democracy is the opposite; those who do not possess much property, and are poor, are in authority. The20 first problem concerns this definition. Suppose that the MAJORITY were rich and had authority in the city-state; yet there is a democracy when ever the majority has authority. Similarly, to take the opposite case, sup pose the poor were fewer in number than the rich, but were stronger and had authority in the constitution; yet when a small group has authority it is said to be an oligarchy. It would seem, then, that these constitutions25 have not been well defined. But even if one combines being few with being rich in one case, and being a majority with being poor in the other, and describes the constitutions accordingly (oligarchy as that in which the rich are few in number and hold the offices, and democracy as that in30 which the poor are many and hold them), another problem arises. For what are we to call the constitutions we just described, those where the rich are a majority and the poor a minority, but each has authority in its Chapter 9The first thing one must grasp, however, is what people say the definingmarks of oligarchy and democracy are, and what oligarchic and democ-ratic justice are. For [1] they all grasp justice of a sort,51 but they go onlyto a certain point and do not discuss the whole of what is just in the mostauthoritative sense. For example, justice seems to be EQUALITY, and it is, 10but not for everyone, only fo r equals. Justice also seems to be inequality,since indeed it is, but not for everyone, only for unequalsY They disre-gard the "for whom," however, and judge badly. The reason is that thejudgment concerns themselves, and most people are pretty poor judgesabout what is their own.53 15 So since what is just is just for certain people, and consists in dividingthings and people in the same way (as we said earlier in the Ethics),54they agree about what constitutes equality in the thing but disagreeabout it in the people. This is largely because of what was just mentioned, that they judge badly about what concerns themselves, but also 20 I t i s evident that this is right. For even if [5] one were to bring theirterritories together into one, so that the city-state of the Megarians wasattached to that of the Corinthians by walls, it still would not be a singlecity-state. Nor would it be so if their citizens intermarried, even though ISthis is one of the forms of community characteristic of city-states. Similarly, if there were some who lived separately, yet not so separately as toshare nothing in common, and had laws against wronging one another intheir business transactions (for example, if one were a carpenter, anothera farmer, another a cobbler, another something else of that sort, and 20their number were ten thousand), yet they shared nothing else in common besides such things as exchange and alliance-not even in this casewould there be a city-state. What, then, is the reason for this? Surely, it is not because of the nonproximate nature of their community. For suppose they joined togetherwhile continuing to share in that way, but each nevertheless treated his 25own household like a city-state, and the others like a defensive allianceformed to provide aid against wrongdoers only. Even then this stillwould not be thought a city-state by those who make a precise study ofsuch things, if indeed they continued to associate with one another inthe same manner when together as when separated. Evidently, then, a city-state is not [5] a sharing of a common location,and does not exist for the purpose of [4] preventing mutual wrongdoing 30and [3] exchanging goods. Rather, while these must be present if indeedthere is to be a city-state, when all of them are present there is still notyet a city-state, but [2] only when households and families live well as acommunity whose end is a complete and self-sufficient life. But this willnot be possible unless they do inhabit one and the same location and 35practice intermarriage. That is why marriage connections arose in citystates, as well as brotherhoods, religious sacrifices, and the LEISUREDPURSUITS of living together. For things of this sort are the result offriendship, since the deliberative choice of living together constitutesfriendship. The end of the city-state is living well, then, but these otherthings are for the sake of the end . And a city-state is the community offamilies and villages in a complete and self-sufficient life, which we say 40is living happily and NOBLY. 128]• So political communities must be taken to exist for the sake of nobleactions, and not for the sake of living together. Hence those who contribute the most to this sort of community have a larger share in the citystate than those who are equal or superior in freedom or family but infe 5rior in political virtue, and those who surpass in wealth but aresurpassed in virtue. 82 Politics III It is evident from what has been said, then, that [ 1 ] those who dispute10 about constitutions all speak about a part of justice. Chapter 1 0 There is a problem as to what part of the state is to have authority, since surely it is either the multitude, or the rich, or decent people, or the one who is best of all, or a tyrant. But all of these apparently involve difficul ties. How so? If the poor, because they are the greater number, divide up15 the property of the rich, isn't that unjust? "No, by Zeus, it isn't, since it seemed just to those in authority." What, then, should we call extreme in justice? Again, if the majority, having seized everything, should divide up the property of the minority, they are evidently destroying the city-state. But virtue certainly does not ruin what has it, nor is justice something20 capable of destroying a city-state. So it is clear, then, that this law57 can not be just. Besides, everything done by a tyrant must be just as well; for he, being stronger, uses force, just as the multitude do against the rich.25 But is it just, then, for the rich minority to rule? If they too act in the same way, plundering and confiscating the property of the multitude, and this is just, then the other case is as well. It is evident, therefore, that all these things are bad and unjust. But should decent people rule and have authority over everything? In that case, everyone else must be deprived of honors by being excluded from30 political office. For offices are positions of honor, we say, and when the same people always rule, the rest must necessarily be deprived of honors. But is it better that the one who is best should rule? But this is even more oligarchic, since those deprived of honors are more numerous. Perhaps, however, someone might say that it is a bad thing in general35 for a human being to have authority and not the LAW, since he at any rate has the passions that beset the soul. But if law may be oligarchic or de mocratic, what difference will that make to our problems? For the things we have just described will happen just the same. Chapter 1 1 As for the other cases, we may let them be the topic of a different dis cussion. 58 But the view that the multitude rather than the few best peo- 59. A panel chosen by lot selected the three best comedies and tragedies at the annual theater festivals in Athens. 84 Politics III legislators arrange to have them elect and INSPECT officials, but prevent them from holding office alone. 6° For when they all come together their 35 perception is adequate, and, when mixed with their betters, they benefit their states, just as a mixture of roughage and pure food-concentrate is more useful than a little of the latter by itself. 61 Taken individually, how ever, each of them is an imperfect j udge. But this organization of the constitution raises problems itself. In the first place, it might be held that the same person is able to j udge whether 40 or not someone has treated a patient correctly, and to treat patients and cure them of disease when it is present-namely, the doctor. The same would also seem to hold in other areas of experience and other crafts.I282• Therefore, j ust as a doctor should be inspected by doctors, so others should also be inspected by their peers. But "doctor" applies to the or dinary practitioner of the craft, to a master craftsman, and thirdly, to someone with a general EDUCATION in the craft. For there are people of 5 this third sort in (practically speaking) all the crafts. And we assign the task of judging to generally educated people no less than to experts. Moreover, it might be held that election is the same way, since choos ing correctly is also a task for experts: choosing a geometer is a task for expert geometers, for example, and choosing a ship's captain is a task for IO expert captains. For even if some laymen are also involved in the choice of candidates in the case of some tasks and crafts, at least they do not play a larger role than the experts. According to this argument, then, the multitude should not be given authority over the election or inspection of officials. But perhaps not all of these things are correctly stated, both because I5 according to the earlier argument the multitude may not be too servile, since each may be a worse judge than those who know, but a better or no worse one when they all come together; and because there are some crafts in which the maker might not be either the only or the best judge-the ones where those who do not possess the craft nevertheless have knowledge of its products. For example, the maker of a house is not 20 the only one who has some knowledge about it; the one who uses it is an even better j udge (and the one who uses is the household manager). A captain, too, judges a rudder better than a carpenter, and a guest, rather than the cook, a feast. 62 Chapter 1 2Since in every science and craft the end is a good, the greatest and bestgood is the end of the science or craft that has the most authority of all 15 63. The one raised at 1281' 1 1 of who should have authority in the city-state.64. See 1281'34-39. 86 Politics III of them, and this is the science of statesmanship. But the political good is justice, and justice is the common benefit. Now everyone holds that what is just is some sort of equality, and up to a point, at least, all agree with what has been determined in those philosophical works of ours 20 dealing with ethical issues.65 For justice is something to someone, and they say it should be something equal to those who are equal. But equal ity in what and inequality in what, should not be overlooked. For this in volves a problem and political philosophy. Someone might say, perhaps, that offices should be unequally distrib uted on the basis of superiority in any good whatsoever, provided the people did not differ in their remaining qualities but were exactly simi- 25 lar, since where people differ, so does what is just and what accords with merit. But if this is true, then those who are superior in complexion, or height, or any other good whatsoever will get more of the things with which political justice is concerned. And isn't that plainly false? The 30 matter is evident in the various sciences and capacities. For among flute players equally proficient in the craft, those who are of better birth do not get more or better flutes, since they will not play the flute any better if they do. It is the superior performers who should also get the superior 35 instruments. If what has been said is somehow not clear, it will become so if we take it still further. Suppose someone is superior in flute play ing, but is very inferior in birth or beauty; then, even if each of these (I mean birth and beauty) is a greater good than flute playing, and is pro- 40 portionately more superior to flute playing than he is superior in flute playing, he should still get the outstanding flutes. For the superiority in1283" wealth and birth would have to contribute to the performance, but in fact they contribute nothing to it. Besides, according to this argument every good would have to be commensurable with every other. For if being a certain height counted S more,66 height in general would be in competition with both wealth and freedom. So if one person is more outstanding in height than another is in virtue, and if height in general is of more weight than virtue, then all goods would be commensurable. For if a certain amount of size is better than a certain amount of virtue, it is clear that some amount of the one is equal to some amount of the other. Since this is impossible, it is clear 10 that in political matters, too, it is reasonable not to dispute over political office on the basis of just any sort of inequality. For if some are slow run- ners and others fast, this is no reason for the latter to have more and theformer less: it is in athletic competitions that such a difference winshonor. The dispute must be based on the things from which a city-stateis constituted. Hence the well-born, the free, and the rich reasonably lay 15claim to office. For there must be both free people and those with assessed property, since a city-state cannot consist entirely of poor people,any more than of slaves. But if these things are needed in a city-state, sotoo, it is clear, are justice and political67 virtue, since a city-state cannotbe managed without these. Rather, without the former a city-state can- 20not exist, and without the latter it cannot be well managed. Chapter 1 3As regards the existence of a city-state, all, or at any rate some, of thesewould seem to have a correct claim in the dispute. But as regards thegood life, education and virtue would seem to have the most just claimof all in the dispute, as was also said earlier.68 But since those equal in 25one thing only should not have equality in everything, nor inequality ifthey are unequal in only one thing, all constitutions of this sort must bedeviant. We said before69 that all dispute somewhat justly, but that not all do so 30in an unqualifiedly just way. The rich have a claim due to the fact thatthey own a larger share of the land, and the land is something common,and that, in addition, they are usually more trustworthy where treaties70are concerned. The FREE and the well-born have closely related claims,for those who are better born are more properly citizens than those ofignoble birth, and good birth is honored at home by everyone. Besides, 35they have a claim because better people are likely to come from betterpeople, since good birth is virtue of family.71 Similarly, then, we shall saythat virtue has a just claim in the dispute, since justice, we say, is a communal virtue, which all the other virtues necessarily accompany.72 Butthe majority too have a just claim against the minority, since they are 40 67. Reading politikis with Ross, Schiitrumpf, and some mss. Alternatively (Dreizehnter and some mss.): "military (polemikis)."68. At 128 1'1-8.69. At 1280'7-25.70. sumbolaia: or contracts.7 1 . A slightly different definition is given at 1 294'2 1 .72. Because justice is complete virtue i n relation t o another person (NE 1 129h2S-1 1 30'5). 88 Politics III stronger, richer, and better, when taken as the majority in relation to the minority. If they were all present in a single city-state, therefore (I mean, for ex-1283b ample, the good, the rich, the well-born, and a political multitude in addition), will there be a dispute as to who should rule or not? Within each of the constitutions we have mentioned, to be sure, the decision as 5 to who should rule is indisputable, since these differ from one another because of what is in authority; for example, because in one the rich are in authority, in another the excellent men, and each of the others differs the same way. But be that as it may, we are investigating how the matter is to be determined when all these are present simultaneously. Suppose, 10 for example, that those who possess virtue are extremely few in number, how should the matter be settled? Should their fewness be considered in relation to the task? To whether they are able to manage the city-state? Or to whether there are enough of them to constitute a city-state by themselves? But there is a problem that faces all who dispute over political office. 15 Those who claim that they deserve to rule because of their wealth could be held to have no j ustice to their claim at all, and similarly those claim ing to do so because of their family. For it is clear that if someone is richer again than everyone else, then, on the basis of the same justice, this one person will have to rule them all . Similarly, it is clear that some one who is outstanding when it comes to good birth should rule those who dispute on the basis of freedom. Perhaps the same thing will also 20 occur in the case of virtue where aristocracies are concerned. For if one man were better than the others in the governing class, even though they were excellent men, then, on the basis of the same justice, this man should be in authority. So if the majority too should be in authority be cause they are superior to the few, then, if one person, or more than one 25 but fewer than the many, were superior to the others, these should be in authority rather than the multitude. All this seems to make it evident, then, that none of the definitions on the basis of which people claim that they themselves deserve to rule, whereas everyone else deserves to be ruled by them, is correct. For the multitude would have an argument of some justice even against those who claim that they deserve to have au- 30 thority over the governing class because of their virtue, and similarly against those who base their claim on wealth. For nothing prevents the multitude from being sometimes better and richer than the few, not as individuals but collectively. 35 Hence the problem that some people raise and investigate can also be Chapter 13 89 dealt with in this way. For they raise the problem of whether a legislatorwho wishes to establish the most correct laws should legislate for thebenefit of the better citizens or that of the majority, when the case justmentioned occurs. But what is correct must be taken to mean what isequitable; and what is equitable in relation to the benefit of the entire 40city-state, and the common benefit of the citizens. And a citizen gener-ally speaking is someone who participates in ruling and in being ruled,although in each constitution he is someone different. It is in the best 1284"one, however, that he is the one who has the power and who deliberatelychooses to be ruled and to rule with an eye to the virtuous life. But ifthere is one person or more than one (though not enough to make up acomplete city-state) who is so outstanding by reason of his superior Svirtue that neither the virtue nor the political power of all the others iscommensurable with his (if there is only one) or theirs (if there are anumber of them), then such men can no longer be regarded as part ofthe city-state. For they would be treated unjustly if they were thought tomerit equal shares, when they are so unequal in virtue and politicalpower. For anyone of that sort would reasonably be regarded as a god 10among human beings. Hence it is clear that legislation too must be con-cerned with those who are equals both in birth and in power, and that forthe other sort there is no law, since they themselves are law. For, indeed,anyone who attempted to legislate for them would be ridiculous, sincethey would presumably respond in the way Antisthenes tells us the lions 1Sdid when the hares acted like popular leaders and demanded equality foreveryone. 73 That is why, indeed, democratically governed city-states introduceostracism. For of all city-states these are held to pursue equality most,and so they ostracize those held to be outstandingly powerful (whetherbecause of their wealth, their many friends, or any other source of polit- 20ical power), banishing them from the city-state for fixed periods oftime.74 The story goes, too, that the Argonauts left Heracles behind forthis sort of reason: the Argo refused to carry him with the other sailorson the grounds that his weight greatly exceeded theirs.75 That is also 25 73. The lions' reply was: "Where are your claws and teeth?" See Aesop, Fables 241 . Antisthenes was a follower of Socrates and a founder of the school of philosophers known as the Cynics.74. Ostracism, or banishment without loss of property or citizenship for ten (later five) years, was introduced into Athens by Cleisthenes. See Ath. XXII.75. Athena had built a board into the Argo that enabled it to speak. 90 Politics III why those who criticize tyranny or the advice that Periander gave Thrasybulus should not be considered to be unqualifiedly correct in their censure. For they say that Periander said nothing to the messenger who had been sent to him for advice, but leveled a cornfield by cutting 30 off the outstandingly tall ears. When the messenger, who did not know why Periander did this, reported what had happened, Thrasybulus un derstood that he was to get rid of the outstanding men. 76 This advice is not beneficial only to tyrants, however, nor are tyrants the only ones who follow it. The same situation holds too in oligarchies 35 and democracies. For ostracism has the same sort of effect as cutting down the outstanding people or sending them into exile. But those in control of power treat city-states and nations in the same way. For exam ple, as soon as Athens had a firm grip on its imperial rule, it humbled 40 Samos, Chios, and Lesbos,77 in violation of the treaties it had with them; and the king of the Persians often cut the Medes and Babylonians down1284b to size, as well as any others who had grown presumptuous because they had once ruled empires of their own. The problem is a general one that concerns all constitutions, even the correct ones. For though the deviant constitutions use such methods S with an eye to the private benefit, the position is the same with those that aim at the common good. But this is also clear in the case of the other crafts and sciences. For no painter would allow an animal to have a disproportionately large foot, not even if it were an outstandingly beau tiful one, nor would a shipbuilder allow this in the case of the stern or 10 any of the other parts of the ship, nor will a chorus master tolerate a member of the chorus who has a louder and more beautiful voice than the entire chorus. So, from this point of view, there is nothing to prevent monarchs from being in harmony with the city-state they rule when they resort to this sort of practice, provided their rule benefits their 15 city-states. Where acknowledged sorts of superiority are concerned, then, there is some political j ustice to the argument in favor of os tracism. It would be better, certainly, if the legislator established the constitu tion in the beginning so that it had no need for such a remedy. But the next best thing is to try to fix the constitution, should the need arise, with a corrective of this sort. This is not what actually tended to happenin city-states, however. For they did not look to the benefit of their own 20constitutions, but used ostracism for purposes of faction. It is evident,then, that in each of the deviant constitutions ostracism is privately advantageous and just, but it is perhaps also evident that it is not unqualifiedly just. In the case of the best constitution, however, there is a considerable 25problem, not about superiority in other goods, such as power or wealthor having many friends, but when there happens to be someone who issuperior in virtue. For surely people would not say that such a personshould be expelled or banished, but neither would they say that theyshould rule over him. For that would be like claiming that they deserved 30to rule over Zeus, dividing the offices. 78 The remaining possibility-andit seems to be the natural one-is for everyone to obey such a persongladly, so that those like him will be permanent kings in their city-states. Chapter 1 4After the matters just discussed, it may perhaps be well to change to an 35investigation of kingship, since we say that it is one of the correct constitutions. What we have to investigate is whether or not it is beneficial fora city-state or territory which is to be well managed to be under a king-ship, or under some other constitution instead, or whether it is benefi-cial for some but not for others. But first it must be determined whether 40there is one single type of kingship or several different varieties. In fact this is easy to see-that kingship includes several types, and 1285'that the manner of rule is not the same in all of them. For kingship inthe Spartan constitution, which is held to be the clearest example ofkingships based on law, does not have authority over everything, butwhen the king leaves the country, he does have leadership in military af- 5fairs. Moreover, matters relating to the gods are assigned to the kings.[ 1 ] This type of kingship, then, is a sort of permanent autocratic gener-alship. For the king does not have the power of life and death, exceptwhen exercising a certain sort of kingship/9 similar to that exercised inancient times on military expeditions, on the basis of the law of force.80Homer provides a clear example. Agamemnon put up with being abused 10 in the assemblies, but when they went out to fight he had the power even of life and death. At any rate, he says: ''Anyone I find far from the battle . . shall have no hope of escaping dogs and vultures, for I myself shall .· 8 1 . Iliad 11.391-393. The last line Aristotle quotes is not in our text. 82. See Plato, Republic 567a-568a. 83. On Pittacus, see 1274b18-23 and note. Alcaeus (born c. 620) was a lyric poet from Mytilene in Lesbos. Antimenides was his brother. 84. Diehl 1.427, fr. 87. 85. Some non-Greek kingships were also of this sort; see 1295•1 1-14. 86. The period described in the Homeric poems. Chapter IS 93 because the first of the line were benefactors of the multitude in thecrafts or war, or through bringing them together or providing them withland, they became kings over willing subjects, and their descendantstook over from them. They had authority in regard to leadership in war,and religious sacrifices not requiring priests. They also d ecided legal 10cases, some doing so under oath, and others not (the oath consisted inlifting up the scepter) . In ancient times, they ruled continuously overthe affairs of the city-state, both domestic and foreign. But later, whenthe kings themselves relinquished some of these prerogatives, and oth- 1Sers were taken away by the crowd in various city-states, only the sacri-fices were left to the kings, and even where there was a kingship worthyof the name, it was only leadership in military affairs conducted beyondthe frontiers that the king held on to. There are, then, these four kinds of kingship. One belongs to the 20heroic age: this was over willing subjects and served certain fixed purposes; the king was general and judge and had authority over matters todo with the gods. The second is the non-Greek kind, which is rule by amaster based on lineage and law. The third is so-called dictatorship, 25which is elective tyranny. Fourth among them is Spartan kingship,which, simply put, is permanent generalship based on lineage. These,then, differ from one another in this way. [5] But there is a fifth kind of kingship, when one person controlseverything in j ust the way that each nation and each city-state controls 30the affairs of the community. It is organized along the lines of householdmanagement. For j ust as household management is a sort of kingshipover a household, so this kingship is household management of one ormore city-states or nations. Chapter 1 5Practically speaking, then, there are just two kinds of kingship to be examined, namely, the last one and the Spartan. For most of the others liein between them, since they control less than absolute kingship but 35more than Spartan kingship. So our investigation is pretty much abouttwo questions: First, whether or not it is beneficial for a city-state tohave a permanent general (whether chosen on the basis of family or byturns). Second, whether or not it is beneficial for one person to con-trol everything. In fact, however, the investigation of this sort of gener- 1 286"alship has the look of an investigation of LAWS rather than of constitu-tions, since this is something that can come to exist in any constitution. 94 Politics III So the first question may be set aside. But the remaining sort of kingS ship is a kind of constitution. Hence we must study it and go through the problems it involves. The starting point of the investigation is this: whether it is more ben eficial to be ruled by the best man or by the best laws. Those who think it beneficial to be ruled by a king hold that laws speak only of the uni-10 versal, and do not prescribe with a view to actual circumstances. Conse quently, it is foolish to rule in accordance with written prescriptions in any craft, and doctors in Egypt are rightly allowed to change the treat ment after the fourth day (although, if they do so earlier, it is at their own risk). It is evident, for the same reason, therefore, that the best con-IS stitution is not one that follows written lawsY All the same, the rulers should possess the universal reason as well. And something to which the passionate element is entirely unattached is better than something in which it is innate. This element is not present in the law, whereas every20 human soul necessarily possesses it. But perhaps it ought to be said, to oppose this, that a human being will deliberate better about particulars. In that case, it is clear that the ruler must be a legislator, and that laws must be established, but they must not have authority insofar as they deviate from what is best, though they should certainly have authority everywhere else. As to what the law cannot decide either at all or well, should the one best person rule, or2S everyone? For as things stand now, people come together to hear cases, deliberate, and decide, and the decisions themselves all concern particu lars. Taken individually, any one of these people is perhaps inferior to the best person. But a city-state consists of many people, just like a feast to which many contribute, and is better than one that is a unity and sim-30 ple. That is why a crowd can also judge many things better than any sin gle individual. Besides, a large quantity is more incorruptible, so the multitude, like a larger quantity of water, are more incorruptible than the few. The judgment of an individual is inevitably corrupted when he is overcome by anger or some other passion of this sort, whereas in the same situation it is a task to get all the citizens to become angry and3S make mistakes at the same time. Let the multitude in question be the free, however, who do nothing outside the law, except about matters the law cannot cover-not an easy thing to arrange where numbers are large.88 But suppose there were a number who were both good men and good citizens, which would bemore incorruptible-one ruler, or a larger number all of whom aregood? Isn't it clear that it would be the larger number? "But such agroup will split into factions, whereas the single person is free of fac- 1286htion." One should no doubt oppose this objection by pointing out thatthey may be excellent in soul just like the single person. So then, if the rule of a number of people, all of whom are good men,is to be considered an aristocracy, and the rule of a single person a king-ship, aristocracy would be more choiceworthy for city-states than king- 5ship (whether the rule is supported by force or not),89 provided that it ispossible to find a number of people who are similar. Perhaps this too isthe reason people were formerly under kingships-because it was rareto find men who were very outstanding in virtue, particularly as thecity-states they lived in at that time were small. Besides, men were madekings because of benefactions, which it is precisely the task of good men 10to confer. When there began to be many people who were similar invirtue, however, they no longer put up with kingship, but looked forsomething communal and established a polity. But when they began toacquire wealth from the common funds, they became less good, and itwas from some such source, so one might reasonably suppose, that oligarchies arose; for they made wealth a thing of honor. 90 Then from oli- 15garchies they changed first into tyrannies, and from tyrannies to democ-racy. For by concentrating power into ever fewer hands, because of ashameful desire for profit, they made the multitude stronger, with theresult that it revolted and democracies arose. Now that city-states havebecome even larger, it is perhaps no longer easy for any other constitu- 20tion to arise besides democracy. 91 But now if one does posit kingship as the best thing for a city-state,how is one to handle the matter of children? Are the descendants to ruleas kings too? If they turn out as some have, it would be harmful. "Butperhaps, because he is in control, he will not give it to his children." But 25this is hardly credible. For it is a difficult thing to do, and demandsgreater virtue than human nature allows. 89. The "force" in question is probably the citizen bodyguards, which Greek kings typically possessed ( 1 285'25-27, 1 286h27-40), and which could be used in a tyrannical fashion.90. Because the end that oligarchy sets for itself is wealth. See 1 3 1 1 '9-1 0; Plato, Republic 554a, Introduction, lxv-lxvi.9 1 . For somewhat different explanations of the changes constitutions undergo, see 1297b l 6-28, 1 3 1 6'1-b27. 96 Politics III Chapter 1 6 Now that we have reached this point the next topic must be that of the1287• king who does everything according to his own wish, so we must investi gate this. For the so-called king according to law does not, as we said, amount to a kind of constitution, since a permanent generalship can 5 exist in any constitution (for example, in a democracy and an aristoc racy), and many places put one per�on in control of managing affairs. There is an office of this sort in Epidamnus, indeed, and to a lesser ex tent in Opus as well. But as regards so-called absolute kingship (which is where the king rules everything in accord with his own wish), some hold that it is not 10 even in accordance with nature for one person, from among all the citi zens, to be in control, when the city-state consists of similar people. For justice and merit must be by nature the same for those who are by nature similar. Hence, if indeed it is harmful to their bodies for equal people to have unequal food or clothing, the same holds, too, where offices are 15 concerned. The same also holds, therefore, when equal people have what is unequal. Which is precisely why it is j ust for them to rule no more than they are ruled, and, therefore, to do so in turn. But this is already law; for the organization is law.94 Thus it is more choiceworthy to have law rule than any one of the citizens. And, by this same argument, evenif it is better to have certain people rule, they should be selected as 20guardians of and assistants to the laws. For there do have to be somerulers; although it is not just, they say, for there to be only one; at anyrate, not when all are similar. Moreover, the sort of things at least thatthe law seems unable to decide could not be discovered by a humanbeing either. But the law, having educated the rulers for this special purpose, hands over the rest to be decided and managed in accordance with 25the most just opinion of the rulers. Moreover, it allows them to make anycorrections by introducing anything found by experience to be an improvement on the existing laws. Anyone who instructs LAW to rule wouldseem to be asking GOD and the understanding alone to rule;95 whereassomeone who asks a human being asks a wild beast as well. For appetite 30is like a wild beast, and passion perverts rulers even when they are thebest men. That is precisely why law is understanding without desire. The comparison with the crafts, that it is bad to give medical treatment in accordance with written prescriptions and more choiceworthyto rely on those who possess the craft instead, would seem to be false.For doctors never do things contrary to reason because of friendship, 35but earn their pay by healing the sick. Those who hold political office,on the other hand, do many things out of spite or in order to win favor.And indeed if people suspected their doctors of having been bribed bytheir enemies to do away with them, they would prefer to seek treatmentderived from books. Moreover, doctors themselves call in other doctors 40to treat them when they are sick, and trainers call in other trainers when 128 7hthey are exercising, their assumption being that they are unable to judgetruly because they are judging about their own cases, and while in pain.So it is clear that in seeking what is just they are seeking the mean; forthe law is the mean.96 Again, laws based on custom are more authorita-tive and deal with matters that have more authority than do written laws, 5so that even if a human ruler is more reliable than written laws, he is notmore so than those based on custom. Yet, it is certainly not easy for a single ruler to oversee many things;hence there will have to be numerous officials appointed under him.Consequently, what difference is there between having them there fromthe beginning and having one person appoint them in this way? Besides, 10 as we said earlier,97 if it really is just for the excellent man to rule because he is better, well, two good ones are better than one. Hence the saying "When two go together . . . ," and Agamemnon's prayer, "May ten such counselors be mine. "98 IS Even nowadays, however, officials, such as jurors, have the authority to decide some things the law cannot determine. For, as regards those matters the law can determine, certainly no one disputes that the law it self would rule and decide best. But because some matters can be cov ered by the laws, while others cannot, the latter lead people to raise and 20 investigate the problem whether it is more choiceworthy for the best law to rule or the best man (since to legislate about matters that call for de liberation is impossible). The counterargument, therefore, is not that it is not necessary for a human being to decide such matters, but that there 25 should be many judges, not one only. For each official judges well if he has been educated by the law. And it would perhaps be accounted strange if someone, when judging with one pair of eyes and one pair of ears, and acting with one pair of feet and hands, could see better than many people with many pairs, since, as things stand, monarchs provide 30 themselves with many eyes, ears, hands, and feet. For they appoint those who are friendly to their rule and to themselves as co-rulers. Now if they are not friendly in this way, they will not do as the monarch chooses. But suppose they are friendly to him and his rule-well, a friend is someone similar and equal, so if he thinks they should rule, he must think that those who are equal and similar to him should rule in a similar fashion. These, then, are pretty much the arguments of those who dispute 35 against kingship. Chapter 1 7 But perhaps these arguments hold in some cases and not in others. For what is by nature both just and beneficial is one thing in the case of rule by a master, another in the case of kingship, and another in the case of rule by a statesman (nothing is by nature both just and beneficial in the 40 case of a tyranny, however, nor in that of the other deviant constitutions, since they come about contrary to nature). But it is surely evident from what has been said that in a case where people are similar and equal, it is1288' neither beneficial nor just for one person to control everything. This 97. At 1 286b3-5. 98. Iliad X.224 and 11.372. Chapter 1 7 99 holds whether there are no laws except the king himself, or whetherthere are laws; whether he is a good person ruling good people, or a notgood one ruling not good ones; and even whether he is their superior invirtue--except in one set of circumstances. What these circumstancesare must now be stated-although we have in a way already stated it.99 5 First, we must determine what kind of people are suited to kingship,what to aristocracy, and what to polity. A multitude should be underkingship when it naturally produces a family that is superior in thevirtue appropriate to political leadership. A multitude is suited to aristocracy when it naturally produces a multitude100 capable of being ruled 10with the rule appropriate to free people by those who are qualified tolead by their possession of the virtue required for the rule of a statesman. And a multitude is suited to polity when there naturally arises in ita warrior multitude101 capable of ruling and being ruled, under a lawwhich distributes offices to the rich on the basis of merit. Whenever ithappens, then, that there is a whole family, or even some one individual I5among the rest, whose virtue is so superior as to exceed that of all theothers, it is just for this family to be the kingly family and to controleverything, and for this one individual to be king. For, as was said ear-lier, this not only accords with the kind of justice customarily put forward by those who establish constitutions, whether aristocratic, oli- 20garchic, or even democratic (for they all claim to merit rule on the basisof superiority in something, though not superiority in the same kind ofthing), but also with what was said earlier. 1 02 For it is surely not properto kill or to exile or to ostracize an individual of this sort, nor to claim 25that he deserves to be ruled in turn. For it is not natural for the part tobe greater than the whole, but this is what happens in the case of some-one who has this degree of superiority. So the only remaining option isfor such a person to be obeyed and to be in control not by turns but unqualifiedly.103 Kingship, then, and what its varieties are, and whether it is beneficial 30for city-states or not, and if so, for which and how, may be determined inthis way. 99. At 1 284'3-b35.100. Reading plethos with Dreizehnter and the mss.101. Reading plethos polemikon with Dreizehnter and the mss.102. At 1284h2S-34.103. The argument in this paragraph is discussed in the Introduction §8. 100 Politics III Chapter 1 8 We say that there are three correct constitutions, and that the best of them must of necessity be the one managed by the best people. This is the sort of constitution in which there happens to be either one particu lar person or a whole family or a number of people whose virtue is supe- 35 rior to that of all the rest, and where the latter are capable of being ruled and the former of ruling with a view to the most choiceworthy life. Fur thermore, as we showed in our first discussions, 104 the virtue of a man must of necessity be identical to that of a citizen of the best city-state. Hence it is evident that the ways and means by which a man becomes ex- 40 cellent are the same as those by which one might establish a city-state ruled by an aristocracy or a king, and that the education and habits thatJ288h make a man excellent are pretty much the same as those that make him statesmanlike or kingly.1 05 Now that these matters have been determined, we must attempt to discuss the best constitution, the way it naturally arises and how it is es tablished. Anyone, then, who intends to do this must conduct the inves- 5 tigation in the appropriate way. 106 104. III.4-5. 105. See Introduction xxv-xxvi. 106. This sentence appears again in a slightly different form as part of the opening sentence of Book VII. It is bracketed as incomplete by Ross.Chapter 1Among all the crafts and sciences that are concerned not only with a 10part but that deal completely with some one type of thing, it belongs toa single one to study what is appropriate for each type. For example:what sort of physical training is beneficial for what sort of body, that is tosay, what sort is best (for the sort that is appropriate for the sort of bodythat is naturally best and best equipped is necessarily best), and whatsingle sort of training is appropriate for most bodies (since this too is a 15task for physical training). Further, if someone wants neither the condi-tion nor the knowledge required of those involved in competition, it belongs no less to coaches and physical trainers2 to provide this capacitytoo. We see a similar thing in medicine, ship building, clothing manufac-ture, and every other craft. 20 Consequently, it is clear that it belongs to the same science3 to study:[ I ] What the best constitution is, that is to say, what it must be like if it isto be most ideal, and if there were no external obstacles. Also [2] whichconstitution is appropriate for which city-states. For achieving the bestconstitution is perhaps impossible for many; and so neither the unquali- 25fiedly best constitution nor the one that is best in the circumstancesshould be neglected by the good legislator and true statesman. Further,[3] which constitution is best given certain assumptions. For a statesmanmust be able to study how any given constitution might initially come 1. The end of iii. l 8 prepares us for a discussion of the best constitution, but IV does not contain one. Indeed, the opening sentence of IV.2 seems to suggest that the best constitution has already been discussed. This is to some extent true, because much is said about the .best constitution in discussing both other people's candidates for that title and aristocracy and kingship ( 1 289h30-32). But Aristotle's own candidate is not formally discussed until VII-VIII.2. See 1 338b6-8.3. Namely, STATESMANSHIP. 101 102 Politics IV into existence, and how, once in existence, it might be preserved for the 30 longest time. I mean, for example, when some city-state happens to be governed neither by the best constitution (not even having the necessary resources) nor by the best one possible in the existing circumstances, but by a worse one. Besides all these things, a statesman should know [4] which constitution is most appropriate for all city-states. Consequently, 35 those who have expressed views about constitutions, even if what they say is good in other respects, certainly fail when it comes to what is use ful. For one should not study only what is best, but also what is possible, and similarly what is easier and more attainable by all. As it is, however, some seek only the constitution that is highest and requires a lot of re- 40 sources, while others, though they discuss a more attainable sort, do away with the constitutions actually in place, and praise the Spartan or some other. But what should be done is to introduce the sort of organi-1289' zation that people will be easily persuaded to accept and be able to par ticipate in,4 given what they already have, as it is no less a task to reform a constitution than to establish one initially, just as it is no less a task to correct what we have learned than to learn it in the first place. That is S why, in addition to what has just been mentioned, a statesman should also be able to help existing constitutions, as was also said earlier.5 But this is impossible if he does not know [5] how many kinds of constitu tions there are. As things stand, however, some people think that there is just one kind of democracy and one of oligarchy. But this is not true. So 10 one must not overlook the varieties of each of the constitutions, how many they are and how many ways they can be combined.6 And [6] it is with this same practical wisdom7 that one should try to see both which laws are best and which are appropriate for each of the constitutions. For laws should be established, and all do establish them, to suit the consti tution and not the constitution to suit the laws. For a constitution is the IS organization of offices in city-states, the way they are distributed, what element is in authority in the constitution, and what the end is of each of the communities. 8 Laws, apart from those that reveal what the constitu- tion is, are those by which the officials must rule, and must guard againstthose who transgress them. Clearly, then, a knowledge of the varieties of 20each constitution and of their number9 is also necessary for establishinglaws. For the same laws cannot be beneficial for all oligarchies or for alldemocracies-if indeed there are several kinds, and not one kind ofdemocracy nor one kind of oligarchy only. 25 Chapter 2Since our initial inquiry concerning constitutions, 1 0 we distinguishedthree correct constitutions (kingship, aristocracy, polity) and three deviations from them (tyranny from kingship, oligarchy from aristocracy,and democracy from polity), and since we have already discussed aristocracy and kingship, for studying the best constitution is the same as 30discussing these names, 11 since each of them tends to be established onthe basis of virtue furnished with resources; and since further, we havedetermined how aristocracy and kingship differ from one another, andwhen a constitution should be considered a kingship, 12 it remains to deal 35with the constitution that is called by the name common to all CONSTITUTIONS, and also with the others--oligarchy, democracy, and tyranny. It is also evident which of these deviations is worst and which secondworst. For the deviation from the first and most divine constitutionmust of necessity be the worst.13 But kingship either must be in name 40only and not in fact or must be based on the great superiority of the per-son ruling as king. Hence tyranny, being the worst, is furthest removed 1289"from being a constitution; oligarchy is second worst (since aristocracy isvery far removed from this constitution); and democracy the most mod-erate. An earlier thinker14 has already expressed this same view, though 5 he did not look to the same thing we do. For he judged that when all these constitutions are good (for example, when an oligarchy is good, and also the others), democracy is the worst of them, but that when they are bad, it is the best. But we say that these constitutions are all of them mistaken, and that it is not right to speak of one kind of oligarchy as bet-10 ter than another, but as less bad. But let us leave aside the judgment of this matter for the present. In stead, we must determine: [ I ] First, how many varieties of the constitu tions there are (if indeed there are several kinds of democracy and oli garchy). Next, [2] which kind is most attainable, and which most15 choiceworthy after the best constitution (if indeed there is some other constitution which, though aristocratic and well constituted, is at the same time appropriate for most city-states), and also which of the other constitutions is more choiceworthy for which people (for democracy is perhaps more necessary than oligarchy for some, whereas for others the20 reverse holds). After these things, [3] how someone who wishes to do so should establish these constitutions (I mean, each kind of democracy or oligarchy). Finally, when we have gone as far as we can to give a succinct account of each of these topics, [4] we must try to go through the ways in which constitutions are destroyed and those in which they are pre-25 served, both in general and in the case of each one separately, and through what causes these most naturally come about. Chapter 3 The reason why there are several constitutions is that every city-state has several parts. 1 5 For in the first place, we see that all city-states are composed of households; and, next, that within this multitude there30 have to be some who are rich, some who are poor, and some who are in the middle; and that of the rich and of the poor, the one possessing weapons and the other without weapons. We also see that the people comprise a farming part, a trading part, and a vulgar craftsman part. And among the notables there are differences in wealth and in extent of their property-as, for example, in the breeding of horses, since this is35 not easy for those without wealth to do. (That is why, indeed, there were oligarchies among those city-states in ancient times whose power lay in their cavalry, and who used horses in wars with their neighbors-as, forexample, the Eretrians did, and the Chalcidians, the Magnesians on theriver Menander, and many of the others in Asia.) There are also differ- 40ences based on birth, on virtue, and on everything else of the sort thatwe characterized as part of a city-state in our discussion of aristocracy, 1290"since there we distinguished the number of parts that are necessary toany city-state.16 For sometimes all of these parts participate in the constitution, sometimes fewer of them, sometimes more. It is evident, therefore, that there must be several constitutions that Sdiffer in kind from one another, since these parts themselves also differin kind. For a constitution is the organization of offices, and all consitutions distribute these either on the basis of the power of the participants, or on the basis of some sort of equality common to them (I mean,for example, of the poor or of the rich, or some equality common to 10both).17 Therefore, there must be as many constitutions as there areways of organizing offices on the basis of the superiority and varieties ofthe parts. But there are held to be mainly two constitutions: just as the windsare called north or south, and the others deviations from these, so thereare also said to be two constitutions, democracy and oligarchy. For aris- 15tocracy is regarded as a sort of oligarchy, on the grounds that it is a sortof rule by the few, whereas a so-called polity is regarded as a sort ofdemocracy, 18 just as the west wind is regarded as northerly, and the eastas southerly. 19 According to some people, the same thing also happens inthe case of harmonies, which are regarded as being of two kinds, the Do- 20rian and the Phrygian, and the other arrangements are called eitherPhrygian types or Dorian types. People are generally accustomed, then,to think of constitutions in this way. But it is truer and better to distinguish them, as we have, and say that two constitutions (or one) are wellformed, and that the others are deviations from them, some from the 25well-mixed "harmony," and others from the best constitution, the more tightly controlled ones and those that are more like the rule of a master being more oligarchic, and the unrestrained and soft ones democratic.20 Chapter 4 30 One should not assert (as some are accustomed to do now)Z1 that democ racy is simply where the multitude are in authority (for both in oli garchies and everywhere else, the larger part is in authority). 22 Nor should an oligarchy be regarded as being where the few are in authority over the constitution. For if there were a total of thirteen hundred peo ple, out of which a thousand were rich people who give no share in office 35 to three hundred poor ones, no one would say that the latter were demo cratically governed even if they were free and otherwise similar to the rich. Similarly, if the poor were few, but stronger than the rich, who were a majority, no one would call such a constitution an oligarchy if the others, though rich, did not participate in office. Thus it is better to say 40 that a democracy exists when the free are in authority and an oligarchyJ29(J exists when the rich are; but it happens that the former are many and the latter few, since many are free but few are rich. Otherwise there would be an oligarchy if offices were distributed on the basis of height (as is 5 said to happen in Ethiopia) or on the basis of beauty, since beautiful peo ple and tall ones are both few in number. Yet these23 are not sufficient to distinguish these constitutions. Rather, since both democracy and oligarchy have a number of parts, we must further grasp that it is not a democracy if a few free people rule 10 over a majority who are not free, as, for example, in Apollonia on the Ionian Gulf and in Thera. For in each of these city-states the offices were held by the well born, the descendants of the first colonists, although they were few among many. Nor is it an oligarchy24 if the rich rule be 15 cause they are the multitude, as was formerly the case in Colophon, where the majority possessed large properties before the war against the 20. The example of music results in this extended musical metaphor in which "harmony" (harmonia) is used as a metaphor for a balanced mixture in a constitution. The well-mixed constitution is identified in IV.9. 21. See Plato, Statesman 29ld. 22. See 1 294•1 1-14 for an explanation. 23. Namely, wealth and freedom. 24. Reading oligarchia with Ross. Alternatively (Dreizehnter and the mss.): "democracy (demos)." Chapter 4 1 07 Lydians.25 Rather, it is a democracy when the free and the poor who area majority have the authority to rule, and an oligarchy when the rich andwell born, who are few, do. 26 20 It has been stated, then, that there are a number of constitutions andwhy this is so. But let us now say why there are more than the ones mentioned,27 what they are, and how they arise, taking as our starting pointwhat was agreed to earlier.28 For we are agreed that every city-state hasnot only one part but several. If we wanted to grasp the kinds of animals, we would first determine 25what it is necessary for every animal to have: for example, certain of thesense organs; something with which to work on and absorb food (such asa mouth and a stomach); and also parts by which it moves. If these werethe only parts, but they had varieties (I mean, for example, if there wereseveral types of mouths, stomachs, and sense organs, and also of loco- 30motive parts), then the number of ways of combining these would necessarily produce a number of types of animals. For the same animal can-not have mouths or ears of many different varieties. Hence, when thesehave been grasped, all the possible ways of pairing them together willproduce kinds of animals, that is to say, as many kinds of animals as 35there are combinations of the necessary parts.29 It is the same way withthe constitutions we have mentioned. For city-states are constituted notout of one but many parts, as we have often said . One of these parts is [ I ] the multitude concerned with food, the onescalled farmers. A second is [2] those called vulgar craftsman. They are 40concerned with the crafts without which a city-state cannot be managed 1291"(of these some are necessary, whereas others contribute to luxury or fineliving). A third is [3] the traders (by which I mean those engaged in sell-ing and buying, retail trade, and commerce) . A fourth is [4] the hired Ia- 5borers. A fifth is [5] the defensive warriors, which are no less necessarythan the others, if the inhabitants are not to become the slaves of any aggressor. For no city-state that is naturally slavish can possibly deserve to 30. At 369d-371e. 3 1 . See 1253'37-39, 1 328b l J-15. 32. The former are those that deal with our necessary needs; the latter, the war riors, etc. What is evident is that a city-state must at least have warriors among its parts. But it will often need a navy as well. See VII.S for further discussion. 33. The unidentified sixth part may be the class of priests (listed as an impor tant part of any city-state at 1328h 1 1-1 3). But it is also possible that the long aside about the Republic has caused Aristotle to go astray in his numbering. Chapter 4 1 09 34. Deliberating in a way that is noble and just requires practical wisdom, the virtue peculiar to a statesmen ( 1 277h2S-26, NE 1 14 l b23-24).35. Presumably, that of statesmen.36. A type (genus) is divided into kinds (species) on the basis of opposite vari eties (differentia). If these characteristics are themselves indivisible, there will then be just two kinds (species). See PA 643'3 1-b8, especially 643'7-8. The sorts of superiority claimed by the rich and the poor are wealth and freedom respectively.37. See VI. l-7.38. See 1 289h27-1290'1 3 . 1 10 Politics I V other kind of multitude there may be. The notables are distinguished by wealth, good birth, virtue, education, and the other characteristics that are ascribed on the basis of the same sort of difference. 30 [ 1] The first democracy, then, is the one that is said to be most of all based on equality. For the law in this democracy says that there is equal ity when the poor enjoy no more superiority than the rich and neither is in authority but the two are similar. For if indeed freedom and equality are most of all present in a democracy, as some people suppose,39 this 35 would be most true in the constitution in which everyone participates in the most similar way. But since the people are the majority, and majority opinion has authority, this constitution is necessarily a democracy. This, then, is one kind of DEMOCRACY.40 [2] Another is where offices are filled on the basis of property assess ments, although these are low, and where anyone who acquires the req- 40 uisite amount may participate, whereas anyone who loses it may not. [3] Another kind of democracy is where all uncontested citizens41 partici-1292" pate, and the law rules. [4] Another kind of democracy is where everyone can participate in office merely by being a citizen,42 and the law rules. [5] Another kind of democracy is the same in other respects, but the 5 multitude has authority, not the law. This arises when DECREES have au thority instead of laws; and this happens because of POPULAR LEADERS. For in city-states that are under a democracy based on law, popular lead ers do not arise. Instead, the best citizens preside.43 Where the laws are 10 not in authority, however, popular leaders arise. For the people become a monarch, one person composed of many, since the many are in authority not as individuals, but all together. When Homer says that "many headed rule is not good,"44 it is not clear whether he means this kind of rule, or the kind where there are a number of individual rulers. In any 15 case, a people of this kind, since it is a monarchy, seeks to exercise monarchic rule through not being ruled by the law, and becomes a mas ter. The result is that flatterers are held in esteem, and that a democracy of this kind is the analog of tyranny among the monarchies. That is also why their characters are the same: both act like masters toward the bet- ter people; the decrees of the one are like the edicts of the other; a pop-ular leader is either the same as a flatterer or analogous. Each of these 20has special power in his own sphere, flatterers with tyrants, popularleaders with a people of this kind. They are responsible for decreesbeing in authority rather than laws because they bring everything beforethe people. This results in their becoming powerful because the people 25have authority over everything, and popular leaders have it over the peo-ple's opinion, since the multitude are persuaded by them. Besides, thosewho make accusations against officials say that the people should decidethem. The suggestion is gladly accepted, with the result that all officesare destroyed. One might hold, however, that it is reasonable to object that this kind 30of democracy is not a CONSTITUTION at all, on the grounds that there isno constitution where the laws do not rule. For the law should rule universally over everything, while offices and the constitution45 should de-cide particular cases. So, since democracy is one of the constitutions, it 35is evident that this sort of arrangement, in which everything is managedby decree, is not even a democracy in the most authoritative sense, sinceno decree can possibly be universal.46 The kinds of democracy, then, should be distinguished in this way. Chapter 5Of the kinds of oligarchy, [ 1 ] one has offices filled on the basis of such ahigh property assessment that the poor, even though they are the major- 40ity, do not participate, but anyone who does acquire the requisiteamount may participate in the constitution. [2] In another the offices arefilled on the basis of a high assessment and they themselves elect some- 1 292hone to fill any vacancy. If they elect from among all of these,47 it is heldto be more aristocratic; if from some specified people, oligarchic. 48 [3] In 45. Reading ten politeian with Dreizehnter and the mss. The oddity of the claim that the constitution decides particular cases is reduced if we remember that "the governing class is the constitution" ( 1 278b l l). In the kind of democ racy under discussion, the people are the governing class.46. With the explicable exception of absolute kingship (III. 17), a genuine CON STITUTION is defined by and governed in accordance with LAWS, which, un like DECREES, must be universal. Hence a democracy governed by decrees is arguably not a constitution.47. All who have the assessed amount of property.48. See 1 300'8-b7 for an explanation. 1 12 Politics IV S another kind of oligarchy a son succeeds his father. [4] In a fourth what was just mentioned occurs, and not the law but the officials rule. This is to oligarchies what tyranny is to monarchies, and to the democracy we10 spoke of last among democracies. Such an oligarchy is called a dynasty. These, then, are the kinds of oligarchy and democracy. But one must not overlook the fact that it has happened in many places that constitu tions which are not democratic according to their laws are none the less governed democratically because of custom and training. Similarly, inIS other places, the reverse has happened: the constitution is more democ ratic in its laws, but is governed in a more oligarchic way as a result of custom and training. This happens especially after there has been a change of constitution. For the change is not immediate, but people are content at first to take from others in smaller ways. Hence the pre-exist-20 ing laws remain in effect, although those who have changed the consti tution are dominant. Chapter 6 It is evident from what has been said that there are this many kinds of democracy and oligarchy. For either all of the aforementioned parts of the people must participate in the constitution, or some must and others25 not. ( 1 ] So when the part that farms and that owns a moderate amount of property has authority over the constitution, it is governed in accor dance with the laws. For they have enough to live on as long as they keep working, but they cannot afford any leisure time. So they put the law in charge and hold only such assemblies as are necessary. And the others may participate when they have acquired the property assessment de-30 fined by the laws. Hence all those who have acquired it may participate. For, generally speaking, it is oligarchic when not all of these may partic ipate, though not if what makes being at leisure impossible is the absence of revenues.49 This, then, is one kind of democracy and these are the rea sons for it. [2] Another kind arises through the following distinction. For it isJS possible for everyone of uncontested birth to participate, but for only those who have leisure actually to do so. Hence in this kind of democ racy the laws rule because there is no revenue. (3] A third kind is when all who are free may participate in the constitution, but, for the reasonjust mentioned, they do not participate, so that law necessarily rules in 40this kind also. [4] A fourth kind of democracy was the last to arise incity-states. For because city-states have become much larger than the 1293"original ones and possess abundant sources of revenue, everyone sharesin the constitution, and so the multitude preponderates. And they all doparticipate and govern, because even the poor are able to be at leisure, 5since they get paid. A multitude of this sort is particularly leisured, in-deed, since care for their own property does not impede them. But itdoes impede the rich, who often fail to take part in the assembly or serveon juries as a result. Hence the multitude of poor citizens come to haveauthority over the constitution and not the laws. The kinds of democ- 10racy, then, are such and so many because of these necessities. As for the kinds of oligarchy, [ 1] when a number of people own prop-erty, but a smaller amount-not too much-this is the first kind of oligarchy. For anyone who acquires the amount may participate. And because of the multitude participating in the governing class, law is 15necessarily in authority, not human beings. For it is necessary for themto consent to having the law rule and not themselves, the more removedthey are from exercising monarchy, and the more they have neither somuch property that they can be at leisure without worrying nor so littlethat they need to be supported by the city-state. 20 [2] But if the property owners are fewer and their properties greaterthan those mentioned before, the second kind of oligarchy arises. For,being more powerful, the property owners expect to get more. Hencethey themselves elect from among the rest of the citizens those who areto enter the governing class. But as they are not yet powerful enough torule without law, they pass a law of this sort. 50 25 [3] But if they tighten this process by becoming fewer and owninglarger properties, the third stage of oligarchy is reached, where theykeep the offices in their own hands, but do so in accordance with a lawrequiring deceased members to be succeeded by their sons. [ 4] Butwhen they now tighten it excessively through their property holdingsand the number of their friends, a dynasty of this sort approximates a 30monarchy, and human beings are in authority, not law. This is the fourthkind of oligarchy, corresponding to the final kind of democracy. 50. Permitting already existing members of the ruling oligarchy to elect new members. 1 14 Politics IV Chapter 7 35 There are also two constitutions besides democracy and oligarchy, one of which is mentioned by everyone and which we said was one of the four kinds of constitutions. The four they mention are monarchy, oligarchy, democracy, and, fourth, so-called aristocracy. There is a fifth, however, which is referred to by the name shared by all constitutions: the one 40 called a politeia (polity). But because it does not occur often, it gets over looked by those who try to enumerate the kinds of constitutions, and, like129Jh Plato, 51 list only the four in their discussion of constitutions. It is well to call the constitution we treated in our first discussions an aristocracy.52 For the only constitution that is rightly called an aristoc racy is the one that consists of those who are unqualifiedly best as regards virtue, and not of those who are good men only given a certain assump- 5 tion. For only here is it unqualifiedly the case that the same person is a good man and a good citizen. But those who are good in other constitu tions are so relative to their constitutions. Nevertheless, there are some constitutions that differ both from constitutions that are oligarchically governed and from so-called polity, and are called aristocracies. For a constitution where officials are elected not only on the basis of wealth 10 but also on the basis of merit differs from both of these and is called aris tocratic. For even in those constitutions where virtue is not a concern of the community, there are still some who are of good repute and held to be decent. Hence wherever a constitution looks to wealth, virtue, and the 15 people (as it does in Carthage), it is aristocratic, 53 as also are those, like the constitution of the Spartans, which look to only two, virtue and the people, and where there is a mixture of these two things, democracy and virtue. There are, then, these two kinds of aristocracy besides the first, which is the best constitution; and there is also a third, namely, [4] those 20 kinds of so-called polity that lean more toward oligarchy. Chapter 8 It remains for us to speak about so-called polity and about tyranny. We have adopted this arrangement, even though neither polity nor the aris- tocracies just mentioned are deviant, because in truth they all fall shortof the most correct constitution, and so are counted among the devia- 25tions, and these deviations are deviations from them, as we mentioned inthe beginning. 54 On the other hand, it is reasonable to treat tyranny last,since it is least of all a constitution, and our inquiry is about constitu-tions. So much for the reason for organizing things in this way. 30 But we must now set forth our views on polity. Its nature should bemore evident now that we have determined the facts about oligarchy anddemocracy. For polity, to put it simply, is a mixture of oligarchy anddemocracy. It is customary, however, to call those mixtures that lean toward democracy polities, and those that lean more toward oligarchy aris- 35tocracies, because education and good birth more commonly accompanythose who are richer. Besides, the rich are held to possess already whatunjust people commit injustice to get, which is why the rich are referredto as noble-and-good men, and as notables. So since aristocracies strive 40to give superiority to the best citizens, oligarchies too are said to consistprimarily of noble-and-good men. And it is held to be impossible for acity-state to be well governed if it is not governed aristocratically, but by 1294•bad people, and equally impossible for a city-state that is not well gov-erned to be governed aristocratically. But GOOD GOVERNMENT does notexist if the laws, though well established, are not obeyed. Hence we musttake good government to exist in one way when the established laws areobeyed, and in another when the laws that are in fact obeyed are well es- 5tablished (for even badly established laws can be obeyed). The secondsituation can come about in two ways: people may obey either the bestlaws possible for them, or the unqualifiedly best ones. Aristocracy is held most of all to exist when offices are distributed onthe basis of virtue. For virtue is the defining mark of aristocracy, wealth 10of oligarchy, and freedom of democracy. But MAJORITY opinion is foundin all of them. For in oligarchy and aristocracy and in democracies, theopinion of the major part of those who participate in the constitutionhas authority. Now in most city-states the kind of constitution iswrongly named, since the mixture aims only at the rich and the poor, at 15wealth and freedom. For among pretty much most people the rich aretaken to occupy the place of noble-and-good men. But there are in factthree grounds for claiming equal participation in the constitution: freedom, wealth, and virtue. (The fourth, which they call good birth, is a 20 Chapter 9 After what has been said, let us next discuss how, in addition to democ- 30 racy and oligarchy, so-called polity arises, and how it should be estab lished. At the same time, however, the defining principles of democracy and oligarchy will also become clear. For what we must do is get hold of the division of these, and then take as it were a token from each to put together. 55 35 There are three defining principles of the combination and mixture: [ 1 ) One is to take legislation from both constitutions. For example, in the case of deciding court cases, oligarchies impose a fine on the rich if they do not take part in deciding court cases, but provide no payment for 40 the poor, whereas democracies pay the poor but do not fine the rich. But what is common to both constitutions and a mean between them is doing both. And hence this is characteristic of a polity, which is a mix-/ 294h ture formed from both. This, then, is one way to conjoin them. [2] An other is to take the mean between the organizations of each. In democra cies, for example, membership in the assembly is either not based on a property assessment at all or on a very small one, whereas in oligarchies it is based on a large property assessment. The common position here is to require neither of these assessments but the one that is in a mean be- 5 tween the two of them. [3] A third is to take elements from both organi zations, some from oligarchic law and others from democratic law. I mean, for example, it is held to be democratic for officials to be chosen Chapter 1 01295• It remained for us to speak about tyranny, not because there is much to say about it, but so that it can take its place in our inquiry, since we as sign it too a place among the constitutions. Now we dealt with kingship in our first discussions59 (when we investigated whether the kind of 5 kingship that is most particularly so called is beneficial for city-states or not beneficial, who and from what source should be established in it, and in what manner). And we distinguished two kinds of tyranny while we were investigating kingship, because their power somehow also overlaps 10 with kingship, owing to the fact that both are based on law. For some non-Greeks choose [ 1 ] autocratic monarchs, and in former times among the ancient Greeks there were [2] people called dictators who became monarchs in this way. There are, however, certain differences between 15 these; but both were kingly in as much as they were based on law, and in volved monarchical rule over willing subjects; but both were tyrannical, in as much as the monarchs ruled like masters in accordance with their own judgment.60 But [3] there is also a third kind of tyranny, which is held to be tyranny in the highest degree, being a counterpart to absolute kingship. Any monarchy is necessarily a tyranny of this kind if the monarch rules in an unaccountable fashion over people who are similar 20 to him or better than him, with an eye to his own benefit, not that of the ruled. It is therefore rule over unwilling people, since no free person willingly endures such rule. The kinds of tyranny are these and this many, then, for the aforemen tioned reasons. Chapter 1 1 25 What is the best constitution, and what is the best life for most city states and most human beings, judging neither by a virtue that is beyond the reach of ordinary people, nor by a kind of education that requires natural gifts and resources that depend on luck, nor by the ideal consti tution, but by a life that most people can share and a constitution in 30 which most city-states can participate? For the constitutions called aris tocracies, which we discussed just now,61 either fall outside the reach of 59. At III.l4-17. 60. See III.l4. 6 1 . At 1 29Jb7- 2 1 . Chapter 11 1 19 most city-states or border on so-called polities (that is why the two haveto spoken about as one). Decision about all these matters depends on the same elements. For if 35what is said in the Ethics is right, and a happy life is the one that expresses virtue and is without impediment, and virtue is a mean, then themiddle life, the mean that each sort of person can actually achieve, mustbe best.62 These same defining principles must also hold of the virtueand vice of a city-state or a constitution, since a constitution is a sort of 40life of city-state. In all city-states, there are three parts of the city-state: the very rich, 1295'the very poor; and, third, those in between these. So, since it is agreedthat what is moderate and in a mean is best, it is evident that possessinga middle amount of the GOODS of luck is also best. For it most readily 5obeys reason, whereas whatever is exceedingly beautiful, strong, wellborn, or wealthy, or conversely whatever is exceedingly poor, weak, orlacking in honor, has a hard time obeying reason. For the former sorttend more toward ARROGANCE and major vice, whereas the latter tendtoo much toward malice and petty vice; and wrongdoing is caused in the 10one case by arrogance and in the other by malice.63 Besides, the middleclasses are least inclined either to avoid ruling or to pursue it, both ofwhich are harmful to city-states. Furthermore, those who are superior in the goods of luck (strength,wealth, friends, and other such things) neither wish to be ruled nor 15know how to be ruled (and this is a characteristic they acquire right fromthe start at home while they are still children; for because of their luxurious lifestyle they are not accustomed to being ruled, even in school).Those, on the other hand, who are exceedingly deprived of such goodsare too humble. Hence the latter do not know how to rule, but only howto be ruled in the way slaves are ruled, whereas the former do not knowhow to be ruled in any way, but only how to rule as masters rule. The re- 20suit is a city-state consisting not of free people but of slaves and masters,the one group full of envy and the other full of arrogance. Nothing isfurther removed from a friendship and a community that is political. Forcommunity involves friendship, since enemies do not wish to share evena journey in common. But a city-state, at least, tends to consist as muchas possible of people who are equal and similar, and this condition be- 25longs particularly to those in the middle. Consequently, this city-state, the one constituted out of those from which we say the city-state is nat urally constituted, must of necessity be best governed. Moreover, of all citizens, those in the middle survive best in city-states. For neither do 30 they desire other people's property as the poor do, nor do other people desire theirs, as the poor desire that of the rich. And because they are neither plotted against nor engage in plotting, they live out their lives free from danger. That is why Phocylides did well to pray: "Many things are best for those in the middle. I want to be in the middle in a city state."64 It is clear, therefore, that the political community that depends on 35 those in the middle is best too, and that city-states can be well governed where those in the middle are numerous and stronger, preferably than both of the others, or, failing that, than one of them. For it will tip the balance when added to either and prevent the opposing extremes from arising.65 That is precisely why it is the height of good luck if those who 40 are governing own a middle or adequate amount of property, because1296• when some people own an excessive amount and the rest own nothing, either extreme democracy arises or unmixed oligarchy or, as a result of both excesses, tyranny. For tyranny arises from the most vigorous kind of democracy and oligarchy,66 but much less often from middle constitu- 5 tions or those close to them. We will give the reason for this later when we discuss changes in constitutions.67 That the middle constitution is best is evident, since it alone is free from faction. For conflicts and dissensions seldom occur among the cit izens where there are many in the middle. Large city-states are also freer from faction for the same reason, namely, that more are many in the 10 middle. In small city-states, on the other hand, it is easy to divide all the citizens into two, so that no middle is left and pretty well everyone is ei ther poor or rich. Democracies are also more stable and longer lasting than oligarchies because of those in the middle (for they are more nu- 15 merous in democracies than in oligarchies and participate in office more), since when the poor predominate without these, failure sets in and they are quickly ruined. The fact that the best legislators have come from the middle citizens should be regarded as evidence of this. For 64. Diehl I.SO, fr. 1 0. Phocylides was a sixth century poet from Miletus. 65. By joining the poor it prevents extreme oligarchy; by joining the rich it pre vents extreme democracy. 66. See 1 3 1 2b34-38, 1 3 1 0b3-4. 67. Perhaps a reference to 1 308"18-24. Chapter l2 121 Solon was one of these, as is clear from his poems, as were Lycurgus (forhe was not a king), Charondas, and pretty well most of the others. 20 It is also evident from these considerations why most constitutionsare either democratic or oligarchic. For because the middle class in themis often small, whichever of the others preponderates (whether theproperty owners or the people), those who overstep the middle way con- 25duct the constitution to suit themselves, so that it becomes either ademocracy or an oligarchy. In addition to this, because of the conflictsand fights that occur between the people and the rich, whenever oneside or the other happens to gain more power than its opponents, theyestablish neither a common constitution nor an equal one, but take their 30superiority in the constitution as a reward of their victory and make inthe one case a democracy and in the other an oligarchy. Then too each ofthose who achieved leadership in Greece68 has looked to their own constitutions and established either democracies or oligarchies in citystates, aiming not at the benefit of these city-states but at their own. As a 35consequence of all this, the middle constitution either never comes intoexistence or does so rarely and in few places. For among those who havepreviously held positions of leadership, only one man69 has ever beenpersuaded to introduce this kind of organization, and it has now becomecustomary for those in city-states not even to wish for equality, but ei- 40ther to seek rule or to put up with being dominated . 1296b What the best constitution is, then, and why it is so is evident fromthese considerations. As for the other constitutions (for there are, as wesay, several kinds of democracies and of oligarchies), which of them is tobe put first, which second, and so on in the same way, according to 5whether it is better or worse, is not hard to see now that the best hasbeen determined. For the one nearest to this must of necessity always bebetter and one further from the middle worse-provided one is notjudging on the basis of certain assumptions. I say "on the basis of certain assumptions," because it often happens that, while one constitutionis more choiceworthy, nothing prevents a different one from being more 10beneficial for some. Chapter 1 2The next thing to go through after what has been said is which constitution and which kind of it is beneficial for which and which kind of peo- pie. First, though, a general point must be grasped about all of them, namely, that the part of a city-state that wishes the constitution to con- IS tinue must be stronger than any part that does not.7° Every city-state is made up of both quality and quantity. By "quality," I mean FREEDOM, wealth, education, and good birth; by "quantity," I mean the superiority of size. But it is possible that the quality belongs to one of the parts of 20 which a city-state is constituted, whereas the quantity belongs to an other. For example, the low-born may be more numerous than the well born or the poor more numerous than the rich, but yet the one may not be as superior in quantity as it is inferior in quality. Hence these have to be judged in relation to one another. Where the multitude of poor peo- 25 ple is superior in the proportion mentioned,71 there it is natural for a democracy to exist, with each particular kind of democracy correspond ing to the superiority of each particular kind of the people. For example, if the multitude of farmers is predominant, it will be the first kind of democracy; if the vulgar craftsmen and wage earners are, the last kind; 30 and similarly for the others in between these. But where the multitude of those who are rich and notable is more superior in quality than it is inferior in quantity, there an oligarchy is natural, with each particular kind of oligarchy corresponding to the superiority of the multitude of oligarchs, in the same way as before. 72 But the legislator should always include the middle in his constitu- 35 tion: if he is establishing oligarchic laws, he should aim at those in the middle, and if democratic ones, he must bring them in by these laws. And where the multitude of those in the middle outweighs either both of the extremes together, or even only one of them, it is possible to have 40 a stable constitution. For there is no fear that the rich and the poor will1297" conspire together against these, since neither will ever want to serve as slaves to the other; and if they look for a constitution that is more com mon than this, they will find none. For they would not put up with rul ing in turn, because they distrust one another; and an ARBITRATOR is 5 most trusted everywhere, and the middle person is an arbitrator. The better mixed a constitution is, the more stable it is. But many of those who wish to establish aristocratic constitutions make the mistake not only of granting more to the rich, but also of deceiving the people. Forsooner or later, false goods inevitably give rise to a true evil; for the ac- 10quisitive behavior of the rich does more to destroy the constitution thanthat of the poor. 73 Chapter 1 3The devices used in constitutions to deceive the people are five in num-ber, and concern the assembly, offices, the courts, weapons, and physical 15training. [ 1 ] As regards the assembly: allowing all citizens to attend assemblies, but either imposing a fine only on the rich for not attending, ora much heavier one on them. [2] As regards offices: not allowing thosewith an assessed amount of property to swear off,74 but allowing the poor 20to do so. [3] As regards the courts: fining the rich for not serving on ju-ries, but not the poor, or else imposing a large fine on the former and asmall one on the latter, as in the laws of Charondas. In some places,everyone who has enrolled may attend the assembly and serve on juries,but once they have enrolled, if they do not attend or serve, they are 25heavily fined. The aim is to get people to avoid enrolling because of thefine, and not to serve or to attend because of not being enrolled. Theylegislate in the same way where possessing hoplite arms and physicaltraining are concerned. [4] For the poor are permitted not to possess 30weapons, but the rich are fined if they do not; [5] and if they do nottrain, there is no fine for the former, but the latter are fined. That waythe rich will participate because of the fine, whereas the poor, not beingin danger of it, will not participate. These legislative devices are oligarchic; in democracies there are op- 35posite devices. For the poor are paid to attend the assembly and serve onjuries, and the rich are not fined for failing to. If one wants to mix justly,then, it is evident that one must combine elements from either side, andpay the poor while fining the rich. For in this way everyone would par- 40ticipate, whereas in the other way the constitution comes to belong toone side alone. The constitution should consist only of those who 1297bpossess weapons; but it is impossible unqualifiedly to define the size ofthe relevant property assessment, and say that it must be so much. One should instead look for what amount15 is the highest that would let thoseS who participate in the constitution outnumber those who do not, and fix on that. For the poor are willing to keep quiet even when they do not participate in office, provided no one treats them arrogantly or takes away any of their property (not an easy thing, however, since those who10 do participate in the governing class are not always cultivated people). People are also in the habit of shirking in time of war if they are poor and do not receive provisions; but if food is provided, they will fight. 76 In some places, the constitution consists not only of those who are serving as hoplites but also of those who have served as hoplites in the past. In Malea, the constitution consisted of both, although the officialsIS were elected from among the active soldiers. Also the first constitution that arose among the Greeks after kingships also consisted of the defen sive warriors.77 Initially, it consisted of the cavalrymen, since strength and superiority in war lay in them. For a hoplite force is useless without20 organized formations, and experience in such things and organizations did not exist among the ancients. Hence their strength lay in their cav alry. But as city-states grew larger and those with hoplite weapons be came a stronger force, more people came to participate in the constitu tion. That is precisely why what we now call polities used to be called25 democracies. But the ancient constitutions were oligarchic and kingly, and quite understandably so. For because of their small population they did not have much of a middle class, so that, being small in number and poor in organization, the people put up with being ruled. We have said, then, [ 1 ] why there are several constitutions-[1 . 1] why30 there are others besides those spoken of (for democracy is not one in number, and similarly with the others), [ 1 .2] what their varieties are, and [ 1 .3] why they arise. In addition, [2] we have said which constitution is best, for the majority of cases, and [3] among the other constitutions which suits which sort of people. Chapter 1 4 As regards what comes next, let us once again discuss constitutions gen-35 erally and each one separately, taking the starting point that is appropri- 82. Democratic constitutions favored election by lot, but were willing to make an exception when the office (for example, a generalship) required expert knowledge ( 1 3 17h20-21). 83. See 1 292'4-30. 84. Alternatively (Dreizehnter and the mss.): "elected or (e) chosen by lot." 85. Reading e with Dreizehnter. Chapter 15 127 to the courts. For they establish a fine for those people they want to haveon juries to ensure that they serve (whereas democrats pay the poor).The same should be done in the case of assemblies too, for they will deliberate better if they all deliberate together, the people with the nota- 20bles, and the latter with the multitude. It is beneficial too if those who dothe deliberating are elected, or chosen by lot, in equal numbers fromthese parts. And even if the democrats among the citizens86 are greatlysuperior in numbers, it is beneficial not to provide pay for all of them,but only for a number to balance the number of notables, or to exclude 25the excess by lot. In oligarchies, however, it is beneficial either to select some additionalpeople from the multitude of citizens to serve as officials or to establisha board of officials like the so-called preliminary councilors or lawguardians that exist in some constitutions, and then have the assemblydeal only with issues that have been considered by this board. In thisway, the people will share in deliberation, but will not be able to abolish 30anything connected to the constitution. It is also beneficial to have thepeople vote only on decrees brought before them that have already undergone preliminary deliberation, or on nothing contrary to them, orelse to let all advise and have only officials deliberate. One should in factdo the opposite of what happens in polities. 87 For the multitude should 35have authority when vetoing measures but not when approving them; inthe latter case, they should be referred back to the officials instead. Forin polities, they do the contrary, since the few have authority when veto-ing decrees but not when passing them; decrees of the latter sort are al-ways referred to the majority instead. 40 This, then, is the way the deliberative part, the part that has authorityover the constitution, should be determined. 88 1299" Chapter 1 5[2] Next after these things comes the division of the offices. 89 For thispart of a constitution too has many varieties: how many offices there are;with authority over what things; with regard to time: how long each 5 86. Reading politon with Ross rather than politikon ("statesmen") with Dreizehnter and the mss.87. Or constitutions generally.88. Reading dei . . . di0risthai with Dreizehnter.89. This topic is further discussed in Vl.8. 128 Politics IV office is to last (some make it six months, some less, some make it a year, some a longer period); and whether they are to be held permanently or for a long time, or neither of these, but instead to be held by the same person several times, or not even twice but only once; and further, as re-10 gards the selection of officials: from whom they should come, by whom, and how. For one should be able to determine how many ways all these can be handled, and then fit the kinds of offices to the kinds of constitu tions for which they are beneficial.I5 But even to determine what should be called an office is not easy. For a political community needs many sorts of supervisors, so that not everyone who is selected by vote or by lot can be regarded as an official. In the first place, for example, there are the priests: for a priesthood must be regarded as something other than and apart from the political offices. Besides, patrons of the theater and heralds are elected, ambas-20 sadors too. But some sorts of supervision are political, either concerned with all the citizens involved in a certain activity (as a general supervises those who are serving as soldiers) or some part of them (for example, the supervisors of women or children). Some are related to household man agement (for corn rationers are often elected),90 while others are subor dinate, and are of the sort that, when there are the resources, are as signed to slaves. Simply speaking, however, the offices most properly so called are25 those to which are assigned deliberation, decision, and issuing orders about certain matters, especially the latter, since issuing orders is most characteristic of office. This problem makes scarcely any difference in practice, but since terminological disputes have not been resolved, there30 is some theoretical work yet to be done. One might rather raise a problem with regard to any constitution about what sorts of offices and how many of them are necessary for the existence of a city-state,91 and which sorts, though not necessary, are yet useful with a view to an excellent constitution, but one might particu larly raise it with regard to constitutions in small city-states. For in large35 city-states one can and should assign a single office to a single task. For because there are many citizens, there are many people to take up office, so that some offices are held again only after a long interval and others are held only once. Also every task is better performed when its supervi- 90. In times of scarcity or when a gift of corn had been given to the city-state, a corn rationer (sitometres) was elected to distribute it among the citizens. 9 1 . Listed in VI.8. Chapter IS 1 29 92. A common claim, see 1 252h l -5, 127Jh9-15; also Plato, Republic 370a-b, 374a-c, 394e, 423c-d, 433a, 443b-c, 453b.93. A spit-lamp (obeliskoluchnion) was a military tool which could be used either as a roasting spit or as a lamp holder.94. See 1 298h26-1299'2. 1 30 Politics IV In the case o f each o f these varieties, there are four99 different ways toproceed. Either all select from all by election or all select from all bylot100 (and101 from all either by sections-by tribe, for example, or bydeme or clan, until all the citizens have been gone through---{)r from all 25on every occasion); or from some by election or from some by lot;102 orpartly in the first way and partly in the second. Again, if only some dothe selecting, they may do so either from all by election or from all bylot; or from some by election or from some by lot; or partly in the firstway and partly in the second-that is to say, for some from all by elec-tion and for some by lot. 103 This gives rise to twelve ways, setting aside 30two of the combinations. 104 Three of these ways of selecting are democratic, namely, when all select from all by election, by lot, or by both (thatis, for some offices by election and for some by lot). But when not all se-lect at the same time, but do so for all from all or from some, whether byelection, lot, or both, or from all for some offices and from some for oth- 35ers, whether by election, lot, or both (by "both," I mean some by lot andothers by election)-it is characteristic of a polity. When some appointfrom all, whether by election, lot, or both (for some offices by lot forothers by vote), it is oligarchic-although it is more oligarchic to do soby both. But when some offices are selected for from all and others from 40some or when some are selected for by election and some by vote, this is some are selectable, (2.2.3) all are selectable for some offices and some are selectable for others; (2.3 . 1) selection is by lot, (2.3.2) selection is by elec tion, (2.3.3) selection is by lot for some offices and by election for others. 99. Reading tettares with the mss in place of Ross's conjectural hex. The text of this entire paragraph is difficult, and many reorganizations and emenda tions have been proposed.100. Deleting the material added by Ross.101. Deleting ei, which Newman brackets.102. Adding e ek tinon hairesei e ek tiniin klero{i), which also appears at •28-29.103. Deleting the material added by Ross.104. The twelve ways referred to are: ( 1 ) all select from all by election; (2) all se lect from all by lot; (3) all select from some by election; (4) all select from some by lot; (5) all select from all partly by election and partly by lot; (6) all select from some partly by election and partly by lot; (7) some select from all by election; (8) some select from all by lot; (9) some select from some by election; ( 10) some select from some by lot; ( 1 1 ) some select from all partly by election and partly by lot; ( 1 2) some select from some partly by election and partly by lot. The two omitted combinations are: (2. 1 .3) all select for some offices and some select for others, and (2.2.3) all are selectable for some offices and some are selectable for others. 132 Politics IV Chapter 1 6 Of the three parts, 105 it remains to speak about [3] the judicial. And we must grasp the ways that it can be organized by following the same sup position as before. The differences between courts are found in three 15 defining principles: from whom; about what; and how. From whom: I mean whether they are selected from all or from some. About what: how many kinds of courts are there. How: whether by lot or by election. First, then, let us distinguish how many kinds of courts there are. They are eight in number. One is [i] concerned with inspection. Another 20 [ii] deals with anyone who wrongs the community. 106 Another [iii] with matters that affect the constitution. A fourth [iv] deals with officials and private individuals in disputes about fines. A fifth [v] deals with private transactions of some magnitude. Besides these there is [vi] a court that deals with homicide and [vii] one that deals with aliens. The kinds of homicide court, whether having the same juries or not, are: [vi. l ] that 25 concerned with premeditated homicide, [ vi.l] that concerned with in voluntary homicide, [vi.3] that concerned with cases where there is agreement on the fact of homicide but the justice of it disputed, and a fourth [ vi.4] concerned with charges brought against those who have been exiled for homicide after their return (the court of Phreatto in Athens107 is said to be an example), but such cases are rare at any timeeven in large city-states. The aliens' court has [ vii.l] a part for aliens dis- 30puting with aliens and [ vii.2] a part for aliens disputing with citizens.Besides all these, there is [viii] a court that deals with petty transactions:those involving one drachma, five drachmas, or a little more (for judgment must be given in these cases too, but it should not fall to a multi-tude of jurors to give it). 35 But let us set aside these courts as well as the homicide and aliens'courts and talk about the political ones, which, when not well managed,give rise to factions and constitutional changes. Of necessity, there arejust the following possibilities: [3 . 1] All decide all the cases just distinguished, and are selected either [3 . 1 . 1 ] by lot or [3 . 1 .2] by election; or[3 . 1 ] all decide all of them, and [3.1 .3] some are selected by lot and some 40by election; or, [3 . 1 .4] although dealing with the same case, some jurorsmay be selected by lot and some by election. Thus these ways are four innumber. [3.2] There are as many again when selection is from only some 1301•of the citizens. For here again either [3.2. 1] the juries are selected fromsome by election and decide all cases; or [3.2.2] they are selected fromsome by lot and decide all cases; or [3 .2.3] some may be selected by lotand some by election; or [3.2.4] some courts dealing with the same casesmay be composed of both members selected by lot and elected members. 5These ways, as we said, are the counterparts of the ones we mentionedearlier. [3.3] Furthermore, these same ones may be conjoined-! mean,for example, some may be selected from all, others from some, and oth-ers from both (as for example if the same court had juries selected partlyfrom all and partly from some); and the selection may be either by lot orby election or by both. We have now listed the possible ways the courts can be organized. Of 10these the first, [3 . 1 ] those which are selected from all and decide allcases, are democratic. The second [3 .2], those which are selected fromsome and decide all cases, are oligarchic. The third [3.3], those whichare partly selected from all and partly from some, are aristocratic orcharacteristic of a polity. 15 107. If someone exiled for involuntary homicide was charged with a second vol untary homicide, he could not enter Attica for trial, but he could offer his defense from a boat offshore at Phreatto, on the east side of Piraeus. B OOK V Chapter 120 Pretty well all the other topics we intended to treat have been discussed. Next, after what has been said, we should investigate: [ I ] the sources of change in constitutions, how many they are and of what sort; [2] what things destroy each constitution; [3] from what sort into what sort they principally change; further, [ 4] the ways to preserve constitutions in general and each constitution in particular; and, finally, [5] the means by which each constitution is principally preserved. 125 We should take as our initial starting point that many constitutions have come into existence because, though everyone agrees about justice (that is to say, proportional EQUALITY), they are mistaken about it, as we also mentioned earlier.2 For democracy arose from those who are equal in some respect thinking themselves to be unqualifiedly equal; for be-30 cause they are equally free, they think they are unqualifiedly equal. Oli garchy, on the other hand, arose from those who are unequaP in some respect taking themselves to be wholly unequal; for being unequal in property, they take themselves to be unqualifiedly unequal. The result is that the former claim to merit an equal share of everything, on the grounds that they are all equal, whereas the latter, being unequal, seek to35 get more (for a bigger share is an unequal one). All these constitutions possess justice of a sort, then, although unqualifiedly speaking they are mistaken. And this is why, when one or another of them does not partic ipate in the constitution in accordance with their assumption,4 they start faction. However, those who would be most justified in starting faction, 1 . (4) The ways to preserve a constitution; ( 5) the steps or devices needed to im- plement them. See 1 3 1 3'34-b32, 1 3 1 9b37-1 320b l 7 . 2. A t III.9. 3 . Specifically, superior ( 1 302b26-27). 4. About the nature of proportional equality. 134 Chapter 1 135 namely, those who are outstandingly virtuous, are the least likely to do 40so.5 For they alone are the ones it is most reasonable to regard as unqual- JJ01bifiedly unequal. There are also certain people, those of good birth, whosuppose that they do not merit a merely equal share because they are un-equal in this way. For people are thought to be noble when they have an-cestral wealth and virtue behind them. These, practically speaking, are the origins and sources of factions, 5the factors that lead people to start it. Hence the changes that are due tofaction are also of two kinds. [ 1 ] For sometimes people aim to change theestablished constitution to one of another kind-for example, fromdemocracy to oligarchy, or from oligarchy to democracy, or from theseto polity or aristocracy, or the latter into the former. [2] But sometimesinstead of trying to change the established constitution (for example, an 10oligarchy or a monarchy), they deliberately choose to keep it, but [2. 1 ]want to have it i n their own hands. Again, [2.2] it may be a question ofdegree: where there is an oligarchy, the aim may be to make the govern-ing class more oligarchic or less so; where there is a democracy, the aim 15may be to make it more democratic or less so; and similarly, in the case ofthe remaining constitutions, the aim may be to tighten or loosen them. 6Again, [2.3] the aim may be to change a certain part of the constitution,for example, to establish or abolish a certain office, as some say Lysandertried to abolish the kingship in Sparta, and King Pausanias the overseer- 20ship.7 In Epidamnus too the constitution was partially altered, since acouncil replaced the tribal rulers, though it is still the case that onlythose members of the governing class who actually hold office areobliged to attend the public assembly when election to office is takingplace. 8 (Having a single supreme official was also an oligarchic feature ofthis constitution.) 25 For faction is everywhere due to inequality, when unequals do not receive proportionately unequal things (for example, a permanent kingship is unequal if it exists among equals). For people generally engage infaction in pursuit of equality. But equality is of two sorts: numerical Chapter 2 Since we are investigating the sources from which both factions and changes arise in constitutions, we must first grasp their general origins and causes. There are, roughly speaking, three of these, each of which 20 must first be determined in outline by itself. We must grasp [ 1 ] the con dition people are in when they start faction, [2] for the sake of what, and, 9. At III.9. 10. The basis of aristocracy. 11. Omitting kai aporoi ("and poor ones") with Dreizehnter and the mss. 12. See 1296'13-18, where a somewhat different explanation is offered. Chapter 3 137 third, [3] what the origins are of political disturbances and factionsamong people. [ 1] The principal general cause of people being in some way disposedto change their constitution is the one we have in fact already mentioned. For those who desire equality start faction when they believethat they are getting less, even though they are the equals of those who 25are getting more; whereas those who desire inequality (that is to say, superiority) do so when they believe that, though they are unequal, theyare not getting more but the same or less. (Sometimes these desires arejust, sometimes unjust.) For inferiors start factions in order to be equal, 30and equals do so in order to be superior. So much for the condition ofthose who start faction. [2] The things over which they start such faction are profit, honor,and their opposites. For people also start faction in city-states to avoiddishonor and fines, either for themselves or for their friends. [3] The causes and origins of the changes, in the sense of the factorsthat dispose people to feel the way we described about the issues we 35mentioned, are from one point of view seven in number and from another more. Two are the same as those just mentioned, but not in theirmanner of operation. For people are also stirred up by profit and honornot simply in order to get them for themselves, which is what we said be-fore, but because they see others, whether justly or unjustly, getting more. 40Other causes are: ARROGANCE, fear, superiority, contempt, and dispropor- 13026tionate growth. Still other ones, although operating in another way, areelectioneering, carelessness, gradual alteration, and dissimilarity. 13 Chapter 3The effect of arrogance and profit, and the way the two operate, are 5pretty much evident. For when officials behave arrogantly and become 1 3 . The seven causes mentioned at '36-37 are profit, honor, arrogance, fear, su periority, contempt, and disproportionate growth in power. The two points of view are: ( l ) treating profit and honor as two causes each of which oper ates in two ways and (2) treating these two ways of operating as distinct causes. If (2) is adopted, there are then more than seven causes. Of the four causes mentioned in the final sentence, the first three (electioneering, care lessness, and gradual alteration) cause political change, but not by giving rise to faction in the way the initial seven (or nine) do (1 303' 1 3 -1 4) . The fourth (dissimilarity) also gives rise to faction, at least "until people learn to pull together" ( 1 303'25-26). 138 Politics V acquisitive, people start faction with one another and with the constitu tions that gave the officials authority. (Sometimes their ACQUISITIVE NESS is at the expense of private properties, sometimes at that of public funds.)10 It is also clear what honor is capable of, and how it causes faction. For people start faction both when they themselves are dishonored and when they see others being honored. This occurs unjustly when people are honored or dishonored contrary to their merit; justly, when it ac cords with merit. Superiority causes faction when some individual or group of individ-1S uals is too powerful for the city-state and for the power of the governing class. For the usual outcome of such a situation is a monarchy or a dy nasty. That is why some places, such as Argos and Athens, have a prac tice of ostracism. Yet it is better to see to it from the beginning that no one can emerge whose superiority is so great than to supply a remedy af-20 terwards. 14 People start faction through fear both when they have committed in justice and are afraid of punishment and when they think they are about to suffer an injustice and wish to avoid becoming its victims. The latter occurred in Rhodes when the notables united against the people because of the lawsuits being brought against them.1525 People also start faction and hostilities because of contempt. For ex- ample, this occurs in oligarchies when those who do not participate in the constitution are in a majority (since they consider themselves the stronger party), 16 and in democracies, when the rich are contemptuous of the disorganization and anarchy. Thus the democracy in Thebes col lapsed because they were badly governed after the battle of Oenophyta, 1730 as was the democracy of the Megarians when they were defeated be cause of disorganization and anarchy. 18 The same happened to the democracy in Syracuse before the tyranny of Gelon,19 and to the one in Rhodes prior to the revolt. 20 Changes also occur in constitutions because of disproportionate growth. For just as a body is composed of parts which must grow in pro- 35portion if balance is to be maintained (since otherwise it will be destroyed, as when a foot is four cubits [six feet] long, for example, and therest of the body two spans [fifteen inches]; or, if the disproportionategrowth is not only quantitative but also qualitative, its shape mightchange to that of another animal), 21 so a city-state too is composed of 40parts, one of which often grows without being noticed-for example, 1303"the multitude of the poor in democracies or polities. This sometimesalso happens because of luck. Thus a democracy took the place of apolity in Tarentum when many notables were killed by the lapygiansshortly after the Persian wars. 22 In Argos too, after the death of those cit- Sizens killed on the seventh23 by the Spartan Cleomenes, the notableswere forced to admit some of their SUBJECT PEOPLES to citizenship; andin Athens, when they had bad luck fighting on land, the notables werereduced in number, because at the time of the war against Sparta thoseserving in the army were drawn from the citizen service-list.24 This sort 10of change also occurs in democracies, though to a lesser extent. Forwhen the rich become more numerous or their properties increase insize, democracies change into oligarchies or polities. But constitutions also change without the occurrence of faction, bothbecause of electioneering, as happened in Heraea (for they replacedelection with selection by lot for this reason, that those who election- 1Seered were elected), and also because of carelessness, when people whoare not friendly to the constitution are allowed to occupy the offices withsupreme authority. Thus the oligarchy in Oreus was overthrown when 24. Lists were kept of those citizens eligible for service in the cavalry, hoplites, or navy. During the Peloponnesian war (43 1-404), the army was recruited from the wealthier citizens, whereas in Aristotle's day it often consisted of mercenaries. 140 Politics V 25. The events in Heraea are otherwise unknown. The changes in Oreus, also called Hestiaea ( 1303h33), occurred in 377 when it revolted from the Spar tans and joined the Athenian Confederacy. 26. See 1290h38-1291 b 1 3, 1326' 16-25, 1328b 16-17. 27. The expelled Troezenians were received at Croton, which destroyed Sybaris in 510. The precise nature of the curse is unknown, but to drive out fellow colonists would have been viewed as a great sacrilege. 28. Nothing is known about this conflict, or about the one in Antissa mentioned in the next sentence. 29. The conflict at Zancle is described in Herodotus VI.22-24. 30. That is to say, after the fall ofThrasybulus in 467. 3 1 . Also referred to at 1 306'2-4. The original Athenian settlers were driven out and Amphipolis was incorporated into the powerful Chalcidian Confeder acy in around 370. Chapter 4 141 that they are treated unjustly because they do not participate equally, inspite of being equal. In democracies, the notables do so because they do Sparticipate equally, in spite of not being equal Y City-states also occasionally become factionalized because of their location, when their territory is not naturally suitable for a city-state thatis a unity. In Clazomenae, for example, the inhabitants of Chytrus cameinto conflict with those on the island, as did the inhabitants of Colophonand those of Notium.33 At Athens, too, the people are not all similar, but 10those in Piraeus are more democratic than those in the town. For just asin battles, where crossing even small ditches breaks up the phalanx, soevery difference seems to result in factional division. The greatest factional division is probably between virtue and vice; next that between 1Swealth and poverty; and so on for the others, including the one we havejust discussed, with each one greater than the next. Chapter 4Factions arise from small issues, then, but not over them; it is over important issues that people start faction. Even small factions gain greaterpower, however, when they arise among those in authority,34 as happenedin Syracuse in ancient times. For the constitution underwent change be- 20cause two young men in office started a faction about a love affair. 35While the first was away, the second, though his comrade, seduced hisboyfriend. The first, enraged at him, retaliated by inducing the second'swife to commit adultery. The upshot was that they drew the entire gov- 25erning class into their quarrel and split it into factions. That is preciselywhy one should be circumspect when such things are beginning, andbreak up the factions of leaders and powerful men. For the error arises atthe beginning, and "well begun is half done," as the saying goes. Consequently, even a small error at the beginning is comparable in effect to all 30the errors made at the later stages. 36 37. Referred to as Oreus at 1303•1 8 . Nothing else is known about this event, which must have occurred prior to the absorption of Hestiaea by Athens in 446. 38. See Thucydides III.Z-50. 39. An agent (proxenos), like a consul or ambassador, was the representative of one city-state to another, but he was a citizen of the latter, not the former. 40. With Thebes (355-347), relating to control of the temple of Apollo at Del phi, which was situated on Phocian territory. The War was ended by Philip of Macedon. Mnason seems to have been a friend of Aristotle's. Chapter 4 143 tighter;41 in return, the seafaring crowd, who were responsible for vic-tory at Salamis, and so for hegemony based on sea power, made thedemocracy more powerful.42 In Argos the notables, having acquiredprestige in connection with the battle against the Spartans at Mantinea, 25undertook to overthrow the democracy. In Syracuse the people, havingbeen responsible for victory in the war against the Athenians, changedthe constitution from a polity to a democracy. In Chalcis the people,with the aid of the notables, overthrew the tyrant Phoxus, and then immediately took control of the constitution. Similarly, in Ambracia the 30people joined with the opponents of Periander to expel him and afterwards took the constitution into their own hands.43 Generally speaking,then, this should not be overlooked-that the people responsible for acity-state's power, whether private individuals, officials, tribes, or, in aword, a part or multitude of any sort, start faction. For either those who 35envy them for being honored start a faction, or they themselves, becauseof their superior achievement, are unwilling to remain as mere equals. Constitutions also undergo change when parts of a city-state that areheld to be opposed, such as the rich and the people, become equal to oneanother, and there is little or no middle class. For if either of the parts J304bbecomes greatly superior, the other will be unwilling to risk going upagainst their manifestly superior strength. That is why those who areoutstandingly virtuous do not cause any faction, practically speaking, forthey are few against many. 5 In general, then, the origins and causes of conflict and change are ofthis sort in all constitutions. But people change constitutions sometimesthrough force, sometimes through deceit. Force may be used right at thebeginning or later on. Deceit is also employed in two ways. Sometimesthey first deceive the others into consenting to a change in the constitu- 10tion and then later keep hold of it by force when the others no longerconsent. Thus the Four Hundred44 deceived the Athenian people bytelling them that the King of Persia would provide money for the war 4 1 . That is to say, less democratic ( 1290•22-29). Prior to the mid fifth century the Areopagus consisted of wealthy citizens of noble birth and was a power fully oligarchic component of the Athenian constitution.42. The navy was recruited from the poorest classes and was a powerfully de mocratic force in Athenian politics. See 1321'1 3-14; Plato, Republic 396a-b, Laws 707b-c.43. In c. 580. Further details are given at 1 3 1 1'39-b l .44. The oligarchy which replaced the democracy at Athens in 4 1 1 , described in Thucydides VIII.45-98. 144 Politics V against the Spartans, and, having deceived them, tried to keep the conIS stitution in their own hands. At other times, they persuade them at the beginning, and continue to persuade them later on and rule with their consent. Simply stated, then, changes generally occur in all constitutions as a result of the factors that have been stated. Chapter 5 We must now take each kind of constitution separately and study what happens to it as a result of these factors.20 Democracies undergo change principally because of the wanton be- havior of popular leaders,45 who sometimes bring malicious lawsuits against individual property owners, causing them to join forces (for a shared fear unites even the bitterest enemies), and at others, openly egg on the multitude against them. One may see this sort of thing happening25 in many instances. In Cos the democracy was overthrown when evil pop ular leaders arose (for the notables banded together),46 and also in Rhodes. For the popular leaders provided pay for public service and pre vented the naval officials from getting what they were owed; the latter were then forced to unite and overthrow the democracy because of the30 lawsuits brought against them.47 Right after the colony was settled, the democracy in Heraclea was also overthrown because of its popular lead ers. For the notables were treated unjustly by them and went into exile. Later the exiles united, returned home, and overthrew the democracy.35 The democracy in Megara48 was overthrown in a somewhat similar way. For the popular leaders expelled many of the notables in order to declare the latters' wealth public property, until they made numerous exiles. The exiles then returned, defeated the people in battle, and established an oligarchy.49 A similar thing happened to the democracy in Cyme, Democracies also change from the traditional kind to the newest kind. For when officials are elected, but not on the basis of a property assess- 30 ment, and the people do the electing, those seeking office, in order to curry favor, bring matters to this point, that the people have authority even over the laws. A remedy that prevents this, or diminishes its effect, is to have the tribes nominate the officials rather than the people as a whole. Pretty well all the changes in democracies, then, happen for these rea- 40 sons. Chapter 6 Oligarchies principally undergo change in two ways that are most evi dent. [ 1 . 1 ] The first is when they treat the multitude unjustly. 57 For any leader is adequate for the task when that happens, particularly if he comes from the ranks of the oligarchs themselves, like Lygdamis of Naxos, who actually became tyrant of the Naxians later on. 58 There are130Sb also several other varieties of faction that originate with other people. 59 [ 1 .2] For sometimes the overthrow comes from the rich themselves, though not the ones in office, when those holding the offices are very S few. This occurred in Massilia, lstrus, Heraclea, and other city-states, where those who did not participate in office agitated until first elder brothers and then younger ones were admitted. (For in some city-states, a father and son, and in others, an elder and younger brother, may not hold office simultaneously.) In Massilia, the oligarchy became more like 10 a polity; the one in Istrus ended in a democracy; and the one in Heraclea went from a small number to six hundred. [ 1 .3] The oligarchy in Cnidus also changed when the notables became factionalized because so few participated in office, and, as was mentioned, if a father participated, his 1S son could not, nor, if there were several brothers, could any but the el dest alone. For while they were engaged in faction, the people inter vened in the conflict, picked one of the notables as their leader, attacked, and were victorious (for what is factionalized is weak). And in Erythrae in ancient times, during the oligarchy of the Basilids, even though those with authority over the constitution governed well, the people neverthe- 20 less resented being ruled by a few and changed the constitution.60 6 1 . The oligarchy of the Thirty Tyrants, of which Charicles was a member, was in control of Athens for a brief period in 404/3. The oligarchy of the Four Hundred gained control there in 41 1 . See Ath. XXVIII-XXXVIII.62. See 1 268'22, note.63. Nothing is known about this event.64. In 406-405.65. Nothing is known about this event.66. Chares was an Athenian general at the head of a troop of mercenaries sta tioned in Corinth in 367 (a likely date for his negotiations). 148 Politics V 67. The thieves attack the oligarchs to avoid punishment; their opponents do so if they sanction the theft of publilfunds. Nothing is known about the event referred to. 68. Nothing is known about this oligarchy. 69. See 1271'9-18. 70. Timophanes became tyrant in 350, during the war with Argos, and was later killed by his brother Timolean. See Plutarch, Timoleon IV.4-8. 7 1 . The Aleuds were a great Thessalian family. The Simus referred to is most probably the one who helped bring Thessaly into subjection to Philip of Macedon in 342. Nothing is know about the events in Abydos. 72. At 1 303b37-1304' 17. Chapter 7 1 49 Chapter 7[ I ] In aristocracies factions arise because few people participate in of-fice, which is just what is said to change oligarchies as well, 76 becausearistocracy too is oligarchy of a sort. For the rulers are few in both,though not for the same reason. At any rate, that is why an aristocracy 25too is thought to be a kind of oligarchy. [ 1 . 1 ] Such conflict is particularlyinevitable [ 1 . 1 . 1 ] when there is a group of people who consider themselves equal in virtue to the ruling few-for example, the so-called Sons 73. Nothing is known about these events. Pillory was not a punishment com- monly inflicted on notables.74. See l 3QSh l 2-18. Nothing is known about the events in Chios.75. See 1 292'4-6 (democracies), 1292hS-10 (oligarchies).76. At 1 306'13-22. I SO Politics V 30 of the Maidens at Sparta (for they were descended from the Equals), who were discovered in a conspiracy and sent off to colonize Taren tum;77 or [ 1 . 1 .2] when powerful men who are inferior to no one in virtue are dishonored by others who are more esteemed, as Lysander was by the kings; or [ 1 . 1 .3] when a man of courage does not participate in office, like Cinadon, who instigated the rebellion against the Spartiates in the 35 reign of Agesilaus;78 or, again, [ 1 .2] when some people are very poor and others very rich, a situation which is particularly prevalent in wartime, and also happened in Sparta at the time of the Messenian war (this is clear from the poem of Tyrtaeus called "Good Government"), 79 for1307" those who were hard pressed because of the war demanded a redistribu tion of the land; or, again, [ 1 .3] when there is a powerful man capable of becoming still more powerful, who instigates conflict in order to become sole ruler, as Pausanias (who was general during the Persian war) is held S to have done in Sparta, and Annan in Carthage. 80 [2] Polities and aristocracies are principally overthrown, however, be cause of a deviation from justice within the constitution itself. For what begins the process in a polity is failing to get a good mixture of democ racy and oligarchy, and in an aristocracy, failing to get a good mixture of these and virtue as well, but particularly the two. I mean by the two 10 democracy and oligarchy, since these are what polities and most so called aristocracies try to mix. For aristocracies differ from what are termed polities in this,81 and this is why the former of them are less and 77. The Equals (homoioi) were Spartan citizens, born of citizen parents, who possessed sufficient wealth to enable them to participate in the communal meals (see 127 1'25-37). Various ancient accounts are given of the Sons of the Maidens: they were the offspring of Spartans degraded to the rank of helots for failing to serve in the First Messanian War; they were the illegiti mate sons of young unmarried Spartan women who were encouraged to in crease the population during that war; or they were the sons of adulterous Spartan women conceived while their husbands were fighting in that war. They founded Tarentum in 708. 78. Lysander was a Spartan general whose plans were thwarted by king Pausa nius in 403, and later by king Agesilaus. Cinadon's rebellion of 398 was dis covered and he was executed. See Xenophon, Hellenica 11.4.29; Plutarch, Lysander XXIII. 79. See Diehl l.7-9, fr. 2-5 . Tyrtaeus was a seventh century Spartan elegiac poet. 80. Annon's identity is uncertain. He may be the Carthaginian general of that name who fought against Dionysius II in Sicily, c. 400. 8 1 . In their way of mixing democracy and oligarchy. Chapter 7 151 the latter more stable. For those constitutions that lean more toward oligarchy get called aristocracies, whereas those that lean more toward the 15multitude get called polities. That is why, indeed, the latter sort are moresecure than the former. For the majority of citizens are the more power-ful party and they are quite content with an equal share; whereas if therich are granted superiority by the constitution, they act arrogantly andtry to get even more for themselves. Generally speaking, whichever direction a constitution leans is the di- 20rection in which it changes when either party grows in power, for exam-ple, polity into democracy and aristocracy into oligarchy. Or it changesin the opposite direction; for example, aristocracy changes into democ-racy (when the poorer people pull it toward its opposite because they arebeing unjustly treated), and polity changes into oligarchy. For the only 25stable thing is equality in accordance with merit and the possession ofprivate property. The aforementioned change82 occurred at Thurii. Because the property assessment for holding office was rather high, achange was made to a smaller one and to a larger number of offices. Butbecause the notables illegally acquired all the land (for the constitution 30was still too oligarchic), they were able as a result to get more. But thepeople, who had received military training during the war, provedstronger than the garrison troops, and forced those who had more thantheir fair share of the land to give it up. Moreover, [3] because all aristocratic constitutions are oligarchic incharacter, the notables in them tend to get more. Even in Sparta, for ex- 35ample, properties keep passing into fewer and fewer hands. The notablesare also freer to do as they please and make marriage alliances as theyplease. The city-state of the Locrians was ruined, indeed, because amarriage alliance was formed with the tyrant Dionysius, something thatwould not have occurred in a democracy or a well-mixed aristocracy. 83 [4] Aristocracies are particularly apt to change imperceptibly by being 40overturned little by little. This is precisely what was said earlier as a gen- 1307hera! point about all constitutions,84 namely, that even a small thing cancause them to change. For once one thing relating to the constitution is 82. From aristocracy to democracy. Nothing is known for certain about the events referred to.83. Locri accepted a marriage alliance with Dionysius I, who was tyrant of Syracuse 367-356, 346-343. Later (starting in 3 56) it suffered under the oppressive tyranny of the offspring of this marriage, Dionysius II.84. At 1 303'20-1304h 1 8. 152 Politics V Chapter 8 Our next topic is the preservation of constitutions generally and each kind of constitution separately. [ I ] It is clear, in the first place, that if we know what destroys a constitution, we also know what preserves it. For opposites are productive of opposite things, and destruction is opposite30 to preservation. In well-mixed constitutions, then, if care should be taken to ensure that no one breaks the law in other ways, small violations should be particularly guarded against. For illegality creeps in unno ticed, in just the way that property gets used up by frequent small ex penditures: the expense goes unnoticed because it does not occur all at35 once. For the mind is led to reason fallaciously by them, as in the so- phistical argument "if each is small, all are also." In one way this is true;in another false: the whole composed of all the parts is not small, but itis composed of small parts. One thing to guard against, then, is destruction that has a starting point of this sort. [2] Secondly, we must not put our faith in the devices that are designed to deceive the multitude, since they are shown to be useless by 40the facts. (I mean the sort of devices used in constitutions that we dis 1308"cussed earlier. )87 [3) Next, we should notice that not only some aristocracies but alsosome oligarchies survive, not because their constitutions are secure, butbecause those in office treat well both those outside the constitution and sthose in the governing class. They do this by not being unjust to thenonparticipants and by bringing their leading men into the constitution;by not being unjust to those who love honor by depriving them of honor,or to the many by depriving them of profit; and by treating each other,the ones who do participate, in a democratic manner. For what democ 10rats seek to extend to the multitude, namely, equality, is not only just forthose who are similar but also beneficial. That is why, if the governingclass is large, many democratic legislative measures prove beneficial, forexample, having offices be tenable for six months in order that all thosewho are similar can participate in them. For those who are similar are al JSready a people of a sort, which is why popular leaders arise even amongthem, as we mentioned earlier. 88 Furthermore, oligarchies and aristocracies of this sort are less likely to fall into the hands of dynasties. For officials who rule a short time cannot so easily do wrong as those who rule along time. For this is what causes tyrannies to arise in oligarchies and 20democracies, since in both constitutions, the ones who attempt to establish a tyranny are either the most powerful (popular leaders in democracies, dynasts in oligarchies) or those who hold the most important offices, and hold them for a long time. [4) Constitutions are preserved not only because of being far awayfrom what destroys them, but sometimes too because they are nearby.89 25For fear makes people keep a firmer grip on the constitution. Hencethose who are concerned about their constitution should excite fears andmake faraway dangers seem close at hand, so that the citizens will de- fend the constitution and, like sentries on night-duty, never relax their 30 guard. [5] Moreover, one should try to guard against the rivalries and fac tions of the notables, both by means of the laws and by preventing those who are not involved in the rivalry from getting caught up in it them selves. For it takes no ordinary person to recognize an evil right from the beginning but a man who is a statesman. [6] As for change from an oligarchy or a polity because of property as- 35 sessments-if it occurs while the assessments remain the same but money becomes more plentiful, it is beneficial to discover what the total communal assessment is compared with that of the past; with that of last 40 year's in city-states with annual assessment, with that of three or five130!Jb years ago in larger city-states. If the total is many times greater or many times less than it was when the rates qualifying someone to participate in the constitution were established, it is beneficial to have a law that tightens or relaxes the assessment; tightening it in proportion to the in- S crease if the total has increased, relaxing it or making it less if the total has decreased. For when oligarchies and polities do not do this, the re sult is that if the total has decreased, an oligarchy arises from the latter and a dynasty from the former, and if it has increased, a democracy 10 arises from a polity and either a polity or a democracy from an oligarchy. [7] It is a rule common to democracy, oligarchy, monarchy, and every constitution not to allow anyone to grow too great or out of all due pro portion, but to try to give small honors over a long period of time rather than large ones quickly. For people are corrupted by major honors, and not every man can handle good luck.9° Failing that, constitutions should at least try not to take away all at once honors that have been awarded all 1S at once, but to do so gradually. They should try to regulate matters by means of the laws, indeed, so as to ensure that no one arises who is far superior in power because of his friends or wealth. Failing that, they should ensure that such men are removed from the city-state by being ostracized.9 1 [8] But since people also attempt to stir up change because of their 20 private lives, an office should be set up to keep an eye on those whose lifestyles are not beneficial to the constitution, whether to the democ racy in a democracy, to the oligarchy in an oligarchy, or similarly for each of the other constitutions. For the same reasons, one must guardagainst the prospering of the city-state one part at a time. 92 A remedy for 25this is always to place the conduct of affairs and the offices in the handsof opposite parts. (I mean that the decent are opposite to the multitude,the poor to the rich.) Another remedy is to try to mix the multitude ofthe poor with that of the rich or to increase the middle class, since thisdissolves faction caused by inequality. 30 [9] But the most important thing in every constitution is for it havethe laws and the management of other matters organized in such a waythat it is impossible to make a profit from holding office.93 One shouldpay particular heed to this in oligarchies. For the many are not as resent-ful at being excluded from office-they are even glad to be given the 35leisure to attend to their private affairs-as they are when they thinkthat officials are stealing public funds. At any rate, they are then painedboth at not sharing in office and at not sharing in its profits. Indeed, theonly way it is possible for democracy and aristocracy to coexist is ifsomeone instituted this,94 since it would then be possible for both the 40notables and the multitude to have what they want. For allowing every- 1309"one to hold office is democratic, but having the notables actually holdthe offices is aristocratic. But this is what will happen if it is impossibleto profit from office. For the poor will not want to hold office, becausethere is no profit in it, but will prefer to attend to their private affairs, 5whereas the rich will be able to hold it, because they need no supportfrom public funds. The result will be that the poor will become richthrough spending their time working, and the notables will not have tobe ruled by anybody and everybody. But to prevent public funds frombeing stolen, the transfer of the money95 should take place in the pres- 10ence of all citizens, and copies of the accounts should be deposited witheach clan, company,96 and tribe. And to ensure that people will hold of-fice without seeking profit, there should be a law that assigns honors toreputable officials. Chapter 9 Those who are to hold the offices with supreme authority should pos sess three qualities: first, friendship for the established constitution; 35 next, the greatest possible capacity for the tasks of office; third, in each constitution the sort of virtue or justice that is suited to the constitution (for if what is just is not the same in all constitutions, there must be dif ferences in the virtue of justice as well). But there is a problem. When all of these qualities are not found in the same person, how is the choice to 40 be made? For example, if one man is an expert general but is vicious and1301Jh no friend to the constitution, whereas another is just and friendly to it, how should the choice be made? It seems that one should consider two things: which quality does everyone have a larger share in, and which a smaller one? That is why, in the case of a generalship, one should con sider experience more than virtue. For everyone shares in generalship 5 less, but in decency more. In the case of guardianship or stewardship, on the other hand, the opposite holds. For these require more virtue than the many possess, but the knowledge they require is common to all. One might also raise the following problem. If someone has the capacity for the tasks of office as well as friendship for the constitution, why does he Chapter 9 157 also need virtue, since even the first two will produce beneficial results? 10Or is it possible for someone who possesses these two qualities to beweak-willed, so that just as people can fail to serve their own interestswell even though they have the knowledge and are friendly to themselves, so nothing prevents them from behaving in the same way wherethe common interest is concerned? Simply speaking, everything in laws that we say is beneficial to constitutions also preserves those constitutions, as does the most important 1Sfundamental principle, so often mentioned, of keeping watch to ensurethat the multitude that wants the constitution is stronger than the multitude that does not.97 In addition to all this, one thing must not be overlooked, which is infact overlooked by deviant constitutions: the mean. For many of thethings that are held to be democratic destroy democracies, and many 20that are held to be oligarchic destroy oligarchies. But those who thinkthat this98 is the only kind of virtue push the constitution to extremes.They do not know that constitutions are just like parts of the body. Astraight nose is the most beautiful, but one that deviates from beingstraight and tends toward being hooked or snub can nevertheless still bebeautiful to look at. Yet if it is tightened still more toward the extreme, 2Sthe part will first be thrown out of due proportion, and in the end it willcease to look like a nose at all, because it has too much of one and too lit-tle of the other of these opposites. The same holds of the other parts aswell. This can also happen in the case of the constitutions. For it is pos- 30sible for an oligarchy or a democracy to be adequate even though it hasdiverged from the best organization. But if someone tightens either ofthem more, he will first make the constitution worse, and in the end itwill not be a constitution at all. That is why legislators and statesmen JSshould not be ignorant about which democratic features preserve ademocracy and which destroy it, or which oligarchic features have theseeffects on an oligarchy. For neither of these constitutions can exist andsurvive without rich people and the multitude, but when a leveling ofproperty occurs, the resulting constitution is necessarily of a differentkind. Hence by destroying these classes through extreme legislation, 40they destroy their constitution. 131()' A mistake is made in both democracies and oligarchies. In democra-cies popular leaders make it where the multitude have authority over the laws. For they divide the city-state in two by always fighting with theS rich, yet they should do the opposite, and always be regarded as spokes men for the rich. In oligarchies, the oligarchs should be regarded as spokesmen for the people, and should take oaths that are the opposite of the ones they take nowadays. For in some oligarchies, they now swear "and I will be hostile to the people and will plan whatever wrongs I can10 against them." But they ought to hold and to seem to hold the opposite view, and declare in their oaths that "I will not wrong the people."99 But of all the ways that are mentioned to make a constitution last, the most important one, which everyone now despises, is for citizens to be educated in a way that suits their constitutions. For the most beneficialIS laws, even when ratified by all who are engaged in politics, are of no use if people are not habituated and educated in accord with the constitu tion-democratically if the laws are democratic and oligarchically if they are oligarchic. For if weakness of will indeed exists in a single indi vidual, it also exists in a city-state. But being educated in a way that suits20 the constitution does not mean doing whatever pleases the oligarchs or those who want a democracy. Rather, it means doing the things that will enable the former to govern oligarchically and the latter to have a demo cratic constitution. In present-day oligarchies, however, the sons of the rulers live in luxury, whereas the sons of the poor are hardened by exer cise and toil, so that the poor are more inclined to stir up change and are2S better able to do so. In those democracies that are held to be particularly democratic, the very opposite of what is beneficial has become estab lished. The reason for this is that they define freedom incorrectly. For there are two things by which democracy is held to be defined: by the majority being in supreme authority and by freedom. For justice is held30 to be equality; equality is for the opinion of the multitude to be in au thority; and freedom is doing whatever one likes. So in democracies of this sort everyone lives as he likes, and "according to his fancy," as Eu ripides says. 100 But this is bad. For living in a way that suits the constitu-35 tion should be considered not slavery, but salvation.10 1 Such, then, simply speaking, are the sources of change and destruc tion in constitutions, and the factors through which they are preserved and maintained. Chapter 1 0It remains to go through monarchy too, both the sources of its destruc-tion and the means by which it is naturally preserved. What happens in 40the case of kingships and tyrannies is pretty much similar to what wesaid happens in constitutions. For kingship is akin to aristocracy, and 131(/tyranny is a combination of ultimate oligarchy and ultimate democ-racy. 1 02 That is why, indeed, tyranny is also the most harmful to those itrules, seeing that it is composed of two bad constitutions and involves 5the deviations and errors of both. Each of these kinds of monarchy comes to be from directly oppositecircumstances. For kingship came into existence to help the decentagainst the people, 103 and a king is selected from among the decent men 10on the basis of a superiority in virtue, or in the actions that spring fromvirtue, or on the basis of a superiority of family of this sort. A tyrant, onthe other hand, comes from the people (that is to say, the multitude) tooppose the notables, so that the people may suffer no injustice at theirhands. This is evident from what has happened. For almost all tyrantsbegan as popular leaders who were trusted because they abused the no- 15tables. For some tyrannies were established in this way in city-states thathad already grown large. Other earlier ones arose when kings departedfrom ancestral customs and sought to rule more in the manner of a mas-ter. Others were established by people elected to the offices that havesupreme authority; for in ancient times, the people appointed "doers of 20the people's business" and "sacred ambassadors" to serve for long peri-ods of time. 104 Still others arose in oligarchies that gave a single electedofficial authority over the most important offices. For in all these wayspeople could easily become tyrants if only they wished, because of thepower they already possessed through the kingship or through other 25 high office. Thus Pheidon of Argos and others became tyrants having al ready ruled as kings; the Ionian tyrants and Phalaris as a result of their high office; and Panaetius in Leontini, Cypselus in Corinth, Pisistratus 30 in Athens, Dionysius in Syracuse, and likewise others, from having been popular leaders. 105 Kingship is, then, as we said, 106 an organization like aristocracy, since it is based on merit, whether individual or familial virtue, or on benefac tions, or on these together with the capacity to perform them. For all those who obtained this office either had benefited or were capable of 35 benefiting their city-states or nations. Some, like Codrus, saved their people from enslavement in war; others, like Cyrus, set them free; oth ers acquired or settled territory, like the kings of the Spartans, Macedo- 40 nians, and Molossians. 107 A king tends to be a guardian, seeing to it that1311• property owners suffer no injustice and the people no arrogance. But tyranny, as has often been said, 108 never looks to the common benefit ex cept for the sake of private profit. A tyrant aims at what is pleasant; a king at what is noble; and that is why it is characteristic of a tyrant to be 5 most acquisitive of wealth 109 and of a king to be most acquisitive of what is noble. Also, a king's bodyguard consists of citizens, whereas a tyrant's consists of foreigners. 1 10 That tyranny has the vices of both democracy and oligarchy is evi- 10 dent. From oligarchy comes its taking wealth to be its end (for, indeed, only in this way can the tyrant possibly maintain his bodyguard and his luxury), and its mistrust of the multitude (which is why, indeed, tyrants deprive them of weapons). It is common to both constitutions (oligarchy and tyranny) to ill-treat the multitude, drive them out of the town, and 15 disperse them. From democracy, on the other hand, comes its hostility 1 05. Pheidon as tyrant in the middle of the seventh century. Phalaris was a no toriously cruel sixth-century tyrant of Agrigentum in Sicily. For Pisistra tus, see 1 305'23-24 note. Cypselus was tyrant of Corinth c. 655-625. Dionysius is Dionysius I. 1 06. At 1 3 1 0b2-3. 1 07. Codrus was a legendary early king of Athens. According to one traditional account he was already king when he gave his life to prevent Athens from Dorian invasion. Cyrus was the first ruler of the Persian empire (559-529); he freed Persia from the Medes in 559. Neoptolemus, the son of Achilles, conquered the Molossians and became their king. 1 08. For example, at 1279h6-1 0, 1295' 1 7-22. 109. On the connection between wealth and the pursuit of pleasure, see 1257h40-1258'5. l lO. See 1285'24-29. Chapter 10 161 t o the notables, its destruction o f them both b y covert and overt means,and its exiling of them as rivals in the craft of ruling and impediments toits rule. For it is from the notables that conspiracies arise, since some ofthem wish to rule themselves, and others not to be enslaved. Hence toothe advice that Periander gave to Thrasybulus when he cut down the 20tallest ears of corn, namely, that it is always necessary to do away withthe outstanding citizens. 1 1 1 A s has pretty much been said, then, one should consider the sourcesof change both in CONSTITUTIONS and in monarchies to be the same.For it is because of injustice, fear, and contemptuous treatment that 25many subjects attack monarchies. In the case of injustice, arrogance isthe principal cause, but sometimes too the seizure of private property.The ends sought are also the same there as in tyrannies and kingships,since monarchs possess the great wealth and high office that everyone 30desires. In some cases, attack is directed against the person of the rulers; inothers, against their office. Those caused by arrogance are directedagainst the person. Arrogance has many forms, but each of them is acause of anger; and most angry people act out of revenge, not ambition. 35For example, the attack on the Pisistratids took place because theyabused Harmodius' sister and showed contempt for Harmodius himself(for Harmodius attacked because of his sister, and Aristogeiton becauseof Harmodius). 112 People plotted against Periander, tyrant of Ambracia,because once when he was drinking with his boyfriend, he asked 40whether he was pregnant by him yet. Philip was attacked by Pausanias 131 Jhbecause he allowed him to be treated arrogantly by Attalus and his co-terie.113 Amyntas the Little was attacked by Derdas because he boastedof having deflowered him. 1 14 The same is true of the attack on Evagorasof Cyprus by a eunuch;115 he felt arrogantly treated because Evagoras' 5son had taken away his wife. Many attacks have also occurred because of the shameful treatment ofother people's bodies by certain monarchs. The attack on Archelaus116 1 1 1 . See 1284'26-33.1 12. The attack on the Athenian Pisistratid tyranny in 5 14 is discussed in Ath. XVIII, Herodotus V.55-65, Thucydides VI.54-9.1 13 . Philip of Macedon was murdered by Pausanius (a young Macedonian) in 330.1 14. Amyntas and Dardas are otherwise unknown.1 1 5. Evagoras ruled Salamis in Cyprus from 41 1 until his death in 374.1 16. King of Macedon 4 13-399. See Plutarch, Amatorius 23. 1 62 Politics V 30 monarchy but fame. Nevertheless, very few people are impelled by this sort of motive, since it presupposes a total disregard for their own safety in the event that the action is not successful. They must be guided by the same fundamental principle as Dion (something that is not easy for most people). For Dion accompanied by a small force marched against 35 Dionysius, saying that whatever point he was able to reach, he would be satisfied to have completed that much of the enterprise, and that if, for example, he were killed after having just set foot on land, he would have a noble death. Like each of the other constitutions, one way a tyranny is destroyed is 40 from the outside, if there is a more powerful constitution opposed toJ]J2b it.126 For the wish to destroy a tyranny will clearly be present, because the deliberate choices of the two are opposed; and people always do what they wish when they have the power. The constitutions opposed to tyranny are democracy, kingship, and aristocracy. Democracy is opposed to it as "potter to potter" (as Hesiod puts it), 127 since the extreme sort of S democracy is also a tyranny. 128 Kingship and aristocracy are opposed to it because of opposition of constitution. That is why the Spartans over threw a large number of tyrannies, as did the Syracusans while they were well governed . Another way a tyranny is destroyed is from within, when those partic ipating in it start a faction. This happened in the tyranny of the family of 10 Gelon and, in our own time, in that of the family of Dionysius. The tyranny of Gelon was destroyed when Thrasyboulus, the brother of Hiero, curried favor with Gelon's son and led him into a life of sensual pleasure, in order that he himself might rule. The family got together to destroy not the entire tyranny, but Thrasyboulus. 129 But those who 1S joined them seized the opportunity and expelled all of them. Dion, who was related by marriage to Dionysius, marched against him, won over the people, and expelled him, but was himself killed afterwards. The two principal motives people have for attacking tyrannies are ha tred and contempt. Of them, hatred always attaches to tyrants, but many overthrows are due to contempt. Evidence of this is the fact that most of 20those who won the office of tyrant held onto it, whereas their successorsalmost all lost it right away. For living lives of indulgence, they easily became contemptible and gave others ample opportunity to attack them. 25Anger must also be considered a part of the hatred, since in a way itgives rise to the same sorts of actions. Often, in fact, it is more conducive to action than hatred. For angry people attack more vehementlybecause passion does not employ rational calculation. People are particularly apt to be led by their angry spirit on account of arrogant treatment. This was the cause of both the overthrow of the Pisistratid 30tyranny and that of many others. But hatred employs calculation morethan anger does. For anger involves pain, and pain makes rational calculation difficult; but hatred does not involve pain. To speak summarily, however, the causes that we said destroy unmixed or extreme oligarchies and extreme democracies should also be 35regarded as destroying tyranny. For these are in fact divided tyrannies. 1 30 Kingship is destroyed least by outside factors, which is also why it islong-lasting. The sources of its destruction generally come from within.It is destroyed in two ways: first, when those who participate in the king-ship start faction, and, second, when the kings try to manage affairs in a 1313•more tyrannical fashion, claiming that they deserve to have authorityover more areas than is customary, and to be beyond the law. Kingshipsno longer arise nowadays, but if any do happen to occur, they tend moreto be tyrannical monarchies. 1 3 1 This is because kingship is rule over will-ing subjects and has authority over more important matters. But nowa- 5days there are numerous men of equal quality, although none so outstanding as to measure up to the magnitude and dignity of the office ofking. Hence people are unwilling to put up with this sort of rule. And ifsomeone comes to exercise it, whether through force or deceit, this isimmediately held to be a tyranny. In the case of kingships based on lineage, there is something besides 10the factors already mentioned that should be considered a cause of theirdestruction, namely, the fact that many kings easily become objects ofcontempt and behave arrogantly, even though they exercise kingly office,not tyrannical power. For then overthrow is easy. For a king whose sub- Chapter 1 1 It is clear, to put it simply, that monarchies are preserved by the opposite causes.132 But kingships in particular are preserved by being made more 20 moderate. For the fewer areas over which kings have authority, the longer must their office remain intact. For they themselves become less like masters, more equal in their characters, and less envied by those they rule. That is also why the kingships of the Molossians lasted a long time, and that of the Spartans as well. In the latter case it was because 25 the office was divided into two parts from the beginning, and again be cause Theopompus, besides moderating it in other ways, instituted the office of the overseers. 133 By diminishing the power of the kingship he increased its duration, so that in a way he made it greater, not lesser. He is supposed to have given precisely this answer, indeed, when his wife 30 asked him whether he was not ashamed to hand over a lesser kingship to his sons than the one he had inherited from his father: "Certainly not," he said, "for I am handing over one that will be longer lasting. " Tyrannies134 are preserved in two quite opposite ways. One of them is 35 traditional and is the way most tyrants exercise their rule. Periander of Corinth is said to have instituted most of its devices, but many may also be seen in the Persian empire. These include the device we mentioned some time ago135 as tending to preserve a tyranny (to the extent that it 40 can be preserved): [ I ] cutting down the outstanding men and eliminat ing the high-minded ones. Others are: [2] Prohibiting messes, clubs, ed-13131 ucation, and other things of that sort. [3] Keeping an eye on anything that typically engenders two things: high-mindedness and mutual trust. [4] Prohibiting schools and other gatherings connected with learning,136 and doing everything to ensure that people are as ignorant of one another as possible, since knowledge tends to give rise to mutual trust. [5] 5Requiring the residents to be always in public view and to pass theirtime at the palace gates. 137 For their activities will then be hard to keepsecret and they will become humble-minded from always acting likeslaves. [6] Imposing all the other restrictions of a similar nature that arefound in Persian and non-Greek tyrannies (for they are all capable ofproducing the same effect). 10 [7] Another is trying to let nothing done or said by any of his subjectsescape notice, but to retain spies, like the so-called women informers ofSyracuse, or the eavesdroppers that Hiero138 sent to every meeting orgathering. For people speak less freely when they fear the presence ofsuch spies, and if they do speak freely, they are less likely to go unno- 15ticed. [8] Another is to slander people to one another, setting friendagainst friend, the people against the notables, and the rich againstthemselves. [9] It is also tyrannical to impoverish the people, so thatthey cannot afford a militia and are so occupied with their daily workthat they lack the leisure for plotting. The pyramids of Egypt, the 20Cypselid monuments, the construction of the temple of Olympian Zeusby the Pisistratids, and the works on Samos commissioned by Polycratesare all examples of this. 139 For all these things have the same result, lackof leisure and poverty for the ruled. [ 1 0] And there is taxation, as in 25Syracuse, when, during the reign of Dionysius, 140 taxation ate up a person's entire estate in five years. [ 1 1 ] A tyrant also engages in warmonger-ing in order that his subjects will lack leisure and be perpetually in needof a leader. And while a kingship is preserved by its friends, it is themark of a tyrant to distrust his friends, on the grounds that while all his 30subjects wish to overthrow him, these are particularly capable of doingso.l41 All the practices found in the extreme kind of democracy are alsocharacteristic of a tyranny: [ 1 2] the dominance of women in the household, in order that they may report on the men, and [ 1 3] the license ofslaves for the same reason. For slaves and women not only do not plot 35against tyrants but, because they prosper under them, are inevitably well disposed toward tyrannies and toward democracies as well (for the peo ple too aspire to be a monarch). That is why a flatterer is honored in both constitutions-in democracies, the popular leader (for the popular 40 leader is a flatterer of the people), in tyrannies, those who are obse quious in their dealings with the tyrant, which is precisely a task for flat-1314• tery. For that is also why tyranny loves vice. For tyrants delight in being flattered. But no free-minded person would flatter them. On the con trary, decent people act out of friendship, not flattery. 142 The vicious are 5 also useful for vicious tasks-"nail to nail," as the saying goes.143 And it is characteristic of a tyrant not to delight in anyone who is dignified or free-minded. For a tyrant thinks that he alone deserves to be like that. But anyone who is a rival in dignity or free-mindedness robs tyranny of its superiority and its status as a master of slaves, and so tyrants hate him as a threat to their rule. And it is also characteristic of a tyrant to have foreigners rather than people from the city-state as dinner guests and 10 companions, on the grounds that the former are hostile to him, whereas the latter oppose him in nothing. These devices are characteristic of tyrants and help preserve their rule, but there is no vice they leave out. They all fall into three cate- J5 gories, broadly speaking. For tyranny aims at three things: first, that the ruled think small, for a pusillanimous person would plot against no one;144 second, that they distrust one another, for a tyranny will not be overthrown until some people trust each other. This is also why tyrants attack decent people. They view them as harmful to their rule not only 20 because they refuse to be ruled as by a master, but also because they command trust among both themselves and others, and do not inform on one another or on anyone else. Third, that the ruled be powerless to act. For no one tries to do what is impossible, and so no one tries to over- 25 throw a tyranny if he lacks the power. Thus the wishes of tyrants may be reduced in fact to these three defining principles, since all tyrannical aims might be reduced to these three tenets: that the ruled not trust one another; that they be powerless; that they think small. 142. A true friend loves one for one's own qualities; a flatterer is someone who seems to do this but does not. If decent people seem friendly it will be be cause they are so, not because they are engaging in flattery (Rh. 1371'17-24). 143. More usually, "nail is driven out by nail," but here something like "it takes a nail to do a nail's work." 144. See NE 1 123b9-26, 1 1 25'19-27. Chapter 11 169 145. Since tyranny differs from kingship in being rule over unwilling subjects.146. Of rendering public accounts and seeming to take care of public funds.147. The mss. have "political virtue (politike areti)." 170 Politics V 2S jects, but neither should any of his followers. The women of his house hold should also be similarly respectful toward other women, as the ar rogant behavior of women has caused the downfall of many tyrannies. Where bodily pleasures are concerned, the tyrant should do the oppo site of what some in fact do. For they not only begin their debaucheries 30 at dawn and continue them for days on end, but they also wish to be seen doing so by others, in order that they may be admired as happy and blessed. But above all the tyrant should be moderate in such matters, or failing that, he should at least avoid exhibiting his indulgence to others. For it is not easy to attack or despise a sober or wakeful man, but it is 3S easy to attack or despise a drunk or drowsy one. [4] A tyrant must do the opposite of pretty well all the things we men tioned a while back. 148 For he must lay out and beautify the city-state as if he were a household steward rather than a tyrant. Again, [5] a tyrant should always be seen to be very zealous about matters concerning the gods, but without appearing foolish in the process. For people are less afraid of suffering illegal treatment at the 40 hands of such people. And if they regard their ruler as a god-fearing131 s• man who pays heed to the gods, they plot against him less, since they think that he has the gods on his side. [6] A tyrant should so honor those who prove to be good in any area S that they do not expect that they would be more honored by citizens liv ing under their own laws. He should bestow such honors himself, but punishments should be administered by other officials and by the courts. But it is a precaution common to every sort of monarchy not to make any one man important, but where necessary to elevate several, so that they will keep an eye on one another. If it happens to be necessary to make one man important, however, at all events it should not be some- 10 one of courageous character. For men of this sort are the most enterpris ing in any sphere of action. And if it is considered necessary to remove someone from power, his prerogatives should be taken away gradually, not all at once. [7] A tyrant should refrain from all forms of arrogance, and from two IS in particular: corporal punishment and arrogance toward adolescents. This is particularly true where those who love honor are concerned. For while lovers of money resent contemptuous acts affecting their prop erty, honor lovers and decent human beings resent those involving dis- honor. Hence either he should not treat people in these ways or else he 20should appear to punish like a father, not out of contempt; and to engagein sexual relations with young people out of sexual desire, and not as if itwere a prerogative of his office. And as a general rule, he should compensate apparent dishonors with yet greater honors. Of those who makeattempts on his life, a tyrant should most fear and take the greatest pre- 25cautions against those who are ready to sacrifice their own lives to destroy him. Hence he should be particularly wary of people who thinkthat he has behaved arrogantly toward them or those they happen tocherish. For people who attack out of anger are careless of themselves.As Heraclitus said, "Anger is a hard enemy to combat, because it pays 30for what it wants with life."149 [8] Since city-states consist of two parts, poor and rich, it is best ifboth believe that they owe their safety to the tyrant's rule, and that neither is unjustly treated by the other because of it. But whichever of themis the stronger should be particularly attached to his rule, so that with JShis power thus increased he will not need to free slaves or confiscateweapons. For the latter of the two parts added to his force will be enoughto make them stronger than attackers. But it is superfluous to discuss all such measures in detail. For their 40aim is evident. A tyrant should appear to his subjects not as a tyrant butas a head of household and a kingly man, not as an embezzler but as a 131Sbsteward. He should also pursue the moderate things in life, not excess,maintaining close relations with the notables, while playing the popularleader with the many. For as a result, not only will his rule necessarily benobler and more enviable, but since he rules better people who have notbeen humiliated he will not end up being hated and feared. And his rule Swill be longer lasting, and his character will either be nobly disposed tovirtue or else half good, not vicious but half vicious. 10 Chapter 1 2Yet, the shortest-lived of all constitutions are oligarchy and tyranny. Forthe longest lasting tyranny was that of Orthagoras and his sons inSicyon. It lasted a hundred years. 150 This was because they treated their 149. Diels-Kranz B85. Heraclitus of Ephesus (c. 540-480) was one of the greatest of the Presocratic philosophers.1 50. The tyranny was founded in 670. Cleisthenes was grandson of Orthagoras and grandfather of the Athenian reformer of the same name. 172 Politics V not become good men. But how could this sort of change be any morepeculiar to the constitution he says is best than common to all the othersand to everything that comes into existence? Yes, and is it during this pe-riod of time, 155 due to which, as he says, everything changes, that eventhings that did not begin to exist at the same time change at the same 1Stime? If something comes into existence on the day before the comple-tion of the cycle, for example, does it still change at the same time aseverything else? Furthermore, why does the best constitution changeinto a constitution of the Spartan sort? For all constitutions more oftenchange into their opposites than into the neighboring one. 156 The sameremark also applies to the other changes. For he says that the Spartan 20constitution changes to an oligarchy, then to a democracy, then to atyranny. Yet change may also occur in the opposite direction. For exam-ple, from democracy to oligarchy, and to it more than to monarchy. Moreover, he does not tell us whether tyranny undergoes change, or 25what causes it to change, if it does. Nor does he tell us what sort of constitution it changes into. The reason for this is that he could not easilyhave told us, since the matter is undecidable, although according to himit should change into his first or best constitution, since that wouldmake the cycle continuous. But in fact tyranny can also change into another tyranny, as the constitution at Sicyon changed from the tyranny ofMyron to that of Cleisthenes; into oligarchy, like that of Antileon in 30Chalcis; into democracy, like that of Gelon and his family at Syracuse;and into aristocracy, like that of Charillus in Sparta [or the one inCarthage]. 1 57 Change also occurs from oligarchy to tyranny, as happened in most of JSthe ancient oligarchies in Sicily: in Leontini, it was to the tyranny ofPanaetius; in Gela, to that of Cleander; in Rhegium, to that of Anaxi-laus; and similarly in many other city-states. 158 It is also absurd to holdthat a constitution changes into an oligarchy because the office holdersare money lovers and acquirers of wealth, 159 and not because those who 40are far superior in property holdings think it unjust for those who do not 1316b own anything to participate equally in the city-state with those who do. And in many oligarchies office holders are not only not allowed to ac quire wealth, but there are laws to prevent it. On the other hand, in5 Carthage, which is governed timocratically, 160 the officials do engage in acquiring wealth, and it has not yet undergone change. It is also absurd to claim that an oligarchic city-state is really two city states, one of the rich and one of the poor. 161 For why is this any more true of it than of the Spartan constitution, or any other constitution where the citizens do not all own an equal amount of property or are not10 all similarly good men? And even when no one becomes any poorer than he was, constitutions still undergo change from oligarchy to democracy, if the poor become a majority, or from democracy to oligarchy, if the rich happen to be more powerful than the multitude, and the latter are careless, while the former set their mind to change. Also, though there are many reasons why oligarchies change into democracies, Socrates15 mentions but one: poverty caused by riotous living and paying interest on loans162-as if all or most of the citizens were rich at the start. But this is false. Rather, when some of the leading men lose their properties, they stir up change; but when some of the others do so, nothing terrible happens. And even when change does occur, it is no more likely to result20 in a democracy than in some other constitution. Besides, if people have no share in office or are treated unjustly or arrogantly, they start factions and change constitutions, even if they have not squandered all their property through being free to do whatever they like (the cause of which, Socrates says, is too much freedom). 16325 Although there are many kinds of oligarchies and democracies, Socrates discusses their changes as if there were only one of each. Chapter 1We have already discussed 1 the number and varieties of the deliberative 30and authoritative elements of constitutions, the ways of organizing of-fices and courts, which is suited to which constitution, and also what theorigins and causes are of the destruction and preservation of constitutions.2 But since it turned out that there are several kinds of democra- 35cies, and similarly of the other constitutions, we would do well to consider whatever remains to be said about these, and to determine whichways of organizing things are appropriate for and beneficial to each ofthem. Moreover, we have to investigate the combinations of all the ways of 40organizing the things we mentioned. For these, when coupled, causeconstitutions to overlap, resulting in oligarchic aristocracies and democ- 1317•ratically inclined polities. I mean those couplings which should be inves-tigated but at present have not been. For example, where the deliberativepart and the part that deals with the choice of officials are organized oligarchically, but the part that deals with the courts is aristocratic; or 5where the part that deals with the courts and the deliberative part areoligarchic, and the part that deals with the choice of officials is aristo-cratic; or where, in some other way, not all the parts appropriate to theconstitution are combined.3 We have already discussed4 the question of which kind of democracyis suited to which kind of city-state; similarly, which kind of oligarchy is 10suited to which kind of people; and which of the remaining constitutions is beneficial for which. Still, since we should make clear not onlywhich kind of constitution is best for a city-state, but also how it and the 1. At IV. 14-16.2. AtV. 1-12.3. These combinations are not discussed in the Politics as we have it.4. At IV. 12. 175 176 Politics VI Chapter 2 40 The fundamental principle of the democratic constitution is freedom. For it is commonly asserted that freedom is shared only in this sort of13J7b constitution, since it is said that all democracies have it as their aim. One component of freedom is ruling and being ruled in turn. For democratic justice is based on numerical equality, not on merit.7 But if this is what 5 justice is, then of necessity the multitude must be in authority, and whatever seems right to the majority, this is what is final and this is whatis just, since they say that each of the citizens should have an equalshare. The result is that the poor have more authority than the rich indemocracies. For they are the majority, and majority opinion is in authority. This, then, is one mark of freedom which all democrats take as a 10goal of their constitution. Another is to live as one likes. This, they say, isthe result of freedom, since that of slavery is not to live as one likes.This, then, is the second goal of democracy. From it arises the demandnot to be ruled by anyone, or failing that, to rule and be ruled in turn. In I5this way the second goal contributes to freedom based on equality. From these presuppositions and this sort of principle arise the following democratic features: [ I ] Having all choose officials from all. [2] Hav-ing all rule each and each in turn rule all. [3] Having all offices, or all 20that do not require experience or skill, filled by lot. [4] Having no prop-erty assessment for office, or one as low as possible. [5] Having no office,or few besides military ones, held twice or more than a few times by thesame person. [6] Having all offices or as many as possible be short-term.[7] Having all, or bodies selected from all, decide all cases, or most of 25them, and the ones that are most important and involve the most author-ity, such as those having to do with the inspection of officials, the constitution, or private contracts. [8] Having the assembly have authority overeverything or over all the important things, but having no office with authority over anything or over as little as possible. The council is the most 30democratic office in city-states that lack adequate resources to payeveryone, but where such resources exist even this office is stripped ofits power. For when the people are well paid, they take all decisions intotheir own hands (as we said in the inquiry preceding this one).8 [9] Hav-ing pay provided, preferably for everyone, for the assembly, courts, and 35public offices, or failing that, for service in the offices, courts, council,and assemblies that are in authority, or for those offices that require theirholders to share a mess. Besides, since oligarchy is defined by family,wealth, and education, their opposites (low birth, poverty, and vulgarity) 40are held to be characteristically democratic.9 [ 1 0] Furthermore, it is democratic to have no office be permanent; and if such an office happens 1318" to survive an ancient change, to strip it of its power, at least, and have it filled by lot rather than by election. These, then, are the features commonly found in democracies. And from the type of justice that is agreed to be democratic, which consists in everyone having numerical equality, comes what is held to be most of S all a democracy and a rule by the people, since equality consists in the poor neither ruling more than the rich nor being alone in authority, but in all ruling equally on the basis of numerical equality, since in that way they would consider equality and freedom to be present in the constitu- 10 tion. Chapter 3 The next problem that arises is how they will achieve this equality. Should they divide assessed property so that the property of five hun dred citizens equals that of a thousand others, and then give equal power to the thousand as to the five hundred?10 Or is this not the way to pro duce numerical equality? Should they instead divide as before, then take IS an equal number of citizens from the five hundred as from the thousand and give them authority over the elections and the courts? Is this the constitution that is most just from the point of view of democratic jus tice? Or is it the one based on quantity? For democrats say that whatever seems just to the greater number constitutes justice, 1 1 whereas oligarchs say that it is whatever seems just to those with the most property. For 20 they say that quantity of property should be the deciding factor. But both views are unequal and unjust. For if justice is whatever the few de cide, we have tyranny, since if one person has more than the others who are rich, then, from the point of view of oligarchic justice, it is just for him alone to rule. 12 On the other hand, if justice is what the numerical 25 majority decide, they will commit injustice by confiscating the property of the wealthy few (as we said earlier). 1 3 What sort of equality there might be, then, that both would agree on is something we must investigate in light of the definitions of justice 1 0. We have two groups, one of five hundred (the rich), another of one thou sand (the poor), each of which has the same amount of property. If we so distribute political power that each group has the same amount, have we treated both the rich and the poor as numerical equality demands? 1 1 . See 1 3 1 7bS-7 12. See 1 283h13 -27. 13. At 1281'14-28. Chapter 4 1 79 they both give. For they both say that the opinion of the MAJORITY of thecitizens should be in authority. So let this stand, though not fully. Instead, since there are in fact two classes in a city-state, the rich and the 30poor, whatever is the opinion of both or of a majority of each shouldhave authority. But if they are opposed, the opinion of the majority (thatis to say, the group whose assessed property is greater) should prevail.Suppose, for example, that there are ten rich citizens and twenty poorones, and that six of the rich have voted against fifteen of the poorerones, whereas four of the rich have sided with the poor, and five of the JSpoor with the rich. When the assessed properties of both the rich andthe poor on each side are added together, the side whose assessed prop-erty is greater should have authority. If the amounts happen to be equal,this should be considered a failure for both sides, as it is at present whenthe assembly or the court is split, and the question must be decided by 40lot or something else of that sort. 131Sb Even if it is very difficult to discover the truth about what equalityand justice demand, however, it is still easier than to persuade people ofit when they have the power to be ACQUISITIVE. For equality and justiceare always sought by the weaker party; the strong pay no heed to them. S Chapter 4Of the four kinds of democracy, the first in order is the best, as we saidin the discussions before these. 14 It is also the oldest of them all. But Icall it first as one might distinguish people. For the first or best kind ofpeople is the farming kind, and so it is also possible to create a democ-racy where the multitude live by cultivating the land or herding flocks. 10For because they do not have much property, they lack leisure and can-not attend meetings of the assembly frequently. And because they donot15 have the necessities, they are busy at their tasks and do not desireother people's property. Indeed, they find working more pleasant thanengaging in politics and holding office, where no great profit is to be had 1Sfrom office, since the many seek money more than honor. Evidence ofthis is that they even put up with the ancient tyrannies, and continue toput up with oligarchies, so long as no one prevents them from workingor takes anything away from them. For in no time some of them become 20 rich, while the others at least escape poverty. Besides, having authority over the election and inspection of officials will give them what they need, if they do have any love of honor. In fact, in some democracies, the multitude do not participate in the election of officials; instead, electors are selected from all the citizens by turns, as in Mantinea; yet if they 25 have authority over deliberation, they are content. (This arrangement too should be regarded as a form of democracy, as it was at Mantinea.) That is why, indeed, in the aforementioned kind of democracy, it is both beneficial and customary for all the citizens to elect and inspect of ficials and sit on juries, but for the holders of the most important offices 30 to be elected from those with a certain amount of assessed property (the higher the office, the higher the assessment), or alternatively for officials not to be elected on the basis of property assessments at all, but on the basis of ability. People governed in this way are necessarily governed well; the offices will always be in the hands of the best, while the people will consent and will not envy the decent; and this organization is neces- 35 sarily satisfactory to the decent and reputable people, since they will not be ruled by their inferiors, and will rule justly because the others have authority over the inspection of officials. For to be under constraint, and not to be able to do whatever seems good, is beneficial, since freedom to 40 do whatever one likes leaves one defenseless against the bad things that131 Ci' exist in every human being. So the necessary result, which is the very one most beneficial in constitutions, is that the decent people rule with out falling into wrongdoing and the multitude are in no way short changed. It is evident, then, that this is the best of the democracies, and also the 5 reason why: that it is because the people are of a certain kind. And for the purpose of establishing a farming people, some of the laws that ex isted in many city-states in ancient times are extremely useful, for exam ple, prohibiting the ownership of more than a certain amount of land under any circumstances, or else more than a certain amount situated between a given place and the city-state's town. And there used to be a 10 law in many city-states (at any rate, in ancient times) forbidding even the sale of the original allotments of land, 16 and also one, said to derive from Oxylus, 17 with a similar sort of effect, forbidding lending against more than a certain portion of each person's land. Nowadays, however, one should also attempt reform by using the law of the Aphytaeans, as it too is useful for the purpose under discussion. For though the citizens of 15Aphytis are numerous and have little land, they all engage in farming,because property assessments are based not on whole estates18 but onsuch small subdivisions of them that even the poor can exceed the assessment. After the multitude of farmers, the best sort of people consists ofherdsmen, who get their living from livestock. For herding is in many 20respects similar to farming, and where military activities are concerned,they are particularly well prepared, because they are physically fit andable to live in the open. The other multitudes, of which the remainingkinds of democracies are composed, are almost all very inferior to these. 25For their way of life is bad, and there is no element of virtue involved inthe task to which the multitude of vulgar craftsmen, tradesmen, and laborers put their hand. 19 Furthermore, because they wander around themarketplace and town, practically speaking this entire class can easily at-tend the assembly. Farmers, on the other hand, because they are scat- 30tered throughout the countryside, neither attend so readily nor have thesame need for this sort of meeting. But where the lay of the land is suchthat the countryside is widely separated from the CITY-STATE, it is eveneasier to create a democracy that is serviceable and a CONSTITUTION. For 35the multitude are forced to make their settlements out in the countryareas, so that, even if there is a whole crowd that frequents the marketplace, one should simply not hold assemblies in democracies without themultitude from the country. How, then, the best or first kind of democracy should be establishedhas been described. But how the others should be established is also evident. For they should deviate in order from the best kind, always ex- 40eluding a worse multitude.20 The ultimate democracy, because everyone participates in it, is not 131CJhone that every city-state can afford;21 nor can it easily endure, if its lawsand customs are not well put together. (The factors that cause the de- struction of this and other constitutions have pretty well all been dis- 5 cussed earlier.)22 With a view to establishing this sort of democracy and making the people powerful, the leaders usually admit as many as possi ble to citizenship, including not only the legitimate children of citizens but even the illegitimate ones, and those descended from citizens on only one side (I mean their mother's or their father's). For this whole10 class are particularly at home in this sort of democracy. This, then, is how popular leaders usually establish such a constitution; yet they should add citizens only up to the point where the multitude outnumber the notables and middle classes, and not go beyond this. For when they do overshoot it, they make the constitution more disorderly and provoke15 the notables to such an extent that they find the democracy hard to en dure (which was in fact the cause of the faction at Cyrene).23 For a small class of worthless people gets overlooked, but as it grows larger it gets more noticed.20 Also useful to a democracy of this kind are the sorts of institutions that Cleisthenes used in Athens when he wanted to increase the power of the democracy, and that those setting up the democracy used at Cyrene.24 For different and more numerous tribes and clans should be created, private cults should be absorbed into a few public ones, and25 every device should be used to mix everyone together as much as possi ble and break up their previous associations. Furthermore, all tyrannical institutions are held to be democratic. I mean, for example, the lack of supervision of slaves (which may really be beneficial to a democracy up to a certain point), or of women or children,25 and allowing everyone to30 live as he likes. For many people will support a constitution of this sort, since for the many it is more pleasant to live in a disorderly fashion than in a temperate one. Chapter 5 For a legislator, however, or for those seeking to establish a constitution of this kind, setting it up is not the most important task nor indeed the 22. In V.S . 2 3 . Perhaps the revolution o f 401 i n which five hundred rich people were put to death. 24. The reforms of Cleisthenes are described in Ath. XXI. The reference to the democracy at Cyrene may be to the one established there in 462. 25. On this sort of supervision, see 1 300'4-8, 1 322b37-1 323'6. The advantage of not having it in a democracy is explained at 1 3 1 3b32-39, 1 323'3-6. Chapter 5 1 83 only one, but rather ensuring its preservation. For it is not difficult for 35those who govern themselves in any old way to continue for a day oreven for two or three days. That is why legislators should make use ofour earlier studies of what causes the preservation and destruction ofconstitutions, and from them try to institute stability, carefully avoidingthe causes of destruction, while establishing the sort of LAWS, both writ-ten and unwritten, which best encompass the features that preserve con- 40 stitutions. They should consider a measure to be democratic or oli- 132(1'garchic not if it will make the city-state be as democratically governed oras oligarchically governed as possible, but if it will make it be so for thelongest time. Popular leaders nowadays, however, in their efforts to curry favor withthe people, confiscate a lot of property by means of the courts. That is 5why those who care about the constitution should counteract this bypassing a law that nothing confiscated from a condemned person shouldbecome common property, but sacred property instead. For wrongdoerswill be no less deterred, since they will be fined in the same way as be-fore, whereas the crowd will less frequently condemn defendants, since 10they will gain nothing by doing so. Public lawsuits too should always bekept to an absolute minimum, and those who bring frivolous o nesshould be deterred by large fines.26 For they are usually brought againstnotables, not democrats; but all the citizens should be well disposed toward the constitution, or, failing that, they should at least not regard 15those in authority as their enemiesY Since the ultimate democracies have large populations that cannot eas-ily attend the assembly without wages, where they also happen to have adearth of revenues, this is hostile to the notables. For the wages have to beobtained from taxes, confiscations of property, and corrupt courts- 20things that have already brought down many democracies. Where revenues are lacking, then, few assemblies should be held, and courts withmany jurors should be in session for only a few days. For this helps reducethe fears of the notables about expense, provided the rich are not paid for 25jury service but only the poor. It also greatly improves the quality of decisions in lawsuits; for the rich are unwilling to be away from their privateaffairs for many days, but are willing to be so for brief periods. Where there are revenues, however, one should not do what popularleaders do nowadays. For they distribute any surplus, but people no 30 sooner get it than they want the same again. Helping the poor in this way, indeed, is like pouring water into the proverbial leaking jug.28 But the truly democratic man should see to it that the multitude are not too poor (since this is a cause of the democracy's being a corrupt one). Mea sures must, therefore, be devised to ensure long-term prosperity. And, 35 since this is also beneficial to the rich, whatever is left over from the rev enues should be collected together and distributed in lump sums to the poor, particularly if enough can be accumulated for the acquisition of a plot of land, or failing that, for a start in trade or farming. And if this cannot be done for all, distribution should instead be by turns on the132rJ basis of tribe or some other part. In the meantime the rich should be taxed to provide pay for necessary meetings of the assembly, while being released from useless sorts of public service. It is by governing in this sort of way that the Carthaginians have won 5 the friendship of their people, since they are always sending some of them out to their subject city-states to become rich. 29 But it is also char acteristic of notables who are cultivated and sensible to divide the poor amongst themselves and give them a start in some line of work. It is a good thing too to imitate the policy of the Tarentines, who retain the goodwill of the multitude by giving communal use of their property to 10 the poor.30 They also divide all their offices into two classes, those that are elected and those chosen by lot: those by lot, so the people partici pate; those elected, so they are governed better. But this can also be done by dividing the same office between those people chosen by lot and 15 those elected. We have said, then, how democracies should be established. Chapter 6 It is also pretty well evident from these remarks how oligarchies should be established. For each oligarchy should be assembled from its oppo- 20 sites, by analogy with the opposite democracy, as in the case of the best mixed and first of the oligarchies. This is the one very close to so-called 28. See 1267bl-5. Forty-nine of Danaus' fifty daughters murdered their hus bands on their wedding night and were punished in Hades by having end lessly to fill leaking jugs with water. 29. Compare l 273b l 8 -24. 30. See 1263'35-40 where this policy is attributed to the Spartans, who were the ancestors of the Tarentines. Chapter 7 185 Chapter 7Since there are four principal parts of the multitude (farmers, vulgar 5craftsmen, tradesmen, and hired laborers), and four useful in war (cav-alry, HOPLITES, light infantry, and naval forces), where the country hap-pens to be suitable for cavalry, natural conditions favor the establishment of a powerful oligarchy. For the security of the inhabitantsdepends on horse power, and horse breeding is the privilege of those 10who own large estates.34 Where the country is suitable for hoplites, onthe other hand, conditions favor the next kind of oligarchy, since hoplites are more often rich than poor. 35 3 1 . Those required for the very existence of a city-state ( 1 283'1 7-22, VI. 9).32. From the farmers first, then from the herdsmen, then from the artisans, and so on. See 1 3 1 9'39-h1 and note.33. See 1 290'22-29 and note.34. See 1 289h33-40.35. Since heavy armor is expensive. 1 86 Politics VI 36. At 1320b2S-29. 37. See 1278'25-26. 38. "Small": because ruled by the few instead of the many; "democracies": be cause the few pursue money just like the many (see 1 3 1 8b16-17). Chapter 8 1 87 Chapter 8After what has just been said, the next topic, as was mentioned earlier,39is the matter of correctly distinguishing what pertains to the offices, howmany they are, what they are, and what they are concerned with. For 5without the necessary offices a city-state cannot exist, and without thoseconcerned with proper organization and order it cannot be well managed. Furthermore, in small city-states the offices are inevitably fewer,while in larger ones they are more numerous, as was also said earlier.40 10Consequently, the question of which offices it is appropriate to combineand which to keep separate should not be overlooked. The first of the necessary offices, then, deals with [ 1 ] the supervisionof the market, where there must be some office to supervise contractsand maintain good order. For in almost all city-states people have to beable to buy and sell in order to satisfy each other's necessary needs. This 15is also the readiest way to achieve self-sufficiency, which is thought to bewhat leads people to join together in one constitutionY Another kind of supervision, connected to this one and close to it, is[2] the supervision of public and private property within the town, sothat it may be kept in good order; also, the preservation and repair of decaying buildings and roads, the supervision of property boundaries, so 20that disputes do not arise over them, and all other sorts of supervisionsimilar to these. Most people call this sort of office town management,though its parts are more than one in number. More populous citystates assign different officials to these; for example, wall repairers, well 25supervisors, and harbor guards. Another office is also necessary and closely akin to this one, since itdeals with [3] the same areas, though it concerns the country and matters outside the town. In some places its holders are called country managers, in others foresters. These, then, are three kinds of supervision that deal with necessities. 30Another is [4] the office that receives public funds, safeguards them, anddistributes them to the various branches of the administration. Its hold-ers are called receivers or treasurers. Another office is [5] that where private contracts and the decisions of avoid it, however, and giving bad ones authority over it is not safe, sincethey are more in need of guarding than capable of guarding others. That 25is why there should not be a single office in charge of guarding prison-ers, nor the same office continuously. Instead, prisoners should be supervised by different people in turn, chosen from among the youngmen, in places where there is a regiment of cadets or guards,45 or fromthe other officials. These offices must be put first, then, as the most necessary. After 30these are others that are no less necessary, but ranked higher in dignity,since they require much experience and trustworthiness. The offices [7]that deal with the defense of the city-state are of this sort, and any thatare organized to meet its wartime needs. In peacetime and wartime alikethere should be people to supervise the defense of the gates and walls, 35and the inspection and organizing of the citizens. In some places thereare more offices assigned to all these areas, in others there are fewer (insmall city-states, for example, a single office deals with all of them).Such people are called generals or warlords. Furthermore, if there is acavalry, a light infantry, archers, or a navy, an office is sometimes estab- 1322blished for each of them. They are called admirals, cavalry commanders,or regimental commanders, whereas those in charge of the units underthese are called warship commanders, company commanders, or triballeaders, and so on for their subunits. But all of these together constitute 5a single kind, namely, supervision of military affairs. This, then, is theway things stand with regard to this office. But since some if not all of the offices handle large sums of publicmoney, there must be [8] a different office to receive and examine theiraccounts which does not itself handle any other matters. Some call these 10inspectors, accountants, auditors, or advocates. Besides all these offices, there is [9] the one with the most authorityover everything; for the same office often has authority over both implementing and introducing a measure, or presides over the multitudewhere the people have authority. For there must be some body to con-vene the body that has authority over the constitution. In some places, 15they are called preliminary councilors, because they prepare businessfor the assembly. 46 But where the multitude are in authority they areusually called a council instead. 45. In Athens and other city-states young men served from the time they were eighteen until they were twenty in such regiments, which acted as police or civic guards.46. See 1 298b26-34. 1 90 Politics VI This, then, is pretty much the number of offices that are political. But another kind of supervision is [ 1 0] that concerned with the worship of the gods: for example, priests, supervisors of matters relating to the 20 temples (such as the preservation of existing buildings, the restoration of decaying ones), and all other duties concerning the gods. Sometimes it happens, for example, in small city-states, that a single office super vises all this, but sometimes, apart from the priests, there are a number of others, such as supervisors of sacrifices, temple guardians, and sacred 25 treasurers. Next after this is the office specializing in the public sacri fices that the law does not assign to the priests; instead, the holders have the office from the communal hearth.47 These officials are called archons by some, kings or presidents by others. To sum up, then, the necessary kinds of supervision deal with the fol- 30 lowing: religious matters, military matters, revenues and expenditures, the market, town, harbors, and country; also matters relating to the courts, such as registering contracts, collecting fines, carrying out of 35 sentences, keeping prisoners in custody, receiving accounts, and in specting and examining officials; and, finally, matters relating to the body that deliberates about public affairs. On the other hand, peculiar to city-states that enjoy greater leisure and prosperity and that also pay attention to good order are [ 1 1 ] the offices dealing with the supervision of women, [ 12] the guardianship of the laws, [ 1 3 ] the supervision of children, [ 1 4] authority over the gymnasia, and1323• also [ 1 5] the supervision of gymnastic or Dionysiac contests,48 as well as of any other such public spectacles there may happen to be. Some of these are obviously not democratic, for example, the supervision of women and that of children, for the poor have to employ their women 5 and children as servants, because of their lack of slaves. There are three offices that city-states use to supervise the selection of the officials who are in authority: [ 1 6] the office of law guardian, [ 17] that of preliminary councilor, and [ 1 8] the council. The office of law guardian is aristocratic, that of preliminary councilor oligarchic, and a council, democratic. 10 Pretty well all the offices have now been discussed in outline. 47. The communal hearth (koine hestia) derives from the hearth in the king's palace which had both a practical and a magico-religious significance. 48. The dramatic festivals in which tragic and comedic poets competed. B oo K V I I Chapter 1Anyone who intends to investigate the best constitution in the properway must first determine which life is most choiceworthy, since if this 15remains unclear, what the best constitution is must also remain unclear.For it is appropriate for those to fare best who live in the best constitu-tion their circumstances allow-provided nothing contrary to reason-able expectation occurs. That is why we should first come to some agreement about what the most choiceworthy life is for practically speakingeveryone,1 and then determine whether it is the same for an individual as 20for a community, or different. Since, then, I consider that I have already expressed much that is adequate about the best life in the "external" works,2 I propose to make useof them here as well. For since, in the case of one division at least, thereare three groups--external GOODS, goods of the body, and goods of the 25soul-surely no one would raise a dispute and say that not all of themneed be possessed by those who are BLESSEDLY HAPPY. For no one wouldcall a person blessedly happy who has no shred of courage, temperance,j ustice, or practical wisdom, but is afraid of the flies buzzing aroundhim, stops at nothing to gratify his appetite for food or drink, betrays his 30dearest friends for a pittance, and has a mind as foolish and prone toerror as a child's or a madman's. But while almost all accept theseclaims, they disagree about quantity and relative superiority. For they 35consider any amount of virtue, however small, to be sufficient, but seekan unlimitedly excessive amount of wealth, possessions, power, reputa-tion, and the like. We, however, will say to them that it is easy to reach a reliable conclusion on these matters even from the facts themselves. For we see that the 191 1 92 Politics VII 40 virtues are not acquired and preserved by means of external goods, but the other way around,3 and we see that a happy life for human beings,132Jh whether it consists in pleasure or virtue or both, is possessed more often by those who have cultivated their characters and minds to an excessive degree, but have been moderate in their acquisition of external goods, than by those who have acquired more of the latter than they can possi- 5 bly use, but are deficient in the former. Moreover, if we investigate the matter on the basis of argument, it is plain to see. For external goods have a limit, as does any tool, and all useful things are useful for some thing; so excessive amounts of them must harm or bring no benefit to their possessors. 4 In the case of each of the goods of the soul, however, 10 the more excessive it is, the more useful it is (if these goods too should be thought of as useful, and not simply as noble). It is generally clear too, we shall say, that the relation of superiority holding between the best condition of each thing and that of others cor responds to that holding between the things whose conditions we say 15 they are. So since the soul is UNQUALIFIEDLY more valuable, and also more valuable to us, than possessions or the body, its best states must be proportionally better than theirs. Besides, it is for the sake of the soul that these things are naturally choiceworthy, and every sensible person 20 should choose them for its sake, not the soul for theirs. We may take it as agreed, then, that each person has just as much hap piness as he has virtue, practical wisdom, and the action that expresses them. We may use GOD as evidence of this. For he is blessedly happy, not because of any external goods but because of himself and a certain qual- 25 ity in his nature.5 This is also the reason that good luck and happiness are necessarily different. For chance or luck produces goods external to the soul, but no one is just or temperate as a result of luck or because of luck. 6 30 The next point depends on the same arguments. The happy city-state is the one that is best and acts nobly. It is impossible for those who do not do noble deeds to act nobly; and no action, whether a man's or a city state's, is noble when separate from virtue and practical wisdom. But the 3. The point is probably not that virtue invariably makes you rich, but that, without virtue, wealth and the rest can do you as much harm as good. 4. See 1256b3 5-36, 1 257h28. 5. See Introduction xliii-xlv. Luck (tuche) and chance (to automaton) and the difference between them are discussed in Ph. Il.4-6. 6. See NE 1 1 53bJ9-25. Chapter 2 193 courage, justice, and practical wisdom of a city-state have the same capacity and are of the same kind as those possessed by each human being JSwho is said to be just, practically wise, and temperate. So much, then, for the preface to our discussion.7 For we cannot avoidtalking about these issues altogether, but neither can we go through allthe arguments pertaining to them, since that is a task for another type ofstudy.8 But for now, let us assume this much, that the best life, both for 40individuals separately and for city-states collectively, is a life of virtuesufficiently equipped with the resources9 needed to take part in virtuousactions. With regard to those who dispute this, if any happen not to be 1324"persuaded by what has been said, we must ignore them in our presentstudy, but investigate them later. Chapter 2It remains to say whether the happiness of each individual human being Sis the same as that of a city-state or not. But here too the answer is evident, since everyone would agree that they are the same. For those whosuppose that living well for an individual consists in wealth will also calla whole city-state blessedly happy if it happens to be wealthy. And thosewho honor the tyrannical life above all would claim that the city-state 10that rules the greatest number10 is happiest. And if someone approves ofan individual because of his virtue, he will also say that the more excel-lent city-state is happier. Two questions need to be investigated, however. First, which life ismore choiceworthy, the one that involves taking part in politics withother people and participating in a city-state, or the life of an alien cut 1Soff from the political community? Second, and regardless of whetherparticipating in a city-state is more choiceworthy for everyone or formost but not for all, which constitution, which condition of the citystate, is best? This second question, and not the one about what is 20choiceworthy for the individual, is a task for political thought or theory.And since that is the investigation we are now engaged in, whereas theformer is a further task, our task is the second question. l l 8. Namely, ethics. 9. That is, external GOODS.10. Presumably, the greatest number of other city-states.11. See Introduction xlvi-xlviii. 194 Politics VII Chapter 3 We must now reply to the two sides who agree that the virtuous life is most choiceworthy, but disagree about how to practice it. For some rule out the holding of political office and consider that the life of a free per son is both different from that of a statesman and the most choiceworthy 20 one of all. But others consider that the political life is best, since it is im possible for someone inactive to do or act well, and that doing well and happiness are the same. We must reply that they are both partly right and partly wrong. On the one hand, it is true to say that the life of a free person is better than that of a master. For there is certainly nothing 25 grand about using a slave as a slave, since ordering people to do neces sary tasks is in no way noble. None the less, it is wrong to consider that every kind of rule is rule by a master. For the difference between rule over free people and over slaves is no smaller than the difference be tween being naturally free and being a natural slave. We have adequately 30 distinguished them in our first discussions. 15 On the other hand, to praise inaction more than action is not correct either. For happiness is ACTION, and many noble things reach their end in the actions of those who are just and temperate. Perhaps someone will take these conclusions to imply, however, that 35 having authority over everyone is what is best. For in that way one would have authority over the greatest number of the very noblest actions. It would follow that someone who has the power to rule should not surren der it to his neighbor but take it away from him, and that a father should disregard his children, a child his father, a friend his friend, and pay no attention to anything except ruling. For what is best is most choicewor- 40 thy, and doing well is best. What they say is perhaps true, if indeed those who use force and com-1325b mit robbery will come to possess the most choiceworthy thing there is. But perhaps they cannot come to possess it, and the underlying assump tion here is false. For someone cannot do noble actions if he is not as su perior to those he rules as a husband is to his wife, a father to his chil- 5 dren, or a master to his slaves. Therefore, a transgressor could never make up later for his deviation from virtue. For among those who are similar, ruling and being ruled in turn is just and noble, since this is equal or similar treatment. But unequal shares for equals or dissimilar ones for similars is contrary to nature; and nothing contrary to nature is 1 5 . 1.4-7. Chapter 4 197 noble. Hence when someone else has superior virtue and his power to do 10the best things is also superior, it is noble to follow and just to obey him.But he should possess not virtue alone, but also the power he needs to dothese things. If these claims are correct, and we should assume that happiness isdoing well, then the best life, whether for a whole city-state collectivelyor for an individual, would be a life of action. Yet it is not necessary, as I5some suppose, for a life of action to involve relations with other people,nor are those thoughts alone active which we engage in for the sake ofaction's consequences; the study and thought that are their own endsand are engaged in for their own sake are much more so. For to do or act 20well is the end, so that ACTION of a sort is the end too. And even in thecase of actions involving external objects, the one who does them mostfully is, strictly speaking, the master craftsman who directs them bymeans of his thought. 16 Moreover, city-states situated by themselves, which have deliberatelychosen to live that way, do not necessarily have to be inactive, since activity can take place even among their parts. For the parts of a city-state 25have many sorts of communal relationships with one another. 17 Similarly, this holds for any human being taken singly. For otherwise GODand the entire universe could hardly be in a fine condition; for they haveno external actions, only the internal ones proper to them. It is evident, then, that the same life is necessarily best both for each 30human being and for city-states and human beings collectively. Chapter 4Since what has just been said about these matters was by way of a pref-ace, and since we studied the various constitutions earlier, 18 the startingpoint for the remainder of our investigation is first to discuss the condi- 35tions that should be presupposed to exist by the ideal city-state we areabout to construct. For the best constitution cannot come into existencewithout commensurate resources. Hence we should presuppose thatmany circumstances are as ideal as we could wish, although none should would be a task for a divine power, the sort that holds the entire universetogether. For beauty is usually found in number and magnitude. Hence acity-state whose size is fixed by the aforementioned limit must also bethe most beautiful. But the size of city-state, like everything else, has a 35certain scale: animals, plants, and tools. For when each of them is nei-ther too small nor too excessively large, it will have its own proper capacity; otherwise, it will either be wholly deprived of its nature or be inpoor condition. For example, a ship that is one span [seven and a halfinches] long will not be a ship at all, nor will one of two stades [twelve 40hundred feet]; and as it approaches a certain size, it will sail badly, be-cause it either is still too small or still too large. Similarly for a city-state: 13266one that consists of too few people is not SELF-SUFFICIENT (whereas acity-state is self-sufficient), but one that consists of too many, while it isself-sufficient in the necessities, the way a nation is, is still no city-state,since it is not easy for it to have a constitution. For who will be the gen-eral of its excessively large multitude, and who, unless he has the voice 5of Stentor, will serve as its herald?24 Hence the first city-state to arise is the one composed of the first multitude large enough to be self-sufficient with regard to living the goodlife as a political community. It is also possible for a city-state that exceeds this one in number to be a greater city-state, but, as we said, this is 10not possible indefinitely. The limit to its expansion can easily be seenfrom the facts. For a city-state's actions are either those of the rulers orthose of the ruled. And a ruler's task is to issue orders and decide. But inorder to decide lawsuits and distribute offices on the basis of merit, each I5citizen must know what sorts of people the other citizens are. For wherethey do not know this, the business of electing officials and decidinglawsuits must go badly, since to act haphazardly is unjust in both theseproceedings. But this is plainly what occurs in an overly populated citystate. Besides, it is easy for resident aliens and foreigners to participate 20in the constitution, since the excessive size of the population makesescaping detection easy. It is clear, then, that the best limit for a city-state is this: it is the greatest size of multitude that promotes life's selfsufficiency and that can be easily surveyed as a whole. The size of thecity-state, then, should be determined in this way. 25 24. Stentor was a Homeric hero gifted with a very powerful voice. 200 Politics VII Chapter 5 Similar things hold in the case of territory. For, as far as its quality is concerned, it is clear that everyone would praise the most self-sufficient. And as such it must produce everything, for self-sufficiency is having everything and needing nothing. In size or extent, it should be large 30 enough to enable the inhabitants to live a life of leisure in a way that is generous and at the same time temperate.25 But whether this defining principle is rightly or wrongly formulated is something that must be in vestigated with greater precision later on, when we come to discuss the question of possessions generally-what it is to be well off where prop- 35 erty is concerned, and how and in what way this is related to its use. For there are many disputes about this question raised by those who urge us to adopt one extreme form of life or the other: penury in the one case, luxury in the other.26 The layout of the territory is not difficult to describe (although on 40 some points the advice of military experts should also be taken): it should be difficult for enemies to invade and easy for the citizens to get out to. 27 Moreover, just as the multitude of people should, as we said, be1327" easy to survey as a whole, the same holds of the territory. For a territory easy to survey as a whole is easy to defend. If the CITY-STATE is to be ideally sited, it is appropriate for it to be well situated in relation to the sea and the surrounding territory. One S defining principle was mentioned above: defensive troops should have access to all parts of the territory. The remaining defining principle is that the city-state should be accessible to transportation, so that crops, timber, and any other such materials the surrounding territory happens to possess can be easily transported to it. Chapter 6 There is much dispute about whether access to the sea is beneficial or harmful to well-governed city-states. For it is said that entertaining for- Chapter 7 We spoke earlier about what limit there should be on the number of cit izens.30 Let us now discuss what sort of natural qualities they should have.20 One may pretty much grasp what these qualities are by looking at those Greek city-states that have a good reputation, and at the way the entire inhabited world is divided into nations. The nations in cold re gions, particularly Europe, are full of spirit but somewhat deficient in intelligence and craft knowledge. That is precisely why they remain25 comparatively free, but are apolitical and incapable of ruling their neigh bors. Those in Asia, on the other hand, have souls endowed with intelli gence and craft knowledge, but they lack spirit. That is precisely why they are ruled and enslaved. The Greek race, however, occupies an in termediate position geographically, and so shares in both sets of charac-30 teristics. For it is both spirited and intelligent. That is precisely why it remains free, governed in the best way, and capable, if it chances upon a single constitution, of ruling all the others.31 Greek nations also differ from one another in these ways. For some have a nature that is one-35 sided, whereas in others both of these capacities are well blended. It is evident, then, that both spirit and intelligence should be present in the natures of people if they are to be easily guided to virtue by the legislator. Some say that guardians should have precisely this quality: they must be friendly to those they know and fierce to those they do not,32 and that40 spirit is what makes them be friendly. For spirit is the capacity of the soul by which we feel friendship. A sign of this is that our spirit is roused 30. In VII.4. 3 1 . Aristotle cannot be supposing that all of Greece might form a single city state; it was.
https://ru.scribd.com/document/384249201/Aristotle-Politics-Hackett-1998-pdf
CC-MAIN-2020-10
en
refinedweb
Dart example program to replace a substring Introduction : In this tutorial, we will learn how to replace a part of a string in dart. Dart string class comes with a method called replaceRange, that we can use to replace a part of the string with a different string. In this tutorial, we will learn how to use replaceRange with an example in Dart. Definition : replaceRange is defined as below : String replaceRange ( int start, int end, String str ) It replaces the string from index start to end with different string str. It returns one new string i.e. the modified string. The start and end indices should be in a valid range. If the value of end is null, it will take the default length length. Example : import "dart:core"; void main() { final givenString = "hello world"; final newString = givenString.replaceRange(0, 3, "1"); print(newString); } It will print the below output : 1lo world As you can see in the above example, it replaced the string part from index 0 to 3 with 1. Try to run the above example with different indices and different strings to learn more about how replaceRange works.
https://www.codevscolor.com/dart-replace-substring/
CC-MAIN-2020-10
en
refinedweb
The Raw data structure: continuous data¶ This tutorial covers the basics of working with raw EEG/MEG data in Python. It introduces the Raw data structure in detail, including how to load, query, subselect, export, and plot data from a Raw object. For more info on visualization of Raw objects, see Built-in plotting methods for Raw objects. For info on creating a Raw object from simulated data in a NumPy array, see Creating MNE’s data structures from scratch. Page contents - - - Extracting data from Rawobjects Exporting and saving Raw objects As usual we’ll start by importing the modules we need: import os import numpy as np import matplotlib.pyplot as plt import mne As mentioned in the introductory tutorial, MNE-Python data structures are based around the .fif file format from Neuromag. This tutorial uses an example dataset in .fif format, so here we’ll use the function mne.io.read_raw_fif() to load the raw data; there are reader functions for a wide variety of other data formats as well. There are also several other example datasets that can be downloaded with just a few lines of code. Functions for downloading example datasets are in the mne.datasets submodule; here we’ll use mne.datasets.sample.data_path() to download the “Sample” dataset, which contains EEG, MEG, and structural MRI data from one subject performing an audiovisual experiment. When it’s done downloading, data_path() will return the folder location where it put the files; you can navigate there with your file browser if you want to examine the files yourself. Once we have the file path, we can load the data with read_raw_fif(). This will return a Raw object, which we’ll store in a variable called raw. sample_data_folder = mne.datasets.sample.data_path() sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample', 'sample_audvis_raw.fif') raw = mne.io.read_raw_fif(sample_data_raw_file) As you can see above, read_raw_fif() automatically displays some information about the file it’s loading. For example, here it tells us that there are three “projection items” in the file along with the recorded data; those are SSP projectors calculated to remove environmental noise from the MEG signals, and are discussed in a the tutorial Background on projectors and projections. In addition to the information displayed during loading, you can get a glimpse of the basic details of a Raw object by printing it: Out: <Raw | sample_audvis_raw.fif, n_channels x n_times : 376 x 166800 (277.7 sec), ~3.7 MB, data not loaded> By default, the mne.io.read_raw_* family of functions will not load the data into memory (instead the data on disk are memory-mapped, meaning the data are only read from disk as-needed). Some operations (such as filtering) require that the data be copied into RAM; to do that we could have passed the preload=True parameter to read_raw_fif(), but we can also copy the data into RAM at any time using the load_data() method. However, since this particular tutorial doesn’t do any serious analysis of the data, we’ll first crop() the Raw object to 60 seconds so it uses less memory and runs more smoothly on our documentation server. Out: Reading 0 ... 36037 = 0.000 ... 60.000 secs... Querying the Raw object¶ We saw above that printing the Raw object displays some basic information like the total number of channels, the number of time points at which the data were sampled, total duration, and the approximate size in memory. Much more information is available through the various attributes and methods of the Raw class. Some useful attributes of Raw objects include a list of the channel names ( ch_names), an array of the sample times in seconds ( times), and the total number of samples ( n_times); a list of all attributes and methods is given in the documentation of the Raw class. The Raw.info attribute¶ There is also quite a lot of information stored in the raw.info attribute, which stores an Info object that is similar to a Python dictionary (in that it has fields accessed via named keys). Like Python dictionaries, raw.info has a .keys() method that shows all the available field names; unlike Python dictionaries, printing raw.info will print a nicely-formatted glimpse of each field’s data. See The Info data structure for more on what is stored in Info objects, and how to interact with them. n_time_samps = raw.n_times time_secs = raw.times ch_names = raw.ch_names n_chan = len(ch_names) # note: there is no raw.n_channels attribute print('the (cropped) sample data object has {} time samples and {} channels.' ''.format(n_time_samps, n_chan)) print('The last time sample is at {} seconds.'.format(time_secs[-1])) print('The first few channel names are {}.'.format(', '.join(ch_names[:3]))) print() # insert a blank line in the output # some examples of raw.info: print('bad channels:', raw.info['bads']) # chs marked "bad" during acquisition print(raw.info['sfreq'], 'Hz') # sampling frequency print(raw.info['description'], '\n') # miscellaneous acquisition info print(raw.info) Out: the (cropped) sample data object has 36038 time samples and 376 channels. The last time sample is at 60.000167471573526 seconds. The first few channel names are MEG 0113, MEG 0112, MEG 0111. bad channels: ['MEG 2443', 'EEG 053'] 600.614990234375 Hz acquisition (megacq) VectorView system at NMR-MGH <Info | 24 non-empty fields acq_pars : str | 13886 items bads : list | MEG 2443, EEG 053 ch_names : list | MEG 0113, MEG 0112, MEG 0111, MEG 0122, MEG 0123, ... chs : list | 376 items (GRAD: 204, MAG: 102, STIM: 9, EEG: 60, EOG: 1) comps : list | 0 items custom_ref_applied : bool | False description : str | 49 items dev_head_t : Transform | 3 items dig : Digitization | 146 items (3 Cardinal, 4 HPI, 61 EEG, 78 Extra) events : list | 1 items experimenter : str | 3 items file_id : dict | 4 items highpass : float | 0.10000000149011612 Hz hpi_meas : list | 1 items hpi_results : list | 1 items lowpass : float | 172.17630004882812 Hz meas_date : tuple | 2002-12-03 19:01:10 GMT meas_id : dict | 4 items nchan : int | 376 proc_history : list | 0 items proj_id : ndarray | 1 items proj_name : str | 4 items projs : list | PCA-v1: off, PCA-v2: off, PCA-v3: off sfreq : float | 600.614990234375 Hz acq_stim : NoneType ctf_head_t : NoneType dev_ctf_t : NoneType device_info : NoneType gantry_angle : NoneType helium_info : NoneType hpi_subsystem : NoneType kit_system_id : NoneType line_freq : NoneType subject_info : NoneType utc_offset : NoneType xplotter_layout : NoneType > Note Most of the fields of raw.info reflect metadata recorded at acquisition time, and should not be changed by the user. There are a few exceptions (such as raw.info['bads'] and raw.info['projs']), but in most cases there are dedicated MNE-Python functions or methods to update the Info object safely (such as add_proj() to update raw.info['projs']). Time, sample number, and sample index¶ One method of Raw objects that is frequently useful is time_as_index(), which converts a time (in seconds) into the integer index of the sample occurring closest to that time. The method can also take a list or array of times, and will return an array of indices. It is important to remember that there may not be a data sample at exactly the time requested, so the number of samples between time = 1 second and time = 2 seconds may be different than the number of samples between time = 2 and time = 3: Out: [12012] [12012 18018 24024] [601 600] Modifying Raw objects¶ Raw objects have a number of methods that modify the Raw instance in-place and return a reference to the modified instance. This can be useful for method chaining (e.g., raw.crop(...).filter(...).pick_channels(...).plot()) but it also poses a problem during interactive analysis: if you modify your Raw object for an exploratory plot or analysis (say, by dropping some channels), you will then need to re-load the data (and repeat any earlier processing steps) to undo the channel-dropping and try something else. For that reason, the examples in this section frequently use the copy() method before the other methods being demonstrated, so that the original Raw object is still available in the variable raw for use in later examples. Selecting, dropping, and reordering channels¶ Altering the channels of a Raw object can be done in several ways. As a first example, we’ll use the pick_types() method to restrict the Raw object to just the EEG and EOG channels: eeg_and_eog = raw.copy().pick_types(meg=False, eeg=True, eog=True) print(len(raw.ch_names), '→', len(eeg_and_eog.ch_names)) Out: 376 → 60 Similar to the pick_types() method, there is also the pick_channels() method to pick channels by name, and a corresponding drop_channels() method to remove channels by name: raw_temp = raw.copy() print('Number of channels in raw_temp:') print(len(raw_temp.ch_names), end=' → drop two → ') raw_temp.drop_channels(['EEG 037', 'EEG 059']) print(len(raw_temp.ch_names), end=' → pick three → ') raw_temp.pick_channels(['MEG 1811', 'EEG 017', 'EOG 061']) print(len(raw_temp.ch_names)) Out: Number of channels in raw_temp: 376 → drop two → 374 → pick three → 3 If you want the channels in a specific order (e.g., for plotting), reorder_channels() works just like pick_channels() but also reorders the channels; for example, here we pick the EOG and frontal EEG channels, putting the EOG first and the EEG in reverse order: channel_names = ['EOG 061', 'EEG 003', 'EEG 002', 'EEG 001'] eog_and_frontal_eeg = raw.copy().reorder_channels(channel_names) print(eog_and_frontal_eeg.ch_names) Out: ['EOG 061', 'EEG 003', 'EEG 002', 'EEG 001'] Changing channel name and type¶ You may have noticed that the EEG channel names in the sample data are numbered rather than labelled according to a standard nomenclature such as the 10-20 or 10-05 systems, or perhaps it bothers you that the channel names contain spaces. It is possible to rename channels using the rename_channels() method, which takes a Python dictionary to map old names to new names. You need not rename all channels at once; provide only the dictionary entries for the channels you want to rename. Here’s a frivolous example: This next example replaces spaces in the channel names with underscores, using a Python dict comprehension: print(raw.ch_names[-3:]) channel_renaming_dict = {name: name.replace(' ', '_') for name in raw.ch_names} raw.rename_channels(channel_renaming_dict) print(raw.ch_names[-3:]) Out: ['EEG 059', 'EEG 060', 'blink detector'] ['EEG_059', 'EEG_060', 'blink_detector'] If for some reason the channel types in your Raw object are inaccurate, you can change the type of any channel with the set_channel_types() method. The method takes a dictionary mapping channel names to types; allowed types are ecg, eeg, emg, eog, exci, ias, misc, resp, seeg, stim, syst, ecog, hbo, hbr. A common use case for changing channel type is when using frontal EEG electrodes as makeshift EOG channels: Out: ['EEG_001', 'blink_detector'] Selection in the time domain¶ If you want to limit the time domain of a Raw object, you can use the crop() method, which modifies the Raw object in place (we’ve seen this already at the start of this tutorial, when we cropped the Raw object to 60 seconds to reduce memory demands). crop() takes parameters tmin and tmax, both in seconds (here we’ll again use copy() first to avoid changing the original Raw object): raw_selection = raw.copy().crop(tmin=10, tmax=12.5) print(raw_selection) Out: <Raw | sample_audvis_raw.fif, n_channels x n_times : 376 x 1503 (2.5 sec), ~8.0 MB, data loaded> crop() also modifies the first_samp and times attributes, so that the first sample of the cropped object now corresponds to time = 0. Accordingly, if you wanted to re-crop raw_selection from 11 to 12.5 seconds (instead of 10 to 12.5 as above) then the subsequent call to crop() should get tmin=1 (not tmin=11), and leave tmax unspecified to keep everything from tmin up to the end of the object: print(raw_selection.times.min(), raw_selection.times.max()) raw_selection.crop(tmin=1) print(raw_selection.times.min(), raw_selection.times.max()) Out: 0.0 2.500770084699155 0.0 1.5001290587975622 Remember that sample times don’t always align exactly with requested tmin or tmax values (due to sampling), which is why the max values of the cropped files don’t exactly match the requested tmax (see Time, sample number, and sample index for further details). If you need to select discontinuous spans of a Raw object — or combine two or more separate Raw objects — you can use the append() method: raw_selection1 = raw.copy().crop(tmin=30, tmax=30.1) # 0.1 seconds raw_selection2 = raw.copy().crop(tmin=40, tmax=41.1) # 1.1 seconds raw_selection3 = raw.copy().crop(tmin=50, tmax=51.3) # 1.3 seconds raw_selection1.append([raw_selection2, raw_selection3]) # 2.5 seconds total print(raw_selection1.times.min(), raw_selection1.times.max()) Out: 0.0 2.5041000049184614 Extracting data from Raw objects¶ So far we’ve been looking at ways to modify a Raw object. This section shows how to extract the data from a Raw object into a NumPy array, for analysis or plotting using functions outside of MNE-Python. To select portions of the data, Raw objects can be indexed using square brackets. However, indexing Raw works differently than indexing a NumPy array in two ways: Along with the requested sample value(s) MNE-Python also returns an array of times (in seconds) corresponding to the requested samples. The data array and the times array are returned together as elements of a tuple. The data array will always be 2-dimensional even if you request only a single time sample or a single channel. Extracting data by index¶ To illustrate the above two points, let’s select a couple seconds of data from the first channel: sampling_freq = raw.info['sfreq'] start_stop_seconds = np.array([11, 13]) start_sample, stop_sample = (start_stop_seconds * sampling_freq).astype(int) channel_index = 0 raw_selection = raw[channel_index, start_sample:stop_sample] print(raw_selection) Out: (array([[-3.85742192e-12, -3.85742192e-12, -9.64355481e-13, ..., 2.89306644e-12, 3.85742192e-12, 3.85742192e-12]]), array([10.99872648, 11.00039144, 11.0020564 , ..., 12.9933487 , 12.99501366, 12.99667862])) You can see that it contains 2 arrays. This combination of data and times makes it easy to plot selections of raw data (although note that we’re transposing the data array so that each channel is a column instead of a row, to match what matplotlib expects when plotting 2-dimensional y against 1-dimensional x): x = raw_selection[1] y = raw_selection[0].T plt.plot(x, y) Extracting channels by name¶ The Raw object can also be indexed with the names of channels instead of their index numbers. You can pass a single string to get just one channel, or a list of strings to select multiple channels. As with integer indexing, this will return a tuple of (data_array, times_array) that can be easily plotted. Since we’re plotting 2 channels this time, we’ll add a vertical offset to one channel so it’s not plotted right on top of the other one: channel_names = ['MEG_0712', 'MEG_1022'] two_meg_chans = raw[channel_names, start_sample:stop_sample] y_offset = np.array([5e-11, 0]) # just enough to separate the channel traces x = two_meg_chans[1] y = two_meg_chans[0].T + y_offset lines = plt.plot(x, y) plt.legend(lines, channel_names) Extracting channels by type¶ There are several ways to select all channels of a given type from a Raw object. The safest method is to use mne.pick_types() to obtain the integer indices of the channels you want, then use those indices with the square-bracket indexing method shown above. The pick_types() function uses the Info attribute of the Raw object to determine channel types, and takes boolean or string parameters to indicate which type(s) to retain. The meg parameter defaults to True, and all others default to False, so to get just the EEG channels, we pass eeg=True and meg=False: eeg_channel_indices = mne.pick_types(raw.info, meg=False, eeg=True) eeg_data, times = raw[eeg_channel_indices] print(eeg_data.shape) Out: (58, 36038) Some of the parameters of mne.pick_types() accept string arguments as well as booleans. For example, the meg parameter can take values 'mag', 'grad', 'planar1', or 'planar2' to select only magnetometers, all gradiometers, or a specific type of gradiometer. See the docstring of mne.pick_types() for full details. The Raw.get_data() method¶ If you only want the data (not the corresponding array of times), Raw objects have a get_data() method. Used with no parameters specified, it will extract all data from all channels, in a (n_channels, n_timepoints) NumPy array: data = raw.get_data() print(data.shape) Out: (376, 36038) If you want the array of times, get_data() has an optional return_times parameter: data, times = raw.get_data(return_times=True) print(data.shape) print(times.shape) Out: (376, 36038) (36038,) The get_data() method can also be used to extract specific channel(s) and sample ranges, via its picks, start, and stop parameters. The picks parameter accepts integer channel indices, channel names, or channel types, and preserves the requested channel order given as its picks parameter. first_channel_data = raw.get_data(picks=0) eeg_and_eog_data = raw.get_data(picks=['eeg', 'eog']) two_meg_chans_data = raw.get_data(picks=['MEG_0712', 'MEG_1022'], start=1000, stop=2000) print(first_channel_data.shape) print(eeg_and_eog_data.shape) print(two_meg_chans_data.shape) Out: (1, 36038) (61, 36038) (2, 1000) Summary of ways to extract data from Raw objects¶ The following table summarizes the various ways of extracting data from a Raw object. Exporting and saving Raw objects¶ Raw objects have a built-in save() method, which can be used to write a partially processed Raw object to disk as a .fif file, such that it can be re-loaded later with its various attributes intact (but see Floating-point precision for an important note about numerical precision when saving). There are a few other ways to export just the sensor data from a Raw object. One is to use indexing or the get_data() method to extract the data, and use numpy.save() to save the data array: It is also possible to export the data to a Pandas DataFrame object, and use the saving methods that Pandas affords. The Raw object’s to_data_frame() method is similar to get_data() in that it has a picks parameter for restricting which channels are exported, and start and stop parameters for restricting the time domain. Note that, by default, times will be converted to milliseconds, rounded to the nearest millisecond, and used as the DataFrame index; see the scaling_time parameter in the documentation of to_data_frame() for more details. sampling_freq = raw.info['sfreq'] start_end_secs = np.array([10, 13]) start_sample, stop_sample = (start_end_secs * sampling_freq).astype(int) df = raw.to_data_frame(picks=['eeg'], start=start_sample, stop=stop_sample) # then save using df.to_csv(...), df.to_hdf(...), etc print(df.head()) Out: Converting "time" to "<class 'numpy.int64'>"... channel EEG_002 ... EEG_060 time ... 10000 38.478851 ... 69.522829 10001 36.128997 ... 70.692262 10003 35.894012 ... 70.809205 10005 37.245177 ... 70.107545 10006 38.478851 ... 70.692262 [5 rows x 59 columns] Note When exporting data as a NumPy array or Pandas DataFrame, be sure to properly account for the unit of representation in your subsequent analyses. Total running time of the script: ( 0 minutes 23.376 seconds) Estimated memory usage: 209 MB Gallery generated by Sphinx-Gallery
https://mne.tools/stable/auto_tutorials/raw/plot_10_raw_overview.html
CC-MAIN-2020-10
en
refinedweb
The new stylesheet used in <junitreport> doesn't work with Java 1.4.1/Xalan 2.2; it complains about a missing 'redirect' class. It works fine with Java 1.4.2, and with Xalan 2.6. Upgrading Xalan 2.6 is a litte tricky; see- j/faq.html#faq-N100CC for details on how to do it. It's indeed extremely annoying but unfortunately there is not much to do as we had to take a decision to support Xalan as bundled in the upcoming JDK 1.5 and I could not find a way to support both kind of directives. See PR 27541 for more information You can however specify the deprecated xsl in ${ant.home}/etc/junit-frames- xalan1.xsl I had a quick look at Xalan CVS, and looks like the new namespace was used starting from Xalan 2.4.1 (and JDK 1.4.2-01):- xalan/java/src/org/apache/xalan/lib/Redirect.java This was more a suggestion to update the doco; it was rather surprising to stumble over it. The release notes, for example, made it clear that Xalan 1 was not supported, but doesn't say that earlier versions of Xalan 2 won't work either. Given the two workarounds (update Xalan or use the old stylesheet) I see no reason to try and make it work with Xalan 2.2, but I do recommend the doco be updated. The reason it is not in the doc is simple. We did not know about it as apparently everyone involved with this fix was running 1.4.2.01+ and it is extremely painful and time consuming to support dozen of versions of products that are not backward compatible. I have updated the docs in CVS to give more information though. Thanks. *** Bug 30524 has been marked as a duplicate of this bug. ***
https://bz.apache.org/bugzilla/show_bug.cgi?id=30200
CC-MAIN-2020-10
en
refinedweb
Given the following code: public interface IUser{ ... } public class UserModel : IUser{ ... } and the steptup.cs services.AddScoped<UserManager<IUser>>(provider => { UserManager<UserModel> um = new UserManager<UserModel>( ... ); return (UserManager<IUser>)um; // <-- casting error } The error i get is that UserManager<UserModel> cannot be converted to UserManager<IUser> even though UserModel implements IUser. I’m trying to type the user manager to the interface type because in some projects my login api is backed by a mongo implementation and some are backed by mysql, but the rest api is the same regardless. I’ve mostly been working in java where this would be valid, we’ve recently switched to c# and i’m having some issues understanding the way polymorphism works with generics submitted by /u/myrddraa11 [link] [comments]
https://howtocode.net/2018/07/casting-and-generics/
CC-MAIN-2018-39
en
refinedweb
Continuing the guide on how to setup HTTP channels in Infor M3 Enterprise Collaborator (MEC), I will illustrate how to setup the HTTPSOut channel for MEC to make requests using HTTP Secure (HTTPS), i.e. HTTP over SSL/TLS; I will investigate the channel’s features and drawbacks, and I will verify if it is safe to use (it is not). Why it matters It is important to use SSL/TLS in partner agreements that need to transfer via HTTP sensitive information such as names, addresses, bank account numbers, purchase orders, credit card numbers, financial transactions, health records, user names, passwords, etc. More generally, it is important to accelerate the adoption of cryptography. HTTPS in brief SSL/TLS is a security protocol that provides privacy for a client and a server to communicate over insecure networks. It is a communication layer that sits between a transport layer (usually TCP) and an application layer (for example HTTP). Secure Sockets Layer (SSL) is the original protocol and is not considered secure anymore. Transport Layer Security (TLS) is the successor and everybody should upgrade to its latest version 1.2. https is the scheme token in the URI that indicates we are using a dedicated secure channel often on port 443. Properties SSL/TLS provides the following properties of secure communication: - Confidentiality, using a cipher to encrypt the plain text and prevent eavesdropping - Integrity, using signed hashes to detect tampering - Authentication, using digital certificates to affirm the identity of the entities It can also provide non-repudiation, using digital signatures to assert the sender cannot deny having sent the message, provided the sender’s private key is not compromised or changed. And depending on the key agreement protocol, it can also provide perfect forward secrecy, using ephemeral key exchanges for each session, to ensure that a message cannot be compromised if another message is compromised in the future. Handshake During the SSL/TLS handshake, the client and server exchange digital certificates and establish cipher suite settings. The connection bootstraps with asymmetric cryptography using public and private keys (which eliminates the problems of distributing shared keys), and then switches to symmetric cryptography using a temporary shared key for the session (which is several orders of magnitude faster). Digital certificates A digital certificate is a public key and the owner’s identity that have been verified and digitally signed by a certificate authority (CA). Public key infrastructure (PKI) is used to create, distribute, and revoke certificates. If an entity trusts a CA, then by transitive relation it will trust that any certificate the CA issues authenticates the owner of the certificate. There can be any number of intermediate CAs in the chain of certificates, and root CAs use self-signed certificates. The client must verify the server certificate, and optionally the server may verify the client certificate: - Verify the chain of trust - Verify the hostname in the certificate using SubjectAltNames and Common Name; this could get tricky with wildcard patterns, null characters, and international character sets - Verify the certificate’s activation and expiration dates - Verify the certificate’s revocation status using a certification revocation list (CRL) or OCSP - Check the X.509 certificate extensions (e.g. can this key sign new certificates?) - Check that the certificates of the intermediate CAs have the CA bit set in the “Basic Constraints” field Despite all that, validating certificates is difficult, and the CA model is broken. Test You can test HTTP over SSL/TLS and see the chain of certificates, with cURL: curl > cacert.pem curl --verbose --cacert cacert.pem with OpenSSL: openssl s_client -connect -showcerts GET / HTTP/1.1 Host: Proxy A web proxy is a program that makes requests on behalf of a client. There are different types of web proxies, for example tunneling proxies, forward proxies, and reverse proxies. And there are different implementations, for example, explicit proxies and transparent proxies. And they have different purposes, for example caching, load balancing, securing, monitoring, filtering, bypassing, and anonymizing. Proxies may require authentication. An explicit web proxy is for example when you set your browser to use a proxy at a certain host and port number. With that proxy, the client makes an HTTP request to the proxy using the CONNECT method, then the proxy establishes a TCP connection to the destination server, and then the proxy acts as a blind tunnel that is forwarding TCP between client and server, seeing only the SSL/TLS handshake and then encrypted traffic. You can test HTTP over SSL/TLS via an explicit proxy, with cURL and Fiddler: curl --verbose --cacert cacert.pem --proxy 127.0.0.1:8888 with proxy authentication: curl --verbose --cacert cacert.pem --proxy with GNU Wget and Fiddler: export https_proxy=localhost:8888 wget --debug --https-only You will see this request and response between client and proxy, then the SSL/TLS handshake, then the HTTP traffic: CONNECT HTTP/1.1 Host: HTTP/1.1 200 Connection Established On the other hand, a transparent proxy intercepts the traffic at the lower network level without requiring any client configuration. It acts as the SSL termination for the client, and establishes a second encryption channel with the destination server thereby being able to monitor and filter the SSL/TLS traffic in transit; in that case the client is not aware of the presence of the proxy but must trust the proxy’s certificate, and the proxy must trust the server’s certificate. For MEC In our case, we want MEC to communicate with partners over a secure channel with confidentiality, integrity, and authentication to protect the data being exchanged, optionally via proxy. Problem MEC does not provide secure channels for HTTP out of the box. For instance, there are no HTTPSIn, HTTPSOut, HTTPSSyncIn, or HTTPSSyncOut channels. There is an HTTPSOut channel, but it is only a sample in an appendix of the documentation (does that mean it is safe to use?), and it does not come out of the box in the Partner Admin, it must be added manually (although it is available in the Java library). Also, there is a WebServiceSyncIn channels that uses WS-Security specifically for XML over SOAP, but in my case I am interested in HTTPS in general, for example for flat files, I am not interested in SOAP. Ideally, I would prefer to use the Infor Grid which already communicates via HTTPS, but unfortunately it does not have a native connection handler for MEC. None of this means MEC is insecure, it just means you have to add the security yourself. Documentation The useful documentation The MEC Partner Admin Tool User Guide contains the necessary source code and some explanation for the HTTPSOut channel and user interface: The obstructing documentation However, the documentation references HTTPS Communication, HttpServer.xml, and HTTPSOut at the same time, yet it does not clearly explain the relationship between them, so it is confusing: I had to find the Communication Plug-in Development User Guide of an old version of MEC to find the answer. It turns out the HttpServer.xml was a file that existed in old versions of MEC to configure the web user interface. I think the sample in the documentation used that server to test the HTTPSOut channel; I do not know. Anyway, that file does not exist anymore after MEC was ported to the Infor Grid, so that chapter is irrelevant, confusing, and unrelated to HTTPSOut. We can ignore it, and Infor should remove it from the Partner Admin guide. Java classes The MEC Java library ec-core-x.y.z.jar includes the Java classes sample.HTTPSOut and sample.HTTPSOutPanel: Features Looking at the source code, the HTTPSOut channel is similar to the HTTPOut channel: they both make a POST HTTP request to a destination server, at a host, port number, and path defined in the Partner Admin, with the message sent in the request body. HTTPSOut uses javax.net.ssl.HttpsURLConnection which in turn uses javax.net.ssl.SSLSocket to establish a secure socket with the destination server. From the HTTPSOut point of view, it just reads/writes plain HTTP to the socket, and the socket underneath takes care of the handshake and encryption/decryption. HTTPSOut has an advantage over HTTPOut. Given the entire HTTP traffic is encrypted over SSL/TLS, we can safely set a username and password for HTTP Basic authentication, unlike with HTTPOut where we should not set a username and password because they transit in clear text (trivial Base64 decode). Drawbacks HTTPOut and HTTPSOut share the same drawbacks: they do not use Java NIO, and there are no proxy settings. HTTPSOut has additional drawbacks: there are no settings for Content-type, multi-part, and keep alive, unlike HTTPOut. Worse, the response is completely ignored unlike HTTPOut where the response is at least added to the debug log. Test You can test the HTTPSOut class with the following code and with a message.txt file: javac -cp log4j-1.2.17.jar;ec-core-11.4.1.0.0.jar;. Test.java java -cp log4j-1.2.17.jar;ec-core-11.4.1.0.0.jar;. Test < message.txt import java.util.Properties; import sample.HTTPSOut; public class Test { public static void main(String[] args) throws Exception { Properties props = new Properties(); props.setProperty(HTTPSOut.HOST, ""); props.setProperty(HTTPSOut.PORT, "443"); props.setProperty(HTTPSOut.PATH, "/"); props.setProperty(HTTPSOut.USER, "username"); props.setProperty(HTTPSOut.PASSWORD, "*****"); props.setProperty(HTTPSOut.TRUST_STORE, "C:\\somewhere\\keystore"); props.setProperty(HTTPSOut.TRUST_STORE_PWD, "*****"); HTTPSOut client = new HTTPSOut(); client.send(System.in, null, props); } } HTTPSOut will send the following request over SSL/TLS: POST /Hello HTTP/1.1 Content-Type: multipart/form-data; boundary=----------------------------afatudbu6sb5-875oo9dmn52fzfypuig0x1kv Authorization: Basic: dXNlcm5hbWU6cGFzc3dvcmQ= User-Agent: M3 Enterprise Collaborator v11.4.1.0 Cache-Control: no-cache Pragma: no-cache Host: Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Connection: keep-alive Content-Length: 256 ------------------------------afatudbu6sb5-875oo9dmn52fzfypuig0x1kv Content-Disposition: form-data; name="name"; filename="output.xml" Content-Type: application/xml Hello, World! ------------------------------afatudbu6sb5-875oo9dmn52fzfypuig0x1kv-- Activity diagram Here is a sample activity diagram of the HTTPSOut channel: Authentication bug There is a bug in the HTTPSOut class regarding the HTTP Basic authentication header that will cause the server to return HTTP/1.1 401 Unauthorized, and that is easy to fix: // incorrect urlConn.setRequestProperty("Authorization: Basic", Base64.encode (to64, "ISO-8859-1")); // correct urlConn.setRequestProperty("Authorization", "Basic " + Base64.encode (to64, "ISO-8859-1")); The bug is located in both the HTTPSOut source code in the Partner Admin guide, and in the HTTPSOut class in the JAR file. And the JAR file is located in both the Partner Admin tool and in the MEC server in the Infor Grid. That code is only executed if you need HTTP Basic authentication (i.e. if you specify a username and password); you can ignore it otherwise. Proxy If you need to use a proxy, add the following code to the HTTPSOut class and recompile it: import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; [...] // get the proxy properties String proxyHost = props.getProperty(PROXY_HOST); int proxyPort = Integer.parseInt(props.getProperty(PROXY_PORT)); String proxyUser = props.getProperty(PROXY_USER); String proxyPassword = props.getProperty(PROXY_PASSWORD); // connect via proxy InetSocketAddress proxyInet = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyInet); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy); // authenticate to proxy Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); //con.setRequestProperty("Proxy-Authorization", "Basic " + Base64.encode(proxyUser + ":" + proxyPassword, "ISO-8859-1")); // this did not work for me You will need to add some if-then-else so the user can choose to use a proxy or not, and add some exception handling around parseInt. Also, for the user interface, you will need to add a group widget, a checkbox, four labels and four text boxes to the HTTPSOutPanel class and recompile it: ✗Security holes Unfortunately, the HTTPSOut class does not verify the certificate and as such the connection is susceptible to man-in-the-middle attack. For instance, it does not verify the hostname of the certificate, it just returns true for any hostname: HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } }; More so, HTTPSOut does not verify the certificate’s dates, revocation, basic constraint, extensions, etc. Thus, HTTPSOut is not safe to use out of the box. You have to implement certificate validation yourself. That is probably why it is only a sample. Compilation To compile the HTTPSOut and HTTPSOutPanel classes: - Recover the source code (either copy/paste it from the Partner Admin guide, or decompile the classes). - Change the code as needed (e.g. fix the authentication bug, add the proxy settings, add certificate validation, etc.) - Compile the source code with: javac -cp lib\log4j-1.2.17.jar;lib\ec-core-11.4.1.0.0.jar sample\HTTPSOut.java javac -cp lib\x86-3.3.0-v3346.jar;lib\log4j-1.2.17.jar;lib\ec-core-11.4.1.0.0.jar;. sample\HTTPSOutPanel.java - Replace the Java classes in both the Partner Admin tool folder and in the MEC server folder of the Infor Grid, for example: D:\Infor\MECTOOLS\Partner Admin\classes\sample\ D:\Infor\LifeCycle\host\grid\M3_Development\grids\M3_Development\applications\MECSRVDEV\MecServer\lib\sample\ - Restart the Partner Admin and restart the MEC server in the Infor Grid. - The class loader will give precedence to the classes you put in the folders over the classes in the JAR file. 1. Preparation Before we can use HTTPSOut, we have to prepare the terrain for SSL/TLS. As a reminder, the HTTPSOut channel is an HTTP client that will make an HTTP request to a destination HTTP server over SSL/TLS, e.g. to. 1.1. Server authentication The short instructions to setup server authentication are: openssl s_client -connect > example.cer keytool.exe -import -file example.cer -keystore example.ks -storepass changeit The long instructions are the following. We need to setup server authentication, i.e. for HTTPSOut to affirm the identity of the server it is connecting to; it will rely on SSLSocket to verify that the server certificate is signed by a certificate authority that is stored in a trusted keystore. Internet Explorer, Google Chrome, Fiddler and other programs that use WinINet ultimately rely on the Windows certificate manager, certmgr.msc, but Firefox and Java each use their own key management. The JRE has its default keystore at %JAVA_HOME%\lib\security\cacerts that SSLSocket uses. HTTPSOut ignores the default keystore and requires the user to specify one. To create a Java keystore we use keytool.exe and import the server’s certificate in it. The steps are: - Open a browser to the destination server over HTTPS and open the certificate: - Inspect the certificate, any intermediate certificate authorities, and the root certificate authority, up the chain, and make sure you trust them (if your browser does not trust them it will throw a big warning sign): - Now we need Java to trust that certificate. Check if one of the certificates in the chain is already in your Java keystore. Java already comes with a list of trusted certificates in its keystore. If the destination server presents a certificate that is already trusted by one of the trusted certificates of the JRE, it will automatically be trusted by the JRE, i.e. the friends of my friends are my friends. In my case, my JVM already trusts the certificate authority DigiCert, so by chain of trust it will automatically trust the certificate presented by. It may be the same case for you: keytool.exe -list -keystore cacerts -storepass changeit | findstr /i DigiCert keytool.exe -list -keystore cacerts -storepass changeit -v -alias digicerthighassuranceevrootca - If you already have the server certificate, good, just keep in mind the location of that keystore, and skip the rest of these steps; otherwise continue reading. - Export the certificate to a file, e.g. example.cer: - Import the certificate to a keystore, e.g. example.ks: keytool.exe -import -file example.cer -keystore example.ks -storepass changeit - Now you have a keystore ready for HTTPSOut. 1.2. Client authentication As for client authentication, the HTTPSOut channel does not support that, i.e. it does not have a public/private keys and a digital certificate to present to the server if the server requests it, so we have to forget about that. If the server needs to authenticate the client, we can use Basic authentication (provided we fix the authentication bug). 2. How to setup Now let’s setup the HTTPSOut channel in MEC. The steps will be: - Setup the Send protocol - Setup the Send channel configuration - Setup the Agreement with detection and processes 2.1. Setup the Send protocol - Open the Partner Admin tool - Go to Manage > Advanced - Select the Send Protocols tab - Click New, and set: Protocol: HTTPSOut Send class: sample.HTTPSOut UI class: sample.HTTPSOutPanel - Click OK - Click Close 2.2. Setup the Send channel configuration - Go to Manage > Communications - Select the Send tab - Click New: - Select protocol HTTPSOut and enter the information host, port number and path to the destination server, as well as the keystore where you saved the certificate and the keystore password, and optionally set user and password for HTTP Basic authentication to the destination server (provided you corrected the authentication bug): Note: The keystore path is relative to the JVM that runs MEC server, i.e. java.exe must be able to access the file and have read permission to it. Also, given the Infor Grid is distributed make sure the keystore file is distributed accordingly to the correct server. - Optionally set the proxy settings if you added that feature to the classes (see proxy section above) - Click Send test message to ensure everything is correct; if you get an error message, test the HTTPSOut class as explained in the test section above, or check the troubleshooting tips in the section below - Click OK - Click Close 2.3. Setup the Agreement with detection and processes -. - Go the agreement > Processes, right-click select Send, and select the HTTPSOut channel: - Click OK - Click Save - The HTTPSOut channel is now ready to use 3. How to test To test the HTTPSOut channel, follow the same instructions as in the test of Part 4. 4. …on the Internet If you are doing the HTTPS requests to a server out on the Internet you should consult with your security team. I have MEC in a LAN behind a NAT, firewall, content based filter, security appliance, and transparent proxy. 5. Troubleshooting In case HTTPSOut does not work as expected, here are some troubleshooting tips. Check the logs The MEC server logs are useful for troubleshooting problems. For example, in one case I got the following exception: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target That means the server certificate validation failed, either because we put the incorrect server certificate in the keystore that we defined in PartnerAdmin, either because a man-in-the-middle server presented a different certificate. Test SSL/TLS connection Some network and security administrators setup firewalls, proxies, and gateways that interfere with SSL/TLS. In my case, I will ensure that my host can access the destination server over SSL/TLS. For that: - Locate on which node is MEC server running: - From that server (for example via Remote Desktop Connection), make a test connection to the destination server over SSL/TLS, for example use OpenSSL s_client: openssl s_client -connect -showcerts - Make sure the server certificate that is presented is the correct one. Test HttpsURLConnection - Check what JVM the MEC server is using: - Use that JVM to test a HttpsURLConnection; that will check if that particular JVM of that host has access to read that keystore, it will check if it can make a SSL/TLS connection to that destination server, and it will show the server certificates received: // javac Test.java && java -cp . Test import java.io.OutputStream; import java.net.URL; import java.security.cert.Certificate; import javax.net.ssl.HttpsURLConnection; public class Test { public static void main(String[] args) throws Exception { System.setProperty("javax.net.ssl.trustStore", "D:\\java\\jre\\lib\\security\\cacerts"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit"); URL url = new URL(""); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setDoOutput(true); OutputStream out = con.getOutputStream(); Certificate[] scerts = con.getServerCertificates(); for (Certificate scert: scerts) { System.out.println(scert.toString()); } con.disconnect(); } } Test HTTPSOut See the section at the top to test the HTTPSOut class. Conclusion That was an illustration of how to setup the HTTPSOut channel in MEC so that MEC can act as a client making secure HTTP requests to servers over SSL/TLS. For that, we reviewed the basics of HTTPS, we reviewed the features and drawbacks of HTTPSOut, we learned how to fix the authentication bug, how to add proxy settings, we identified security holes, we learned how to recompile the classes, how to setup the channel in PartnerAdmin, how to test, and how to troubleshoot. HTTPSOut lacks features, it has a bug, and it has security holes; that is probably why it is just considered a sample channel that is unsafe to use in a production environment. Take it as a starting point from which you can build your own safe channel with production quality. Hopefully, Infor will remove the deprecated documentation from the Partner Admin guide, will enhance the HTTPSOut channel from unsafe sample to safe channel with production quality, and will eventually provide a native connection handler in the Infor Grid for MEC. In the next part of this guide, I will illustrate how to setup HTTPS for inbound messages. (Congratulations if you made it this far! Let me know what you think in the comments below.) Related articles 7 thoughts on “HTTP channels in MEC (part 5)” NOTE: To be more specific, a digital certificate must be verified twice: 1) Verify the certificate before you store it in the keystore for the first time. This should be done out-of-band, i.e. not using the same communication channel for SSL/TLS but using another communication channel, like phone or email or snail mail; it’s a public key so it doesn’t matter if it’s seen, as long as it’s not tampered with. Windows, browsers, Firefox and the JRE come pre-loaded with certificates they trust. If you are using a certificate that’s not in those key stores, for example if you install the certificate of a partner, then you should verify out-of-band what your SSL/TLS client receives. 2) Verify the certificate programmatically in your Java code. That’s what the sample.HTTPSOut class does not do and that you should add. That’s all standard for digital certificates. Nothing specific to MEC. UPDATE: The folder for the Java classes may not be MecServer\lib\ folder but MecServer\custom\ . To be verified. NOTES: some examples of certificate validation: CWE-295: Improper Certificate Validation CWE-297: Improper Validation of Certificate with Host Mismatch UPDATE: Unless you have specific requirements to use non-blocking I/O with java.nio (unusual; needed mostly for gigabyte file transfers), for sending HTTPS from MEC, I would use the Web Service process which despite its name is not SOAP exclusive but byte-based and can send anything such as XML, text, etc. That’s built-in MEC. I wouldn’t mess with the HTTPSOut above. See this post for more details UPDATE: Here is a new post replacing this:
https://m3ideas.org/2015/04/03/http-channels-in-mec-part-5/
CC-MAIN-2018-39
en
refinedweb
Introduction: Hack. See pictures. Step 4: Chop Time Step 5: Putting It All Back Together The first video shows stuffing the board back in, and the second is the gears. In the first I was at an awkward angle becuase of the camera, so I couldn't close the case all the way. You get the Idea. Step 6: Code Here is a link to some test code. Just hook up the ground and power of the servo to the Arduino 5v and GND, then hook up the yellow or orange PWM control wire to pin 9 on Arduino. Copy and paste this code into the program, upload, and see if if works! I hope this helps you guys out with your servos. Check out Make Magazine's page on servos. 73 Discussions Um, hello? I am a 9 year old kid who plays with electronic stuff. I am using a BBC Micro:Bit, a Tower Pro SG90 micro servo and a AX-microBIT extension board. I do not have an Arduino. Can this method be used with the Micro:Bit too? after all the hack, can this servo rotate with 2 directions? and how about degree rotation ? can we set that ? thanks so much yea i wonder the same thing all videos are gone OH yeah, I accidentially deleted my vimeo account. I'll try to make a new one here soon Please send me the link when you re-create your account I am looking forward to seeing your videos! Thanks alot. Please give me your name on vimeo after you re-uploaded the videos thanks do you know what is the max voltage input for the motor if i wanted to control the motor bypassing the board? I Used two 2.2K resistor and this code. It works fine for rotate in two directions. sorry my english #include <Servo.h> Servo myservo; void setup() { Serial.begin(9600); } void loop() { if ( Serial.available()) { char ch = Serial.read(); switch(ch) { case '1': // direction 1 delay(50); myservo.attach(9); myservo.write(148); //you can change from 76 to 180 for change speed break; case '2': // direction 2 delay(50); myservo.attach(9); myservo.write(0); //you can change from 72 to 0 for change speed break; case '3': // stop myservo.detach(); break; } } now, I have to find a solution for rotate in an angle with presition } Nice! i have removed the collar from pot and the mechanical stopper so can i use the motor without 2.2k resistor? plz help am stuck at this thing...thank you You need to make a voltage divider of some sorts. Use a 1k -3.3k resistor if you have to. My SG90 had the pot directly soldered to the board, which made it difficult to remove. So I read the comments and chose to leave it in place. Instead I stripped out the keyway on the main/final/potentiometer gear by twisting it, then eyeballed mid-position on the pot and epoxied the pot wiper and shaft in place. Testing it with the Arduino Servo:Sweep example works great. The speed then sweeps up, slows down, and reverses, and repeats endlessly. Has anyone found a good way to control the speed? I tried setting the signal pin high and adding a delay then setting it low, but that doesn't accurately work below about a 20 millisecond delay. Thanks. Did you try changing this? delayMicroseconds(servoPosition); servoPosition is set at 2000, try changing that. Thanks! That's Works! Here's a shortcut that worked for me: only break the plastic stopper on the top most gear (as shown in Clip #313). I didn't have to remove the pot nor the black sleeve thingy. Use the following code: ! I like it! I modified servo before 6 months ,possible i used 2.2 resistance , i am not sure. On my servo it is a succes. Try this : #include <Servo.h> Servo myservo; int val = 0; void setup() { myservo.attach(9); } void loop() { myservo.attach(9); for(val = 0; val < 60; val += 1) { myservo.write(45); delayMicroseconds(1100); } myservo.detach(); delay(1000); } 1 .Now i have clockwise 45 degrees ABOUT If i chance myservo.writte(148) i have 45 degrees anticlockwise. 2 .if i change myservo.write(90) and delayMicroseconds(900) i have step 20 degrees. 3.if i change myservo.write(95) and delayMicroseconds(900) i have step 11.25 degrees 4 PLAY with value myservo.write(X) and delayMicroseconds(Y) to find the correct degree you need to your servo. I put after myservo.detach() , delay(1000) to count the steps . ZERO in my servo is 102-103 . after that value start anticlockwise. GOOD LUCK
https://www.instructables.com/id/How-to-Make-a-TowerPro-Micro-Servo-Spin-360/
CC-MAIN-2018-39
en
refinedweb
According to my *biased* sample, I noticed people with Computer Science background prefer SQL++ more than AQL. Simply because they're trained to write SQL queries. However, when I show AsterixDB to Computational Physics/Engineering/Data Science folks whom they are used to Matlab and Python, they seems to like AQL more. They say "it looks like writing a Python code". I think it depends on how people are trained to do stuff. On Sat, Feb 4, 2017 at 11:49 AM, Mike Carey <dtabass@gmail.com> wrote: > My $0.01: > > - I think users in general will like SQL++ better than AQL for sure. This > is based on having given lots of talks on AsterixDB and never feeling like > the audience has been sold on AQL's not being SQL-based. Now that Yannis > P. has provided a nice SQL-oriented extension that has the power of AQL, > and especially since Don Chamberlin (originator of SQL and major XQuery > contributor) is putting brain power into SQL++, I think we should surely > move over time (and preferably not a lot of time). > > - There is a style of SQL++ queries that is very much like AQL - namely, > where you use SELECT VALUE and use explicit record constructors - that > should prove surprisingly easy to migrate to. Thus, I don't think > migrating our query generator will be as bad as one might think. (I am > hopeful that there will be mostly localized 1:1 substitutions in the > generator's template query components.) I would estimate a person week or > less to make the move (for someone who knows the generator) - maybe 2-3 > days to do the work and 1-2 days to exercise it thoroughly in terms of > tests. I could assess this better (and would be happy to) if someone wants > to spend an hour projecting the source code for the generator on my office > screen and chatting about the differences. (Maybe in March between > quarters?) > > - It would be nice for new work on projects like BAD to be "future-based" > rather than "past-based" - e.g., ideally, when there is AsterixDB syntax > for window functions someday, it would be nice for those to be extending > SQL++ rather than AQL. I suspect we could get invaluable free language > consulting from Yannis P. and maybe even Don Chamberlin on our extensions > if SQL++ was their basis. (I think that most of the rest of BAD is pretty > language-agnostic, so I would estimate a day or so to migrate most/all of > what's there. Channels are function-bodied and functions are in both > languages; there's probably very little DML code in the broker, and what's > there will migrate trivially.) > > Anyway, I agree with Chen that we should continue to support AQL for > awhile - but I also think we should deprecate it, i.e., make it clear that > it's not the future, so that extension work doesn't start from the "wrong" > starting point. Note that the reason for wanting to deprecate it is that, > while it's fun to say we are bi-lingual, and to point to that as a benefit > of our nicely structured Asterix software stack, it is pretty expensive in > person time to maintain two of everything - so we could get more > functionality for our person-buck if we were to focus on one thing going > forward. (Otherwise we always need to be trying everything in two places, > run everything on two languages - doubling the cost of running regression > tests! - etc.) > > Summary: I would personally like to see us plan, as a community, to > indeed make a shift. What I found when I wrote the 101 for SQL++ was that > it was nice - more concise than AQL - and also more intuitive for the most > part. (And that it's also not necessarily as different, when used in the > way I mentioned above, as you'd think.) > > Cheers, > > Mike > > PS - It's tempting to do a 300-person user study at the end of CS122a in > early March - they're all going to use AsterixDB in the last 1-2 weeks of > my class - i.e., it'd be interesting to see what happens if half used AQL > and half used SQL++. (But I'm not sure how we'd assess the results.) :-) > > > On 2/3/17 7:28 PM, Chen Li wrote: > >> This issue came out during our weekly Cloudberry meeting today. >> >> We need to be careful about this transition from AQL to SQL++. Considering >> the amount of effort put into the logic of AQL translation in Cloudberry, >> it will be good to keep supporting AQL for a while. Meanwhile, @Jianfeng, >> we should start thinking about migrating the translation to SQL++. >> >> On Fri, Feb 3, 2017 at 7:21 PM, Till Westmann <tillw@apache.org> wrote: >> >> It currently doesn’t, but it also requires some more work. >>> >>> If we want to use it for AQL, we should simply be able to create a second >>> instance of it with the AQL compilation provider. >>> >>> Cheers, >>> Till >>> >>> >>> On 3 Feb 2017, at 18:57, Taewoo Kim wrote: >>> >>> Regarding this, I have a question. >>> >>>> Does the new revised HTTP API - Query Service (/query/service) support >>>> AQL? >>>> I am asking this since inside the code, it gets the SQLPP compilation >>>> provider. >>>> >>>> public class CCApplicationEntryPoint implements >>>> ICCApplicationEntryPoint { >>>> >>>> >>>> protected IServlet createServLet(HttpServer server, Lets key, >>>> String... >>>> paths) { >>>> >>>> switch (key) { >>>> >>>> case QUERY_SERVICE: >>>> >>>> return new QueryServiceServlet(server.ctx(), paths, >>>> ccExtensionManager.getSqlppCompilationProvider(), >>>> >>>> ccExtensionManager.getQueryTr >>>> anslatorFactory(), >>>> componentProvider); >>>> >>>> Best, >>>> Taewoo >>>> >>>> On Fri, Feb 3, 2017 at 6:34 PM, Jianfeng Jia <jianfeng.jia@gmail.com> >>>> wrote: >>>> >>>> @Yingyi, I’m not saying learning SQL++ is difficult. >>>> >>>>> Currently, we have a class called AQLGenerator that can translate the >>>>> Cloudberry request syntax to AQL. It took us several weeks finishing >>>>> it. >>>>> I guess it will take similar time to write a SQLPPGenerator to achieve >>>>> the >>>>> same goal. >>>>> >>>>> As long as the RESTFul API can accept AQL, we don’t need to spend time >>>>> to >>>>> implement a new generator. >>>>> >>>>> On Feb 3, 2017, at 6:02 PM, Yingyi Bu <buyingyi@gmail.com> wrote: >>>>> >>>>>> It will be a hard work to switch to SQL++. >>>>>> >>>>>>> Why translating to SQL++ is harder than AQL? I wonder if the current >>>>>>> >>>>>> SQL++ >>>>> >>>>> language design and implementation misses some key pieces. >>>>>> >>>>>> >>>>> >>>>> > -- *Regards,* Wail Alkowaileet
http://mail-archives.apache.org/mod_mbox/asterixdb-dev/201702.mbox/%3CCALgBV_dZN4dUUBUSVbLWDcuktRD9SsC3pQ=TihtohpQFRjd8Zg@mail.gmail.com%3E
CC-MAIN-2018-39
en
refinedweb
Fast iterations on large numbers of cache objectskburns Sep 21, 2004 2:43 AM Hi, I have a large number of objects in my cache (1000) all under the same node (/a/b), all instances of the same class (A). Each of these objects itself contains a Vector of objects (class B). Part of my business logic requires calling a method of class B for all class B instances contained in all Class A instances. I've implemented this as follows: 1. query for all class A instances myTree.getChildrenNames("/a/b") 2. for each FQN in the returned Set, get the object A obj = (A) myTree.getObject(FQN) 3. for each instance of class A, iterate over the Vector of B's calling the method When running this test, it takes around 4 - 5 seconds to complete. I really need this time to be around 0.5 seconds. When using a Vector in place of the cache, the test takes less than 100 ms - hardly surprising since the objects are already in memory. I assume that the creation of the objects (during the myTree.getObject() process) is what is taking the time. The best solution I can think of is to maintain two copies of the objects that I need to quickly iterate over. One copy in the cache, a separate copy in memory (a Vector). This solution is viable only because this fast iteration only involves reading the object's data. When the object changes (in the cache) I can update the Vector version through a TreeCacheListener.nodeModified() mechanism. Has anyone else faced a similar issue? Have I overlooked a way to just use the cache only to do this fast iteration? Many thanks Ken 1. Re: Fast iterations on large numbers of cache objectsNorbert von Truchsess Sep 21, 2004 4:12 AM (in response to kburns) If not being evicted, all your objects will reside in memory. What takes the time is the way you gonna access them. Looking up a thousand Names first and then looking up a thousand Objects by name is pretty much the slowest way at all to do this. This is like a paperboy that just delivers one paper at a time returning to his office to get the address of the next customer instead of making use of the fact that all customers live in houses that are neatly lined up in a row :-) Doing it this way will be much faster: Node myNode = myTree.get("/a/b"); Map allOfMyNodesChildren = myNode.getChildren(); Iterator it = allOfMyNodesChildren.entrySet().iterator(); while(it.hasNext()) { ... } Even faster would be if you implement a TreeCacheListener that stores references to all the objects in question in a vector you gonna iterate over. Keep in mind, as long we are not talking of Strings or explicit use of 'clone()' Java Objects are passed by reference and not copied. Therefore it's pretty cheap (in terms of memory and cpu-use) to keep a (redundant) list of references to your objects. All u have to make shure is, that u don't keep references of objects u want to be garbage-collected. 2. Re: Fast iterations on large numbers of cache objectskburns Sep 21, 2004 9:22 PM (in response to kburns) Hi Norbert, I tried your second suggestion with storing (a reference) to the objects in a Vector. Just to recap to setup: - 1000 objects of class A, each storing a Vector containing 10 objects of class B - Iterate over the 1000 objects (A), for each, calling a method on each of the B's Case 1: Store the 1000 objects in a TreeCacheAop -> Query (from the cache) takes about 2.5 seconds Case 2: Store the 1000 objects in a Vector only -> Query (from the Vector) takes about 20 ms Case 3: Store the 1000 objects in a TreeCacheAop and also "add" the object to a Vector -> Query (from the Vector, ignoring the cache) takes about 2.5 seconds Why is Case 3 taking so much time (and also about the same time as Case 1)? I don't understand the inner workings of the cache, but is it the CacheInterceptor that is slowing things down? To me it appears that all operations on the object are being routed through the cache version, no matter if I query the cache or the reference in my Vector? Looks like the only way to handle this fast access is to maintain a seperate copy of the object? Can anyone help? Regards Ken 3. Re: Fast iterations on large numbers of cache objectsBen Wang Sep 21, 2004 9:38 PM (in response to kburns) Ken, If you are using TreeCacheAop, I am interested to see why it takes this long. Is it possible that you can send me your setup? I prefer it in JUnit test case file so I may incorporate it into the testsuite later. You will get the credit, of course. :-) To answer your Case 3 question, yes, if you declare both Class A and B *advisable*, then everything you do is intercepted. But the cost of aop is upfront; that is, during putObject. Afterwards, it should be relatively quick. -Ben 4. Re: Fast iterations on large numbers of cache objectskburns Sep 22, 2004 3:05 AM (in response to kburns) Hi Ben, After some further investigations, I've gone back to the Person, Student classes in the release examples. Seems that the aop interception is happening during access of objects, and that accessing objects contained within objects significantly increases access times. Here is the setup I used. 1. Add the following lines into the "Person" class: Vector myHobbies = new Vector(); public void addHobby(Hobby theHobby) { myHobbies.add(theHobby); } public Vector getHobbyVector() { return myHobbies; } 2. Create a new class "Hobby" public class Hobby { String name = null; public Hobby(String theName) { name = theName; } public Hobby() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "name=" + getName(); } } 3. Create objects: 1000 Students adding 10 "Hobby" instances to each student via the addHobby() method in the Person class. 4. Add each Student instance into a TreeCacheAop instance and also into a Vector (myVector). 5. Iterate: Do a query on the Vector (myVector)... Object[] array = myVector.toArray(); Student a = null; String hobbyName; Vector hobVect = null; Object[] hobarray = null; for (int i=0; i<array.length; i++) { a = (Student) array; // test 1 hobbyName = a.getName(); // test 2 hobVect = a.getHobbyVector(); hobArray = hobVect.toArray(); // test 3 loop through hobArray calling "getName()" on each } Results: test 1 - duration = 100ms test 2 - 430ms test 3 - 530 ms Seems to me that as soon as you access the Vector of objects (hobbies) under each Student is where the performance hit is kicking in? I'll try and put this into a JUnit test for you tomorrow. Hope the above sheds some light. Any ideas so far? Many thanks Ken
https://developer.jboss.org/thread/83107
CC-MAIN-2018-39
en
refinedweb
Red Hat Bugzilla – Bug 67829 X-term wierdness and Traceback Last modified: 2007-07-31 15:03:50 EDT Description of Problem:After the 'Oracle connection information' screen, an x-window pops up and starts streaming data, and when it closes, there's a traceback in the console window: None Traceback (innermost last): File "/usr/lib/python1.5/site-packages/libglade.py", line 28, in __call__ ret = apply(self.func, a) File "/mnt/cdrom/usr/sbin/satinstall", line 412, in onOracleInfoPageNext satInstall.installSchema(self.username, self.password, self.sid,terminal) File "/mnt/cdrom//usr/share/rhn/satinstall/satInstall.py", line 183, in installSchema if ret: NameError: ret Is this supposed to be some kind of status indicator? Version-Release number of selected component (if applicable): see bug 63780 This should be fixed with last nights commit. Using installer built at 03-Jul-2002 10:49 from QA, CVS version .99.3.1, no change, install fails. Perhaps there are rpm's missing? I notice that up2dateAuth.py and transports.py were worked on, and those aren't in my download tree: up2date -d --nosig apache apache-devel mod_perl `up2date --showall --channel=redhat-rhn-satellite-i386-7.2 | sed 's/-[^-]*-[^-]*$//' | grep -v tk` Sorry - that didn't make a lot of sense... just trying to be sure I'm downloading everything I should for the iso built. There was no traceback with the "09-Jul-2002 11:52" installer.iso. Currently a couple of status windows pop up. IIRC, the first one indicates the status of namespace clearing. The second just kind of pops up and does nothing. The processes are obviously running (as evidenced by the lack of window refresh), but the status window doesn't really provide any useful information. I'll take a look at why the second window never draws. It's about as close as I can get to a useful progress feedback at the moment. Fixed in latest installer (installer_10jul02_1521.iso). Closing.
https://bugzilla.redhat.com/show_bug.cgi?id=67829
CC-MAIN-2018-39
en
refinedweb
Stemming, variations, and accent folding¶ The problem¶ The indexed text will often contain words in different form than the one the user searches for. For example, if the user searches for render, we would like the search to match not only documents that contain the render, but also renders, rendering, rendered, etc. A related problem is one of accents. Names and loan words may contain accents in the original text but not in the user’s query, or vice versa. For example, we want the user to be able to search for cafe and find documents containing café. The default analyzer for the whoosh.fields.TEXT field does not do stemming or accent folding. Stemming¶ Stemming is a heuristic process of removing suffixes (and sometimes prefixes) from words to arrive (hopefully, most of the time) at the base word. Whoosh includes several stemming algorithms such as Porter and Porter2, Paice Husk, and Lovins. >>> from whoosh.lang.porter import stem >>> stem("rendering") 'render' The stemming filter applies the stemming function to the terms it indexes, and to words in user queries. So in theory all variations of a root word (“render”, “rendered”, “renders”, “rendering”, etc.) are reduced to a single term in the index, saving space. And all possible variations users might use in a query are reduced to the root, so stemming enhances “recall”. The whoosh.analysis.StemFilter lets you add a stemming filter to an analyzer chain. >>> rext = RegexTokenizer() >>> stream = rext(u"fundamentally willows") >>> stemmer = StemFilter() >>> [token.text for token in stemmer(stream)] [u"fundament", u"willow"] The whoosh.analysis.StemmingAnalyzer() is a pre-packaged analyzer that combines a tokenizer, lower-case filter, optional stop filter, and stem filter: from whoosh import fields from whoosh.analysis import StemmingAnalyzer stem_ana = StemmingAnalyzer() schema = fields.Schema(title=TEXT(analyzer=stem_ana, stored=True), content=TEXT(analyzer=stem_ana)) Stemming has pros and cons. - It allows the user to find documents without worrying about word forms. - It reduces the size of the index, since it reduces the number of separate terms indexed by “collapsing” multiple word forms into a single base word. - It’s faster than using variations (see below) - The stemming algorithm can sometimes incorrectly conflate words or change the meaning of a word by removing suffixes. - The stemmed forms are often not proper words, so the terms in the field are not useful for things like creating a spelling dictionary. Variations¶ Whereas stemming encodes the words in the index in a base form, when you use variations you instead index words “as is” and at query time expand words in the user query using a heuristic algorithm to generate morphological variations of the word. >>> from whoosh.lang.morph_en import variations >>> variations("rendered") set(['rendered', 'rendernesses', 'render', 'renderless', 'rendering', 'renderness', 'renderes', 'renderer', 'renderements', 'rendereless', 'renderenesses', 'rendere', 'renderment', 'renderest', 'renderement', 'rendereful', 'renderers', 'renderful', 'renderings', 'renders', 'renderly', 'renderely', 'rendereness', 'renderments']) Many of the generated variations for a given word will not be valid words, but it’s fairly fast for Whoosh to check which variations are actually in the index and only search for those. The whoosh.query.Variations query object lets you search for variations of a word. Whereas the normal whoosh.query.Term object only searches for the given term, the Variations query acts like an Or query for the variations of the given word in the index. For example, the query: query.Variations("content", "rendered") ...might act like this (depending on what words are in the index): query.Or([query.Term("content", "render"), query.Term("content", "rendered"), query.Term("content", "renders"), query.Term("content", "rendering")]) To have the query parser use whoosh.query.Variations instead of whoosh.query.Term for individual terms, use the termclass keyword argument to the parser initialization method: from whoosh import qparser, query qp = qparser.QueryParser("content", termclass=query.Variations) Variations has pros and cons. - It allows the user to find documents without worrying about word forms. - The terms in the field are actual words, not stems, so you can use the field’s contents for other purposes such as spell checking queries. - It increases the size of the index relative to stemming, because different word forms are indexed separately. - It acts like an Orsearch for all the variations, which is slower than searching for a single term. Lemmatization¶ Whereas stemming is a somewhat “brute force”, mechanical attempt at reducing words to their base form using simple rules, lemmatization usually refers to more sophisticated methods of finding the base form (“lemma”) of a word using language models, often involving analysis of the surrounding context and part-of-speech tagging. Whoosh does not include any lemmatization functions, but if you have separate lemmatizing code you could write a custom whoosh.analysis.Filter to integrate it into a Whoosh analyzer. Character folding¶ You can set up an analyzer to treat, for example, á, a, å, and â as equivalent to improve recall. This is often very useful, allowing the user to, for example, type cafe or resume and find documents containing café and resumé. Character folding is especially useful for unicode characters that may appear in Asian language texts that should be treated as equivalent to their ASCII equivalent, such as “half-width” characters. Character folding is not always a panacea. See this article for caveats on where accent folding can break down. Whoosh includes several mechanisms for adding character folding to an analyzer. The whoosh.analysis.CharsetFilter applies a character map to token text. For example, it will filter the tokens u'café', u'resumé', ... to u'cafe', u'resume', .... This is usually the method you’ll want to use unless you need to use a charset to tokenize terms: from whoosh.analysis import CharsetFilter, StemmingAnalyzer from whoosh import fields from whoosh.support.charset import accent_map # For example, to add an accent-folding filter to a stemming analyzer: my_analyzer = StemmingAnalyzer() | CharsetFilter(accent_map) # To use this analyzer in your schema: my_schema = fields.Schema(content=fields.TEXT(analyzer=my_analyzer)) The whoosh.analysis.CharsetTokenizer uses a Sphinx charset table to both separate terms and perform character folding. This tokenizer is slower than the whoosh.analysis.RegexTokenizer because it loops over each character in Python. If the language(s) you’re indexing can be tokenized using regular expressions, it will be much faster to use RegexTokenizer and CharsetFilter in combination instead of using CharsetTokenizer. The whoosh.support.charset module contains an accent folding map useful for most Western languages, as well as a much more extensive Sphinx charset table and a function to convert Sphinx charset tables into the character maps required by CharsetTokenizer and CharsetFilter: # To create a filter using an enourmous character map for most languages # generated from a Sphinx charset table from whoosh.analysis import CharsetFilter from whoosh.support.charset import default_charset, charset_table_to_dict charmap = charset_table_to_dict(default_charset) my_analyzer = StemmingAnalyzer() | CharsetFilter(charmap) (The Sphinx charset table format is described at )
https://whoosh.readthedocs.io/en/latest/stemming.html
CC-MAIN-2018-39
en
refinedweb
Michael wrote: could someone please tell me how I would modify the "file library" example to store an attribute with the file? (like the guest_name in message book) well, I don't have the example to hand, but my guess would be that you're looking to do something like:well, I don't have the example to hand, but my guess would be that you're looking to do something like: from AccessControl import getSecurityManager myfile.manage_addProperty('guest_name', getSecurityManager().getUser().getId() 'string') ...where myfile is your file object. That said, try just doing: myfile.getOwner(), it may do what you want already... Chris -- Simplistix - Content Management, Zope & Python Consulting - _______________________________________________ Zope maillist - Zope@zope.org ** No cross posts or HTML encoding! **(Related lists - )
https://www.mail-archive.com/zope@zope.org/msg18706.html
CC-MAIN-2018-39
en
refinedweb
I want enable colors from DirectX::Colors in my program, but without giving out that DirectX is used, so i'm trying this: namespace Colors { using namespace DirectX::Colors; } I hoped it would allow me to use e.g. Colors::Blue, but it doesn't. How can i do it? To use namespace alias: namespace Colors = DirectX::Colors; and then Colors::...
http://databasefaq.com/index.php/answer/379506/c-namespaces-directx-abstraction-hide-directx-namespace-inside-my-namespace
CC-MAIN-2018-26
en
refinedweb
Writing Unit Testable Code in C# with Dependency Injection ##Hello Test Driven Development## The idea of test driven development is to drive the development through unit tests. When ever we attempt to write a unit of code or a method we follow the following steps. - First write a unit test case for the method. This test case is going to fail at first because we don’t have our actual method implemented yet. Can’t even compile the code sometimes. - Write the actual method with the minimum code required to make the test case pass. - Refactor the method while keeping the test passing. Test driven development also helps improve the productivity because while writing a particular method, you can isolate and test a particular method, rather than debugging the entire application. If it’s a web application, the time to activate the entire application and debug a particular part of code is waste of time. ##Problem with Dependencies While Unit Testing## Another important nature of unit test is, they should execute fast and no matter how many time they execute, should produce the exact same results. Assume a method is performing an database update operation and every time you run the unit test case, its going to update the database. That’s not an acceptable behaviour of a unit test. The moment your method makes a call to an external database while running, the unit test actually becomes an integration test. The outcome of the test is going to change every time depending on the values persisted in the database which is again violates the rules of unit testing. So how do we make sure to eliminate external dependencies such as database from unit testing. That’s the tricky part. In-order to do test driven development, the code also should have a TDD complying design. Otherwise its very hard to follow TDD. Let’s explore by example. Let say we have an order class as follows and we want to unit test this class. public class Order{ public int OrderId {get; set;} public Type OrderType {get; set;} private DbConnection con; public Order(){ con = new DbConnection(); } public bool SaveOrder(){ bool result; if(OrderType == Type.Rush) { result = con.SaveRushOrder(OrderId); } else { result = con.SaveOrder(OrderId); } return result; } } We can write a test like following but is this truly a unit test. Every time we execute this test, its going to update a record in the database because the “Order” class is creating a “DbConnection” and invoking save operations on them, which is not what we want. public void OrderTest(){ Order testOrder = new Order(); testOrder.OrderType = Type.Rush; var result= testOrder.SaveOrder(); Assert.Equal(true, result); } ##Injecting Dependencies (Dependency Injection)## So how we do prevent this. The problem with our Order class is that it’s tightly coupled with DbConnection class. DbConnection is a dependency of Order class but its not allowing us to control that dependency rather its creating its dependencies inside the class. Which is a very bad practice in object oriented programming. Let do some change here to make the “Order” class more testable. public Interface IPersistanceConnection{ void SaveRushOrder(int OrderId); void SaveOrder(int OrderId); } public Class DbConnection : IPersistanceConnection{ public void SaveRushOrder(int OrderId){ //Actual persistance implementation goes here } public void SaveOrder(int OrderId){ //Actual persistance implementation goes here } } public class Order{ public int OrderId {get; set;} public Type OrderType {get; set;} private IPersistanceConnection con; public Order(IPersistanceConnection connection){ con = connection; } public bool SaveOrder(){ bool result; if(OrderType == Type.Rush) { result = con.SaveRushOrder(OrderId); } else { result = con.SaveOrder(OrderId); } return result; } } We created an interface called “IPersistanceConnection” and created a DbConnection class which implements “IPersistanceConnection” interface. Additionally we modified the “Order” class to accept an implementation of “IPersistanceConnection” interface. Now the “Order” class does not care about any concrete implementation. All it does know is that it can call two methods with some parameters and that’s it. Now we have the control to pass what ever implementation into the “Order” class as we want. This is called Dependency Injection. The “DbConnection” was a dependency of the “OrderClass”, but we extracted that dependency out of the class and injecting it through the constructor. Let’s modify the unit test case to make use of the new implementation. It’s time to create a mock implementation of the connection class called “FakeConnection” so that we can pass it to the “Order” class while unit testing. public Class FakeConnection : IPersistanceConnection{ public void SaveRushOrder(int OrderId){ //Fake implementation goes here } public void SaveOrder(int OrderId){ //Fake implementation goes here } } public void OrderTest(){ var fakeConnection = new FakeConnection(); Order testOrder = new Order(fakeConnection); testOrder.OrderType = Type.Rush; var result= testOrder.SaveOrder(); Assert.Equal(true, result); } Now when ever we execute the unit test, the “Order” class will call the fake connection’s Save methods which is not going to do any persistence operation and that’s what we wanted. But you might think do I need to create a fake or mock implementation every-time when I need to test the method? Well technically we need to create them, but the good news is there are tools to make them easy and hassle free. Will discuss them in the next post.
http://raathigesh.com/Writing-Unit-Testable-Code-in-C-with-Dependency-Injection/
CC-MAIN-2018-26
en
refinedweb
Introduction to Fluent API in C# In object orientation programming, fluent APIs are just like any other APIs but they provide a more human redable code. Consider a scenario where we want to build an object called Car and assign some properties to it. Var Car = new Car(); Car.Name = "Tesla Model S"; Car.Type = "Electric"; Car.Color = "Blue"; Arguablly the above code is still readable. If we are to translate the above code to plain english, it would be, “Create a car with the name Tesla Model S, which is type of electric with blue color”. The fluent APIs will provide the ability to write code which looks some what close to the translated englist phrase. So the code would look like the following if this car is created with a fluent API. var Car = new Car() .WithName("Tesla Model S") .WithType("Electric") .WithColor("Blue"); Isn’t that a more clear way to build the car object. Isn’t that Neat? So let’s see the implementaion of the fluent car builder which will build cars for us. public class Car{ public string Name {get; set;} public string Type {get; set;} public string Color {get; set;} public Car WithName(string Name){ this.Name = Name; return this; } public Car WithType(string Type){ this.Type = Type; return this; } public Car WithColor(string Color){ this.Color = Color; return this; } } The key thing to notice here is that we are returning ‘this’ in all the methods. This allows us to chain the method calls one after the other making the code redable and fun to write. Another imporant advantage of fluent style API is, they are self discoverable. Meaning that they are easy to learn than normal APIs. Even C# team realized the convenience of fluent style API’s and used them to implemented API like LINQ. Consider the following example. var Results = items.Where(e => e.Approved) .OrderBy(e => e.ProductionDate) .Select(e => e.Name) .FirstOrDefault(); Even though fluent APIs are neat, they wont be appicable for all the situations. As programmers we have a tendency to apply the new thing we learn in all the places. Honestly I tried to apply fluent API in several situations when I got to know about them. But in some instances they just dont work. But there are best fit certain scenarios where fluent APIs excel as well. So use them wisely!
http://raathigesh.com/Introduction-to-Fluent-API-in-C/
CC-MAIN-2018-26
en
refinedweb
Until we find a decent heuristic on how to choose between multiple identical trees, there is no point in supporting multiple mappings. This also enables matching of nodes with parents of different types, because there are many instances where this is appropriate. For example for and foreach statements; functions in the global or other namespaces.
https://reviews.llvm.org/D36183
CC-MAIN-2018-26
en
refinedweb
MYTableViewIndex is a re-implementation of UITableView section index. This control is usually seen in apps displaying contacts, tracks and other alphabetically sorted data. MYTableViewIndex completely replicates native iOS section index, but can also display images and has additional customization capabilities. Features - Can display images - Fully customizable: use custom fonts, background views, add your own type of items - Compatible with any UIScrollView subclass - Works properly with UITableViewController and UICollectionViewController - Automatic layout, inset management and keyboard avoidance (via TableViewIndexController) - Right-to-left languages support - Haptic Feedback support - Accessibility support Below are the screenshots for some of the features: Usage 1. Instantiation Manual setup The component is a UIControl subclass and can be used as any other view, simply by adding it to the view hierarchy. This can be done via Interface Builder or in code: let tableViewIndex = tableViewIndex(frame: CGRect()) view.addSubview(tableViewIndex) Note that in this case no layout is done automatically and all the required index view alignment is completely up to you. Using TableViewIndexController Things get more complicated when dealing with UITableViewController/UICollectionViewController. The root view of these view controllers is a UIScrollView descendant and using it as a superview for TableViewIndex is generally a bad idea, since UIScrollView delays touch delivery by default. Enter TableViewIndexController. When used, it creates a TableViewIndex instance, adds it to the hierarchy as a sibling of the root view and sets up the layout. The controller also observes UIScrollView insets and updates index view size accordingly. This makes sense when e.g. keyboard shows up. You can also use the controller to hide TableViewIndex for cirtain table sections, like Apple once did in its Music app: Using TableViewIndexController the setup can be done in just one line of code: let tableViewIndexController = TableViewIndexController(scrollView: tableView) 2. Data source To feed index view with data, one should simply implement the following method of TableViewIndexDataSource protocol: func indexItems(for tableViewIndex: TableViewIndex) -> [UIView] { return UILocalizedIndexedCollation.currentCollation().sectionIndexTitles.map{ title -> UIView in return StringItem(text: title) } } And attach it to the index view: tableViewIndexController.tableViewIndex.dataSource = dataSourceObject Several predefined types of items are available for displaying strings, images, magnifying glass and truncation symbols. You can provide your own type of item though. 3. Delegate To respond to index view touches and scroll table to the selected section, one should provide a delegate object and implement the following method: func tableViewIndex(_ tableViewIndex: TableViewIndex, didSelect item: UIView, at index: Int) -> Bool { let indexPath = NSIndexPath(forRow: 0, inSection: sectionIndex) tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: false) return true // return true to produce haptic feedback on capable devices } 4. Customization MYTableViewIndex is fully customizable. See TableViewIndex properties for more details. Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements - iOS 8.0+ - Swift 4.0 If you’d like to use the library in a project targeting Swift 3.x, please use swift-3.x branch. Installation CocoaPods MYTableViewIndex is available through CocoaPods. To install it, simply add the following line to your Podfile: pod 'MYTableViewIndex' Manually Download and drop all .swift files from MYTableViewIndex folder to your project. Objective-C All public classes of MYTableViewIndex are exposed to Objective-C, just import the library module: @import MYTableViewIndex; And don’t forget to enable frameworks in your Podfile: use_frameworks! Author Makarov Yuriy, [email protected] License MYTableViewIndex is available under the MIT license. See the LICENSE file for more info. Latest podspec { "name": "MYTableViewIndex", "version": "0.6.1", "summary": "A pixel perfect replacement for UITableView section index, written in Swift.", "description": "MYTableViewIndex is a re-implementation of UITableView section index. This control is usually seen in apps displaying contacts, music tracks and other alphabetically sorted data. MYTableViewIndex completely replicates native iOS section index, but can also display images and has many customization capabilities.", "homepage": "", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "Makarov Yuriy": "[email protected]" }, "source": { "git": "", "tag": "0.6.1" }, "social_media_url": "", "platforms": { "ios": "8.0" }, "source_files": "MYTableViewIndex/**/*", "pushed_with_swift_version": "4.0" } Sun, 28 Jan 2018 14:20:08 +0000
https://tryexcept.com/articles/cocoapod/mytableviewindex
CC-MAIN-2018-26
en
refinedweb
im_similarity_area, im_similarity - apply a similarity transform to an image #include <vips/vips.h> int im_similarity_area(in, out, s, a, dx, dy, x, y, w, h) IMAGE *in, *out; double s, a, dx, dy; int x, y; int w, h; int im_similarity(in, out, s, a, dx, dy) IMAGE *in, *out; double s, a, dx, dy; im_similarity_area() applies a similarity transformation on the image held by the IMAGE descriptor in and puts the result at the location pointed by the IMAGE descriptor out. in many have any number of bands, be any size, and have any non-complex type.. The functions return 0 on success and -1 on error. As with most resamplers, im_similarity performs poorly at the edges of images. similarity(1), similarity_area(1) N. Dessipris - 13/01/1992 J.Ph. Laurent - 12/12/92 J. Cupitt - 22/02/93 13 January 1992
http://huge-man-linux.net/man3/im_similarity_area.html
CC-MAIN-2018-26
en
refinedweb
IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 429 Secure Knowledge Management: Confidentiality,Trust,and Privacy Elisa Bertino,Fellow,IEEE,Latifur R.Khan,Ravi Sandhu,Fellow,IEEE,and Bhavani Thuraisingham,Fellow,IEEE Abstract—Knowledge management enhances the value of a corporation by identifying the assets and expertise as well as ef- ficiently managing the resources.Security for knowledge manage- ment is critical as organizations have to protect their intellectual assets.Therefore,only authorized individuals must be permitted to execute various operations and functions in an organization.In this paper,secure knowledge management will be discussed,fo- cusing on confidentiality,trust,and privacy.In particular,certain access-control techniques will be investigated,and trust manage- ment as well as privacy control for knowledge management will be explored. Index Terms—Data mining,privacy,role-based access control (RBAC),secure knowledge management,security policy,semantic web,trust negotiation (TN),usage control (UCON). I.I NTRODUCTION K NOWLEDGE management is about corporations sharing their resources and expertise,as well as building intel- lectual find the expertise in the corporation. Furthermore,when experts leave the corporation through retire- ment or otherwise,it is important to capture their knowledge and practices so that the corporation does not lose the valuable information acquired through many years of hard work [15]. One of the challenges in knowledge management is main- taining security.Knowledge management includes many tech- nologies such as data mining,multimedia,collaboration,and the web.Therefore,security in web data management,multi- media systems,and collaboration systems all contribute toward securing knowledge-management practices.In addition,one needs to protect the corporation’s assets such as its intellectual property.Trade secrets have to be kept highly confidential so that competitors do not have any access to it.This means one Manuscript received February 1,2005;revised July 1,2005.This paper was recommended by Guest Editors H.R.Rao and S.J.Upadhyaya. E.Bertino is with the Department of Computer Sciences,Purdue University, West Lafayette,IN 47907 USA (e-mail:bertino@cs.purdue.edu). L.R.Khan and B.Thuraisingham are with The University of Texas,Dallas, Richardson,TX 75083 USA (e-mail:bhavani.thuraisingham@utdallas.edu). R.Sandhu is with the Industrial and Systems Engineering (ISE) Department, George Mason University,Fairfax,VA 22030 USA. Digital Object Identifier 10.1109/TSMCA.2006.871796 needs to enforce some formof access control such as role-based access control (RBAC),credential mechanism,and encryption. To have secure knowledge management,we need to have secure strategies,processes,and metrics.Metrics must in- clude support for security-related information.Processes must include secure operations.Strategies must include security strategies.The creator may specify to whom the knowledge can be transferred when knowledge is created.The manager of the knowledge may enforce additional access-control tech- niques.Knowledge sharing and knowledge transfer operations must also enforce access control and security policies.Secure knowledge-management architecture may be built around the corporation’s Intranet. While this paper provides an overview of secure knowledge management,it focuses mainly on confidentiality,trust,and privacy aspects.Section II provides an overview of knowl- edge confidentiality,trust,and privacy management.Furthermore,for each aspect,several techniques have been proposed.For example,various access- control policies such as read/write policies have been designed and implemented.We will focus on RBAC and UCON as they are emerging as two of the prominent access-control techniques and are natural for use in a corporate environment.RBAC is now being enforced in many commercial products and is a widely used standard.Models such as UCON encompass RBAC models and are becoming popular.Trust management and negotiation is inherent to knowledge management.For example,in an organization,a vice president may be authorized to receive the information,but the president may not have sufficient trust in the vice president to share the sensitive infor- mation.Finally,privacy is becoming critical for organizational knowledge management and data sharing.Furthermore,impor- tant knowledge-management technologies such as data mining and the semantic web have inferencing capabilities,and as a result,privacy as well as confidentiality may be compromised. Researchers are working on secure knowledge management that complements the ideas we have presented in this paper. An excellent introduction to secure knowledge management is given in [25].Work on trust management and policy-driven approaches for the semantic web have been reported in [7],[9], [11],and [12]. 1083-4427/$20.00 ©2006 IEEE 430 IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 Fig.1.Aspects of secure knowledge management. II.S ECURE K NOWLEDGE M ANAGEMENT As stated in Section I,secure knowledge management con- sists of secure strategies,processes,and metrics.In addition, security technologies such as the secure semantic web and privacy-preserving data mining are technologies for secure knowledge management.Security techniques for knowledge management include access control and trust management. Fig.1 illustrates the various aspects of secure knowledge man- agement.We will describe each component in this section. Security strategies for knowledge management include the policies and procedures that an organization sets in place for secure data and information sharing as well as protecting the intellectual property.Some of the questions that need to be an- swered include howoften should knowledge be collected?How often should the organization conduct audit strategies?What are the protection measures that need to be enforced for secure knowledge sharing?Secure knowledge-management strategies should be tightly integrated with business strategies.That is, if by enforcing intellectual-property protection the organization is going to be unprofitable,then the organization has to rethink its secure knowledge-management strategy. Secure processes for knowledge management include secure workflowprocesses as well as secure processes for contracting, purchasing,and order management.Security has to be incor- porated into the business processes for workflow,contracting, and purchasing.For example,only users with certain creden- tials can carry out various knowledge-management processes. Metrics for secure knowledge management should focus on the impact of security on knowledge-management metrics.Some examples of knowledge-management metrics include the num- ber of documents published,number of conferences attended, or the number of patents obtained.When security is incorpo- rated,then the number of documents published may decrease as some of the documents may be classified.Organizations should carry out experiments determining the impact of security on the metrics gathered. Security techniques include access control,UCON,trust management,as well as privacy control.These techniques are Fig.2.Secure knowledge-management architecture. enforced at all stages of knowledge-management processes. Secure knowledge-management technologies include data min- ing,the semantic web,as well as technologies for data and information management.The component technologies have to be secure if we are to ensure secure knowledge management. Fig.2 illustrates an architecture for secure knowledge management.The components of the architecture are a secure knowledge-creation manager,secure knowledge-representation manager,a secure knowledge manipulation and sustainment manager,and a secure knowledge dissemination and trans- fer manager.The secure knowledge-creation task includes creating knowledge as well as specifying security policies enforced based on the knowledge.Secure knowledge- representation tasks include representing the knowledge as well as policies in a machine-understandable format.Knowledge- representation languages such as rules and frames as well as some of the more recent semantic-web languages such as resource descriptive framework (RDF) and ontology languages are appropriate for knowledge and policy representation.Secure knowledge-manipulation tasks include querying and updating the knowledge base.In addition,the knowledge gained has to be sustained as long as possible.Various processes have to be in place to sustain the knowledge securely.Finally,secure knowledge dissemination and transfer task includes disseminat- ing and transferring the knowledge to authorized individuals. This section has provided an overview of the various aspects of secure knowledge management.The remainder of the paper will discuss certain security techniques for confidentiality,trust, and privacy. III.O PTIONAL I NFORMATION FOR C OMPUTER G EEKS ON C REATION OF E LECTRONIC I MAGE F ILES As we have stated,various access-control techniques may be applied for knowledge management to ensure confidentiality. These could be simple read–write policies,role-based policies, and UCON policies.We have chosen to discuss RBAC and UCON as we believe that they are important for secure knowl- edge management.RBAC is a standard implemented in several commercial products,and UCON encompasses RBAC. 1) RBAC for Knowledge Management:The concept of RBAC has emerged in the past decade as a widely deployed and highly successful alternative to conventional discretionary and mandatory access controls.The principal idea in RBAC is BERTINO et al.:SECURE KNOWLEDGE MANAGEMENT:CONFIDENTIALITY,TRUST,AND PRIVACY 431 that users and permissions are assigned to roles.Users acquire permissions indirectly via roles.For example,Alice is assigned to the analyst role and gets the permissions of the analyst role. This remarkably simple idea has many benefits and elabora- tions.Administration of authorization is much simplified in RBAC.Separation of user–role assignment and permission– role assignment facilitates different business processes and administrators for these tasks.Modifications to the permissions of a role immediately apply to all users in the role.Users are easily deassigned and assigned roles as their job functions and responsibilities change.There are two major elaborations of the simple RBAC concept.One elaboration is to have hier- archical roles,such as senior analyst and junior analyst.The senior analyst automatically inherits the permissions assigned to the junior analyst.This further simplifies administration. The second elaboration is to have separation of duty and other constraints.For example,we may require the roles of analyst and mission specialist to be mutually exclusive,so the same user cannot be assigned to both roles. Due to strong commercial interest by vendors and users in RBAC over time,the RBAC model evolved into a National Institute of Standards and Technology/American National Stan- dards Institute (NIST/ANSI) standard model first introduced in 2001 [8] and formally adopted as an ANSI standard in 2004.Even though there is agreement on a core standard for RBAC,much work remains to be done to truly exploit the potential of this technology for various applications including knowledge management.RBAC is especially relevant to the protection of information in a local environment as well as in a global environment across a coalition.The NIST/ANSI stan- dard model only captures aspects of RBACthat were mature for standardization.It explicitly lists a number of items on which the standard is silent.These include administration of roles and cross-organizational roles.These open issues are central to deployment of RBAC in complex environments.Traditional approaches to RBAC administration often are heavy weight in involving explicit actions by human administrators.These tradi- tional approaches,where a human is in the loop in every admin- istrative decision,are not scalable to the flexible and automated environment of knowledge management.Thus,one of the chal- lenges for managing security in an environment is to make the administration as seamless as possible.The assignment of users and permissions to appropriate roles should occur trans- parently as part of the normal workflow of the organization. Recently,Sandhu and co-workers have introduced lightweight administration models for RBAC based on user attributes [1] and have also examined interaction of roles and workflow [13]. We need to build upon this work to develop administrative models for RBAC for knowledge management with the goal of being as lightweight and seamless as possible without com- promising security.Traditional approaches to RBAC adminis- tration are also focused on the needs of a single organization or environment.This reflects the roots of this technology in enterprise access control.These approaches to security man- agement do not scale to a cross-coalition global environment. Different local environments may use completely different roles or use the same role names but with very different meaning.The hierarchical relationships between the roles may be different Fig.3.RBAC model. and possibly inconsistent.In some environments,a professor role may be senior to a student role,whereas in other envi- ronments within the same university,the student role may be senior to professor.For example,a student may be a dean taking a class from a professor,but this particular student is also the professor’s boss.Another example would be a student who is the president of an association taking a class from a professor who is a member of the same association. The basic structure of RBAC as developed in [18] is illus- trated in Fig.3.One of the key questions in applying RBAC to secure knowledge management is the nature of permissions in the knowledge-management context.The RBAC model is deliberately silent about the nature of permissions since this is highly dependent on the kind of system or application under consideration.Secure knowledge management requires control of access to a diverse set of information resources and services. We can identify the following broad categories: 1) information sources including structured and unstruc- tured data,both within the organization and external to the organization; 2) search engines and tools for identifying relevant pieces of this information for a specific purpose; 3) knowledge extraction,fusion,and discovery programs and services; 4) controlled dissemination and sharing of newly produced knowledge. Access to structured information in an organization,which resides in the organization’s databases and other application repositories,is likely to already be under the purview of some form of RBAC using organizational roles.It is reasonable to assume that these organizational roles could be the foundation for role-based access to unstructured information. However,access to unstructured information,which may reside on individual users’ personal computers or small department-level servers,is fundamentally more problematic. Organizations will need to articulate and enforce access-control policies with respect to this information.While the initial thrust 432 IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 of knowledge management has been on techniques to extract useful knowledge fromthis scattered but extremely valuable in- formation,challenging access-control issues must be addressed before these techniques can be applied in production systems. We can assume a facility for distinguishing shared information fromprivate information on a user’s personal computer. Existing personal-computer platforms have notoriously weak security so it will require fundamental enhancements in personal-computer technology to give us a reasonable level of assurance in this regard.Fortunately,there are several industry initiatives underway and,hopefully,some of these will come to fruition.The users will also need to determine how to share the public information.While reasonably fine-grained sharing tech- niques are available,it is unreasonable and undesirable to rely on the end users to specify these policies in detail.Moreover, current approaches are based on individual identities rather than roles.Scalability of information-sharing policies will require that they use organizational roles as a foundation.Information- sharing policies must be under control of the organization and cannot degenerate into anarchy where every user shares what they feel appropriate.There is a strong industry trend towards managing the corporate user’s platformfor a variety of reasons, so the requirement to impose role-based information-sharing policies would be consistent with this trend. Access to specific search engines might involve access con- trols because of the cost or sensitivity issues.Cost comes about in terms of cost of licenses and such for accessing the search engine as well as the cost of the actual effort of performing the search.Sensitivity comes about in terms of sensitivity of the results obtained by the search.Similar comments apply to the knowledge-extraction algorithms.Finally,the resulting knowledge itself needs to be shared and protected,thus com- pleting the cycle. The challenge for RBAC is to go beyond the traditional pic- ture of human administration of authorizations as depicted by the administrative roles in Fig.3,and move to a more seamless and less user-intrusive administrative model.More generally, we may need to invent new forms of RBAC that allow users to do some degree of exploration in the information space of an or- ganization without allowing carte blanche access to everything. This presents a significant research challenge to information- security researchers. 2) UCON for Knowledge Management:The concept of UCON was recently introduced in the literature by Park and Sandhu [17].In recent years,there have been several attempts to extend access-control models beyond the basic access matrix model of Lampson,which has dominated this arena for over three decades.UCON unifies various extensions proposed in the literature in context of specific applications such as trust management and digital rights management.The UCONmodel provides a comprehensive framework for the next-generation access control.A UCON system consists of six components: subjects and their attributes,objects and their attributes,rights, authorizations,obligations,and conditions.The authorizations, obligations,and conditions are the components of the UCON decisions.An authorization rule permits or denies access of a subject to an object with a specific right based on the subject and/or object attributes,such as role name,security classifica- Fig.4.UCON components. tion or clearance,credit amount,etc.An attribute is regarded as a variable with a value assigned to it in each system state. UCON is an attribute-based model,in which permission is authorized depending on the values of subject and object at- tributes.UCONextends the traditional access-control models in one aspect that the control decision depends not only on autho- rizations,but also on obligations and conditions.Obligations are activities that are performed by the subjects or by the sys- tem.For example,playing a licensed music file requires a user to click an advertisement and register in the author’s web page. Such an action can be required before or during the playing process.Conditions are system and environmental restrictions that are not directly related to subject or object attributes,such as the system clock,the location,system load,system mode, etc.Another aspect that UCON extends traditional access- control models is the concepts of continuity and mutability. A complete usage process consists of three phases along the time—before usage,ongoing usage,and after usage.The control-decision components are checked and enforced in the first two phases,named predecisions and ongoing decisions, respectively.The presence of ongoing decisions is called conti- nuity,as indicated Fig.4.Mutability means that the subject or object attribute value may be updated to a new value as a result of accessing.Along with the three phases,there are three kinds of updates:preupdates,ongoing updates,and postupdates.All these updates are performed and monitored by the security sys- tem as the access being attempted by the subject to the object. Updating of attributes by the side effect of subject activity is a significant extension to classic access control where the refer- ence monitor mainly enforces existing permissions.Changing subject and object attributes has an impact on other ongoing BERTINO et al.:SECURE KNOWLEDGE MANAGEMENT:CONFIDENTIALITY,TRUST,AND PRIVACY 433 or future usage of permissions involving this subject or object. This aspect of mutability makes UCON very powerful.The new expressive power brought in by UCON is very germane to the automated and seamless security administration required in environments.The core UCON model in [17] is illustrated in Fig.4. The concept of a role is easily accommodated in UCON by means of attributes.A role is simply another attribute attached to subjects and objects.UCON extensions to the RBAC model will be very useful in specifying access-control policies for secure knowledge management.The authorization component of UCON is of course fundamental to access control.However, the concept of attribute mutability brings in an important addi- tional component that allows us to control the extent of service provided to a user based on cost.Mutable attributes are auto- matically updated as a consequence of access.Thus,they can be used to limit the cost incurred by a knowledge search or knowl- edge extraction.Attribute mutability can also be used to control the scope of a knowledge search.Information about the past ac- tivities of a user can be aggregated in attributes associated with the user so these now become available for controlling future access to others. The concept of obligations in UCON also is beneficial for knowledge management.Obligations are actions required to be performed before access is permitted.Obligations can be used to determine whether or not an expensive knowledge search is required or whether the knowledge is already available in the system.Obligations can also be used to escalate anomalous re- source usage by a user so as to require additional conforming of the business need for the requested activity by that user or some other user.Ongoing obligations can be brought into play to reg- ulate the amount of resources spent on a knowledge search or extraction operation when these resources may not be predict- able in advance. The use of conditions can allow resource-usage policies to be relaxed during times of low activity or tightened during peak periods of high usage.This can be correlated with cost at- tributes.Thus,the cost at times of high load may be higher than the cost at times of low load.UCON facilitates the automatic adaptation of such policies. IV.T RUST M ANAGEMENT AND N EGOTIATION Trust management and negotiation is a key aspect of secure knowledge management.Knowledge management is essentially about corporations sharing knowledge to get a com- petitive advantage.This means that one needs to trust the individuals with whom he or she is prepared to share the knowledge.Furthermore,corporations may have to negotiate contracts about knowledge sharing,and this means that a corporation has to trust another corporation before drawing up the contracts.This section will discuss trust management and negotiation concepts and issues applicable for knowledge management. In today’s web-based knowledge-intensive applications,trust is an important goal.A question that many users have when interacting with a web server,with an application,or with an in- formation source is “Can I trust this entity?” Ideally,one would like to have available tools able to automatically evaluate the level of trust one may place on an unknown party encountered on the web.Though we are still far fromachieving such a goal, the problemof trust is currently being actively investigated and several notions and tools addressing aspects related to trust have been developed.Trust management and negotiation is be- coming an important aspect of secure knowledge management. When knowledge is shared across and within organizations,the parties involved have to establish trust rules for collaboration. Therefore,trust management plays an important role in knowl- edge management. In this section,we first discuss possible definitions of trust to give an idea of the different meanings associated with it,and we point out the notion that we refer to in the remainder of the discussion.We then discuss two different issues related to trust: how trust is established and how it is managed.Finally,we discuss a class of systems,known as trust-negotiation (TN) systems,that establishes a form of trust through a controlled exchange of credentials among some interacting parties.It is important to notice that trust,in its many forms,relies on infor- mation and knowledge about the interacting entities.As such, TN is an area where sophisticated knowledge-management tools could be profitably used.Furthermore,trust management is a key security technique for knowledge management.This is because organizations have to establish trust before sharing data,information,and knowledge. 1) Some Definitions of Trust:The notion of trust is used in a large number of different contexts and with diverse meanings, depending on how it is used.It is a complex notion about which no consensus exists in the computer and information- science literature,although its importance has been widely recognized.Different definitions are possible depending on the adopted perspective.For example,Kini and Choobineh [14] define trust fromthe perspectives of personality theorists,soci- ologists,economists,and social psychologists.They highlight the implications of these definitions and combine their results to create their definition of trust in a system.They define trust as:“a belief that is influenced by the individual’s opinion about certain critical system features.” Their analysis covers various aspects of human trust in computer-dependent systems,but they do not address the issue of trust between parties (humans or processes) involved in web-based transactions. A different definition is based on the notion of compe- tence and predictability.The Trust-EC project (. jrc.it/TrustEC/) of the European Commission Joint Research Centre (ECJRC) defines trust as:“the property of a business relationship,such that reliance can be placed on the business partners and the business transactions developed with them.” Such definition emphasizes the identification and reliability of business partners,the confidentiality of sensitive information, the integrity of valuable information,the prevention of unautho- rized copying and use of information,the guaranteed quality of digital goods,the availability of critical information,the man- agement of risks to critical information,and the dependability of computer services and systems.Another relevant definition is by Grandison and Sloman [10],and they define trust as:“the firmbelief in the competence of an entity to act dependably,se- curely,and reliably within a specified context.” They argue that 434 IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 trust is a composition of many different attributes—reliability, dependability,honesty,truthfulness,security,competence,and timeliness—which may have to be considered depending on the environment in which trust is being specified. A main difficulty of all these definitions as well as others is that they provide a notion of trust for which establishing metrics and developing evaluation methodologies are quite difficult.We thus adopt a more restricted notion of trust,which is the one underlying TN systems.Such notion was initially proposed by Blaze and Feigenbaum,according to whom,“Trust management problems include formulating security policies and security credentials,determining whether particular sets of credentials satisfy the relevant policies,and deferring trust to third parties” [5].Such a definition of trust basically refers to security policies regulating accesses to resources and cre- dentials that are required to satisfy such policies.TN thus refers to the process of credential exchanges that allows a party requiring a service or a resource from another party to provide the necessary credentials in order to obtain the service or the resource.Notice that,because credentials may contain sensitive information,the party requiring the service or the resource may ask to verify the other party’s credentials before releasing its own credentials.This definition of trust is very natural for secure knowledge management as organizations may have to exchange credentials before sharing knowledge. 2) Trust Services:The notion of trust services is not new; there are various financial,insurance,and legal services avail- able that make business activities simpler and less risky.In the web-based transaction context,trust services are emerg- ing as a business enabler,with the goal of delivering trust and confidence at various stages of the interaction among the parties involved in a transaction,including:establishing and maintaining trust,negotiations,contract formation,fulfillment, collaboration,through to dispute resolution.Trust services at- tempt to solve problems such as:establishing the authenticity of electronic communications;ensuring that electronic signatures are fair and legally binding,and creating an electronic audit trail that can be used for dispute resolution.The area of trust services is today a fast-moving area and it is difficult to an- ticipate the range of trust services that will be available in the next few years.We can,however,reasonably expect that they include mechanisms to support trust establishment,negotiation, agreement,and fulfillment,such as identity services,authoriza- tion services,and reputation services.Knowledge-management strategies make use of the trust services. 3) TN Systems:TN is an emerging approach exploiting the concept of properties of the entities as a means for establishing trust,particularly in open environments such as the web,where interacting entities are usually unknown to each other.TN is a peer-to-peer interaction,and consists of the iterative disclosure of digital credentials,representing statements certified by given entities,for verifying properties of their holders in order to establish mutual trust.In such an approach,access to resources (data and/or services) is possible only after a successful TN is completed.A TN system typically exploits digital identity information for the purpose of providing a fine-grained access control to protected resources.However,unlike conventional access-control models,TN assumes that the interacting parties Fig.5.Organization of a TN process. are peer and that each peer needs to be adequately protected. For instance,with respect to the peer owning the resource to be accessed,assets that need to protected are,in addition to the resource,the access-control policies,as they may contain sensitive information,and the credentials of the resource owner. With respect to the peer requiring access to the resource,the assets to be protected are the credentials as they often contain private information about the individual on behalf of whomthe peer is negotiating. 4) TN Building Blocks:We now briefly describe how ne- gotiations are generally intended,and identify the main phases and functional components of negotiations as given in [2].Such an approach is ideal for knowledge management.ATNinvolves two entities,namely a client,which is the entity asking for a cer- tain resource,and a server,which is the entity owning (or more generally,managing access to) the requested resource.The model is peer to peer:Both entities may possess sensitive re- sources to be protected,and thus must be equipped with a com- pliant negotiation system.The notion of resource comprises both sensitive information and services,whereas the notion of entity includes users,processes,roles,and servers.The term resource is intentionally left generic to emphasize the fact that the negotiations we refer to are general purpose,that is,a re- source is any sensitive object (e.g.,financial information,health records,and credit card numbers) whose disclosure is protected by a set of policies. Fig.5 illustrates a typical negotiation process.During the negotiation,trust is incrementally built by iteratively disclosing digital credentials in order to verify properties of the negotiating parties.Credentials are typically collected by each party in ap- propriate repositories,called subject profiles.Another key com- ponent of any TN is a set of access-control policies,referred to as disclosure policies,governing access to protected resources through the specification of the credential combinations that must be submitted to obtain access to the resources. To carry out a TN,parties usually adopt a strategy,which is implemented by an algorithmdetermining which credentials to disclose,when to disclose them,and whether to succeed or fail the negotiation.Several TNstrategies can be devised,each with different properties with respect to speed of negotiations and caution in releasing credentials and policies.The efficiency of BERTINO et al.:SECURE KNOWLEDGE MANAGEMENT:CONFIDENTIALITY,TRUST,AND PRIVACY 435 a strategy depends on two factors:the communication cost and the computational cost.The communication cost includes the sizes of the messages exchanged and their number.Communi- cation and computational costs of a negotiation strictly depend on the adopted strategy and vary from exponential,when a brute-force strategy is adopted,to more efficient strategies. 5) TN Requirements:We now discuss the relevant dimen- sions with respect to which policy languages can be analyzed. These dimensions can be classified in two main groups,i.e., those related to the adopted language and those related to the system and its components.It is important to note that these requirements are a partial list and other requirements are likely to be identified as research and deployment of negotiation sys- tems progress,given also the increasing number of researchers actively contributing to the trust-management area. a) Language requirements:TN policy languages are a set of syntactic constructs (e.g.,credentials,policies) and their associated semantics,encoding security information to be ex- changed during negotiations.Effective TNlanguages should be able to simplify credential specification and also to express a wide range of protection requirements through specification of flexible disclosure policies.The main relevant dimensions for these languages are related with expressiveness and semantics. b) System requirement:The development of comprehen- sive TN systems is quite challenging.On the one hand,such systems should be flexible,scalable,and portable.On the other,they should support advanced functions,such as sup- port for credential chains,authentication of multiple identities, and complex compliance-checking modes whose efficient im- plementation is often difficult.In particular,the compliance checker should be able to interpret a remote policy and check whether there exists a set of local credentials that satisfy the received policy. 6) Selected TN Systems:Because of the relevance of TN for web-based applications and knowledge management, several systems and research prototypes have been devel- oped.The most well-known systems include KeyNote by Blaze et al.[5],TrustBuilder by Yu and Winslett [26],and Trust-X by Bertino et al.[3],which we briefly discuss in what follows.These systems are relevant for TNin knowledge- management systems. KeyNote has been developed to work for large- and small- scale Internet-based applications.It provides a single unified language for both local policies and credentials.KeyNote cre- dentials,called assertions,contain predicates that describe the trusted actions permitted by the holders of a specific public key.As a result,KeyNote policies do not handle credentials as a means of establishing trust,mainly because the language was intended for delegation authority.Therefore,it has sev- eral shortcomings with respect to the requirements we have outlined. TrustBuilder is one of the most significant systems in the negotiation research area.It provides several negotiation strate- gies,as well as a strategy- and language-independent nego- tiation protocol ensuring the interoperability of the defined strategies.In TrustBuilder,each negotiation participant has an associated security agent that manages the negotiation.During a negotiation,the security agent uses a local negotiation strategy to determine which local resources to disclose next and to ac- cept new disclosures from other parties.TrustBuilder includes a credential-verification module,a policy-compliance checker, and a negotiation-strategy module,which is the system’s core. The system relies on a credential-verification module,which performs a validity check of the received credentials.Some re- cent investigation carried out in the framework of TrustBuilder includes support for sensitive policies (obtained by introduc- ing hierarchies in policy definitions),and privacy protection mechanisms (obtained by introducing dynamic policies,that is, policies dynamically modified during a negotiation). Trust-X supports all aspects of negotiation,specifically de- veloped for peer-to-peer environments.Trust-X supports an Extensible Markup Language (XML)-based language,known as XML-based Trust Negotiation Language (X-TNL),for speci- fying Trust-Xcertificates and policies.Trust-Xhas a typing cre- dential systemand addresses the issue of vocabulary agreement using XMLnamespaces.The use of namespaces combined with the certificate-type system helps the TN software in correctly interpreting different credentials’ schema,even when issued by different entities not sharing a common ontology.A novel aspect of X-TNL is its support for special certificates,called trust tickets.Trust tickets are issued on successfully completing a negotiation and can speed up subsequent negotiations for the same resource.X-TNL provides a flexible language for spec- ifying policies and a mechanism for policy protection,based on the notion of policy preconditions.A Trust-X negotiation consists of a set of phases that are sequentially executed.In particular,Trust-X enforces a strict separation between policy exchange and resource disclosure.This distinction results in an effective protection of all the resources involved in negotiations. Trust-X is a flexible system,providing various TN strategies that allow better tradeoffs between efficiency and protection requirements.In particular,Trust-X supports three different negotiation modes.The first,based on trust tickets,can be adopted when the parties have already successfully completed a negotiation for the same resource.The second mode,based on using specific abstract data structures called negotiation trees, performs a runtime evaluation of the negotiation’s feasibility by determining a sequence of certificate disclosures that can successfully end the negotiation.The last mode exploits a notion of similarity between negotiations and is based on the observation that a service provider usually handles many sim- ilar negotiations.Some recent investigation carried out in the framework of Trust-X includes support for privacy,anonymity, the development of a recovery protocols,and the integration with federated identity management. V.P RIVACY M ANAGEMENT Secure knowledge-management technologies include tech- nologies for secure data management and information manage- ment including databases,information systems,semantic web, and data mining.For example,data mining is an important tool in making the web more intelligent.Because of its ability to extract data on the web,it can aid in the creation of the se- mantic web and,subsequently,in the knowledge-management strategies and processes.The semantic web can be utilized 436 IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 by the knowledge manager to execute the various strategies and processes as well as to collect metrics.However,both the semantic web and data mining have inferencing capabilities, and therefore,one could combine pieces of information to- gether and infer information that is highly private or highly sensitive [20].This problemis the privacy problem[21]. Now,the semantic-web community has come up with plat- form for privacy preferences (P3P) [16] specifications.That is, when a user enters a web site,the site will specify its privacy policies and the user can then submit information if he/she desires.However,the web site may give out say medical records and names separately to a third party such as an advertising agency.This third party can make unauthorized inferences from the information legitimately obtained from the web site and deduce private information that associates the medical records with the names.That is,while data mining and the semantic web are very useful knowledge-management technologies,for secure knowledge management,we need to ensure that the information extracted as a result of data mining does not com- promise security and privacy.Furthermore,the semantic-web engine has to go beyond P3P enforcement to ensure privacy.In this section,we will discuss an approach to ensuring privacy for the semantic web so that privacy is managed as part of the knowledge-management process. Since data may be mined and patterns and trends extracted, security and privacy constraints can be used to determine which patterns are private and sensitive and to what extent.For exam- ple,suppose one could extract the names of patients and their corresponding healthcare records.If a privacy constraint states that names and healthcare records taken together are private, then this information is not released to the general public.If the information is semiprivate,then it may be released to those who have a need to know,such as say a healthcare administrator. Essentially,the inference-controller approach discussed in [19] is one solution to achieve some level of privacy.That is,the inference controller examines the privacy constraints,the query, and the information that has been released,and determines whether to release any further information.This approach can be regarded to be a type of privacy-sensitive data mining [22]. In our research,we have found many challenges to the inference-controller approach as discussed in [19].For exam- ple,how long can the systemmaintain the history information? How can we ensure that the constraints are consistent and complete?These challenges will have to be addressed when handling security and privacy constraints for the semantic web. Fig.6 illustrates security/privacy controllers for the semantic web.As illustrated,there are data-mining tools on the web that mine the web databases.The privacy controller should ensure privacy-preserving data mining.Ontologies may be used by the privacy controllers.For example,there may be ontology specifications for privacy constraints and these specifications may be used by the inference controller to reason about the ap- plications.Furthermore,XML and resource description frame- work (RDF) may be extended to specify security and privacy policies [4],[6]. The secure knowledge manager will utilize the secure se- mantic web to execute its knowledge-management strategies and processes.For example,the semantic web will be utilized Fig.6.Privacy controller for the semantic web. for various operations such as order management,procure- ment,and contracting.The security and privacy controllers will ensure that the security and privacy rules are not violated when executing the knowledge-management processes.We have dis- cussed a high-level design.The next step is to design the details of the security and privacy controllers and implement a secure semantic web for secure knowledge management.Some details of the design and algorithms are given in [24] and [23]. VI.S UMMARY AND D IRECTIONS This paper has discussed some key points in secure knowl- edge management.We have stressed that security has to be incorporated into the knowledge-management lifecycle.We discussed issues on integrating security strategy with knowl- edge management and business strategies of an organization. We also discussed an architecture for secure knowledge man- agement.Then,we focused on two prominent security tech- niques.With respect to access control,we discussed both RBAC and UCON and showed with examples how these ap- proaches may be applied for knowledge management.Then, we discussed trust management and negotiation for knowledge management.Because knowledge management will involve multiple organizations or multiple departments within an orga- nization,it is very important that the different parties establish TN rules for collaboration.Finally,we discussed privacy for secure knowledge management including privacy problems that arise due to data mining and inferencing inherent to the semantic web. There are many areas that need further work.First,we need to develop a methodology for secure knowledge management. While we have discussed some aspects of secure knowledge- management strategies,processes,and metrics,we need a comprehensive lifecycle for secure knowledge management. We also need to investigate further RBAC and UCON,as well as trust management and negotiation.The definitions and rules discussed in this paper have to be formalized for RBAC, UCON,and trust.The security critical components have to be BERTINO et al.:SECURE KNOWLEDGE MANAGEMENT:CONFIDENTIALITY,TRUST,AND PRIVACY 437 identified for knowledge management.Finally,privacy issues need to be investigated further. In addition to enhancing and formalizing the policies dis- cussed here,we also need to explore the incorporation of some of the real-world policy specifications into the knowledge- management strategies.For example,we need to examine the P3P specified by the World Wide Web Consortium and deter- mine how we can enforce such a policy within the framework of secure knowledge management.We also need to investigate integrity aspects of knowledge management.For example,how do we ensure the integrity of the data and the activities?How can we ensure data,information,and knowledge quality?The best way to test out the policies is to carry out pilot projects for different types of organizations including those fromacademia, industry,and government.Based on the results obtained,we can then continue to refine the policies for knowledge management. In summary,secure knowledge management will continue to be critical as organizations work together,share data,as well as collaborate on projects.Protecting the information and activities while sharing and collaborating will be a major consideration.This paper has provided some directions for incorporating confidentiality,trust,and privacy for knowledge management. A CKNOWLEDGMENT The authors would like to thank N.Tsybulnik and L.Liu for web and privacy-preserving data mining. R EFERENCES [1] M.Al-Kahtani and R.Sandhu,“A model for attribute-based user-role assignment,” in Proc.17th Annu.Computer Security Applications Conf., Las Vegas,NV,Dec.2002,pp.353–362. [2] E.Bertino,E.Ferrari,and A.C.Squicciarini,“Trust negotiations:Con- cepts,systems and languages,” Comput.Sci.Eng.,vol.6,no.4,pp.27–34, Jul./Aug.2004. [3] ——,“A peer-to-peer framework for trust establishment,” IEEE Trans. Knowl.Data Eng.,vol.16,no.7,pp.827–842,Jul.2004. [4] E.Bertino,B.Carminati,E.Ferrari,and B.Thuraisingham,“Secure third party publication of XML documents,” IEEE Trans.Knowl.Data Eng., vol.16,no.10,pp.1263–1278,Oct.2004. [5] M.Blaze,J.Feigenbaum,and J.Lacy,“Decentralized trust management,” in Proc.IEEE Symp.Security Privacy,1996,pp.164–173. [6] B.Carminati,E.Ferrari,and B.Thuraisingham,“Securing RDF doc- uments,” in Proc.DEXA Workshop Web Semantics,Zaragoza,Spain, Aug.2004,pp.472–480. [7] G.Denker,L.Kagal,T.Finin,M.Paolucci,and K.Sycara,“Security for DAML web services:Annotation and matchmaking,” in Proc.Int. Semantic Web Conf.,2003,pp.335–350. [8] D.F.Ferraiolo,R.Sandhu,S.Gavrila,D.R.Kuhn,and R.Chandramouli, “Proposed NIST standard for role-based access control,” ACMTrans.Inf. Syst.Secur.,vol.4,no.3,pp.224–274,Aug.2001. [9] T.Finin and A.Joshi,“Agents,trust,and information access on the semantic web,” ACMSIGMODRec.,vol.31,no.4,pp.30–35,Dec.2002. [10] T.Grandison and M.Sloman,“A survey of trust in Internet applications,” Commun.Surveys Tuts.,vol.3,no.4,pp.2–16,4th Quarter 2000. [11] L.Kagal,T.Finin,and A.Joshi,“A policy based approach to security for the semantic web,” in Proc.Int.Semantic Web Conf.,2003,pp.402–418. [12] L.Kagal,M.Paolucci,N.DSrinivasan,G.Denker,T.Finin,and K.Sycara,“Authorization and privacy for semantic web services,” IEEE Intell.Syst.,vol.19,no.4,pp.50–56,Jul./Aug.2004. [13] S.Kandala and R.Sandhu,“Secure role-based workflow models,” in Database Security XV:Status and Prospects,D.Spooner,Ed.Norwell, MA:Kluwer,2002. [14] A.Kini and J.Choobineh,“Trust in electronic commerce:Definition and theoretical consideration,” in Proc.IEEE 31st Int.Conf.System Sciences, 1998,pp.51–61. [15] D.Morey,M.Maybury,and B.Thuraisingham,Eds.,Knowledge Management,Cambridge,MA:MIT Press,2001. [16] Platform for Privacy Preferences.[Online].Available: [17] J.Park and R.Sandhu,“The UCONABC usage control model,” ACM Trans.Inf.Syst.Secur.,vol.7,no.1,pp.128–174,Feb.2004. [18] R.Sandhu,E.Coyne,H.Feinstein,and C.Youman,“Role-based access control models,” Computer,vol.29,no.2,pp.38–47,Feb.1996. [19] B.Thuraisingham and W.Ford,“Security constraint processing in a multilevel secure distributed database management system,” IEEE Trans. Knowl.Data Eng.,vol.7,no.2,pp.274–293,Apr.1995. [20] B.Thuraisingham,“Security standards for the semantic web,” Comput. Stand.Interfaces,vol.27,no.3,pp.257–268,Mar.2005. [21] ——,Database and Applications Security:Integrating Data Management and Information Security.Boca Raton,FL:CRC Press,May 2005. [22] ——,“Privacy preserving data mining:Developments and directions,” J.Database Manage.,vol.16,no.1,pp.75–87,Mar.2005. [23] ——,Building Trustworthy Semantic Webs.Boca Raton,FL:CRC Press,Jun.2006. [24] N.Tsybulnik,B.Thuraisingham,and L.Khan,“Design and implementa- tion of a security controller for the semantic web,” Univ.Texas,Dallas, Tech.Rep.UTDCS-06-06,2005. [25] S.Upadhyaya,H.R.Rao,and G.Padmanabhan,“Secure knowledge man- agement,” in Encyclopedia of Knowledge Management,D.Schwartz,Ed. Hershey,PA:Idea Group Inc.,2005. [26] T.Yu and M.Winslett,“A unified scheme for resource protection in automated trust negotiation,” in Proc.IEEE Symp.Security and Privacy, 2003,pp.110–122. Elisa Bertino (SM’83–F’02) received the B.S. and Ph.D.degrees in computer science from the University of Pisa,Pisa,Italy,in 1977 and 1980, respectively. She is a Professor of computer science and elec- trical and computer engineering at Purdue Univer- sity,West Lafayette,IN,and serves as Research Director of CERIAS.Previously,she was a Faculty Member at the Department of Computer Science and Communication of the University of Milan where she directed the DB&SEC laboratory.She has been a Visiting Researcher at the IBM Research Laboratory (now Almaden) in San Jose,at the Microelectronics and Computer Technology Corporation,at Rutgers University,and at Telcordia Technologies.She has been a consul- tant to several Italian companies on data management systems and applica- tions and has given several courses to industries.She has been involved in several projects sponsored by the EU.Her main research interests include security,privacy,database systems,object-oriented technology,multimedia systems.In those areas,she has published more than 250 papers in all major refereed journals,and in proceedings of international conferences and sym- posia.She a Coeditor in Chief of the Very Large Database Systems (VLDB) Journal.She is a coauthor of the books Object-Oriented Database Systems—Concepts and Architectures (Addison-Wesley,1993),Indexing Tech- niques for Advanced Database Systems (Kluwer,1997),and Intelligent Data- base Systems (Addison-Wesley,2001).She also serves on the editorial boards of several scientific journals,incuding IEEE Internet Computing,ACM Transac- tions on Information and System Security,Acta Informatica,the Parallel and Distributed Database Journal,the Journal of Computer Security,Data and Knowledge Engineering,the International Journal of Cooperative Information Systems,and Science of Computer Programming. Prof.Bertino is a member of the advisory board of the IEEET RANSACTIONS ON K NOWLEDGE AND D ATA E NGINEERING .She has served as Program Co-Chair of the 1998 IEEE International Conference on Data Engineering (ICDE).She has served as Program Committee members of several interna- tional conferences,such as ACM SIGMOD,VLDB,and ACM OOPSLA,as ProgramChair of the 2000 European Conference on Object-Oriented Program- ming (ECOOP 2000),and as Program Chair of the 7th ACM Symposium of Access Control Models and Technologies (SACMAT 2002).She recently served as ProgramChair of the 2004 EDBT Conference.She is a Fellow of the ACMand has been named a Golden Core Member for her service to the IEEE Computer Society.She received the 2002 IEEE Computer Society Technical Achievement Award for “outstanding contributions to database systems and database security and advanced data management systems.” 438 IEEE TRANSACTIONS ON SYSTEMS,MAN,AND CYBERNETICS—PART A:SYSTEMS AND HUMANS,VOL.36,NO.3,MAY 2006 Latifur R.Khan received the B.Sc.degree in com- puter science and engineering from the Bangladesh University of Engineering and Technology,Dhaka, in 1993,and the M.S.and Ph.D.degrees in computer science from the University of South- ern California,Los Angeles,in 1996 and 2000, respectively. He has been an Assistant Professor of Computer Science department at the University of Texas at Dal- las since September 2000.He is currently supported by Grants from the National Science Foundation, Nokia Research Center,Texas Instruments,and Alcatel,USA.He has authored more than 70 articles,book chapters,and conference papers focusing in the areas of multimedia information management,data mining,and intrusion detection.He has also served as a Referee for database/data mining journals and conferences (e.g.,IEEE TKDE,KAIS,ADL,VLDB),and he is currently serving as a ProgramCommittee Member for the 11th ACMSIGKDD Interna- tional Conference on Knowledge Discovery and Data Mining (SIGKDD2005), International Conference on Database and Expert Systems Applications DEXA 2005,and International Conference on Cooperative Information Sys- tems (CoopIS 2005),and Program Co-Chair of the ACM SIGKDD Interna- tional Workshop on Multimedia Data Mining,2005.He has also given a tutorial in the 14th ACMInternational World Wide Web Conference,WWW2005,May 2005,Chiba,Japan,and he has been an Associate Editor of Computer Standards and Interfaces Journal by Elsevier Publishing since June 2005. Dr.Khan has been awarded the Sun Equipment Grant. Ravi Sandhu (M’89–SM’90–F’02) received the B.Tech.and M.Tech.degrees in electrical engineer- ing from the Indian Institutes of Technology at Bombay and Delhi,respectively,and the M.S.and Ph.D.degrees in Computer Science from Rut- gers University,NJ,in 1975,1980,and 1983, respectively. He is a Professor of Information and Software Engineering and Director of the Laboratory for Information Security Technology at the George Mason University,Fairfax,VA.He is a leading au- thority on access control,authorization,and authentication models and proto- cols.His seminal paper on role-based access control (RBAC) introduced the RBAC96 model,which evolved into the 2004 National Institute of Standards and Technology/American National Standards Institute (NIST/ANSI) standard RBAC model (and is on track to become an ISO standard).More recently, he introduced the usage control (UCON) model as a foundation for next- generation access control by integrating obligations and conditions with the usual notion of authorization in access control and providing for continuity of enforcement and mutability of attributes.He has also served as the principal designer and security architect of TriCipher’s Armored Credential System (TACS),which earned the coveted FIPS 140 level-2 rating from NIST.He has provided high-level security consulting services to several private and government organizations.His research has been sponsored by numerous pub- lic and private organizations currently including Lockheed Martin,Northrop Grumman,Intel,Verizon,Network Associates,Defense Advanced Research Projects Agency,Department of Defense,Department of Energy,National Security Agency,National Reconnaissance Agency,National Science Founda- tion,Naval Research Laboratory,Internal Revenue Service,and the Advanced Research and Development Activity agency.Previously,he has published influential and widely cited papers on various security topics including safety and expressive power of access-control models,lattice-based access controls, and multilevel secure relational and object-oriented databases.He has published over 160 technical papers on computer security in refereed journals,conference proceedings and books.He founded the ACMTransactions on Information and Systems Security (TISSEC) in 1997 and served as Editor-In-Chief until 2004. He served as Chairman of ACM’s Special Interest Group on Security Audit and Control (SIGSAC) from 1995 to 2003,and founded and led the ACM Conference on Computer and Communications Security (CCS) and the ACM Symposium on Access Control Models and Technologies (SACMAT) to high reputation and prestige. Dr.Sandhu is a Fellow of the ACM.Most recently,he founded the IEEE Workshop on Pervasive Computing Security (PERSEC) in 2004. Bhavani Thuraisingham (SM’97–F’03) received the B.S.degree in mathematics and physics from the University of Ceylon,Sri Lanka,in 1975,the M.S.degree in mathematics from the University of Bristol,Bristol,U.K.,in 1977,and the Ph.D.degree in computer science from the University of Wales, Wales,U.K.,in 1979. She has served as an expert consultant in informa- tion security and data management to the Department of Defense,the Department of Treasury,and the Intelligence Community for over ten years and is an Instructor for Armed Forces Communication and Electronics Association (AFCEA) since 1998.Prior to joining the University of Texas at Dallas, she was an Intergovernmental Personnel Act (IPA) at the National Science Foundation (NSF) from MITRE Corporation.At NSF,she established the Data and Applications Security Program and cofounded the Cyber Trust theme and was involved in interagency activities in data mining for coun- terterrorism.She has been at MITRE from January 1989 until June 2005, and has worked in MITRE’s Information Security Center and was later a Department Head in data and information management as well as Chief Scientist in data management.She has recently joined the University of Texas at Dallas as a Professor of Computer Science and Director of the Cyber Security Research Center in the Erik Jonsson School of Engineering.Her industry experience includes six years of product design and development of CDCNET at Control Data Corporation and research,development and tech- nology transfer at Honeywell Inc.Her academia experience includes being a Visiting Faculty at the New Mexico Institute of Technology,Adjunct Professor of Computer Science first at the University of Minnesota and later at Boston University.Her research in information security and information management has resulted in over 70 journal articles,over 200 refereed conference papers, and three U.S.patents.She is the author of seven books in data management, data mining,and data security,including one on data mining for counter- terrorismand another on database and applications security.She has given over 25 keynote presentations at various research conferences and has also given invited talks at the White House Office of Science and Technology Policy and at the United Nations on Data Mining for counter-terrorism.She serves (or has served) on editorial boards of top research journals.She is also establishing the consulting company “BMT Security Consulting” specializing in data and applications security consulting and training and is the Founding President of the company. Ms.Thuraisingham is a Fellow of the American Association for the Ad- vancement of Science (AAAS).She received IEEE Computer Society’s pres- tigious 1997 Technical Achievement Award for “outstanding and innovative contributions to secure data management.” She was elected as Fellow of the British Computer Society in February 2005.
https://www.techylib.com/el/view/cheeseturn/secure_knowledge_management_confidentiality_trust_and_privacy
CC-MAIN-2018-26
en
refinedweb
muroar_beep - Send notify beep to RoarAudio sound daemon #include <muroar.h> int muroar_beep (int fh); This function sends a notify beep to the sound daemon fh is connected to. fh need to be connected using muroar_connect(3) to a sound server supporting the RoarAudio protocol and the BEEP command. On success this call return 0. On error, -1 is returned. The beep is canceld at the server side as soon as the connection is closed. This means that you should not close the connection before the beep is played completly. This commands requests the server for a default beep. No other kind of beep can be send. There is in addition no way to tell the actual length of the beep. The application should at least wait a bit more than 512ms before closing the socket. In case possible it is good to wait a minimum of about one secound to be really sure the beep ended. This function first appeared in muRoar version 0.1rc2. muroar_connect(3), muroar_quit(3), RoarAudio(7).
http://huge-man-linux.net/man3/muroar_beep.html
CC-MAIN-2018-26
en
refinedweb
I am running the following code which I wrote in c on my Mac. #include <unistd.h> #include <stdio.h> int main(int argc, const char * argv[]) { int i = 0; printf("Starting pid:%d\n", getpid()); while(i++<3){ int ret = fork(); printf("hello(%d)%d, %d ", i, getpid(), ret); if(!ret){ printf("\n"); return 0;} } } Starting pid:7998 hello(1)8009, 0 hello(1)7998, 8009 hello(2)8010, 0 hello(1)7998, 8009 hello(2)7998, 8010 hello(3)7998, 8011 hello(1)7998, 8009 hello(2)7998, 8010 hello(3)8011, 0 When you fork a process, the memory in parent is duplicated in the child. This includes the stdout buffer. Starting on the second iteration of the loop in the parent, you have hello(1)7998, 8009 in the buffer. When the second child forks, this text is still in that child's buffer. The second child then prints hello(2)8010, 0, then a newline. The newline flushes the child's buffer, so the second child prints this: hello(1)7998, 8009 hello(2)8010, 0 After the fork, the parent prints hello(2)7998, 8010 which is added to the output buffer. Then on the third iteration, the third child inherits this and prints: hello(1)7998, 8009 hello(2)7998, 8010 hello(3)8011, 0 The parent then prints hello(3)7998, 8011 which is again added to the buffer. Then parent then exits the loop and exits, after which the buffer is flushed and the parent outputs: hello(1)7998, 8009 hello(2)7998, 8010 hello(3)7998, 8011 To correct this, then parent process needs to clear the output buffer before forking. This can be done either by calling fflush(stdout) after calling printf, or by adding a newline ( \n) to the end of the printf.
https://codedump.io/share/OS8FVhdrRaD9/1/trying-to-understand-more-on-fork-in-c
CC-MAIN-2018-26
en
refinedweb
This Week in Rust Hello and welcome to another issue of This Week in Rust. We’re gearing up for the 0.8 release in 2-3 weeks. It looks like it’s going to be a really solid release. I’ll write another State of Rust, hopefully before it is released. What’s cooking in master? 68 PRs were merged this week. Breaking changes std::iteratorhas been renamed to std::iter. - The std::num::Primitivetrait is now constrained by the Cloneand DeepClonetraits, as well as Orderable. - Some more free functions have been removed from std::vec. unzipnow takes an iterator, a Permutationsiterator has been added, and some rarely-used, obsolete, functions were removed. - A bunch of changes to Optionand Resultwere made. Specifically, chainwas changed to and_thenand unwrap_or_defaultto unwrap_or. - rustpkg builds into target-specific subdirectories now. Additions and fixes - debuginfo now has namespace support. Looking at all the various PRs Michael has opened over the summer, it seems DWARF is a very flexible, nice debuginfo format, but gdb and LLVM don’t support it very well. - Correct range_stepand range_step_inclusiveiterators have been added. They are correct in cases of overflow, and are generic. - A handy sleepfunction has been added to newrt. - File IO in newrt works on windows now. - A bug where nested items in a default method weren’t compiled has been fixed. - A rendezvous concurrency structure, much like Ada’s, has been added. - Buffered IO wrappers have been added. - nmatsakis landed a PR that closed 7 issues at once. - rustpkg now uses extra::workcacheto prevent recompilation of already-compiled crates. Meeting The Tuesday meeting discussed the github commit policy, implicit copyability, patterns, and the fate of &const. Other things - Eric Reed (ecr)’s intern presentation: An I/O System for Rust. Unfortunately, the audio cuts out. - Evict-BT, a git-integrated issue tracker. - Computer Graphics and Game Development. Also note the #rust-gamedevchannel. - rust-for-real, a collection of Rust examples to aid in learning. Needs more examples!
http://cmr.github.io/blog/2013/09/15/this-week-in-rust/
CC-MAIN-2018-26
en
refinedweb
'---need to import Microsoft.WindowsCE.Forms.dll--- Dim instance As Microsoft.WindowsCE.Forms.WinCEPlatform instance = Microsoft.WindowsCE.Forms.SystemSettings.Platform() MsgBox(instance.ToString) Dim OS As OperatingSystem OS = Environment.OSVersion MsgBox(OS.ToString) This widget requires JavaScript to run. Visit Site for more... Dim soundplayer As New Media.SoundPlayer With soundplayer .SoundLocation = "\Windows\Alarm1.wav" .Play() End With Dim soundplayer As New Media.SoundPlayer With soundplayer .SoundLocation = "\Windows\Alarm1.wav" .Play() End With Media.SystemSounds.Asterisk.Play() Media.SystemSounds.Beep.Play() Media.SystemSounds.Exclamation.Play() Media.SystemSounds.Hand.Play() Media.SystemSounds.Question.Play() Compression The compression classes available in the desktop version of the .NET Framework is now finally available in .NET CF 3.5. The compression algorithms supported are GZip and Deflat. The following shows how you can use the new classes to perform compression and decompression. First, ensure that you import the required namespaces: Imports System.IO Imports System.IO.Compression: '---data is the array containing the compressed data--- dc_data = ExtractBytesFromStream(zipStream, data.Length): To test the functions defined above, use the following statements: Dim str As String = "Hello world" Dim compressed_data As Byte() '---compress the data--- compressed_data = _ Compress(System.Text.ASCIIEncoding.ASCII.GetBytes(str)) '---decompress the data--- Dim decompressed_data As Byte() decompressed_data = Decompress(compressed_data) '---print out the decompressed data--- MsgBox(System.Text.ASCIIEncoding.ASCII.GetString( _ decompressed_data, 0, decompressed_data.Length)) Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled. Your name/nickname Your email WebSite Subject (Maximum characters: 1200). You have 1200 characters left.
http://www.devx.com/dotnet/Article/36320/0/page/3
CC-MAIN-2018-39
en
refinedweb
Getting Started At the start of every guizero program, choose the widgets you need from the guizero library and import them: from guizero import App, PushButton, Slider You only need to import each widget once, and then you can use it in your program as many times as you like. Hello World All guizero projects begin with a main window which is called an App. At the end of every guizero program you must tell the program to display the app you have just created. Let's create an app window with the title "Hello world": from guizero import App app = App(title="Hello world") app.display() Save and run the code - you've created your first guizero app! Adding widgets Widgets are the things which appear on the GUI, such as text boxes, buttons, sliders and even plain old pieces of text. All widgets go between the line of code to create the App and the app.display() line. from guizero import App, Text app = App(title="Hello world") message = Text(app, text="Welcome to the Hello world app!") app.display() Let’s look at the Text widget code in a bit more detail: message = Text(app, text="Welcome to the Hello world app!") message =- The Textobject has a name, just like any variable Text- an object which creates a piece of text on the screen app– This tells the Textwhere it will live. Most of the time your widgets will live directly inside the app. text="Welcome to the Hello world app!"- The text to display And that's it! Now have a look on the documentation pages for the individual widgets to find out more about how to use them.
https://lawsie.github.io/guizero/start/
CC-MAIN-2018-39
en
refinedweb
RobustRobust Robust is an Android HotFix solution with high compatibility and high stability. Robust can fix bugs immediately without publishing apk. EnvironmentEnvironment - Mac Linux and Windows - Gradle 2.10+ , include 3.0 - Java 1.7 + UsageUsage Add below codes in the module's build.gradle. apply plugin: 'com.android.application' //please uncomment fellow line before you build a patch //apply plugin: 'auto-patch-plugin' apply plugin: 'robust' compile 'com.meituan.robust:robust:0.4.82' Add below codes in the outest project's build.gradle file. buildscript { repositories { jcenter() } dependencies { classpath 'com.meituan.robust:gradle-plugin:0.4.82' classpath 'com.meituan.robust:auto-patch-plugin:0.4.82' } } There are some configure items in app/robust.xml,such as classes which Robust will insert code,this may diff from projects to projects.Please copy this file to your project. AdvantagesAdvantages - Support 2.3 to 8.x Android OS - Perfect compatibility - Patch takes effect without a reboot - Support fixing at method level,including static methods - Support add classes and methods - Support ProGuard,including inline methods or changing methods' signature When you build APK,you may need to save "mapping.txt" and the files in directory "build/outputs/robust/". AutoPatchAutoPatch AutoPatch will generate patch for Robust automatically. You just need to fellow below steps to genrate patches. For more details please visit website StepsSteps Put 'auto-patch-plugin' just behind 'com.android.application',but in the front of others plugins。like this: apply plugin: 'com.android.application' apply plugin: 'auto-patch-plugin' Put mapping.txt and methodsMap.robust which are generated when you build the apks in diretory app/robust/,if not exists ,create it! After modifying the code ,please put annotation @Modifyon the modified methods or invoke RobustModify.modify()(designed for Lambda Expression )in the modified methods: @Modify protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // protected void onCreate(Bundle savedInstanceState) { RobustModify.modify() super.onCreate(savedInstanceState); } Use annotation @Addwhen you neeed to add methods or classes. //add method @Add public String getString() { return "Robust"; } //add class @Add public class NewAddCLass { public static String get() { return "robust"; } } After those steps,you need to run the same gradle command as you build the apk,then you will get patches in directory app/build/outputs/robust/patch.jar. Generating patches always end like this,which means patches is done Demo UsageDemo Usage Excute fellow command to build apk: ./gradlew clean assembleRelease --stacktrace --no-daemon After install apk on your phone,you need to save mapping.txt and app/build/outputs/robust/methodsMap.robust Put mapping.txt and methodsMap.robust which are generated when you build the apks into diretory app/robust/,if directory not exists ,create it! After modifying the code ,please put annotation @Modifyon the modified methods or invoke RobustModify.modify()(designed for Lambda Expression )in the modified methods. Run the same gradle command as you build the apk: ./gradlew clean assembleRelease --stacktrace --no-daemon Generating patches always end like this,which means patches is done Copy patch to your phone: adb push ~/Desktop/code/robust/app/build/outputs/robust/patch.jar /sdcard/robust/patch.jar patch directory can be configured in PatchManipulateImp. Open app,and click Patch button,patch is used. Also you can use our sample patch in app/robust/sample_patch.jar ,this dex change text after you click Jump_second_Activity Button. In the demo ,we change the text showed on the second activity which is configured in the method getTextInfo(String meituan)in class SecondActivity AttentionsAttentions You should modify inner classes' private constructors to public modifier. AutoPatch cannot handle situations which method returns this,you may need to wrap it like belows: method a(){ return this; } changed to method a(){ return new B().setThis(this).getThis(); } Not Support add fields,but you can add classes currently, this feature is under testing. Classes added in patch should be static nested classes or non-inner classes,and all fields and methods in added class should be public. Support to fix bugs in constructors currently is under testing. Not support methods which only use fields,without method call or new expression. Support to resources and so file is under testing. For more help, please visit Wiki LicenseLicense Copyright 2017 Meituan-Dianping.
https://www.ctolib.com/Robust-Android.html
CC-MAIN-2018-39
en
refinedweb
TDD 0 Posted November 22, 2009 Hello! Firstly, i'll refer to the original thread located at: Lod3n created an example, which i've been messing with, but i'm extremely inexperienced with AutoIT (I'd ask him, but he hasn't logged in for a month), and was wondering, does this monitor ALL inbound connections, and outbound, or specifically those to the internet? (As in, does it ignore any connections to 192.168.1.* as that is not internet but LAN). I have a feeling it does include local connections, as when I was doing a backup to my network HDD (192.168.1.103), it increased the outbound a lot... If it doesn't, how could it be modified to ignore any transfers to 192.168.1.*? So far I've messed with the code in order to create a total of the downloads and uploads in MB versus bytes, which i'm rather proud of for my first AutoIT code. My ultimate goal is to use it to silently and invisibly log all this information to a text file so that I can use RainMeter to display this on a config, to use it as an internet download quota manager... as the default RainMeter traffic monitor also includes lan. Thanks, TDD By the way, here's the code I have modified from lod3n's: expandcollapse popup#include <GUIConstants.au3> GUICreate("Lod3n's Bandwidth Monitor",220,50,150,150,-1) $label1 = GUICtrlCreateLabel ( "Waiting for data...", 10, 5,200,20) $label2 = GUICtrlCreateLabel ( "Waiting for data...", 10, 25,500,20) GUISetState () $wbemFlagReturnImmediately = 0x10 $wbemFlagForwardOnly = 0x20 $colItems = "" $strComputer = "localhost" $objWMIService = ObjGet("winmgmts:\\" & $strComputer & "\root\CIMV2") $inmax = 0 $outmax = 0 $lastin = 0 $lastout = 0 while 1 ;$colItems = $objWMIService.ExecQuery("SELECT BytesReceivedPersec,BytesSentPersec FROM Win32_PerfFormattedData_Tcpip_NetworkInterface", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) $colItems = $objWMIService.ExecQuery("SELECT BytesReceivedPersec,BytesSentPersec FROM Win32_PerfRawData_Tcpip_NetworkInterface", "WQL", $wbemFlagReturnImmediately + $wbemFlagForwardOnly) If IsObj($colItems) then For $objItem In $colItems $newin = $objItem.BytesReceivedPersec $newout = $objItem.BytesSentPersec ;new realtime counter code... if $lastin = 0 and $lastout = 0 Then $lastin = $newin $lastout = $newout endif $in = $newin - $lastin $out = $newout - $lastout $lastin = $newin $lastout = $newout if $in <> 0 and $out <> 0 Then $inmax = $inmax + $in $outmax = $outmax + $out $inP = Round((($inmax / 1024) / 1024), 2) $outP = Round((($outmax / 1024) / 1024), 2) $intext = "Bytes In/Sec: " & int($in) & " [" &$inP & " MB]" & @CRLF $outtext = "Bytes Out/Sec: " & int($out) & " [" &$outP & " MB]" &@CRLF GUICtrlSetData ($label1,$intext) GUICtrlSetData ($label2,$outtext) EndIf ExitLoop ; I only care about the first network adapter, yo Next EndIf sleep(1000) ; bytes PER SECOND If GUIGetMsg() = $GUI_EVENT_CLOSE Then ExitLoop WEnd Share this post Link to post Share on other sites
https://www.autoitscript.com/forum/topic/105812-using-autoit-as-an-internet-bandwidth-monitor/
CC-MAIN-2018-39
en
refinedweb
ASP.NET Core Identity is an authentication and membership system that lets you easily add login functionality to your ASP.NET Core application. It is designed in a modular fashion, so you can use any "stores" for users and claims that you like, but out of the box it uses Entity Framework Core to store the entities in a database. By default, EF Core uses naming conventions for the database entities that are typical for SQL Server. In this post I'll describe how to configure your ASP.NET Core Identity app to replace the database entity names with conventions that are more common to PostgreSQL. I'm focusing on ASP.NET Core Identity here, where the entity table name mappings have already been defined, but there's actually nothing specific to ASP.NET Core Identity in this post. You can just as easily apply this post to EF Core in general, and use more PostgreSQL-friendly conventions for all your EF Core code. See here for the tl;dr code! Moving to PostgreSql as a SQL Server aficionado ASP.NET Core Identity can use any database provider that is supported by EF Core - some of which are provided by Microsoft, others are third-party or open source components. If you use the templates that come with the .NET CLI via dotnet new, you can choose SQL Server or SQLite by default. Personally, I've been working more and more with PostgreSQL, the powerful cross-platform, open source database. As someone who's familiar with SQL Server, one of the biggest differences that can bite you when you start working with PostgreSQL is that table and column names are case sensitive! This certainly takes some getting used to, and, frankly is a royal pain in the arse to work with if you stick to your old habits. If a table is created with uppercase characters in the table or column name, then you have to ensure you get the case right, and wrap the identifiers in double quotes, as I'll show shortly. This is unfortunate when you come from a SQL Server world, where camel-case is the norm for table and column names. For example, imagine you have a table called AspNetUsers, and you want to retrieve the Id, To query this table in PostgreSQL, you'd have to do something like: SELECT "Id", "Email", "EmailConfirmed" FROM "AspNetUsers" Notice the quote marks we need? This only gets worse when you need to escape the quotes because you're calling from the command line, or defining a SQL query in a C# string, for example: $ psql -d DatabaseWithCaseIssues -c "SELECT \"Id\", \"Email\", \"EmailConfirmed\" FROM \"AspNetUsers\" " Clearly nobody wants to be dealing with this. Instead it's convention to use snake_case for database objects instead of CamelCase. snake_case > CamelCase in PostreSQL Snake case uses lowercase for all of the identifiers, and instead of using capitals to demarcate words, it uses an underscore, _. This is perfect for PostgreSQL, as it neatly avoids the case issue. If, we could rename our entity table names to asp_net_users, and the corresponding fields to id, This makes the PostgreSQL queries way simpler, especially when you would otherwise need to escape the quote marks: $ psql -d DatabaseWithCaseIssues -c "SELECT id, email, email_confirmed FROM asp_net_users" If you're using EF Core, then theoretically all this wouldn't matter to you. The whole point is that you don't have to write SQL code yourself, and you can just let the underlying framework generate the necessary queries. If you use CamelCase names, then the EF Core PostgreSQL database provider will happily escape all the entity names for you. Unfortunately, reality is a pesky beast. It's just a matter of time before you find yourself wanting to write some sort of custom query directly against the database to figure out what's going on. More often than not, if it comes to this, it's because there's an issue in production and you're trying to figure out what went wrong. The last thing you need at this stressful time is to be messing with casing issues! Consequently, I like to ensure my database tables are easy to query, even if I'll be using EF Core or some other ORM 99% of the time. EF Core conventions and ASP.NET Core Identity ASP.NET Core Identity takes care of many aspects of the identity and membership system of your app for you. In particular, it creates and manages the application user, claim and role entities for you, as well as a variety of entities related to third-party logins: If you're using the EF Core package for ASP.NET Core Identity, these entities are added to an IdentityDbContext, and configured within the OnModelCreating method. If you're interested, you can view the source online - I've shown a partial definition below, that just includes the configuration for the Users property which represents the users of your app public abstract class IdentityDbContext<TUser> { public DbSet<TUser> Users { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<TUser>(b => { b.HasKey(u => u.Id); b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique(); b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex"); b.ToTable("AspNetUsers"); } // additional configuration } } The IdentityDbContext uses the OnModelCreating method to configure the database schema. In particular, it defines the name of the user table to be "AspNetUsers" and sets the name of a number of indexes. The column names of the entities default to their C# property values, so they would also be CamelCased. In your application, you would typically derive your own DbContext from the IdentityDbContext<>, and inherit all of the schema associated with ASP.NET Core Identity. In the example below I've done this, and specified TUser type for the application to be ApplicationUser: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } With the configuration above, the database schema would use all of the default values, including the table names, and would give the database schema we saw previously. Luckily, we can override these values and replace them with our snake case values instead. Replacing specific values with snake case As is often the case, there are multiple ways to achieve our desired behaviour of mapping to snake case properties. The simplest conceptually is to just overwrite the values specified in IdentityDbContext.OnModelCreating() with new values. The later values will be used to generate the database schema. We simply override the OnModelCreating() method, call the base method, and then replace the values with our own: public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<TUser>(b => { b.HasKey(u => u.Id); b.HasIndex(u => u.NormalizedUserName).HasName("user_name_index").IsUnique(); b.HasIndex(u => u.NormalizedEmail).HasName("email_index"); b.ToTable("asp_net_users"); } // additional configuration } } Unfortunately, there's a problem with this. EF Core uses conventions to set the names for entities and properties where you don't explicitly define their schema name. In the example above, we didn't define the property names, so they will be CamelCase by default. If we want to override these, then we need to add additional configuration for each entity property: b.Property(b => b.EmailConfirmation).HasColumnName("email_confirmation"); Every. Single. Property. Talk about laborious and fragile… Clearly we need another way. Instead of trying to explicitly replace each value, we can use a different approach, which essentially creates alternative conventions based on the existing ones. Replacing the default conventions with snake case The ModelBuilder instance that is passed to the OnModelCreating() method contains all the details of the database schema that will be created. By default, the database object names will all be CamelCased. By overriding the OnModelCreating method, you can loop through each table, column, foreign key and index, and replace the existing value with its snake case equivalent. The following example shows how you can do this for every entity in the EF Core model. The ToSnakCase() extension method (shown shortly) converts a camel case string to a snake case string. public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); foreach(var entity in builder.Model.GetEntityTypes()) { // Replace table names entity.Relational().TableName = entity.Relational().TableName.ToSnakeCase(); // Replace column names foreach(var property in entity.GetProperties()) { property.Relational().ColumnName = property.Relational().ColumnName.ToSnakeCase(); } foreach(var key in entity.GetKeys()) { key.Relational().Name = key.Relational().Name.ToSnakeCase(); } foreach(var key in entity.GetForeignKeys()) { key.Relational().Name = key.Relational().Name.ToSnakeCase(); } foreach(var index in entity.GetIndexes()) { index.Relational().Name = index.Relational().Name.ToSnakeCase(); } } } } The ToSnakeCase() method is just a simple extension method that looks for a lower case letter or number, followed by a capital letter, and inserts an underscore. There's probably a better / more efficient way to achieve this, but it does the job!(); } } These conventions will replace all the database object names with snake case values, but there's one table that won't be modified, the actual migrations table. This is defined when you call UseNpgsql()or UseSqlServer(), and by default is called __EFMigrationsHistory. You'll rarely need to query it outside of migrations, so I won't worry about it for now. With our new conventions in place, we can add the EF Core migrations for our snake case schema. If you're starting from one of the VS or dotnet new templates, delete the default migration files created by ASP.NET Core Identity: - 00000000000000_CreateIdentitySchema.cs - 00000000000000_CreateIdentitySchema.Designer.cs - ApplicationDbContextModelSnapshot.cs and create a new set of migrations using: $ dotnet ef migrations add SnakeCaseIdentitySchema Finally, you can apply the migrations using $ dotnet ef database update After the update, you can see that the database schema has been suitably updated. We have snake case table names, as well as snake case columns (you can take my word for it on the foreign keys and indexes!) Now we have the best of both worlds - we can use EF Core for all our standard database actions, but have the option of hand crafting SQL queries without crazy amounts of ceremony. Note, although this article focused on ASP.NET Core Identity, it is perfectly applicable to EF Core in general. Summary In this post, I showed how you could modify the OnModelCreating() method so that EF Core uses snake case for database objects instead of camel case. You can look through all the entities in EF Core's model, and change the table names, column names, keys, and indexes to use snake case. For more details on the default EF Core conventions, I recommend perusing the documentation!
https://andrewlock.net/customising-asp-net-core-identity-ef-core-naming-conventions-for-postgresql/
CC-MAIN-2019-26
en
refinedweb
Create Tests for Hystrix-based Command 06/03/2019 You will learn - Why you should care about resilience - How to make the call to the OData service resilient by using Hystrix-basedcommands - How to write Tests for the new Hystrix-basedcommand - To deploy the application on SAP Cloud Platform Cloud Foundry min * (1 – 0.9999) = 4.32 min). Now assume failures are cascading, so one service being unavailable means the whole application becomes unavailable. Given the equation used above, the situation now looks like this: 43200 min * (1 – 0.9999^30) = 43200 min * (1 – 0.997) = 129.6 min. The SAPallowsstrixto perform remote service calls asynchronously and concurrently. These threads are non-container-managed, so regardless of how many threads are used by your Hystrixcommands, they do not interfere with your runtime container. Circuit breaker: Hystrixuses the circuit breaker pattern to determine whether a remote service is currently available. Breakers are closed by default. If a remote service call fails too many times, Hystrixwill open/trip the breaker. This means that any further calls that should be made to the same remote service, are automatically stopped. Hystrixwill periodically check if the service is available again, and close the open. Now that we have covered why resilience is important, it’s finally time to introduce it into our application. In the last tutorial we created a simple servlet that uses the SDK’s Virtual Data Model (VDM) and other helpful abstractions to retrieve business partners from an Erp system. In order to make this call resilient, we have to wrap it in an Erp Command. So first we will create the following class: ./application/src/main/java/com/sap/cloud/sdk/tutorial/GetBusinessPartnersCommand.java package com.sap.cloud.sdk.tutorial; import org.slf4j.Logger; import java.util.Collections; import java.util.List; import com.sap.cloud.sdk.cloudplatform.logging.CloudLoggerFactory; import com.sap.cloud.sdk.s4hana.connectivity.ErpCommand;; public class GetBusinessPartnersCommand extends ErpCommand<List<BusinessPartner>> { private static final Logger logger = CloudLoggerFactory.getLogger(GetBusinessPartnersCommand.class); private static final String CATEGORY_PERSON = "1"; protected GetBusinessPartnersCommand() { super(GetBusinessPartnersCommand.class); } @Override protected List<BusinessPartner> run() throws Exception {) .top(10) .execute(); return businessPartners; } @Override protected List<BusinessPartner> getFallback() { logger.warn("Fallback called because of exception:", getExecutionException()); return Collections.emptyList(); } } The GetBusinessPartnersCommand class inherits from ErpCommand, which is the SDK’s abstraction to provide easy-to-use Hystrix commands. To implement a valid ErpCommand we need to do two things: first, we need to provide a constructor. Here we simply add the default constructor. Second, we need to override the run() method. As you might have noticed already, we can simply use the VDM-based after logging the exception that led to the fallback being called. We could also serve static data or check whetherBusinessPartnersCommand() { super(HystrixUtil .getDefaultErpCommandSetter( GetBusinessPartnersCommand.class, HystrixUtil.getDefaultErpCommandProperties().withExecutionTimeoutInMilliseconds(10000)) .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter().withCoreSize(20))); } Now that we have a working command, we need to adapt our BusinessPartnerServlet: ./application/src/main/java/com/sap/cloud/sdk/tutorial/BusinessPartnerServlet.java.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner; { try { final List<BusinessPartner> businessPartners = new GetBusinessPartnersCommand().execute(); response.setContentType("application/json"); response.getWriter().write(new Gson().toJson(businessPartners)); } catch (final Exception e) { logger.error(e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().write(e.getMessage()); } } } Thanks to our new GetBusinessPartnersCommand, we can now simply create a new command and execute it. As before, we get a list of business partners as result. But now we can be sure that our application will not stop working all-together if the OData service is temporarily unavailable for any tenant. There are two things we need to address in order to properly test our code: we need to provide our tests with an ERP endpoint and a Hystrix request context. We provide the ERP destination as explained in the previous blog post as a systems.json or systems.yml file. In addition, you may provide a credentials.yml file to reuse your SAP S/4HANA login configuration as described in the Appendix of the previous tutorial step. To provide credentials in this manner,. The MockUtil class of the SAP Cloud SDK, introduced in the previous blog post, is our friend once again. Using MockUtil's requestContextExecutor() method we can wrap the execution of the GetBusinessPartnersCommand in a request context. Now let’s have a look at the code, to be placed in a file integration-tests/ src/test/java/com/sap/cloud/ sdk/tutorial/ GetBusinessPartnersCommandTest.java: package com.sap.cloud.sdk.tutorial; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.util.Collections; import java.util.List; import com.sap.cloud.sdk.cloudplatform.servlet.Executable; import com.sap.cloud.sdk.testutil.MockUtil; import com.sap.cloud.sdk.s4hana.datamodel.odata.namespaces.businesspartner.BusinessPartner; import static org.assertj.core.api.Assertions.assertThat; public class GetBusinessPartnersCommandTest { private MockUtil mockUtil; @Before public void beforeClass() { mockUtil = new MockUtil(); mockUtil.mockDefaults(); } private List<BusinessPartner> getBusinessPartners() { return new GetBusinessPartnersCommand().execute(); } @Test public void testWithSuccess() throws Exception { mockUtil.mockErpDestination(); new RequestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { assertThat(getBusinessPartners()).isNotEmpty(); } }); } @Test public void testWithFallback() throws Exception { mockUtil.mockDestination("ErpQueryEndpoint", new URI("")); new RequestContextExecutor().execute(new Executable() { @Override public void execute() throws Exception { assertThat(getBusinessPartners()).isEqualTo(Collections.emptyList()); } }); } } We use JUnit’s @Before annotation to setup a fresh MockUtil for each test. use the default ERP destination information using mockUtil.mockErpDestination so that the endpoint points to the SAP S/4HANA system configured in your systems.json file. For the sake of simplicity we simply assert that the response is not empty. For testWithFallback(), we intentionally provide a destination (localhost) that does not provide the called OData service in order to make the command fail. Since we implemented a fallback for our command that returns an empty list, we assert that we actually receive an empty list as response. Simply run mvn clean install as in the previous tutorials to test and build your application. Consider the following before deploying to/), you need to similarly set the environment variable ALLOW_MOCKED_AUTH_HEADER=true on your local machine before starting the local server, in addition to supplying the destinations (as described in Step 4). This wraps up the tutorial on making our sample application resilient using Hystrix and the SAP Cloud SDK. Continue with the next tutorial Step 6: Caching and also explore other tutorial posts on topics like security!
https://developers.sap.com/portugal/tutorials/s4sdk-resilience.html
CC-MAIN-2019-26
en
refinedweb
Not too long ago I wrote about sending emails in an Ionic Framework app using the Mailgun API. To get you up to speed, I often get a lot of questions regarding how to send emails without opening the default mail application from within an Ionic Framework application. There are a few things that could be done. You can either spin up your own API server and send emails from your server via an HTTP request or you can make use of a service. To compliment the previous post I wrote for Ionic Framework, I figured it would be a good idea to demonstrate how to use Mailgun in an Ionic 2 application. Mailgun, for the most part, is free. It will take a lot of emails before you enter the paid tier. Regardless, you’ll need an account to follow along with this tutorial. Let’s start by creating a new Ionic 2 project. From the Command Prompt (Windows) or Terminal (Mac and Linux), execute the following: ionic start MailgunApp blank --v2 cd MailgunApp ionic platform add ios ionic platform add android A few important things to note here. The first thing to note is the use of the --v2 tag. This is an Ionic 2 project, and to create Ionic 2 projects, the appropriate Ionic CLI must be installed. Finally, you must be using a Mac if you wish to add and build for the iOS platform. This project uses no plugins or external dependencies. This means we can start coding our application. Starting with the logic file, open your project’s app/pages/home/home.ts file and include the following code: import {Component} from '@angular/core'; import {Http, Request, RequestMethod} from "@angular/http"; @Component({ templateUrl: 'build/pages/home/home.html' }) export class HomePage { http: Http; mailgunUrl: string; mailgunApiKey: string; constructor(http: Http) { this.http = http; this.mailgunUrl = "MAILGUN_URL_HERE"; this.mailgunApiKey = window.btoa("api:key-MAILGUN_API_KEY_HERE"); } send(recipient: string, subject: string, message: string) { var requestHeaders = new Headers(); requestHeaders.append("Authorization", "Basic " + this.mailgunApiKey); requestHeaders.append("Content-Type", "application/x-www-form-urlencoded"); this.http.request(new Request({ method: RequestMethod.Post, url: "" + this.mailgunUrl + "/messages", body: "[email protected]&to=" + recipient + "&subject=" + subject + "&text=" + message, headers: requestHeaders })) .subscribe(success => { console.log("SUCCESS -> " + JSON.stringify(success)); }, error => { console.log("ERROR -> " + JSON.stringify(error)); }); } } There is a lot going on in the above snippet so let’s break it down. First you’ll notice the following imports: import { Http, Request, RequestMethod } from "@angular/http"; The Mailgun API is accessed via HTTP requests. To make HTTP requests we must include the appropriate Angular dependencies. More on HTTP requests can be seen in a previous post I wrote specifically on the topic. Next we define our Mailgun domain URL and corresponding API key. For prototyping I usually just use the sandbox domain and key, but it doesn’t cost any extra to use your own domain. However, notice the following: this.mailgunApiKey = window.btoa("api:key-MAILGUN_API_KEY_HERE"); We are making use of the btoa function that will create a base64 encoded string. Having a base64 encoded string is a requirement when using the authorization header of a request. Finally we get into the heavy lifting. The send function is where all the magic happens. The send function expects an authorization header as well as a content type. The Mailgun API expects form data to be sent, not JSON data. This data is to be sent via a POST request. This brings us into our UI. To keep things simple our UI is just going to be a form that submits to the send function. Open your project’s app/pages/home/home.html file and include the following code: <ion-header> <ion-navbar> <ion-title>Mailgun App</ion-title> </ion-header> <ion-content <ion-list> <ion-item> <ion-label floating>Recipient (To)</ion-label> <ion-input</ion-input> </ion-item> <ion-item> <ion-label floating>Subject</ion-label> <ion-input</ion-input> </ion-item> <ion-item> <ion-label floating>Message</ion-label> <ion-textarea [(ngModel)]="message"></ion-textarea> </ion-item> </ion-list> <div padding> <button block (click)="send(recipient, subject, message)">Send</button> </div> </ion-content> The above form has two standard text input fields for the recipient and subject. There is a text area for the message body and a button for submitting the form data. The input elements are all bound using an ngModel. This allows us to pass the fields into the send function. Give it a try, you should be able to send emails now via HTTP. You just saw how to send emails without opening an email client on the users device. This could be useful for sending logs to the developer, or maybe a custom feedback form within the application. Previously I wrote about how to use Mailgun in an Ionic Framework application, but this time we saw how with Ionic 2, Angular, and TypeScript.
https://www.thepolyglotdeveloper.com/2016/05/send-emails-ionic-2-mobile-app-via-mailgun-api/
CC-MAIN-2019-26
en
refinedweb
Stopping the integration of an ODE at some condition Posted February 27, 2013 at 02:30 PM | categories: ode | tags: | View Comments Updated February 27, 2013 at 02:30 PM Matlab post” function. You setup an event function and tell the ode solver to use it by setting an option.. from pycse import * import numpy as np k = 0.23 Ca0 = 2.3 def dCadt(Ca, t): return -k * Ca**2 def stop(Ca, t): isterminal = True direction = 0 value = 1.0 - Ca return value, isterminal, direction tspan = np.linspace(0.0, 10.0) t, CA, TE, YE, IE = odelay(dCadt, Ca0, tspan, events=[stop], full_output=1) print 'At t = {0:1.2f} seconds the concentration of A is {1:1.2f} mol/L.'.format(t[-1], CA[-1]) At t = 2.46 seconds the concentration of A is 1.00 mol/L. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/02/27/Stopping-the-integration-of-an-ODE-at-some-condition/
CC-MAIN-2019-26
en
refinedweb
37036/nmap-nmap-portscannererror-nmap-program-was-not-found-path I am facing some error while using python-nmap: I am running the following: import nmap nm = nmap.PortScanner() I am getting this error: Traceback (most recent call last): File "a.py", line 2, in <module> nm = nmap.PortScanner() File "/home/edureka/.local/lib/python2.7/site-packages/nmap/nmap.py", line 131, in __init__ os.getenv('PATH') nmap.nmap.PortScannerError: 'nmap program was not found in path. PATH is : ' python-nmap module used in python happens to use nmap binary installed in the system. The error you are getting is because python can't find the depending nmap. Installing nmap should solve this. To install nmap, run the following command: sudo apt-get install nmap Python doesn't know what $FILEDIR is. Try an absolute path ...READ MORE raw_input is not supported anymore in python3. ...READ MORE This is the code that I am ...READ MORE You know what has worked for The pip library is called SpeechRecognition, not ...READ MORE To print the message that file is not ...READ MORE OR
https://www.edureka.co/community/37036/nmap-nmap-portscannererror-nmap-program-was-not-found-path?show=37038
CC-MAIN-2019-26
en
refinedweb
index.mdwn | 4 + reference/dependencies.mdwn | 131 ++++++++++++++++++++++++++++++++++++++++++++ xsf.css | 5 + 3 files changed, 140 insertions(+) New commits: commit dfb93d750512f99ecbbe8e7d97db97acb6641505 Author: Cyril Brulebois <kibi@debian.org> Date: Tue Feb 1 13:34:52 2011 +0100 dependencies: New reference document. diff --git a/index.mdwn b/index.mdwn index f3e1efc..ab5e152 100644 --- a/index.mdwn +++ b/index.mdwn @@ -8,6 +8,10 @@ * [How to configure input](howtos/configure-input.html) * [How to configure outputs](howtos/use-xrandr.html) +## Reference documentation + + * [Dependencies between server and drivers](reference/dependencies.html) + ## Other documentation * [Upstream features](upstream-features.html) diff --git a/reference/dependencies.mdwn b/reference/dependencies.mdwn new file mode 100644 index 0000000..fa0e816 --- /dev/null +++ b/reference/dependencies.mdwn @@ -0,0 +1,131 @@ +# Dependencies between server and drivers + +Cyril Brulebois <kibi@debian.org> + + +## Upstream-side: ABI version numbers + +The X server defines several +[ABI]() in +`hw/xfree86/common/xf86Module.h`, through the +`SET_ABI_VERSION(maj,min)` macro. In this document, the focus is on +`ABI_VIDEODRV_VERSION` and `ABI_XINPUT_VERSION`, which are +respectively about `video` drivers and `input` drivers. + +An example of input ABI is `12.1`, `12` being the `major`, `1` being +the `minor`. + +Like in usual shared libraries, the major is bumped when interfaces +are broken. There’s no compatibility at all in that case. + +The minor gets bumped when interfaces are added. In other words, if a +driver is working with `x.y`, it should also work with higher minors: +`x.z`; `z>y`. The converse is not true, if a driver requires a given +minor (for example because it needs a new feature, like MultiTouch), +it won’t work with lower minors (which didn’t provide the needed +feature). Put another way: we have ascending compatibility with the +minors. + +Conclusion: We need to keep track of both major and minor. + +Thanks to `pkg-config` we can query them: + + $ pkg-config --variable=abi_videodrv xorg-server + 9.0 + $ pkg-config --variable=abi_xinput xorg-server + 12.1 + + +## Debian-side: Using virtual packages + +### Server’s build system + +When `xorg-server` gets built, we use `pkg-config`’s output to +determine the current major. Through substitution variables, we add +two virtual packages in the `Provides` field of the server (for both +`xserver-xorg-core` and `xserver-xorg-core-udeb`): `xorg-input-abi-$x` +and `xorg-video-abi-$y`, where `$x` and `$y` are the major part of the +version queried through `pkg-config` variables. +***FIXME: Currently we have both major and minor.*** + +To handle ascending compatibility for minors, we maintain in +`debian/serverminver` the minimal version of `xserver-xorg-core` which +is needed. When a minor is bumped, we store the server version in that +file. This way, drivers built afterwards will depend on a *minimal* +version of the driver, the last which saw a minor version bump. In +other words: they will “depend on the server version they were built +against, or a higher/compatible one”. + +Both ABI and minimal server version are recorded in two files shipped +in `xserver-xorg-dev`, to be used while building drivers: + + * `/usr/share/xserver-xorg/xinputdep` + * `/usr/share/xserver-xorg/videodrvdep` + +Example for `xinputdep`: + + xorg-input-abi-11, xserver-xorg-core (>= 2:1.8.99.904) + +***FIXME: Lies! That's currently `xorg-input-abi-11.0, …` instead.*** + + +### Driver’s control file + +Drivers also use substitution variables in their control file, +replaced at build time. + + # Input driver: + Depends: ${xinpdriver:Depends}, … + Provides: ${xinpdriver:Provides} + + # Video driver: + Depends: ${xviddriver:Depends}, … + Provides: ${xviddriver:Provides} + +For now, `${xinpdriver:Provides}` is always replaced with +`xorg-driver-input`, and `${xviddriver:Provides}` is always replaced +with `xorg-driver-video`. Hopefully provided packages will not change, +but using substitution variables is cheap, and makes it easy to add +tweaks afterwards if needed. + + +### Driver’s build system + +To set those variables, we ship a `dh_xsf_substvars` script in +`xserver-xorg-dev` starting with ***FIXME_version***, to be run before +`dh_gencontrol`. It iterates on the packages listed by +`dh_listpackages` (very old `debhelper` command) and does the +following work: + + * It reads variables from the files mentioned above. + * If a package name ends with `-udeb`, it replaces + `xserver-xorg-core` with `xserver-xorg-core-udeb`. + * If a package name ends with `-dbg`, it does nothing for this + package. Debug packages usually depend strictly on the non-debug + packages, which in turn have appropriate dependencies. + * If a package name starts with `xserver-xorg-input-`, it appends + `xinpdriver:Depends=…` and `xinpdriver:Provides=…` to this + package’s substvars file. + * If a package name starts with `xserver-xorg-video-`, it appends + `xviddriver:Depends=…` and `xviddriver:Provides=…` to this + package’s substvars file. + +Why such heuristics? The idea is to avoid getting “unused substitution +variable” warning messages while building. And since there’s a clear +`xserver-xorg-{input,video}-*` namespace, we can use that to specify . + +We probably should have some way of tracking ABI bumps automatically, +to make sure we bump `serverminver` when needed. commit 45ae4b42e61f581087bdad27a42df4b80fb37206 Author: Cyril Brulebois <kibi@debian.org> Date: Tue Feb 1 12:14:36 2011 +0100 css: Avoid too much margin in nested lists. diff --git a/xsf.css b/xsf.css index 1b7aaf6..5c070c4 100644 --- a/xsf.css +++ b/xsf.css @@ -59,6 +59,11 @@ ol { text-align: justify; } +/* Avoid too much margin in nested lists */ +ul ul, ol ul, ul ol, ol ol { + margin-left: 0px; +} + pre { margin-left: 60px; }
https://lists.debian.org/debian-x/2011/02/msg00021.html
CC-MAIN-2019-26
en
refinedweb