text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Introduction Overview The custom control The control properties Using the control Conclusion When I saw a Microsoft's sample for using SQLXML that demonstrate a little project management application I said to myself, "It would be cool to have a similar progress control functionality in the dataset directly.". I work with data a lot and sometimes there are data items that are of a percentage type, that represent some progress#. It is very effective to show such data in a graphical way. What we have here is a little sample of how to do such thing. It is a sample of how to create a custom control derived from the System.Windows.Forms.DataGrid object, and how to write custom property modify dialog. The Component allows the consumer to specify which columns are of the progress type within the grid, and the grid then renders the progress based upon specified attributes given to the grid object (like the color or style of the progress control). System.Windows.Forms.DataGrid The project for the custom control itself is a standard C# Custom Control project. When creating it I just set up the new project from the custom project template. The whole component implementation is done in one file - CProgressDataGrid.cs in the CProgressControls namespace (I thought that maybe it can be usefull to create more similar controls and put them under the same namespace.) CProgressControls As you can see from the source, the class is separated into several areas, the functional API of the component to access the attributes programatically (via functionz or properties), - the region named 'accessor functions', and the main part, implemented in the region named 'painting functions'. This region contains the main OnPaint handler. The logic is very straightforward, get the list of columns that are marked as progress column types and then for every cell in such column, get its value and draw the box there. Simple as that. OnPaint There are some properties you can set up into the control, via Visual Studio's designer or via the component's API: There is the custom dialog used to select the columns for the progress control. To implement your own property dialog you need to undertake several steps. First you need to create your own new value editor class. In this case it is CProgressDataGridColumnsValueEditor, as you can see it is derived from the UITypeEditor class. Basically you need to override two functions - GetEditStyle and EditValue. The GetEditStyle function is called from the VS.NET framework to retrieve the information about the type of the editor used for the property, there are 3 types defined - Modal, DropDown and None, for exact description see the documentation for the UITypeEditorEditStyle class. CProgressDataGridColumnsValueEditor UITypeEditor GetEditStyle EditValue Modal DropDown None UITypeEditorEditStyle In our case we use UITypeEditorEditStyle.Modal type. If you look at the EditValue function, you can see that this is very simple too. You can get the instance of the container if you wish, just type the context.Instance to your control's type. Here we have function call like: UITypeEditorEditStyle.Modal context.Instance CProgressDataGrid oGrid = (CProgressDataGrid)context.Instance; On the next lines we create an instance of our dialog used to populate the list of columns. I will not go into description of the form used to do that (called CProgressDataGridColumnsValueEditorForm), it is not important for this sample, but the source is included so you can observe that part of code as well. CProgressDataGridColumnsValueEditorForm Once the property dialog ends it returns control to the EditValue function, it is recommended to store the information if the data was changed in the dialog and check it here, if this is the case then just copy the data to the value variable and return it so the value will be stored in the property. value I had a collection of type ArrayList that held the columns selected as progress bar columns, but whenever the persistent data was loaded from the resource file, the deserialization process went wrong. I tried to find a solution, but finally gave up, once I have some more time I'll dig into that again, of course if you have any ideas how to make a collection as a property persistent and updatable via the VS.NET designer, drop me a message. Anyway, in the end I decided to do it with a little trick. The list is stored in the string property, where the column indexes are delimited by the comma (,) separator, there is a little helper function that turns the string into the ArrayList object. ArrayList So, "How can I use that" you migh ask. First place the built assembly, or the source, onto your machine and build it (in the case of the source). Once this is done, go into the Toolbox window and right click when you have some form selected, choose the "Customize toolbox" menu item and add the reference to this assembly. At the end of the component's list you will see the CProgressDataGrid, place it onto your form. CProgressDataGrid Then you need to specify a table style, and add some columns to the style according to the your underlaying dataset. Then you can scroll down and find the property group "Progress control", and specify the required color and type, whether you want to see the text or not, and the Table name within the data set. Once you have done this then click the "..." in the ProgressColumns attribute and use the dialog to select your "progress" columns. Save the project and build it. That's it, if you have proper dataset bound to the data grid with some numerical data for the progress column you have chosen, then you should see the progress bars in that column. DataGridBoolColumn.
http://www.codeproject.com/Articles/2197/Custom-DataGrid-with-Progress-Bar-control
CC-MAIN-2015-35
refinedweb
959
59.23
Today we will look into android internal storage. Android offers a few structured ways to store data. These include - Shared Preferences - Internal Storage - External Storage - SQLite Storage - Storage via Network Connection(on cloud) In this tutorial we are going to look into the saving and reading data into files using Android Internal Storage. Table of Contents: FileOutputStream fOut = openFileOutput("file name",Context.MODE_PRIVATE); The method openFileOutput()returns an instance of FileOutputStream. After that we can call write method to write data on the file. Its syntax is given below: String str = "test data"; fOut.write(str.getBytes()); fOut.close(); - openFileInput(): This method is used to open a file and read it. It returns an instance of FileInputStream. Its syntax is given below: FileInputStream fin = openFileInput(file); After that, we call read method to read one character at a time from the file and then print it. Its syntax is given below: int c; String temp=""; while( (c = fin.read()) != -1){ temp = temp + Character.toString((char)c); } fin.close(); <RelativeLayout xmlns: <TextView android: <EditText android: <requestFocus /> </EditText> <Button android: <Button android: </RelativeLayout> The MainActivity contains the implementation of the reading and writing to files as it was explained above. package com.journaldev.internalstorage; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; public class MainActivity extends Activity { EditText textmsg; static final int READ_BLOCK_SIZE = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textmsg=(EditText)findViewById(R.id.editText1); } // write text to file public void WriteBtn(View v) { // add-write text into file try { FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE); OutputStreamWriter outputWriter=new OutputStreamWriter(fileout); outputWriter.write(textmsg.getText().toString()); outputWriter.close(); //display file saved message Toast.makeText(getBaseContext(), "File saved successfully!", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } } // Read text from file public void ReadBtn(View v) { //reading text from file try { FileInputStream fileIn=openFileInput("mytextfile.txt"); InputStreamReader InputRead= new InputStreamReader(fileIn); char[] inputBuffer= new char[READ_BLOCK_SIZE]; String s=""; int charRead; while ((charRead=InputRead.read(inputBuffer))>0) { // char to string conversion String readstring=String.copyValueOf(inputBuffer,0,charRead); s +=readstring; } InputRead.close(); textmsg.setText(s); } catch (Exception e) { e.printStackTrace(); } } }_0<< The file “mytextfile.txt” is found in the package name of the project i.e. com.journaldev.internalstorage as shown below: Download the final project for android internal storage example from below link. Hello i have a question…. I am capturing photo from camera intent and i can set this as an imageview. But i want to save this captured photo to internal storage. How can i do that? I am new in android area. Sorry if it is a basic question. Hi Anupam, I am facing a problem with file operations in native NDK code. In my native NDK code, i am opening a file and writing some app specific data in it and close it. Later when the app reopens, it tries to read that file and populate app data. When read is done, the content is NULL and thus failing. Any pointers? FIle path is on external storage and file permissions set in manifest.xml. FIle operations being done using fread( ) and fwrite( ) syscalls. hi, can i get the app storage size through java code? Is it possible to access the file location by the app itself.? I want to write some info in the file and upload that file to server. great… It is working like a charm Can you please tell be some extra code to save it in a folder, for example InternalStorage/folder/filename.txt Thanks Hey there, does it work with API 29? Thank you man, It was awsome! Thanks a ton for this. I had been looking high and low on how to save and recall strings. Glad this helped you Bil Bo. I am not able to find this file in my android phone i need how to store in sqllite database and retrieve in .txt file format in android with external storage i can’t find the .txt file in android device emulator Hello! Thanks for the tutorial. I have tried your project on my emulator in Android Studio and on my smartphone but no file is written at all. Do you have any idea about the reason of this behavior? Thanks! hi. thanks when we install this app in mobile, where does the text file locate ? I cannot find it Me also Same Doubt this code will never work, you have not declared or used the buttons in your class files therefore when you click the button’s nothing will happen. Hi, The onClick methods for each of the buttons are defined in the xml itself. Thanks Thank you Hello! This example helped me a lot more I was left with a doubt, I need to take a photo to the profile of the user (perfil.jpg) and save in Internal Storage If I am saving a profile image of the user and when I start the activity I need to read the profile.jpg file I do not need to check first if it already exists? Dear Anupam, thanks for your free example. I’m just starting my first game app using pentacubes and I want to prepare the tasks in files in internal storage. So, the files to write / read works in eclipse and emulator, but not, if I upload the apk on my smartphone. What is the way to realize this ?
https://www.journaldev.com/9383/android-internal-storage-example-tutorial
CC-MAIN-2021-04
refinedweb
929
60.01
A Flutter plugin to use the Firebase Cloud Storage API. For Flutter plugins for other Firebase products, see FlutterFire.md. Note: This plugin is still under development, and some APIs might not be available yet. Feedback and Pull Requests are most welcome! To use this plugin, add firebase_storage as a dependency in your pubspec.yaml file. See the example directory for a complete sample app using Firebase Cloud Storage.. eventsstream. pause, resume, cancel. writeToFile. getParent, getRoot, getStorage, getName, getPath, getBucket. putfunction and added putFileand putDatato upload files and bytes respectively. pathgetter to retrieve the path component for the storage node. example/README.md Demonstrates how to use the firebase_storage plugin. For help getting started with Flutter, view our online documentation. Add this to your package's pubspec.yaml file: dependencies: firebase_storage: ^2.1.0+1 You can install packages from the command line: with Flutter: $ flutter packages get Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:firebase_storage/firebase_storage.dart'; We analyzed this package on Apr 17, 2019, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: Flutter References Flutter, and has no conflicting libraries.
https://dart-pub.mirrors.sjtug.sjtu.edu.cn/packages/firebase_storage
CC-MAIN-2019-18
refinedweb
211
52.36
Suppose we have a type called wibble defined as a concrete data type (that is, a type whose representation is fully visible) as shown in Listing latter problem by declaring your data members private. These costs are sufficiently high that software developers have invented techniques to hide a type's representation: turn it into an Abstract Data Type. This is simply a type that does not reveal its representation; a type that abstracts away its representation. In this article I'll look at two abstract data type implementation techniques: Opaque Data Types, and Shadow Data Types. Opaque data types The term Opaque Data Type is a well established term for the technique of exposing only the name of the type in its header file. This is done with a forward type declaration. This certainly has the effect of not exposing any representation! typedef struct wibble wibble; wibble * wopen(int); ... void wclose(wibble *); A definite downside with this approach is that clients cannot create objects themselves. . So how can wibble's source file actually create them? The first possibility is to use an object with auto storage class: ... wibble * wopen(int value) { wibble opened; ... return &opened; // very very bad } ... A second possibility is to create the objects with static storage class: ... Types The term Shadow Data Type, in contrast to Opaque Data Type, is not a well established term. The technique. typedef struct { unsigned char size_shadow[16]; } wibble; void wopen(wibble *, int); ... void wclose(wibble *); The 'true' definition of the type (together with its accompanying #includes) moves into the source file (Listing 2). We can fix this by simply putting the union inside a struct! #include "alignment.h" typedef struct { union { unsigned char size[16]; alignment universal; } shadow; } wibble; ... This is now sufficiently tricky to warrant an abstraction of its own (Listing 3). Synchronized size? The second problem is hinted at by the comment in wibble.c // sizeof(wibble) >= sizeof(wibble_rep) This comment, like all comments, has no teeth. Ideally we'd like an assurance that if the sizes lose synchronization we're told about it. This can be done by asserting the relationship inside a unit test of course. The problem with this (Listing 4). Note that the assertion uses >= rather than ==. This allows binary compatibility with any alternative smaller representation. == allows binary compatibility with any alternative smaller representation. Casting the shadow Inside the source file we can create a helper function to overlay the true representation onto the client's memory (the fragment in Listing 5 uses the dot designator syntax introduced in c99). (Listing 6).wibble objects if desired, at the cost of copying struct objects (Listing 7). Summary In C it is impossible to expose a type's size without also exposing its representation. It is possible to explicitly specify a concrete type's representation as being 'unpublished' but since C does not offer the C++ private keyword using the representation is always possible and remains a constant temptation.. Once one piece of client code succumbs more are sure to follow and like a dam bursting the client and implementation quickly become tightly coupled and any separation is washed away. Completely hiding a type's representation behind an opaque pointer/handle removes the temptation and creates a powerful abstraction but at the price of hiding the size of the type and the consequent restriction on the storage class of client memory. A shadow data type offers a half-way house where a type is effectively split into two, with one part exposing the size and the other part holding the representation. The alignment and sizes of the two parts must correspond. Client code is then able to use all three storage class options. The implementation code takes the full load of the extra complexity mapping/overlaying between the split parts. One interesting observation is that the client code would be unaffected (other than needing recompilation) if the representation was moved back into the client side type (to try and improve performance perhaps). No mechanism is universally applicable and the shadow data type is no exception! Experience and time alone will tell if and how useful it is. Caveat emptor.
https://accu.org/index.php/journals/1593
CC-MAIN-2019-09
refinedweb
692
54.93
Any way to profile performance of JSX layer to find bottlenecks? I noticed that on Windows 10 my script is running significantly slower than on MacOS. Still, on both platforms it would be great to profile and find which methods take the longest to run and where are the bottlenecks. Any tools already available for that? function TimeIt() { // member variables this.startTime = new Date(); this.endTime = new Date(); // member functions // reset the start time to now this.start = function () { this.startTime = new Date(); } // reset the end time to now this.stop = function () { this.endTime = new Date(); } // get the difference in milliseconds between start and stop this.getTime = function () { return (this.endTime.getTime() - this.startTime.getTime()) / 1000; } // get the current elapsed time from start to now, this sets the endTime this.getElapsed = function () { this.endTime = new Date(); return this.getTime(); } } a = new TimeIt(); ... a.getElapsed(); There is also $.hiresTimer but I've never used it. You can also try function init_log() { _timer_log_ = new Array(); _last_line_ = 1; $.hiresTimer; } function log_delay(l) { var time = $.hiresTimer/1000000; _timer_log_.push([time, "line " + _last_line_ + " to " + l + " \tdelay = " + time.toFixed(3)]); _last_line_ = l; } function show_log() { function cmp(a, b) {if (a[0] < b[0]) return 1; if (a[0] > b[0]) return -1; return 0; } _timer_log_.sort(cmp); var s = ""; for (var i in _timer_log_) s += _timer_log_[i][1] +" \n"; alert(s); } // example of your script init_log(); app.activeDocument.channels[0].histogram; //example of your code log_delay($.line) app.activeDocument.channels[1].histogram; //example of your code app.activeDocument.channels[2].histogram; //example of your code log_delay($.line) app.activeDocument.histogram; //example of your code log_delay($.line) // ...the other part of the code // log_delay($.line) // ...the other part of the code // log_delay($.line) show_log(); The ExtendScript ToolKit (ESTK) has a dedicated profiling tool, that is documented on page 35,36 of the JavaScript Tools Guide.pdf – you should be able to find it in the ESTK own folder. Davide
https://forums.adobe.com/thread/2423250
CC-MAIN-2018-39
refinedweb
322
71.1
Details Description In the version 1.0 of Jaxen integer worked in this function. I can't imagine that this problem is a new feature, because integer can always be converted into a double without any lose of information whereas even String is accepted. Since we use Jaxen in the core of our main application, we will have to change a lot of methods in order to upgrade to the new version of Jaxen. Therefore it would be great when you could fix this issue in the next version. An example from our code: We use XML to generate dynamic web sites. The "g:if" condition uses Jaxen: <g:if After an update to the new version of Jaxen this condition is always false. Though String '1' is converted to a number, it can't be compared to the function "count", because this function returns an integer value. To fix this issue you have to add to NumberFunction.evaluate(Object obj, Navigator nav) something like this: else if( obj instanceof Integer){ return (Double) obj; } Activity Thank you for your reply. In the example I compare a Number value with a String. "1" is a String, but "form('count')" returns an integer. Here is the usage of Jaxen in our code. A sample of XML code: <g:if The code where XPath is called to evaluate whether the condition is true: if ("if".equals(localName) && optimizeIf == 0 && !suspendOptimizeIf) { try { String value = attributes.getValue("test"); value = expandAVT(value, true, currentElement); JDOMXPath path = new JDOMXPath(value); path.setFunctionContext(xPathFunctions); boolean ok = path.booleanValueOf(currentElement); ... The variable "value" contains the String: "form('campaignClone.uid') and form('orderClone.state') = '1'" xPathFunctions is an Instance of XPathFunctions, a subclass of FunctionContext. xPathFunctions defines how the condition is interpreted. form('orderClone.state') calls getOrderClone.getState and form('campaignClone.uid') calls getCampaignClone.getUid of the corresponding form class. public int getState(){ return state; } public Long getUid(){ return uid; } This condition is always false with the new version of Jaxen, because getState is an Integer and getUid is a Long value We had to patch the NumberFunction so we could use Jaxen as usual. Here is the code. public static Double evaluate(Object obj, Navigator nav) { if (obj instanceof Double) else if (obj instanceof Number){ return ((Number) obj).doubleValue(); } else if (obj instanceof String) { String str = (String) obj; try catch (NumberFormatException e){ return NaN; } } else if (obj instanceof List || obj instanceof Iterator){ return evaluate(StringFunction.evaluate(obj, nav), nav); } else if (nav.isElement(obj) || nav.isAttribute(obj)) { return evaluate(StringFunction.evaluate(obj, nav), nav); } else if (obj instanceof Boolean) { if (obj == Boolean.TRUE) else{ return new Double(0); } } return NaN; } I think that this problem is a bug, because a Not a Number Exception for an Integer value is an unexpected behavior of a class called “NumberFunction”. A number function is expected to work with all kinds of numbers, especially integer and not only double and String. Otherwise it could be called “DoubleFunction”. This class indeed worked that way in the former version. When only doubles are used internally, other kind of numbers should be accepted and casted the same way it is done with Strings It would be good when this issue would be solved, so we won't have to patch the class after every update of Jaxen. I think the problem is how you've written your external function. Int is not an acceptable return value for call in the Function interface. Only four types are allowed here: Double, String, Boolean, and List. If this worked in previous versions, then that was incorrect. If you change your Function implementation so call() returns a Double, all should be fine. This has been true since at least 1.1.0. It looks like something we tightened up in moving from 1.0 to 1.1. You need to understand "Number" as a number defined in the XPath 1.0 specification, not as a number as defined in Java. Thank you for your reply. Unfortunately it would be very difficult for us to update our code, because the library is used on our main Framework and therefore a lot of methods have to be changed. The changes in Jaxen would be very small as I wrote in the former message. The NumberFunction in Jaxen 1.0 accepted a Java Number value. I can imagine that a general Number can cause problems, but integer can always be converted into a double value without any loss of information or could there be any negative consequences? I'll look into this. However it's not immediately apparent to me that this is a bug. XPath does not have an integer data type. All numbers in XPath are floating point, not integers: Do you have a test case that demonstrates the bug by evaluation of an XPath expression? (i.e. does not directly call the Number function in code). That would be more convincing. In the example you cite I think you're actually comparing strings, not numbers. Try <g:if instead and see if that works.
http://jira.codehaus.org/browse/JAXEN-213?focusedCommentId=274657&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel
CC-MAIN-2015-06
refinedweb
844
58.58
In image processing, we frequently apply the same algorithm on a large batch of images. In this paragraph, we propose to use joblib to parallelize loops. Here is an example of such repetitive tasks: from skimage import data, color, util from skimage.restoration import denoise_tv_chambolle from skimage.feature import hog def task(image): """ Apply some functions and return an image. """ image = denoise_tv_chambolle(image[0][0], weight=0.1, multichannel=True) fd, hog_image = hog(color.rgb2gray(image), orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True) return hog_image # Prepare images hubble = data.hubble_deep_field() width = 10 pics = util.view_as_windows(hubble, (width, hubble.shape[1], hubble.shape[2]), step=width) To call the function task on each element of the list pics, it is usual to write a for loop. To measure the execution time of this loop, you can use ipython and measure the execution time with %timeit. def classic_loop(): for image in pics: task(image) %timeit classic_loop() Another equivalent way to code this loop is to use a comprehension list which has the same efficiency. def comprehension_loop(): [task(image) for image in pics] %timeit comprehension_loop() joblib is a library providing an easy way to parallelize for loops once we have a comprehension list. The number of jobs can be specified. from joblib import Parallel, delayed def joblib_loop(): Parallel(n_jobs=4)(delayed(task)(i) for i in pics) %timeit joblib_loop()
https://scikit-image.org/docs/dev/user_guide/tutorial_parallelization.html
CC-MAIN-2019-18
refinedweb
229
50.43
I'm trying to run some basic openmp examples with MS Visual Studio 2008 SP1 x64. My next step is to install the intel c++ compiler but I'd rather get it working with VS2008 only because then I'm sure I will have problems when I write Matlab MEX files with openMP x64. I start a new Win32 console project with VS2008 SP1. I then add the x64 configuration in the configuration manager. I then add under Project Properties/Configuration Properties/C/C++/Langauage and change OpenMP Support to "Yes /openmp" The application compiles fine but when I run it I get the error: "Unable to start program .... This application has failed to start because the application configuration is incorrect. Review the manifest file for possible errors." What am I doing wrong? Does microsoft visual c++ 2008 doesn't support x64 openmp and it's win32 only? #include "stdafx.h" #include #include int main (int argc, char *argv[]) { int th_id, nthreads; ; }
https://software.intel.com/en-us/forums/intel-moderncode-for-parallel-architectures/topic/293611
CC-MAIN-2017-51
refinedweb
162
64.51
***Note: This post is edited to reflect the newly shipped MP version 6.0.6958.0 Get it from the download center here: This really looks like a nice addition to the Base OS MP’s. This update centers around a few key areas for Windows 2008 and 2008 R2: Let take a look at these changes in detail: Cluster Share Volume discovery and monitoring: We added a new discovery and class for cluster shared volumes: We added some new monitors for this new class: NTFS State Monitor and State monitor are disabled by default. The guide states: I’d probably leave these turned off. The free space monitoring for CSV’s is different than how we monitor Logical disks. This is good – because CSV’s are hosted by the cluster virtual resource name, not by the Node, as logical disks are handled. What CSV’s have is two monitors, which both run a script every 15 minutes, and compare against specific thresholds. Free space % is 5 (critical) and 10 (warning) while Free space MB is 100 (critical) and 500 (warning) by default. Obviously you will need to adjust these to what’s actionable in your Hyper-V cluster environment. BOTH of these unit monitors act and alert independently, as seen in the above graphic for state, and below graphic for alerts: Some notes on how free space monitoring of CSV’s work: There are also collection rules for the CSV performance: Best Practices Analyzer monitor: A new monitor was added to run the Best Practices Analyzer. You can read more about the BPA here: This monitor is shipped DISABLED out of the box to reduce noise, however, you can enable it if you would like to create alerts when your Server 2008 R2 computers are not following best practice configurations. We can open Health Explorer and get detailed information on what's not up to snuff: Alternatively – we can run this task on demand to ensure we have resolved the issues: Changes to built in Monitors and Rules: Many rules and monitors were changed from a default setting, to provide a better out of the box experience. You might want to look at any overrides you have against these and give them a fresh look: A full list of all disabled rules, monitors and discoveries is available in the guide in the Appendix section. The disabling of all these logical disk and memory perf collections is AWESOME. This MP really collected more perf data than most customers were ready to consume and report on. By including these collection rules, but disabling them, we are saving LOTS of space in the databases, valuable transactions per second in SQL, network bandwidth, etc… etc.. Good move. If a customer desires them – they are already built and a quick override to enable them is all that’s necessary. Great work here. I’d like to see us do more of this out of the box from a perf collection perspective. Changes to MP views: The old on the left – new on the right: Top level logical disk and network adapter state views removed. Added new views for Cluster Shared Volume Health, and Cluster Shared Volume Disk Capacity. New Reports! Performance by system, and Performance by utilization: There are two new reports deployed with this new set of MP’s (provided you import the new reports MP that ships with this download – only available from the MSI and not the catalog) ***Note: These two new reports are shipped in their own new MP: the Microsoft.Windows.Server.Reports.mp. These reports are supported only when your SQL servers supporting the OpsMgr backend are SQL 2008 or later. They will not deploy on SQL 2005. To run the Performance by System report – open the report, select the time range you’d like to examine data for, and click '”Add Object”. This report has already been filtered only to return Windows Computer objects. search based on computer name, and add in the computer objects that you’d like to report on. On the right – you can pick and choose the performance objects you care about for these systems. We can even show you if the performance value is causing an unhealthy state – such as my Avg % memory used – which is yellow in the example: Additionally – there is a report for showing you which computers are using the most, or the least resources in your environment. Open “Performance by Utilization”, select a time range, choose a group that contains Windows Computers, and choose “Most”. Run that, and you get a nice dashboard – with health indicators – of which computers are consuming the most resources, and potentially also impacted by this: Using the report below – I can see I have some memory issues impacting my Exchange server, and my Domain Controller is experiencing disk latency issues. By clicking the DC01 computer link in the above report – it takes me to the “Performance by System” report for that specific computer – very cool! Summary: In summary – the Base OS MP is already a rock solid management pack. This made some key changes to make the MP even less noisy out of the box, and added critical support for discovering and monitoring Cluster Shared Volumes. Known Issues in this MP: 1. A note on upgrading these MP’s – I do not recommend using the OpsMgr console to show “Updates available for Installed Management Packs”. The reason for this, is that the new MP’s shipping with this update (for CSV’s and BPA) are shipped as new, independent MP’s…. and will not show up as needing an update. If you use the console to install the updated MP’s – you will miss these new ones. This is why I NEVER recommend using the Console/Catalog to download or update MP’s…. it is a worst practice in my personal opinion. You should always download the MSI from the web catalog at and extract them – otherwise you will likely end up missing MP’s you need. 2. The “Available Megabytes of Memory” monitor script was updated in this version. Along with this update, the default threshold was changed from “2.5” to “100”. The current monitor – the “100” reflects “MBytes”. This value is a good indication of memory pressure, however, in your environment this might create a lot of alerts that might not be actionable depending on your environment. You should review any previous overrides you have set on this monitor, and adjust the default setting as necessary. 3. The “Logical Disk Free Space” monitors were completely re-written. The datasource and monitortype was changed from a script that runs once per hour and drives monitor state, to a new script that runs once every 15 minutes, and drives monitor state after 4 consecutive samples. That seems like a good design change to control any noise from fluctuating disks. However, running the script every 15 minutes might increase the performance impact with more scripts per hour executing on your agents. The script datasource no longer outputs the %Free and MBFree values in the propertybag, therefore – these had to be removed from the Alert Description and Health Explorer. The monitor still works as designed – it creates an alert whenever the threshold is breached. The only change exposed to the end user – is that these values for actual free space in MB and % are not going to be exposed to the alert notification recipient. 4. When you try and run the report “Performance By Utilization” you get an error: An error has occurred during Report Processing. Query execution failed for dataset ‘PerfDS’. Procedure or function Microsoft_SystemCenter_Report_Performance_By_Utilization has too many arguments specified. An error has occurred during Report Processing. Query execution failed for dataset ‘PerfDS’. Procedure or function Microsoft_SystemCenter_Report_Performance_By_Utilization has too many arguments specified. On a reporting server without remote errors enabled – you might only see the top two lines in the error above. I recommend enabling remote errors on you reporting server so the report output will show you the full details of the error: How to Enable Remote errors on SQL reporting server If you are getting the “too many arguments specified” error, this is caused by the Windows 2003 MP. It also contains the stored procedure definition for Microsoft_SystemCenter_Report_Performace_By_Utilization, however the definition in the Windows 2003 MP is missing the “@DataAggregation INT,” variable. Depending on the MP import process, it is possible that the stored procedure from the Microsoft.Windows.Server.Reports.mp will not be deployed, which does contain this variable. In order to resolve this issue – we need to modify the existing stored procedure, and add the “@DataAggregation INT,” line just below the “Alter procedure” line. Ensure you back up your Data Warehouse database FIRST, and if you are not comfortable editing stored procedures, open a case with Microsoft on this issue. An alternative, is to use the SCOM Authoring console, open the Microsoft.Windows.Server.Reports.mp file, go to reporting, Data Warehouse Scripts, Microsoft.Windows.Server.Reports.PerformancebyUtilization.Script properties, Install tab, and copy the actual script. You can run this script in a SQL query window targeting your DW database, and it will create/modify your sproc. The above instructions ONLY cover the SPECIFIC “Too many arguments” error. If you are getting ANY OTHER error, the above method will not resolve your issue and you should open a case for resolution. i exported out my override mp and imported this MP. now when i try to re-import my old overrides i get the following error. looks like a parameter name has changed? any ideas on how to find the new name and fix it? Error 1: :]). @ worldzfree - Why on earth would you export out your override MP first? SCOM is designed so that's never necessary. The whole purpose of using sealed MP's was that you can upgrade them without fear or issue - your override MP's stay intact and still apply. There isnt any reason to export or remove your unsealed MP's except for simple backup purposes. As to your specific issue - I am not aware that were changed any overrideable parameters in the Free space monitortypes.... When running the report Performance by Utilization I got an error from the reportserver System.Data.SqlClient.SqlException: Procedure or function Microsoft_SystemCenter_Report_Performace_By_Utilization has too many arguments specified For the new report Performance by system I'll try this tomorrow as its based on the daily counters of the dataset @Roland - Interesting! Can you try and scope the Utilization report to a smaller group? What group did you choose? I wonder if there are too many group members - if this might be the cause. Also - there is a limit to SQL 2005 and how many object tables it can bind together - I wonder if you are on SQL 2005 or SQL 2008? Also - does it matter if you choose from Yesterday to Today - only scoping the report to the last 24 hours? Hi I have the same problem than worldzfree. I make upgrade of the mp Windows 2003, but now I cant add a new override on my override MP because I have the same error: Note: The following information was gathered when the operation was attempted. The information may appear cryptic but provides context for the error. The application will continue to run. : Verification failed with [1] errors: :].Cannot find OverridableParameter with name [SystemDriveWarningMBytesThreshold] defined on [Microsoft.Windows.Server.2003.FreeSpace.Monitortype] : Cannot find OverridableParameter with name [SystemDriveWarningMBytesThreshold] defined on [Microsoft.Windows.Server.2003.FreeSpace.Monitortype] How i can fix it? Thx Ok guys - I will look into this and see what I find out. Ok guys - I see whats wrong. Yes - there is a bug here. They did modify how this monitor works - I dont know why.... but the composition of the monitortype is completely different. They removed some of the previous override-able parameters... like debugflag and timeoutseconds. However - the key problem that you are experiencing is that they mispelled the Overidable parameter for the 2003 disk free space monitortype. Previously it was correctly spelled: SystemDriveWarningMBytesThreshold Now it is defined as: SystemDriveWarningMBytesTheshold It is missing the "r" in "Threshold". This is now breaking the Override MP verification and causing your issue. Here are your options for a workaround: 1. Go directly into the XML, and delete that override which references that property. Then re-create it back again normailly using the UI. or 2. Go into the XML, find all the overrides that reference this monitortype, and then edit the XML for the override-able property to the new mispelled word. :-) Note - I will report this... but if we "fix it" with a new version it will break your adjusted overrides again... so keep that in mind. Thx it is ok after modify! But the problem is for Windows 2003 AND Windows 2008. After importing the MP, soon I began to receive this error for all my 2008 servers (219) except for 1. "There has been a Best Practice Analyzer engine error for Model Id: 'Microsoft/Windows/ApplicationServer' during execution of the Model. (Inner Exception: One or more model documents are invalid: {0}Discovery exception occurred processing file '{0}'..") For more information on the BPA issues detected, view the diagnostic output in the State Change Events tab for the Windows Server 2008 R2 Operating System BPA Monitor in Health Explorer. Alternately, the View Best Practices Analyzer compliance results task can be manually executed to have the results returned." On all my 2008 servers, powershell ExecutionPolicy is forced to RemoteSigned by a GPO (except the one that is working, it's Unrestricted). How could I override this ? Thanks How do I override BSA rule in such away that my RMS and DW server are not flagged as needing to the WSUS role added ? Server Role: Microsoft/Windows/WSUS ==================================== Title : The Windows Server Update Services Role should be installed Problem : The Windows Server Update Services Role is not installed. Impact : The WSUS Best Practices Analyzer scan will not run unless the WSUS Role is installed on the machine. Resolution : Install the WSUS Role through Server Manager. @Robert - this is either due to your specific execution policy and this powershell clashing - or something environmental. Normally I would expect "remote signed" to work just fine. If you manually perform a Get-ExecutionPolicy -List on a server - do ALL types show RemoteSigned? It is possible that this specific monitor code does not work under RemoteSigned policy, I can't say I have heard this. @ Azren - This new feature is all or nothing. It simply runs the OS built in functionality for retuning ANY errors from the BPA. In SCOM - you can either turn it on, or off. I expect many customers will disable this and consider it noise, unless they have a commitment to run all servers in accordance with the BPA. The new MP looks great, however I've imported the new Reports MP, and the new reports just aren't in the console. Is there some issue with them being hidden or anything? The reporting MP is there, I've even removed it and reimported with success, it's just not in the reporting section. Any ideas? @moter - It takes up to an hour to deploy the reports. This is normal. Did you wait long enough? If you have a report that is not deploying - you will see some srtitical events on the RMS OpsMgr event log stating the "why". at the reimport of the MP my scom server logged this alert: Data Warehouse failed to deploy database component.: 'f652ee20-fdfd-1cb2-5491-c2cc5fb8daa6'; Target: Database, Server name: 'SCOMDB01\SCOM,1036 ', Database name: 'OperationsManagerDW'. Batch ordinal: 1; Exception: Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon. Incorrect syntax near ','. Incorrect syntax near the keyword 'ELSE'.
http://blogs.technet.com/b/kevinholman/archive/2011/09/30/opsmgr-new-base-os-mp-6-0-6956-0-adds-cluster-shared-volume-monitoring-bpa-and-many-changes.aspx?PageIndex=5
CC-MAIN-2015-06
refinedweb
2,647
62.48
procmgr_timer_tolerance() Get or set the default timer tolerance for a process Synopsis: #include <sys/procmgr.h> int procmgr_timer_tolerance( const pid_t pid, const uint64_t * const ntime, uint64_t *otime ); Since: BlackBerry 10.1.0 Arguments: - pid - The process ID of the process whose default timer tolerance you want to set, or 0 to set it for the calling process. - ntime - NULL, or the default timer tolerance, in nanoseconds. Specify a value of ~0ULL for infinite tolerance. - otime - NULL, or a pointer to a location where the function can store the current or previous timer tolerance. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The procmgr_timer_tolerance() function sets or gets the default timer tolerance for a process. This tolerance is used when calculating timer tolerance if the timer doesn't already have a tolerance set, or has the TIMER_PRECISE flag set. This includes the implicit timer used for TimerTimeout() operations. In order to set the default tolerance of another process, the calling process must have the same user ID, be root, or possess the PROCMGR_AID_DEFAULT_TIMER_TOLERANCE ability. For more information, see procmgr_ability(). The default timer tolerance is inherited across a fork(), but not an exec*() or a spawn*(). Errors: - EPERM - Insufficient permission. - ESRCH - There's no process with the specified process ID. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/p/procmgr_timer_tolerance.html
CC-MAIN-2019-35
refinedweb
243
58.99
Hi guys, I'm very new to C/C++ libraries. I know the syntaxes of c/c++, like how to declare classes,pointers array etc. But when it comes down to using the libraries , i totally suck at it. I am using Microsoft visual studio 8 (or 2005). There are some questions which i hope you guys can help me out : 1. Does C++ have different standard libraries? Since microsoft provided them, wouldn't they be the same for everyone? Such as for Java, everyone has the same JDK 2. I've searched for C++ standard library, they include stuff like cmath and iterators. However I also discovered there are header files like : #include <windows.h> #include <stdio.h> #include <winuser.h> #include <windowsx.h> which are used in a simple keylogger, I couldnt find these in the Standard Library reference, the problem now is how do i find the references to these classes? It's really difficult to start with the library, I mean there are so many stuff out there but so hard to locate them. Does anyone know of any resource which can slowly guide me? I know I could Google it, but most of the searched that come out does not help at all.. Thanks
https://cboard.cprogramming.com/cplusplus-programming/96974-new-use-c-cplusplus-library-printable-thread.html
CC-MAIN-2017-30
refinedweb
209
76.62
Using gradlew with gradle 2.13. So I noticed that there is a .gradle folder in both my project and my home folder. For some reason, having the project .gradle folder is causing an odd issue with my build. I have a complicated gradle build script that downloads artifacts from a repository and package them into an AAR file but the first time the build ran, it didn’t include the downloaded artifacts and there is no build error. The same exact build command ran the 2nd time will include the artifacts. Has anyone seen this problem before? The .gradle folder in your project has always been there. It is known as the project-cache-dir and can be overridden form the command-line. I suspect the issue you are seeing has nothing to do with it, unless you accidentaly include it in your archive. The behaviour you are mentioning is typical when one task depends on the output of another, but the de[ency has not been declared properly or the inputs of the second task are finalised prematurely. I should clarify I am helping debug a fellow developer’s complex gradle issue, so I am still learning what the build script is doing. I discovered that the project build.gradle depends on gradle intermediate build paths like build/outputs/aar to store additional files that needed to be included in the final aar. This isn’t ideal as gradle may have changed how they handled the intermediate build steps and somehow clean out the additional files only on the 1st build and not subsequent builds. BTW, is there a reliable way to create a fat aar that includes files from an external source? I googled but couldn’t find a reliable way to do this still it seems. Any input is much appreciated. Thanks. I cannot help with the AAR question, but may @Ken_Kousen, author of Gradle Recipes for Android, will know thanks for your help @Schalk_Cronje. @Ken_Kousen if you have any tips, I would greatly appreciate it. AAR files are like regular Java library dependencies, except that they include other Android dependencies like resource files and/or merged manifest info. If you were to create an Android Library from scratch using the wizard in Android Studio, it would add another module to your existing project with its own build file, and the top level settings.gradle file would show it as a subproject. If your project depends on an existing aar file, then using it is much like adding another Java library dependency – it’s listed in your build.gradle file in the dependencies block. The hope then is that it’s already complete and self-contained, so any dependencies it needs are already bundled in. It’s hard to tell from your question, but that may be the issue with the lack of dependencies which are then filled in on the second build. Either way, I agree with @Schalk_Cronje that I doubt the .gradle folder has anything to do with your issue. Personally, I’ve used Android projects that had the additional Android Library project included in the source, and those have worked without a problem. I had one case where a client supplied an AAR file, and everything worked except for the manifest merger, which is supposedly fixed in the latest version of the Gradle plugin for Android. When you ultimately create the apk, everything is bundled into that, including the aar file dependency. That’s effectively your “fat jar”, if I’m interpreting your question correctly. Deploying the app generates the (debug) apk, but you can always just run one of the Gradle assemble tasks to generate it directly. Thanks for your feedback. My project needs to download an AAR file from a repo and then include it in the project’s AAR creating a fat AAR to be included in yet another project which then produces an APK. I have tried multiple ways to add the external AAR as a dependency, e.g., using flatDir and dependencies and it would build fine but it does include the external AAR contents as part of the final AAR. Here’s the code snippet, I am putting the external AAR in libs folder repositories{ flatDir{ dirs 'libs' } dependencies { compile 'abc:1.0.0@aar' } I have also tried to add this in dependencies: compile fileTree(dir: 'libs', include: ['*.aar']) But I am getting warnings like Only Jar-type local dependencies are supported. Cannot handle: aar. Am I missing something basic? That should work - we actually use a similar style in the JRuby-Gradle plugin as part of our testing - Agreed, it should work but it doesn’t, like I said it builds just fine but did not include the external AAR into the final AAR and compile fileTree only handles .jar file types, so I am not sure what’s going on. I assume compile is an Android gradle task, it’s not easy to determine which plugin a task belongs to. You can get a rough idea, by running gradle model, finding your task and then by looking at its namespace and the name of its creator. However compile is not a task, it is a configuration which is added by JavaBasePlugin. @Ken_Kousen Got a question on this. If I have three dependencies in my project (1- AAR file in libs folder, 2- AAR file from a maven repo, 3 - Jar file in libs folder). - Will all these dependencies be compiled/treated similarly? - Will the final size of an AAR file include all the dependencies including other AARs and Jars( including from libs, repo etc) - What happens to transitive dependencies and when its compiled to an APK? ( if there is a same dependency xyz in AAR 1 and AAR 2) Thanks Rahul
https://discuss.gradle.org/t/gradle-folder-in-project/17617
CC-MAIN-2022-40
refinedweb
967
62.48
In this tutorial, we’ll cover both the basic and technical sides of the interview. We shall start from the beginner (entry) questions, and build up to the more advanced ones as we progress through the tutorial. Table of Contents - 1. Getting to Know Python Basics - 1.1. Question 1: What is Python? - 1.2. Question 2: Can you name the type of Python language? Is it scripting or programming? - 1.3. Question 3: What key features of Python could you name? - 1.4. Question 4: Why is Python better than Java? - 1.5. Question 5: How many data types are there in Python? - 1.6. Question 6: What’s the difference between a ‘tuple’ and a ‘list’? - 1.7. Question 7: What’s ‘pickling’ and ‘unpickling’? - 1.8. Question 8: What is ‘lambda’? - 1.9. Question 9: How is memory managed within Python? - 1.10. Question 10: What is ‘pass’? - 1.11. Question 11: Can you copy an object in Python? - 1.12. Question 12: How to delete a file within Python? - 1.13. Question 13: What is a ‘dictionary’? - 1.14. Question 14: Is Python an interpreted language? - 1.15. Question 15: Which of these is wrong? - 1.16. Question 16: How is Python object-oriented? - 1.17. Question 17: What is ‘slicing’? - 1.18. Question 18: What is ‘namespace’ in Python? - 1.19. Question 19: What is ‘self’ in Python? - 1.20. Question 20: Do you really need to use ‘indentation’ in Python? - 2. Advanced Python Questions - 2.1. Question 1: Write a code that would calculate a list of given numbers. - 2.2. Question 2: Write a code that would randomize items from the list. - 2.3. Question 3: Is there a difference between ‘range’ and ‘xrange’? - 2.4. Question 4: What is a Dogpile effect? - 2.5. Question 5: Explain what is Encapsulation. - 2.6. Question 6: When does Abnormal Termination happen? - 2.7. Question 7: Write a code that would count all of the capital letters in your file. - 2.8. Question 8: Does Python have a compiler? - 2.9. Question 9: What is Monkey Patching? - 2.10. Question 10: How to save an image when you know the URL? - 2.11. Question 11: If list1 is [4, 6, 8, 1, 0, 3], what will list1[-1] be? - 2.12. Question 12: What is a ‘decorator’? - 2.13. Question 13: What are the 'sub()', 'subn()' and 'split()' methods? - 2.14. Question 14: What do the processes of 'compiling' and 'linking' do? - 2.15. Question 15: What do the functions ‘help()’ and ‘dir()’ do? - 3. General Tips - 4. Conclusions Getting to Know Python Basics Let’s take it from the top and start by covering the more general questions and answers. These are questions that you are most likely to get asked at the beginning of the interview, just to see if you truly do have a fundamental understanding of Python. After that, we'll move on to some technical questions and finish off with a few general tips and advice. Latest Udacity Coupon Found: UP TO 85% OFF Limited-time Udacity Coupon For a limited time only, get 70% off bundle subscriptions & extra 15% off upfront payments. Use this Udacity coupon & save big on high-quality learning! Question 1: What is Python? As you’ve probably expected, this is one of the very first Python interview questions that you’re bound to get asked. Your employers are probably going to expect a concise and thorough answer, so let’s provide them one. Python is a portable, high-level programming language that has inbuilt automatic memory management, threads, strings, is object-based. It is loved for the simplicity and built-in data structure - the fact that Python is open source also contributes to its fame. Question 2: Can you name the type of Python language? Is it scripting or programming? Python is a general-purpose programming language that is capable, if needed, of scripting. Question 3: What key features of Python could you name? Before Python interview questions, take a look at the list of key Python programming language features: - Python is one of the most universal programming languages. It can be interpreted, which means, that it does not need to be compiled before it is run. - The programming language is dynamically typed. It does not require the user to state the variables before compiling. For example, you can write “x=123” or x="good" afternoon” without an error. - Python is well suited to object-orientated programming. That allows the definition of classes along with composition and inheritance. - Its’ functions are first-class objects. It can be assigned to variables, returned and passed into other functions. - The use of Python is very wide - it can be used in automation, web applications, scientific modeling, big data applications, etc. It can be used as a combining element to get other languages and components to work together. Question 4: Why is Python better than Java? Some of your interview questions might involve comparisons with other programming languages - these can be random, but Java seems like the most common one that employers ask. In short, Python (when compared with Java) is easier to use and has much better coding speeds. Also, when it comes to data, Java is statically typed, while Python offers dynamic typing. This is considered to be a huge advancement. But just to be sure, prepare for Python interview questions and answers. Question 5: How many data types are there in Python? One of the more common interview questions on Python - you might get asked to either say the number or name them. Python has five different data types: string, list, number, dictionary, and tuple. Question 6: What’s the difference between a ‘tuple’ and a ‘list’? The main difference is that lists are slower, but they can be edited, while tuples work faster, but cannot be modified. Question 7: What’s ‘pickling’ and ‘unpickling’? Pickling happens when a module within Python is accepted and converted into a string module, and then later dumped into the file. As opposed to that, unpickling is when you retrieve the string module from the file. For such comparison-based Python interview questions, try to keep your explanations as simple as possible. Your potential employers will probably appreciate that you can explain tough topics in a simple-to-understand manner. Question 8: What is ‘lambda’? Lambda is an anonymously performed function with just one, single expression. Question 9: How is memory managed within Python? Python's private heap space is responsible for memory management. It is only accessible by an interpreter - if you’re a Python programmer, you won’t be able to reach it. The language also has an inbuilt recycler that is responsible for creating more free heap space (this is done by recycling unused memory). Question 10: What is ‘pass’? Pass simply indicates a space that should be left blank within the compound statement. Question 11: Can you copy an object in Python? Even though it sounds like one of the basic Python interview questions, you would probably be surprised how many people manage to stumble with it. Yes, you can copy objects in Python, but not all of them. The most general and well-known way to do it is to use the copy.copy() command. Question 12: How to delete a file within Python? To delete something in Python, use the command os.remove(name_of_the_file). Question 13: What is a ‘dictionary’? Remember the data types that we’ve talked about earlier? The inbuilt ones? A dictionary is exactly that. Dictionaries are comprised of keys and the key corresponding values. Here’s an example: dict={'Car':'Ford','Type':'Mustang','Year':'1967'} print dict[Car] Ford print dict[Type] Mustang print dict[Year] 1967 Question 14: Is Python an interpreted language? Again, one of the most commonly asked Python interview questions - you should keep this in mind. Yes, Python is an interpreted programming language. What does this mean? It’s a three-way process - you write source code, Python converts it into an intermediate language (for easier understanding) and then it’s yet again changed into machine codes that are then executed. Question 15: Which of these is wrong? a) xyz = 5,000,000 b) x,y,z = 1000, 3000, 7000 c) x y z = 1000 3000 7000 d) x_y_z = 5,000,000 The answer: C is the wrong one. Question 16: How is Python object-oriented? Object-oriented programming languages (OOPs) are based on classes and objects of those classes. Python is exactly that. More so, Python possesses the features that are credited to OOPs - inheritance, polymorphism, etc. Question 17: What is ‘slicing’? In Python, slicing is when you select multiple items from places like lists, strings and so on. So - those are the more basic Python interview questions that you might receive during your job interview. Now, let’s try and move more towards the advanced stuff and some untouched Python technical interview questions. Question 18: What is ‘namespace’ in Python? It is the process of naming the system that is used to make sure that all the names are unique and different. Question 19: What is ‘self’ in Python? Self is an instance or an object of a class. In Python programming language, it helps to differentiate between the methods and attributes of a class with local variables. Question 20: Do you really need to use ‘indentation’ in Python? Yes, it is crucial. Indentation specifies the block of code. Within the indented block, there are all the codes with loops, classes, and functions. If the code is not indented, it will not execute accurately and will show an error. Advanced Python Questions While the basic Python interview questions can be vital during the job interview, it is also important to pay some attention to the advanced ones, since most of the time they are more tricky to remember and learn. Question 1: Write a code that would calculate a list of given numbers. def list_sum(num_List): if len(num_List) == 1: return num_List[0] else: return num_List[0] + list_sum(num_List[1:]) print(list_sum([3, 5, 8, 9, 9])) The Result: 34 Question 2: Write a code that would randomize items from the list. from random import shuffle x = ['Skyrim', 'Belongs', 'To', 'The', 'Nords'] shuffle(x) print(x) The result: [‘Nords’, ‘Skyrim’, ‘To’, ‘Belongs’, ‘The’]. Question 3: Is there a difference between ‘range’ and ‘xrange’? Yes, albeit it might not be noticeable at first. In terms of functionality and the tasks they perform, both commands are nearly identical. The key difference, however, is that range (when used) brings back a list object, while xrange returns an xrange object. Question 4: What is a Dogpile effect? This is one of the Python interview questions that might be tricky to memorize at first, so do give it a few good tries. A Dogpile effect happens when a website’s cache expires, yet it is hit by many different requests from the user. This can cause many different problems, from lag spikes to complete crashes. A system called semaphore lock is used to prevent Dogpiles from happening. Question 5: Explain what is Encapsulation. Encapsulation is one of the features that Python has because it’s an object-oriented programming language. Be sure to add this to your answer pool. Encapsulation is a process of grouping related data members into one, single place. Along with the member, encapsulation also returns their functions, too. Question 6: When does Abnormal Termination happen? First of all, during the Python interview questions and answers, it should be said - abnormal termination is bad. You don’t want it to happen in your coding experience, although it’s almost unavoidable at one point or another, especially when you're a beginner programmer. Abnormal termination is a crash of your program in the middle of its execution, while the main tasks are still running. This is usually caused by a faulty code or some software issues. Question 7: Write a code that would count all of the capital letters in your file. with open(I_LIKE_APPLES) as fh: count = 0 text = fh.read() for character in text: if character.isupper(): count += 1 Question 8: Does Python have a compiler? This is one of the tougher Python interview questions, mostly because not many people pay attention to it. Python indeed does have its compiler, but it’s rather easy to miss. This is because it works automatically - you don’t notice it. Question 9: What is Monkey Patching? Monkey patching refers to modifications that you would make to the code when it’s already running. Question 10: How to save an image when you know the URL? To save an image locally, you would use this type of code: import urllib.request urllib.request.urlretrieve("URL", "image-name.jpg") Question 11: If list1 is [4, 6, 8, 1, 0, 3], what will list1[-1] be? “-1” always points to the last index in a list, so the answer would be 3. Question 12: What is a ‘decorator’? There are a lot of terms that you need to know during Python interview questions and this is one of them. Decorators are used to inserting new and fresh pieces of code into an already existing class or function. With the help of decorators, you can make these codes run before or after the original one. Question 13: What are the 'sub()', 'subn()' and 'split()' methods? A module called “re” lets you modify your strings in Python. There are three methods of how you can do this: - sub(): finds specific strings and replaces them. - subn(): same as the sub(), but also return the new strings with the exact number of replacements. - split(): splits a specific string into a list. I’ve given you a very general overview of the three “re” methods of string modifications within Python. It is advisable to do more research on this topic before your job interview - these strings are usually a part of very popular Python interview questions that potential employers ask their job nominees. Question 14: What do the processes of 'compiling' and 'linking' do? I’ve already mentioned the Python compiler earlier, but this is also one of the questions and answers that you might find useful. Compiling lets you, well… Compile new extensions within your code without any errors. After that, linking can be a fluid process - a successful compilation smoothens out linking and eliminates any possible issues throughout the process. This can be considered one of the more easier Python coding interview questions if your potential employer doesn’t ask you to go in: What do the functions ‘help()’ and ‘dir()’ do? I thought it would be a good idea to finish off with one of the more Python technical interview questions. Both of these functions can be accessed from the Python interpreter. They are used to view consolidated dumps from inbuilt functions. help() shows you the documentation string, while dir() displays the defined symbols. Now that I’ve given you some of the more advanced Python interview questions, let’s move on to some general tips that you could apply before and during your interview. General Tips Job interviews can be tough and stressful, but you shouldn’t let that get the better of you. You can read all of the questions and answers that you’ll find on the internet and still flunk that interview. How so? First of all, your potential employer isn’t only going to ask you about Python. He might ask you about your previous experiences, check what kind of a person you are, get to know your hobbies - all of these factors are very important for landing that job. One good way to leave a good impression is to not act like your life depends on the outcome of the interview - if you’re sitting there and trying to answer technical Python interview questions while sweating profusely and shaking like a leaf, you might scare the person your talking to. Also, don’t be cocky - sure, you might have 20 years of expert Python experience, but what good will that do you if you don’t get the job only because you scoffed at some of the easier Python coding interview questions and came off as arrogant because of it? Get a good night’s sleep and don’t worry about it - show your potential employer the person that you truly are, and you'll be likely to succeed. Remember - these people are professionals that deal with wannabe employees daily - if you try to lie or cheat, they will most likely catch on to you in mere seconds. Conclusions With such an increased need for Python programmers and developers, it wouldn’t be surprising if you went through hundreds of interviews with thousands of Python interview questions until you finally land that dream job - which can be a good thing! When you answer so many Python-related questions, you’ll become more and more relaxed and confident in your ability to succeed. If you think that your Python skills are not up to the level for these questions, be sure to enroll in BitDegree's interactive Python tutorial to advance your!
https://www.bitdegree.org/tutorials/python-interview-questions/
CC-MAIN-2022-40
refinedweb
2,875
65.73
Flask jQuery UI Bootstrap minimalistic fork of Flask-Bootsrap extension Project description Flask jQuery Ui Bootstrap Flask-JqueryUiBootstrap is minimalistic fork of Flask-Bootstrap project. This project packages Twitter’s Bootstrap with jQuery UI and is based on jQuery UI Bootstrap project. If you don’t need jQuery UI Bootstrap is strongly recommended to use better original plugin Flask-Bootstrap. Usage Here is an example: from flask.ext.jqueryuibootstrap import Bootstrap [...] Bootstrap(app) This makes base layout templates available: jqueryuibootstrap_base.html. This layout file have predefined blocks where you can put your content. The core block to alter is body_content, otherwise see the source of the template for more possibilities. Macros A few macros are available to make your life easier. These need to be imported (I recommend create your own base.html template that extends one of the bootstrap base templates first and including the the macros there). An example base.html: {% extends "jqueryuibootstrap_base.html" %} {% import "jqueryuibootstrap_wtf.html" as wtf %} Forms The jqueryuiboot) }} Configuration options There are a few configuration options used by the templates: A note on versifying Flask-JqueryUiBootstrap tries to keep some track of jQuery UI Bootstrap releases. Versifying is usually in the form of x.y.z of jQuery UI Bootstrap version with .z micro version of Flask extension Package. For example, a version of 0.5.0.0 bundles version 0.5.0 of jQuery UI Bootstrap version and is initial release of Flask-JqueryUiBootstrap containing that version. How can I add custom javascript to the template? Use Jinja2’s super() in conjunction with the bootstrap_js_bottom block. The super-function adds the contents of a block from the parent template, that way you can even decide if you want to include it before or after jQuery/bootstrap. Example: {% block bootstrap_js_bottom %} {{super()}} <script src="my_app_code.js"> {% endblock %} Contribute - We are open for any help. - 0.5.0.3 (2013-09-15) - Important API change Bootstrap to JqueryUiBootstrap (Flask-Bootstrap no conflict) 0.5.0.1 (2013-08-26) - Initial version Project details Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/Flask-JqueryUiBootstrap/
CC-MAIN-2022-27
refinedweb
358
60.31
Masonite 1.4 brings several new features and a few new files. This is a very simple upgrade and most of the changes were done in the pip package of Masonite. The upgrade from 1.3 to 1.4 should take less than 10 minutes This requirement file has the masonite>=1.3,<=1.3.99 requirement. This should be changed to masonite>=1.4,<=1.4.99. You should also run pip install --upgrade -r requirements.txt to upgrade the Masonite pip package. There is now a new cache folder under bootstrap/cache which will be used to store any cached files you use with the caching feature. Simply create a new bootstrap/cache folder and optionally put a .gitignore file in it so your source control will pick it up. Masonite 1.4 brings a new config/cache.py and config/broadcast.py files. These files can be found on the GitHub page and can be copied and pasted into your project. Take a look at the new config/cache.py file and the config/broadcast.py file. Just copy and paste those configuration files into your project. Masonite comes with a lot of out of the box functionality and nearly all of it is optional but Masonite 1.4 ships with three new providers. Most Service Providers are not ran on every request and therefore does not add significant overhead to each request. To add these 3 new Service Providers simple add these to the bottom of the list of framework providers: PROVIDERS = [# Framework Providers...'masonite.providers.HelpersProvider.HelpersProvider','masonite.providers.QueueProvider.QueueProvider',# 3 New Providers in Masonite 1.4'masonite.providers.BroadcastProvider.BroadcastProvider','masonite.providers.CacheProvider.CacheProvider','masonite.providers.CsrfProvider.CsrfProvider',# Third Party Providers# Application Providers'app.providers.UserModelProvider.UserModelProvider','app.providers.MiddlewareProvider.MiddlewareProvider',] Note however that if you add the CsrfProvider then you will also need the CSRF middleware which is new in Masonite 1.4. Read the section below to add the middleware Masonite 1.4 adds CSRF protection. So anywhere there is any POST form request, you will need to add the {{ csrf_field }} to it. For example: <form action="/dashboard" method="POST">{{ csrf_field }}<input type="text" name="first_name"></form> This type of protection prevents cross site forgery. In order to activate this feature, we also need to add the CSRF middleware. Copy and paste the middleware into your project under the app/http/middleware/CsrfMiddleware.py file. Lastly, put that middleware into the HTTP_MIDDLEWARE list inside config/middleware.py like so: HTTP_MIDDLEWARE = ['app.http.middleware.LoadUserMiddleware.LoadUserMiddleware','app.http.middleware.CsrfMiddleware.CsrfMiddleware',] There has been a slight change in the constants used in the config/database.py file. Mainly just for consistency and coding standards. Your file may have some slight changes but this change is optional. If you do make this change, be sure to change any places in your code where you have used the Orator Query Builder. For example any place you may have: from config import databasedatabase.db.table(...) should now be: from config import databasedatabase.DB.table(...) with this change
https://docs.masoniteproject.com/upgrade-guide/masonite-1.3-to-1.4
CC-MAIN-2020-34
refinedweb
512
60.31
The prototype of the function is written as given below, time_t mktime (struct tm * Timeptr) ; The function converts the broken down time representing local time in the structure pointed to by Timeptr into calendar time. In Program the day of the week is determined; it finds the day of the week on 15th August 2010. Illustrates mktime () function #include <stdio.h> #include <time.h> int main () { time_t T1; char *const wday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; struct tm Time ; Time.tm_year = 2010 - 1900; Time.tm_mon = 8 - 1; Time.tm_hour = 21; Time.tm_min = 41; Time.tm_sec = 25; Time.tm_isdst = -1; Time.tm_mday = 15; mktime (&Time); clrscr(); printf("The day is %s.\n", wday [Time.tm_wday]); printf("%u\n", mktime(&Time)); time(&T1); printf("%u\n", T1);
http://ecomputernotes.com/what-is-c/function-a-pointer/function-mktime
CC-MAIN-2019-47
refinedweb
127
72.02
This, if possible, and to be handled by something better than pure code (eg. BPMN). The model for this experiment is straightforward. We create a layer with three states: state.1, state.2, and state.3. Upon start charm kicks off execution of state.1, which then transit itself to the state.2, then to state.3, and then loop back to state.1. The key questions to answer in this experiment are: - What is the entry point to start the first state? - If setting two states true, are they executed serially or in parallel? - Can a blocking command halt state transition even if there are states being true and can be acted upon? Screencast Top left window shows the juju debug-log which prints state transition among three states. Top right window juju status also shows state transitions in Message column which is set by set_status in each state's function block. The 1st state How to start the first state? In this test we experimented using hooks to introduce the first state since hooks are executed in a predetermined sequence. However, set_state has no effect and actually should be avoided within hook execution according to document (needs reference). To safely start the whole process, we settled on @only_once: @only_once def state_0(): log('something------------------') Chain state pattern The three primary states follow the same pattern. Using state.1 for example: @when('state.1') def state_1(): """State.1 """ # set status t = time.ctime(time.time()) status_set('maintenance', 'state.1 %s' % t) # workload time.sleep(TEST_TIMEOUT) # state transition remove_state('state.1') set_state('state.2') Multiple states being true If we set multiple states true, will they be executed in parallel? From previous article on state execution, we can already see that states are first saved in a dictionary and then scanned by iterator. Therefore, there is no parallel computing built in the charm execution mechanism. Further, execution order of two states have no guarantee except they will all be done sooner or later because Python dictionary does not enforce any order. Multiple truestates will be executed in serial. Orders of execution is undetermined. Long running process Will a shell blocking call halt state transition? In this test we want to verify whether starting a long running process will block charm's state transition. We used subprocess.check_all to start a blocking call while state 1-3 are kept to loop as designed. def state_4(): """State4. """ subprocess.check_all("apt update && apt dist-upgrade") The result is clear that state machine will come to a halt at this blocking call, which would have to be the case since we already know how states are being scanned and executed from previous article. All states are cached in a dictionary and are scanned in a tight loop per iteration. Thus a blocking call in any handler will cause the loop to a halt. Nowhere in code will take a signal so this behavior can not be interruptted either.
http://fengxia.co.s3-website-us-east-1.amazonaws.com/juju%20charm%20chained%20states.html
CC-MAIN-2019-09
refinedweb
493
67.55
Intro Are you a C++ crazy fan? I’m! don’t be shy. I can’t imagine life without programming in C++, so now that I’m getting into IoT I wanted to explore the feasibility of using C++, after all programming ESP8266 in the Arduino IDE you can, why can’t we on the official SDK? Out of the box the projects build on top of Espressif SDK are compiled in C. And that’s a good thing. A better one is to program our projects in C++. I didn’t find any useful information, so I tried it myself, and I succeded! So far I just tried to use my own classes, I haven’t tested the STL library, but they would work (I don’t want to forget the steps I followed, so I’m in a hurry!). Procedure I tried theses steps in Linux Mint, but there’s nothing weird that cannot be done in either Windows or Mac. I’m assuming you have an Espressif SDK environment up and running. My setup is so simple: STEP 1: Do everything is needed to compile your projects in C under the Espressif SDK. This is a great introduction. STEP 2: Say you’re following the “Hello world” example. Look for the file hello_world_main.c under the hello_world/main folder, and delete it. STEP 3: In that same folder create a new file called hello_world_main.cpp and populate it with the next content: /* Hello World Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Modified by fjrg76, 26/04/21, Mexico City */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_spi_flash.h" class MyClass { int a; public: void set( int val ) { a = val; } int get() { return a; } }; int f() { MyClass c; c.set( 100 ); return c.get(); } // app_main() is the entry point for our programs and it must be a C function: #ifdef __cplusplus extern "C"{ #endif void app_main() { printf("Hello world!\n"); /* Print chip information */ esp_chip_info_t chip_info; esp_chip_info(&chip_info); printf("This is ESP8266 chip with %d CPU cores, WiFi, ", chip_info.cores);); } // for testing the C++ compiler: int v = f(); printf( "Value is: %d\n", v ); vTaskDelay( 500 / portTICK_PERIOD_MS ); printf("Restarting now.\n"); fflush(stdout); esp_restart(); } #ifdef __cplusplus } #endif It’s almost the same code as the original example, but I added some things: - The most important fact to be aware is that the function app_main()is surrounded with the macro __cplusplusin order to be compiled as C function. Otherwise it won’t work. The entry point for the user code is the function app_main()and it must be a C function. - I added a silly class and a silly function f(). Actually this f()function might be the entry point for our programs (if you aren’t using FreeRTOS tasks). - Inside the function app_main()I called the function f()so that it is compiled, and we use the instance cfrom the class MyClass. You’ll end up with these 3 files: STEP 4: Open the file CMakeLists.txt and modify it with this next content: idf_component_register(SRCS "hello_world_main.cpp" INCLUDE_DIRS "") The only change with regards to the original one is that I’ve changed the extension from .c to .cpp. STEP 5: Build the project and enjoy programming the ESP8266 in C++ along the real time operating system FreeRTOS: $ make clean $ make The make clean instruction is to clean up the environment. It contains debris from those times when the project was compiled with the C compiler. Once done you don’t need to repeat it. The make instruction actually compiles the project using the C++ compiler. If you get this next output, you’re done! STEP 5: Upload your program into the chip: $ make flash You don’t need to emit two instructions: make and then make flash; with the latter is enough. I used a single make so you can see the output. You might want to see what the program is doing. Press and release the reset button on your board (I need to do it by hand on mine) and type: $ make monitor (To exit from the monitor type Ctrl + ]). This is the output: What’s next We’ve seen how to program using C++; the next logical step is to try the STL. If you speak spanish, or at least you understand it, and you aren’t aquainted with FreeRTOS, you might want to take a look to my free course on “Arduino en tiempo real” (Arduino in real time). If you like this post please drop me a line to say “Hello!”. Or better off, suscribe!
https://arduinoforadvanceddevelopers.wordpress.com/
CC-MAIN-2021-31
refinedweb
808
73.07
What is the return value of following function for arr[] = {9, 12, 2, 11, 2, 2, 10, 9, 12, 10, 9, 11, 2} and n is size of this array.Bit Algorithms int fun(int arr[], int n) { int x = arr[0]; for (int i = 1; i < n; i++) x = x ^ arr[i]; return x; } Discuss it Question 1 Explanation: Note that 9 is the only element with odd occurrences, all other elements have even occurrences. If the input array has all elements with even occurrences except one, then the function returns the only element with odd occurrences. Note that XORing an element with itself results 0 and XOR of 0 with a number x is equal to x. Try following complete program. # include <iostream> using namespace std; int fun(int arr[], int n) { int x = arr[0]; for (int i = 1; i < n; i++) x = x ^ arr[i]; return x; } int main() { int arr[] = {9, 12, 2, 11, 10, 9, 12, 10, 9, 11, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << fun(arr, n) << endl; return 0; } What does the following C expression do? x = (x<<1) + x + (x>>1);Bit Algorithms Discuss it Question 2 Explanation: The expression multiplies an integer with 3.5. For example, if x is 4, the expression returns 15. If x is 6, it returns 21. If x is 5, it return 17. See Multiply a given Integer with 3.5 for more details. What does the following C expression do?Bit Algorithms x = x & (x-1) Discuss it Question 3 Explanation: The expression simply turns off the rightmost set bit. For example, if x = 14 (1110), it returns 12 (1100) Given two arrays of numbers a1, a2, a3,...an and b1, b2, .. bn where each number is 0 or 1, the fastest algorithm to find the largest span(i, j) such that ai + ai+1, ....aj = bi + bi+1, .. bj. or report that there is not such span,Bit Algorithms GATE-CS-2006 Discuss it Question 4 Explanation: The problem can be solved in Takes θ(n) time and space. The idea is based on below observations. Below is Complete Algorithm. See Longest Span with same Sum in two Binary arrays for complete running code - Since there are total n elements, maximum sum is n for both arrays. - Difference between two sums varies from -n to n. So there are total 2n + 1 possible values of difference. - If differences between prefix sums of two arrays become same at two points, then subarrays between these two points have same sum. - Create an auxiliary array of size 2n+1 to store starting points of all possible values of differences (Note that possible values of differences vary from -n to n, i.e., there are total 2n+1 possible values) - Initialize starting points of all differences as -1. - Initialize maxLen as 0 and prefix sums of both arrays as 0, preSum1 = 0, preSum2 = 0 - Travers both arrays from i = 0 to n-1. - Update prefix sums: preSum1 += arr1[i], preSum2 += arr2[i] - Compute difference of current prefix sums: curr_diff = preSum1 – preSum2 - Find index in diff array: diffIndex = n + curr_diff // curr_diff can be negative and can go till -n - If curr_diff is 0, then i+1 is maxLen so far - Else If curr_diff is seen first time, i.e., starting point of current diff is -1, then update starting point as i - Else (curr_diff is NOT seen first time), then consider i as ending point and find length of current same sum span. If this length is more, then update maxLen - Return maxLen Consider the following code snippet for checking whether a number is power of 2 or not.Bit Algorithms /* Incorrect function to check if x is power of 2*/ bool isPowerOfTwo (unsigned int x) { return (!(x&(x-1))); }What is wrong with above function? Discuss it Question 5 Explanation: There are 5 questions to complete.
https://tutorialspoint.dev/algorithm/algorithms/algorithms/bit-algorithms
CC-MAIN-2021-10
refinedweb
653
70.02
Introduction to WCF WCF is also known as the Windows Communication Foundation. It is mainly part of the .Net framework. It is used for developing service-oriented applications. It is used to create and consume services. WCF provides the platform for building and deploying various distributed network services. It mainly consists of Address, Binding and contracts, known as ABC for WCF. WCF service can be hosted in IIS, self-hosting and windows activation service as well. Why should WCF be used? WCF service is easy to use, and it is flexible as well. This service can be hosted in IIS, self-hosting, and windows activation service. It supports various protocols like HTTP, WS-HTTP, TCP, P2P, MSMQ and named pipes, etc. It is a service that helps in message exchange in XML format using HTTP protocol for interoperability, and it also acts as a remoting service to exchange the message in binary format using TCP protocol for performance. WCF service helps in communicating with the people or exchanging the data with the help of chat. It supplies the data to monitor the service like a traffic report. It is one of the security services to process the transactions. Some application uses this service to get the latest data feed and put the data into a logical and visual representation. Features of WCF The features of WCF are mentioned below: - It supports service-oriented architecture. - It supports multiple transport and encoding. - Multiple message patterns. - Data contracts. - Service Metadata. - Durable messages. - Reliable and Queued messages. - Ajax and Rest Support. Advantages of WCF The advantages of WCF are mentioned below: - It is service-oriented. - It is platform-independent. - It is independent of location and language. - It can maintain the transactions. - Concurrency is being controlled through WCF. - It is one of the fastest communication technology. - It provides excellent performance. - It can be configured to work independently. - It helps in maintaining the state. - It can be hosted via several means (IIS, WAS, Self-hosting) WCF Service Components The WCF service main components for creating and consuming the service are Address, Binding, and Contracts. It is also called as endpoints. These are explained below: - Address: The address of the service will define where to send the messages. It identifies the endpoint and defines where the service is located. An URL (Uniform Resource Locator) property defines the address of the service. It’s mainly divided into 4 parts: - Schema: This is the first part of the address. It is mainly “HTTP:” - Machine: It can be a URL like “localhost.” - Port: It is optional and tells which port it should hit. - Path: To locate the service files. - Binding: It will define the communication of the client to the service. The protocol that is being used for communication to the client. The different protocols can be used based on the requirement. The binding mainly consists of three things that are mentioned below: - Protocol: It is mainly used to define the binding like security or transaction. - Transport: It mainly defines the base protocol that is being used for communication like TCP, HTTP, MSMQ and named pipes, etc. - Encoding: It is used in which format data should be sent, text or binary. - Contracts: The contracts are being used to provide the types of operations and structure that are being allowed between the client and service on which they agreed on for the process of communication. It mainly takes care of the type of operations, message form, input parameters and data, and response of the message. It is of many types that are mentioned below: - Data Contract: It is used to define the type of variable that will be used for the WCF service. A data contract is used to serialize and de-serialize the data. It helps in defining the format of data that needs to be passed from the service. It maps the common language runtime type to an XML schema. It is also referred to as a versioning system to manage the data. To define data contract, use [DataContract] and [DataMember] attribute. - Service Contract: It is used to define the operations that are being exposed to others. It acts as an interface for the service. It defines the name and namespace for the service. It is defined with the [ServiceContract] attribute - Operation Contract: It defines the method that is exposed to the client for the information exchanging between server and client. It tells that functionality to be given to the client. It is defined with the [OperationContract] attribute. - Message contract: It is used to define the message elements that need to be passed, like a message header and a message body. It provides high-level security to messages as well. It is defined with the [MessageContract] attribute. - Fault contract: It is used to define the error that is raised by the service and handling of the error. It is defined with the [FaultContract] attribute. Career Growth WCF is widely used for creating and consuming the service by the .Net developers and projects. The individual with the skill of WCF and .Net framework is earning a good salary and having a great range of opportunities available in the market. There are many organizations that are only working in Microsoft technologies, and WCF is one of the most used technology. The job seekers for this skill can look for opportunities through various platforms and grow their career in this technology. Conclusion WCF is simple and easy to learn. It is mainly used for building SOAP services. It is very secured and used the data to show in logical representation. It is one of the good services to be used than web service. It is flexible and provides many features for developing the service, and easy to consume as well. Its architecture is not complex. The programmers used this service because of its features and advantages that are mentioned above. Recommended Article This has been a guide to What is WCF. Here we discussed the Basic concepts, working, and architecture with the advantage of WCF. You can also go through our other suggested articles to learn more –
https://www.educba.com/what-is-wcf/?source=leftnav
CC-MAIN-2021-43
refinedweb
1,015
58.69
Let dp(i, j) be the answer for strings A[i:] and B[j:]. Let's try to compute it by a top-down dp: - When i == len(A) or j == len(B), one of the strings is empty, so the answer is just the sum of the remaining lengths. - When A[i] == B[j], the answer is just dp(i+1, j+1). For example, when evaluating the distance between "acai" and "apple", we only need to look at the distance between "cai" and "pple". - When A[i] != B[j], then they both cannot be in the final word, so we either delete A[i]or B[j]. Thus, our answer is 1 + min(dp(i+1, j), dp(i, j+1)). def minDistance(self, A, B): memo = {} def dp(i, j): if (i, j) not in memo: if i == len(A) or j == len(B): ans = len(A) + len(B) - i - j elif A[i] == B[j]: ans = dp(i+1, j+1) else: ans = 1 + min(dp(i+1, j), dp(i, j+1)) memo[i, j] = ans return memo[i, j] return dp(0, 0) We could have also attempted a bottom-up DP, as shown below. def minDistance(self, A, B): M, N = len(A), len(B) dp = [[0] * (N+1) for _ in xrange(M+1)] for i in xrange(M): dp[i][-1] = M-i for j in xrange(N): dp[-1][j] = N-j for i in xrange(M-1, -1, -1): for j in xrange(N-1, -1, -1): if A[i] == B[j]: dp[i][j] = dp[i+1][j+1] else: dp[i][j] = 1 + min(dp[i+1][j], dp[i][j+1]) return dp[0][0]
https://discuss.leetcode.com/topic/89333/python-straightforward-with-explanation
CC-MAIN-2017-43
refinedweb
289
78.62
Dilemmas With React Hooks - Part 1: States And Reducers The new Hooks API is fun and easy to use, but we need to change our state of mind in order to use it correctly in terms of readability and performance. Some of the hooks seem similar, and we need to choose one over another. In this article, I will compare some of the new React API, and share from my own experience. useState vs useReducer Both hooks are used for managing local data in the component. Some good articles were written about this subject by Kent C. Dodds and Matt Hamlin. The main advantage of useState over useReducer is its simplicity. You just write: const [color, setColor] = useState('blue') and you have already an initialized local state and a method for changing it. Things are getting more complicated when you need multiple states. For example, let’s say that we make an asynchronous AJAX call for fetching a list of users. We will use two states for it, one for handling the list of the users, and the other for saving the loading state. The code will look like: const [usersList, setUsersList] = useState([]) const [loading, setLoading] = useState(false) const fetchUsers = () => { setLoading(true) fetch('').then(response => response.json()).then(data => { setLoading(false) setUsersList(data) }) } The two setter methods will trigger two render calls. It shouldn’t surprise you because it would happen also in the same situation on a class component with two setState calls. Currently, React will only batch separate setState/useState calls when they are triggered within React event handlers. However, multiple calls to setState/useState from setTimeout, promises, and async functions won’t be batched. Look at this issue for a reference. So what is the big deal, you probably ask. Why not to wrap everything on a single state? It will look like this: const [state, setState] = useState({ loading: false, users: [] }) const fetchUsers = () => { setState(previousState => ({ ...previousState, loading: true })) fetch('').then(response => response.json()).then(data => { setState({ users: data, loading: false }) }) } And the number of lines is even smaller! Unfortunately, in my opinion, the size doesn’t matter in this case. You can see in the example above that you can send to the setter function two types of arguments: Function that its input is the current state and its output is the next state or just the value of the next state. It corresponds to the abilities of setState on class components. However, there is a noticeable difference between the setter function from useState to setState. With setState We could just call this.setState({ loading: true }) and if the state object contains other attributes besides useState, we had to write setState(previousState => ({ ...previousState, loading: true })) and explicitly set the previous state, otherwise it will be override. Also, the code becomes less readable, especially if we have more “sub-states” in our single state object. To our luck, we have another option - the useReducer hook. Now the code will be like this: const [state, dispatch] = useReducer((previousState, action) => { switch(action.type) { case 'loading': return ({ ...previousState, loading: true }) case 'users_fetched': return ({ loading: true, users: action.users }) default: throw new Error('unexpected action type') } }, { loading: false, users: [] }) const fetchUsers = () => { dispatch(({ type: 'loading' })) fetch('').then(response => response.json()).then(data => { dispatch(({ type: 'users_fetched', users: data })) }) } Yes, I know what you are thinking about. We still have to destruct the previous state, and now we have a much longer code. So what are the obvious benefits of the new code? - The code is more readable. We give names to our actions - “loading”, “users_fetched”. It is a sort of documentation to our state changes. - The code in the reducer is reusable - we can dispatch the same action from multiple places without copying the logic of the setter. On the other side, instead of using useReducer, we could just create a named function for each scenario of the setter of useState and achieve the same goals, but useReducer is a central place that can solve all our problems, and I will show more advantages of it on the next section. For now, I will summarize this point by expressing that I would use useState for simple components that don’t contain much sub-states and logic, and useReducer for more complex ones. Callback functions vs dispatch Let’s imagine an app when we have a list of colors, and some buttons with actions to change the list. We will divide it into three components: - ColorsApp - The root component of our app. - ColorsList - List with all the current colors. - ButtonsPanel - Panel which includes action buttons to change our list. We will manage an array with all the colors in the root component because we need to access/change it from the list component and from the buttons panel component. Now, look at an implementation of ColorsApp with useState: const [colorsList, setColorsList] = useState([]) const fetchRandomColors = () => setColorsList(...) const deleteDarkestColor = () => setColorsList(...) const addBlueColor = () => setColorsList(...) return ( <> <ColorsList colorsList={colorList} /> <ButtonsPanel fetchRandomColor={fetchRandomColors} deleteDarkestColor={deleteDarkestColor} addBlueColor={addBlueColor} /> </> ) So far so good. Whenever you write a new component, I advise you to put a console.log inside it to ensure it is rendered when you think it should render. Now, please assume that the ButtonsPanel is a functional component that is wrapped by React.memo, and there is a console.log statement at the beginning of this function. When we click on one of the buttons, it will trigger a change in the colorList state. To our surprise, the ButtonsPanel component will be rendered again. But none of the props of the ButtonsPanel has changed, right? Wrong! Every time we render the ColorsApp component, the callbacks functions are recreated, so their reference is different from the last render and the shallow equal check returns false. In order to prevent it we need to wrap each callback with useCallback which will memoize it: const fetchRandomColors = useCallback(() => setColorsList(...), []) const deleteDarkestColor = useCallback(() => setColorsList(...), []) const addBlueColor = useCallback(() => setColorsList(...), []) It is already look messier. Also, it sucks to pass three callbacks as three different props, and if we need to add more actions so we will have more props. No worry, useReducer comes to our rescue: const [state, dispatch] = useReducer((previousState, action) => { switch(action.type) { case 'fetch_random_colors': return ({ ...previousState, colors: ... }) case 'delete_darkest_color': return ({ ...previousState, colors: ... }) case 'add_blue_color': return ({ ...previousState, colors: ... }) default: throw new Error('unexpected action type') } }, { colors: [] }) return ( <> <ColorsList colorsList={colorList} /> <ButtonsPanel dispatch={dispatch} /> </> ) Much cleaner in my opinion. The dispatch variable is guaranteed to remain the same, so we don’t need to memoize it, and we only send one prop for all our needs to change the state. Also, if we have a deep component tree where we want to call those actions, we can use the useReducer with useContext. This is a recommended pattern by the React team. However, a major drawback of this method is the lack of descriptiveness. When you see the dispatch function in your props, you don’t know the actions that you can invoke and you need to make reverse engineering. It would be avoided if we had passed each callback directly as a prop. Inline Reducer vs Outline Reducer Assuming you have decided to use the useReducer hook in your component, where should you define the reducer? Outside or inside the functional component? When I write “reducer” I mean the first parameter of the useReducer hook, the function which gets a state and action and returns the updated state. An obvious advantage of putting the reducer inside the functional component is the possibility to use the props inside the reducer. If you ever used Redux and wanted to use props in the reducer without the need of passing it through the action, your dream comes true. You don’t need to send the props in the dispatch function. They are already available in the reducer function because its closure contains it. This helps to make the dispatches of the actions thinner. So where is the catch? Sometimes the reducer is being called twice. You can see some references here and here. I didn’t encounter this issue personally, and there is no answer from a React team member yet. So in the meantime, I can only advise writing an inline reducer with caution - only if you really need access to props. Also, put a console.log in the reducer to ensure it is being called when you expect it. If not, you can always wrap it with useCallback or define it outside the function and send the needed props when you dispatch the actions. This is all for now. I hope you understand better the useState and useReducer hooks and the dilemmas they can possibly arise. In the next parts, I will represent more dilemmas and more hooks. Watch out!
http://brianyang.com/dilemmas-with-react-hooks-part-1-states-and-reducers/
CC-MAIN-2020-50
refinedweb
1,454
56.86
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives Hello, I wanted to discuss my take on a "type class" concept in a dynamically typed language. The language is called Ela () and for now it lacks any way to provide a function overloading. The language itself has Haskell/ML style syntax (layout based), is strict by default (lazy by demand), it is also pure and dynamically typed. I was playing with an idea of overloading for quite some time but didn't actually come to a good solution. So another attempt. First of all it is quite different from regular type classes as soon as it relies on a dynamic, not static dispatch. Also it is just single dispatch for now (which somewhat logical as soon as all functions are curried). The preview version (link below) contains three new entities. The first is a 'type' entity that creates a user type: type user x = User x This declaration is basically a function (and is first class therefore). The right hand can contain any expression. Here a variant (aka polymorphic variant) tag is used which simply "wraps" a given value. Variant is helpful as soon as it can be used to "unwrap" the value like so: let (User x) = ... The second is a 'class' entity, which is defined like so: class Foo foo bar (This syntax is probably a bit clumsy). Ela requires that all "class members" are functions, signature is not required as soon as they are untyped. Basically a declaration like the one above creates two global functions 'foo' and 'bar' (classes are mostly ignored by the run-time). These two functions are quite different from regular functions as soon as they are organized as "vocabularies", type-indexed functions. Having a class and a type one can create an instance of a class for a type like so: instance Foo user where foo (User x) = "Foo:" ++ show x et bar (User x) = "Bar:" ++ show x An instance adds these functions to the previously defined vocabularies. These vocabularies are basically mutable objects however all instances are always executed before any user code. When implementing an instance it is required to provide an implementation for all functions in a class. It is not possible to override an existing instance (it is not a problem technically however I am not sure that this is a good feature). And of course it is possible to define instances for built-in types (such as int, double, string, list, etc.). "Class functions" also can't be shadowed by other bindings (Ela does support shadowing for regular bindings). What do you think about such an approach? There is a preview for this implementation. It only comes with prelude that defines several classes/instances for built-ins and other basic functions (such as composition, application operators, etc.) and REPL. Requires Mono 2.6+/.NET 2.0+, 1MB: BTW. There's a short language reference and a side-by-side comparison with Haskell if you're interested: Type classes in Haskell offer several advantages that you probably cannot pursue in a dynamic language: Ela at least avoids some of the dynamic-typing problems you might otherwise face (implicit coercion, inheritance). But it seems to me that you don't really benefit much from the typeclass packaging (unless your goal is to ... statically ... ensure certain functions are defined together?) I'd suggest just overloading functions with pattern matching (like your `let` example) at arbitrary points in the toplevel. The idea is "open functions", not typeclasses. Actually Ela has open functions defined like so: let extends (Foo x) + (Foo y) = x+y There are a couple of problems with them. First each definition like the one above rebinds a new function to the same name. This is obviously a problem because if you reference two modules and each of these modules extends a prelude function you will only see the function from the last referenced module. Even if we solve this problem - there is another. Match clauses are processed in order. So if somebody would define another "extends" like so: let extends x + (Foo y) = x+y a previous definition would never be called. And finally this is an uncontrolled way of overloading. For example somebody may decide to overload just division operator and give it a completely different meaning. Having a class Num controls this to some extent. And when you actually try to think how to resolve all these issues you come to ... well, type classes. The main benefit of type classes is closely related to user defined types. Basically they allow you to write polymorphic code - e.g. you can implement your own container and all functions like fold, map, flter, etc. would be able to work with it if you provide a specific instance. Without it you cant even compare non-standard type using standard equality operator. Or another example - chars in Ela cannot be used in ranges. However this can be "fixed" by providing an instance of Num and Ord for a char. It seems like quite a serious benefit. Without it if I define a user type - say datetime - i wouldn't be able to use merely all previously defined functions, e.g. no show, no read, filtering wouldn't work for a list of datetime's, etc. In fact I *didn't* want to add type classes - at least because they do complicate the language which is not my intent - but i don't really see any other way to achieve the same result at the moment. if you reference two modules and each of these modules extends a prelude function you will only see the function from the last referenced module. In Haskell this is a known concern with what Haskellers call "orphan instances". The usual answer is "don't do that." And, most of the time, that's a fine answer. if somebody would define another "extends" like so: let extends x + (Foo y) = x+y a previous definition would never be called. if somebody would define another "extends" like so: let extends x + (Foo y) = x+y a previous definition would never be called. Maybe, but you'll face similar issues with typeclasses. In this case there are two related issues - multi-parameter type classes, and overlapping instances. MPTCs are pretty much indispensable - I find it hard to work without them. Overlapping instances mostly indicate design error. Without it if I define a user type - say datetime - i wouldn't be able to use merely all previously defined functions, e.g. no show, no read, filtering wouldn't work for a list of datetime's, etc. It isn't as though typeclasses save you from defining things. Perhaps you want to automatically derive most functions? (cf. GeneralizedNewtypeDeriving extension for Haskell.). No, that is a different problem. I can easily have two modules that define different instances of the same class - and that was impossible to achieve with "extends". If we have two instances for the same class the current approach is to reject such a program. Maybe, but you'll face similar issues with typeclasses. In this case there are two related issues - multi-parameter type classes, and overlapping instances. MPTCs are pretty much indispensable - I find it hard to work without them. Overlapping instances mostly indicate design error. I will face a similar issue only if I add a support for multi dispatch. With the current approach it is not a problem. Previously I tried a more classical approach to overloading - there is even a post somewhere here - and it was powerful, but... i wasn't always sure by myself which function is going to be called. However you are right and it is a serious limitation. I would probably need to decide if it is worth to add multi dispath again. But with the current approach I do process classes and instances in compile time and the most straightfroward solution might be just to reject a program with overlapping instances. It isn't as though typeclasses save you from defining things. Perhaps you want to automatically derive most functions? (cf. GeneralizedNewtypeDeriving extension for Haskell.) That is a "nice to have" thing but this is not what I am talking about. Yes, you will still have to implement all the equality functions, ord functions, etc. for your type - but now you can write polymorphic code that can compare any types, fold any container, etc. Previously it was only possible by explicitly providing a comparison, etc. function as a parameter which is not very convinient. Let's say that I have 50+ functions that work with a container. I can write my own container type and use all of these functions with my container. That was the goal actually - to simplify writing polymorphic code. I see - it's because your `let extends` structure is constrained by lexical scope that you feel you need a `typeclass` notion that is more globally accessible so functions can accept types that aren't visible in lexical scope. Fixing your `let extends` into a more useful open functions model would solve the same problems as your proposed typeclasses. Yes. Actually this approach to a type class is a result of thinking how to "fix" "let extends" functions. A naive take on globally accessible "let extends" == multi methods. And as a result you have a global state that is mutating as long as your program runs. Which is not a good thing I believe. It can be solved with static resolution through. So "let extends" + globally accessible + static resolution + avoid overlapping + organize functions in meaningful groups (e.g. Eq, Ord, Num, etc.) == what I have at the moment. I've just realized that I have completely overlooked Clojure. It provides a support for so called protocols which are completely equal to my prototype implementation - including single first argument dispatch, dispatch only by type tags, no inheritance, etc. The funny thing that it was introduced in a language as a sort of a replacement for multi methods. Oleg Kiselyov describes in Implicit Configurations a more dynamically scoped approach to associating values with types - essentially creating "local" typeclasses. I've also pursued a solution to configurations, precise resource acquisition, and dependency injection for complex Haskell values - leveraging Haskell's own dynamic types. The idea is injection of values and volatile resources (like threads, connections, or GLUT contexts) based on which types are used in a computation. The result is much more declarative than interleaving construction of resources in an IO monad with defining values. My work on this is tabled for the moment, since I found a subset that solves my immediate needs - a way of associating resources with types in an infinite abstract space of resources. (I plan to tackle the greater configurations problem and the plugins problem together, since I'd really like adaptive reconfiguration based on changes in plugins). Anyhow, all these approaches associate values with types. Perhaps that's all you need? Maybe typeclasses aren't the right way to approach this, but rather some form of context object that can associate values with types. I have a feeling that your are proposing something very close to what I have implemented :) Can you expland this "associate values with types" strategy a bit? Dynamic dispatch basically works because values (functions) are associated with types (by placing a "type tag" on a function). So you have, say, a set of (+) functions each with a unique type tag. May be I am actually abusing the notion of "type class" here (which is most likely anyway). But I am just trying to understand how your approach will be different from what I have now. Maybe typeclasses aren't the right way to approach this, but rather some form of context object that can associate values with types. Do you mean that this context object should be explicitly set by a client code so that a single (+) function might have a different meaning depending on a context? Or this context should be inferred somehow? My design is to solve a configurations problem - rich configuration, possibly multiple or changing configurations. The client can provide high priority rules to override defaults, and a simple constraint model can allow other rules to adapt. My basic design reduces to: (Typeable a, Typeable b) => a -> b [[TypeRep]] Then I wrap this in an Applicative, so I can interleave providing rules with defining the final value. Mostly, this makes it easy to provide defaults (which the client may later override). I have an idea on how to extend this with soft constraints (i.e. preferences, weighted logic) richer than simple ordering to provide a sort of hill-climbing optimization of large applications. I also plan to make this work well with plugins (which should not be difficult; GHC has one of the cleanest plugins models I've seen). Basically, I'm linking based on types, constraints, and preferences rather than names. Stone soup programming. I have something useful to say here about open type classes and interfaces, but it's hard to formulate exactly. I'm going to thrash around here and hope people can see what I'm trying to point at. Consider an "Interface" as defined in Java. It defines a set of methods that a particular object responds to. It may not be the only such set; some objects have a lot of different interfaces. You may be used to thinking of interface types as "Mixins." You can consider an interface to be something analogous to a type. An object that has many interfaces may be treated by polymorphic code as having many types. But some objects implement the same interface in ways that are semantically different (are not Liskov-substitutable for other things having that interface). Consider a "Queue" interface that has "insert" and "fetch" and "count" methods. A FIFO queue and a LIFO queue both implement the interface but are not Liskov-Substitutable for each other. Clearly neither is properly a subtype of the other, but just as clearly the "Queue" interface is a (virtual) type that they are both subclasses of. So how are the subclasses derived or specified, in terms of interfaces? The answer is that the idea of an "interface" has to be extended to include some semantics. The virtual class/interface for "Queue" would include statements like (Every "Queue" A isa "Collection") (FORALL A, FORALL datum: A.count() + 1 == (A.insert(datum)).count()) and (FORALL A: if A.count() >= 1 (A.fetch(@datum)).count() == A.count() - 1), which define a relationship of these three methods with reference to each other that is true for all Queues. Then for the LIFO queue, you'd add more semantics definitions: something like (every "Lifo" L isa "Queue");(FORALL L, FORALL datum: (L.insert(datum)).fetch(@datum2) == L && datum == datum2). For the FIFO queue, more semantics again and this time you'll have to do it by induction. Other subclasses of the same generic "Queue" will include things like a Priority Queue. So why are we writing math that *describes* code, instead of writing code? Because we're still describing interfaces ("open classes") rather than implementations ("object types"). You may have a bunch of different things that all implement FIFO queues in different ways; with a linked list, with an array of fixed-width objects, with an array of pointers to variable width objects, etc. But all of them are described by the "Fifo" interface and all of them are described by the "Queue" interface and none of them are described by the "Lifo" interface. This means you can define routines that take "Queues" (if they don't rely on any semantics not guaranteed by the "Queue" interface) or you can define routines that take "Fifos" (if they don't rely on any semantics not guaranteed by the union of the "Queue" and "Fifo" interfaces). Just as a note, I want to point out that the "Fifo" and "Lifo" interfaces do not specify any additional methods. The only difference between them is the specification of their semantics, and all the semantics that apply to "Queues" apply equally to them. When you want to instantiate an object, its "type" is basically the set of all the different interfaces it's supposed to respond to, including the inherited interfaces of the parents of any of those interfaces that are derived. You can implement that functionality however you want. Now, it may be that your programming language can check your code against your stated interface properties and tell you if you've made a mistake. This is a resolution devoutly to be wished in language design, but "tricky" to code in a general case. And now we get to polymorphism. Consider another routine definition. Suppose I have a generic function that takes a "Queue" as one of its six arguments. It can take a Fifo or a Lifo or some other kind of Queue, and it doesn't rely on any properties or methods other than those guaranteed by the Queue interface. But it doesn't need to be defined as part of that interface. It could be defined as part of a different interface. Indeed, it doesn't need to be defined as part of *any* interface if it isn't appropriate for it to be. And aside from being automatically specialized by calling the specialized methods of whatever arguments it gets, it may have thirty or forty completely different overloaded implementations depending on all kinds of different combinations of the types of its arguments. These implementations may be scattered around the code, wherever the definitions seem to make the most sense, with lots of "see also" clickable links in the comments (and lots of "this guy must have been crazy" muttered by the people who have to maintain the code, if it really gets that baroque). So this is a way of thinking about "open type classes" -- as Interfaces with some added semantic constraints. Class inheritance and specialization can be inheritance and specialization in terms of interfaces, and then when you define an actual object type (what you're used to thinking of as a "class") you don't derive it from the interfaces; instead you write code to meet the set of interfaces it's committed to. And generic functions with many implementations and complex type dispatch can coexist with specialized methods that are properties of a type. And while you *can* shoehorn one model into the other, it's usually not a good fit IMO to force them to be the same thing. So anyway... I feel like I've talked all the way around my point now but somehow can't quite hit it on the head. There's something about generic functions, type dispatch, method inheritance, and the importance of semantics in defining "open type classes" that is there in the examples but I can't quite name it. Ray Type classes -- at least in the sense the word is commonly understood -- have no untyped semantics. Type classes dispatch on types independent from values. This cannot possibly work in an untyped (aka dynamically typed) language. The closest you can get is something akin to CLOS multi methods, but it won't achieve all the expressive power of type classes (which, again, is fundamentally dependent on types). Of course it is different - as I mentioned. I do dispatch on types, not on values but it happens at run-time rather than compile time. I do dispatch on types, not on values From my understanding of your description, I don't think that's true. You're doing dispatch on (the types of) concrete values. You can't do dispatch without having a value, which is what type classes can do. but it happens at run-time rather than compile time. It's a common misconception to think that type class dispatch is static. It is not. It can often be optimized away statically, but not in the general case -- e.g. not in the presence of existential types or polymorphic recursion. The problem here is that the whole notion of type is different in static and dynamic languages. From the standpoint of a dynamic language I do dispatch on types, as soon as functions are associated with type tags, not with values. From the standpoint of a statically typed language there are no types here at all. As for existentials... You can surely do dynamic dispatch in Haskell but isn't it pretty close to what we have in OOP languages, e.g. dispatch against values? In support of this viewpoint, consider what happens when you enable overlapping instances and let Haskell attempt to find a best matching instance - the dispatch will only ever take into account the apparent type and not the actual ground type. For example, in a context of a polymorphic function where a variable has type [a], an instance matching [a] will be selected over [Int], and will be used uniformly, even if the polymorphic function is eventually instantiated at a=Int. But of course you said "dispatch", not "instance selection", so I'm not saying you're wrong, but I prefer to look at it like this: the map from apparent type to instance is static, but if you have first class types (existential types) or infinitely many types (as is possible with polymorphic recursion), then you're going to need a some kind of run-time representation of types that can compute the mapping. Right (@Andreas, and for the OP) I'm no Haskell specialist but I am skeptical as well whether the OP needs to borrow Haskell's type classes for his language, seemingly fairly dynamic-flavored (contradictory with type classes' design motivation AFAIK). I don't know Haskell well, though I can read it, but I did get especially interested in type classes introduction in the language some while ago, after realizing I was devising something along similar lines independently (before noticing Haskell's type classes). In my understanding, they are a clever way to enable Haskell make its concrete syntax more flexible upon the programmer's inventivity, and embed DSLs much more easily than without them. They for sure are no types, but they feed themselves on static types as they range over type kinds, and I said clever because they have been designed to reside, and be used, at the most suitable level for their purpose : that is, at the intersection of the static type system and the concrete syntax of type kinds, precisely, prior existing in 98, to enforce the former's rules. Thus, they allow Haskell and its users to cheat a lot, and often fruitfully, on other languages' built in features, where those languages' syntax design decisions are more involved and coupled with their type system. Hence, Haskell plus type classes capabilities that allow to "just" well... emulate/borrow those other languages' features (e.g., OO-related) within sometimes several DSLs used all at once, dissimulating themselves (to the untrained eye) in the same few lines of code. Or even more crudely: type classes in Haskell == one of the rare evidences by the example in language design, of a clean, powerful meta programming facility without a text replacement-based preprocessor (often, much less clean, as we know) Needless to say, but just to be clear, I welcome the Haskell experts correcting me on what I got wrong about type classes, of course. EDIT Btw, I suspect them to be strictly more expressive (in any interesting sense) than generics a la Java, or even, .NET. I also welcome any pointers about maybe a formal proof of this claim, if already done somewhere, that I have missed(?) EDIT2 IMO, independently of other paradigmatic considerations, the ongoing designs of other languages, those that aim to provide static type checking, have a great opportunity to learn (and borrow) from Haskell type classes, oft-overlooked by them it seems (AFAIC, I see type classes orthogonal to the rest of Haskell strengths and weaknesses). My (still vaporware) Y# is one of them. :) I can't think of any meaningful correspondence of type classes in a language that dispatches on values' (of a dynamic type setting) runtime types, though. It's a noble wish, but I'm afraid for dynamic languages it's as contradictory as, say, a precise rationals representation based on a mantissa+exponent (unfeasible) vs. numerator + denominator. The latter takes into account what actually defines a rational : the ambient division operation of two integers, while the former completely ignores it. I think you are confusing type classes with something else. They are not directly related to generics and/or static typing. Generics in Haskell are indeed much more expressive than in .NET and even in Java. But they are simply the tool to implement type classes in a statically typed Haskell and clearly do not have any meaning or application in a dynamically typed environment. Types classes are classes of types, an abstraction over types. This abstraction is feasible in a system with any typing. The initial objection is more against the "type" part here, not the "class" part. Dynamically typed languages clearly do not have types in the same meaning as static languages, therefore "dispatch on types" appears to be a different type of dispatch in a statically and dynamically typed language. But dynamic languages clearly do not prohibit abstractions at any level. This is just plain wrong. I think you are confusing type classes with something else. Maybe. I did write I'm no specialist there, but as far as my own understanding of Haskell's type classes go vs. (statically checked) types in OO languages, the closest I could find is what's explained here :. They are not directly related to generics and/or static typing. Generics in Haskell are indeed much more expressive than in .NET and even in Java. Sorry for the confusion. I was just alluding to the fact that in order to implement, say, GADTs, with static type checking in .NET or Java, the closest you can find for this purpose is their generics, but it's much, much more painful (i.e., tedious) in their case than in Haskell (I tried, in several occasions, in C# that I know quite well, and it's a real pain. The syntax outcome you get is systematically too hairy.) [...]therefore "dispatch on types" appears to be a different type of dispatch in a statically and dynamically typed language.. Otherwise, that would not allow, by definition, to maintain a (statically) type-safe usage of type classes by the programmer. I didn't write such an over-general (and indeed, untrue) claim anywhere, and I never would.. The main disconnection between static and dynamic languages here is that a notion of type is used in *completely* different meaning in static and dynamic world. This might be more of a terminology problem (or one might say that the term type is simply abused by those who find it applicable to dynamic languages). The problem is that in a static language when you can a expression like so: x = 2 You read it as: A name x of type integer. But this is not valid in a dynamic language. In dynamic language you would read it as: A name x which has a value of type integer. Types are bound to values and basically don't exist without values. Compiler do not reason about types at all, instead run-time environment inspects types of values as type tags. The concept of a class is in the first place a concept of "class of operations" that can be used as an abstraction over types. Such an abstraction is perfectly valid (and I believe useful) in both static and dynamic languages. But it is naturally different as soon as you are abstracting over a different thing. Whether it is valid (or not) to speak about type classes in dynamic environment depends whether it is valid to speak about presence of types in a dynamic language at all. I personally prefer to think that there are simply two ways to define "type" - in dynamic and in static world. BTW. I am actually not the first one who is trying to abuse the "type class" in such a manner. For example, there is "Type classes without types" () paper where a Scheme implementation is discussed. Well, I hear you. (I skimmed thru your Ela language's source repository, and I find it interesting in fact.) Just to be clear, though I happen to use a mainstream statically typed language (C#) if only to make a living, I hold absolutely nothing that'd be negatively dogmatic against dynamic languages. I actually enjoy using them, in some specific contexts I'm confident enough to put them at work. And that doesn't date from yesterday either, btw. I was trying to say: you may not want, for the problem you're trying to solve to enhance Ela, to distract yourself with borrowing a feature of Haskell which has (just IMO*) already made design choices more involved than what you really need. EDIT *But, hell, I may be wrong. Right. The initial idea is not to implement type classes in Ela. In fact my initial take was completely different. The idea is to do the following. Having a function defined like so: let sum (+) x y = x+y to be able to write it just as: let sum x y = x+y so that a particular implementation of (+) can be somehow "inferred". I would also like a solution to be "safe" - which might mean to provide it with some static behavior, e.g. to deal with overlapping statically, etc. I would like to "group" functions as well. For example, we have functions 'head', 'tail' and 'nil'. I want all these function to belong to a single function group so that if you want to overload 'head' you will have to overload the rest as well (as soon as overloading just 'head' without 'tail' and 'nil' seems quite meaningless for me). BTW. I am actually not the first one who is trying to abuse the "type class" in such a manner. For example, there is "Type classes without types" Interesting. So, looks like you've already found the most relevant paper for your concerns, anyway. Too bad my reading Scheme is even less confident than re: Haskell itself. ;) Then, just be aware of what the paper's authors have been wise enough not to omit in their conclusion, at least: In the case of multiple parameter classes, operations need not be dependent upon all the class predicates. Despite interest in and known uses for multiple parameter type classes for Haskell, as well as support for them in several implementations, type checking of programs that make use of them is undecidable in the general case. Nonetheless they are considered useful, and various means have been proposed to make them tractable [Jon00, PJM97, DO02, CKPM05]. In the Scheme system, lack of dispatch information can also be problematic, especially if multiple instances of the class have overlapping predicates. A call to an operation with this sort of ambiguity results in the most recent instance’s operation being called. An implementation of this system could recognize such ambiguities and report them as warnings at compile-time and as errors at runtime, but the system we describe here does not. It's one thing you won't want to miss to address if that applies to your plans for Ela as well, I suppose. I am aware of this problem. For now my answer is - no multiple dispatch at all (no "multi parameter type classes"). The version I am currently working on will provide a more civilized (yet still single parameter based) way of dispatch. A class will be defined like so: class Show a where showf:: _->a So that you don't have to do dispatch based on the first argument only, but an instance is still done for one specific type, e.g. 'instance Show int'. In fact the current version of Ela (2012.5) has an experimental "let extends" feature that implements "open functions". Besides some scoping issues, it does have a problem with overlapping which renders it (almost) useless. Actually one of my ideas (probably even the main idea) with this new approach is to simplify the resolution and to deal with overlapping strictly statically (by rejecting overlapping instances in compile time). By the way the paper "Type classes without types" is more of a theoretical research, when in reality there is an existing implementation of something pretty similar in another Lisp-like language - I mean protocols in Clojure (which I myself discovered just recently). And interesting thing is that Clojure protocols are awfully a lot like my prototype implementation and are intended as a sort of a replacement for multi methods. I remember discussion about edit-time "type classes", where the implicit values/dictionaries are determined at edit-time rather than compile time. Does somebody remember the thread where this discussion took place? What is "edit-time"? The phase when the programmer is writing the program (as opposed to compile-time: the phase when the compiler is compiling the program, or in your case run-time: the phase when the program is run). But in order to resolve type classes in a typeful language a program should be typed. So it simply looks like that your program compiles (at least partially) as you type code in your code editor. What difference does it make in comparison with regular static resolution? I think I vaguely remember that in some or all cases the programmer has to select which instance to use. But this is the reason I'm asking whether somebody remembers the thread :) Google was not helping. Here Is that what you're thinking of? Yes, that was was I was thinking of. In my memory the concept was more fleshed out in the thread than it seems to be... Can you explain why you think that type classes should be resolved at edit time, and what kind of UI for doing this you had in mind? One rationale for doing instance selection at edit time is that instance selection/overload resolution is ad hoc and complicated to reason about. Rather than even trying to reason about overload resolution, it seems better that we just inspect the result of the resolution to verify that it picked the symbol we wanted in each instance. Another thing is that for me, this is the same mechanism as module disambiguation. So if you type 'x * y', it needs to resolve which '*' you mean, and looks at types to figure that out. So in some sense I have truly ad hoc overloading, which Haskell doesn't (and doesn't want), but because it's at edit time, and you get to see which symbol you picked. The UI for this right now is to show the ascii as typed, and then to replace symbols with more descriptive symbols when the instance/ambiguity can be resolved (more descriptive symbols possibly being a different unicode symbol maybe with a subscript, so < might turn into < with a Z subscript when the integer version is selected, indicating a namespace tag). Sean warned me that this might be annoyingly jarring, and I think he's right. Particularly jarring is when the horizontal size of the replacement changes, as that shifts everything else on the line. I'm going to try smoothing animations to see if I can minimize the annoyance. It's also annoying if you have to go back when you realize you aren't going to end up removing an ambiguity, so I'm going to add key strokes that let you edit/resolve the previous ambiguity without moving the cursor there. I've posted about some of this elsewhere on LtU not too long ago, but I don't find it. My intuition is that any width change are unacceptable even if smoothly animated. You could try padding the width so they all are same size instead. Is there a demo I can mess around with? I have some other ideas and think I can find something that works. Adding extra padding ahead of time is an idea I could try. I could also only have it do replacements in response to certain events, like when you hit tab or reach the end of a line, and before that just indicate in a generic way that a symbol is no longer ambigous (e.g. underline ambiguity in red). For the UI, I have a C++ / OpenGL prototype to render everything, but I'm not ready to release it yet. I probably will release something before I finish bootstrapping the language & IDE, but I want to get a little further than I am now. So essentially you have code completion and instead of selecting 1 candidate, you can select a whole set of candidates? Instead of selecting int.multiply, you can select the whole set multiply which means anything.multiply, and later select the exact one or have the exact one inferred? You could show the same short identifier even after disambiguation, and only show the full disambiguation and extra information when you put your cursor on that identifier or when you go into a "show all inferred types" mode. Type classes allow you to hide the parameter to a function to keep the function generic, for example: mult3 a b c = a*b*c Written out this becomes: mult3 (*) a b c = a*b*c How do you plan to deal with this? Is this done automatically behind the scenes? How do you decide whether an identifier needs to be disambiguated further vs whether to add it as a hidden parameter? Would inferring that automatically involve a global process? That would probably be less problematic than usual because it happens at edit time. Do you keep track of which selections were made by a human and which were inferred? For example if you have x*y and due to other code it is inferred that this is an integer multiplication, but later that other code gets edited and now it's a vector multiplication. What happens with the x*y? What if the integer multiplication was selected by the programmer? Is that a type error, or fixed up automatically? Right now I only do one resolution at a time, but that can result in cascading resolutions. I use tags rather than a namespace hierarchy so that I can produce minimal disambiguations of symbols in scope (<_Z vs. Integer.<). You're right, I didn't mention the definition side of type classes. I have a system of theories that's kind of like ML modules that underlies all of this. Also, I'm not pushing the bag of constraints style typing that happens in Haskell when you have type classes. Typically (caveats apply), what matters when you write something like mult3 is whether you're working in a context in which Num, *, etc. are concrete or abstract, which is this mechanism I have... I started to write more the first time around to answer your last paragraph's questions, but yes, when a disambiguation is deduced from types, that can currently be undone by a changes to the code around. There are some somewhat thorny issues about when things need to be firmed up and what things do when you're passing through error states.
http://lambda-the-ultimate.org/node/4542
CC-MAIN-2017-47
refinedweb
6,604
61.67
Introduction:. I2C is commonly used in GPIO expanders, EEPROM/Flash memory chips, temperature sensors, real-time clocks, LED drivers, and tons of other components. If you spend much time looking for new, cool parts you'll probably wind up with several I2C parts. Fortunately it is a protocol that is available on most microcontrollers, though it is a bit more complex than others. Learning it is tough at first, but once you know I2C it is a powerful tool. I2C Tools of Interest: Before you dig too deep into I2C communications, you'll want to have some things on hand that will make your learning experience easier. 1. Various I2C-compatible parts - Anything goes, as long as it's I2C. If you're writing a master driver you need some things to talk to. I like Texas Instruments' TMP100 temperature sensor as it's cheap (free if you sample) and has a simple protocol (just send an I2C read command to get temp values). I more recently purchased some Microchip MCP23017 GPIO expanders which give you 16 bits of additional GPIO over the I2C bus. 2. Something that has a working I2C master - You'll want something to test/compare against if possible. An Arduino with the Wire library will work, but more recently I prefer my Raspberry Pi with the Linux i2ctools package. i2cdetect, i2cset, i2cget, and i2cdump are invaluable when writing code, especially slave-mode code. 3. Oscilloscope. I know this is a big one, but if you can work with one (either own one, borrow one, or go to a lab where you can use one) it's a super amazing help. I2C uses two wires, so a two-channel scope works great. I used my Rigol DS1052E (100Mhz modded) and it helped a TON. Of course, I did most of the work with it and am telling you what I learned, so hopefully it'll be easier for you. Step 1: What Is I2C - 1 I2C (Inter-Integrated Circuit bus), originally developed by Phillips (now NXP Semiconductor) and also commonly known as TWI (Two Wire Interface) by Atmel and other companies who don't want to get into trademark issues, is a two-wire synchronous serial bus. Let's take a look at what each of those words means: Two wire - This one's easy, I2C uses two wires (in addition to ground, of course!) They're called SDA (serial data) and SCL (serial clock). These are wired in an open-drain configuration, which means that the outputs of all connected devices cannot directly output a logic-level 1 (high) and instead can only pull low (connect to ground, outputting a 0). To make the line go high, all devices release their pull on the line and a pull-up resistor between the line and the positive rail pulls the voltage up. A good pull-up resistor is 1-10K ohms, low enough that the signal can be seen as a high level by all devices but high enough that it can easily be shorted out (pulled down) and not cause damage or significant power usage. There is one pull-up resistor on SDA and one on SCL. Synchronous - This means that data transfer is synchronized via a clock signal that is present to all connected devices. This is generated by the master. To contrast, an asynchronous serial system does not have a clock signal. Instead, it uses a pre-determined time-base, or baud rate. An example of asynchronous serial is RS-232 (the common serial port on many computers). Serial - Data transferred serially means that one single bit is transferred at a time over a single wire. To contrast, parallel data transfer has multiple wires, each carrying one bit, which are all sampled at once to transfer multiple bits in parallel. Bus - A bus is a system which allows many devices to communicate to each other over a single set of wires. While it may be called a bus, USB is not a true bus at the hardware level, as connecting multiple devices requires a hub. A bus such as I2C allows new devices to be added simply by attaching their SDA and SCL connections to the existing line. Busses (I2C, USB, PCI, etc) all use an addressing system, in which each device has a unique address. An address in this case is simply a binary number, and all messages to that device must be sent with that address. Step 2: What Is I2C - 2 On an I2C bus, there are masters and there are slaves. A master initiates a connection while a slave must wait for a master to address it before it sends or receives anything. I2C has multi-master capability, which means that more than one master may exist, and if two masters attempt a transmission at the same time, they must perform arbitration to correct the problem. This tutorial will not cover multi-master configurations, but it should be noted that they do exist. A master may either request to send or receive data from a slave. During a send, the master writes data to the bus and the slave reads the data off the bus and stores it in its memory. During a receive, the master reads the bus for data sent out by the slave. In both situations, the master provides the clock signal on SCK. At the end of every byte (which is 8 bits) transmitted on the I2C bus, the receiving device must provide an acknowledgement (ACK). The only time in which this does not happen is when the master is receiving data from the slave, in which it ends the transmission with a not-acknowledgement (NACK or NAK) indicating that the slave should stop sending data. An ACK is represented by a low (pulled-down or 0) state while a NACK is represented by a high (not pulled-down or 1) state. Since the default state of the bus is high, an ACK is a confirmation that the other device is present and has successfully processed the transmission. In addition to ACK's and NACK's, I2C has two additional framing conditions known as a start condition and a stop condition. A start condition is transmitted by the master to indicate the start of a transmission. During a start transition, the SDA line first transitions from high to low and then, after a noticeable amount of time, the SCL does the same. A stop condition, which is issued by the master at the end of a transmission, is the reverse. First the SCL line goes from low to high, then the SDA does the same. Note that the SDA and SCL lines both are high when the bus is inactive. The first byte in an I2C transmission is the address byte. This is sent by the master and is used to determine what slave to talk to and whether to perform a send or receive (also known as write and read, respectively). A slave address is 7 bits long, and there are several reserved addresses. One such reserved address is 0x00, which is often considered a global write (write to all slaves). You usually configure the slave device's address by tying address select pins high or low, though on a microcontroller you set the address programmatically as we will do on the ATTiny2313. The least-significant bit of the address byte is the Read/Write bit which indicates whether to perform a read or write. If one, the operation is a read, if zero a write. Step 3: What Is I2C - 3 That basically covers the I2C protocol itself, in that a master can initiate a read or a write, and transfer continues until the master sends a stop condition. When the master is reading from a slave, it will issue a NACK instead of an ACK on the last byte, before the stop condition, to indicate that it is done receiving. From here, with a proper implementation thus far, you can communicate to all the devices you want. However, there is one extra thing that I want to point out, as it is used quite often. On some I2C devices (or should I say most, it's very common), the access protocol is set up as a register bank. To read or write from these registers, you must first write an internal address which is the address of the register you wish to read or write. After writing an internal address, you may read or write multiple bytes and the internal address will increment with each byte. This is the preferred protocol for almost all I2C memory devices as well as most sensors and I/O expanders. While it is possible to have a protocol that doesn't follow the register bank protocol, the vast majority of devices do and many I2C tools are built around it. As such, it is worth pointing out. It is also the protocol that I will implement on the ATTiny2313. As mentioned before, before reading or writing any register you must send the device internal address, which is done by performing a write operation of one byte, which contains the internal address. For write operations, the transmission may continue with data values, the first of which will be stored in the desired address and any additional bytes will increment upwards by one each time. For reads, the master will send a stop condition, then start a new transmission for reading. This is because you can not have both a write and a read in the same transmission. In some cases, a repeated start may be sent instead of a stop then start. A repeated start is a high-to-low transition on SDA while SCL is high. Step 4: ATTiny USI I2C Code Implementation - Overview At this point in the tutorial, you should be at least basically familiar with the I2C protocol. Now I'm going to go into detail on the actual I2C protocol implementation for the ATTiny USI hardware. To preface this, the board shown on this step's main picture is a custom unipolar stepper motor controller that I designed as part of my senior project this Spring. The board is capable of driving a single unipolar stepper motor with PWM, variable speed, and three different stepping modes (single-stepping, power stepping, and half-stepping). It also operates in bursts, as the controller will only run the motor for the given number of steps. For continuous operation, the stepping counter must be reloaded by whatever is driving the board before it reaches zero. None of this is important for the tutorial. The important part here is that the robot these boards power has three wheels (omnidirectional wheels, arranged in a triangular pattern). I wanted to build three identical boards but only use a single RS-232 serial interface from the robot's main computer (a laptop) to control all three. The idea I came up with was to use the serial port for the computer interface and the I2C bus to connect all three boards. In this setup, the board connected to the PC takes on the master role in addition to being a slave node. The PC then sends I2C formatted messages onto the bus for the three boards to operate upon. For this task, my boards would have to support both I2C modes, being able to operate as both a slave and a master depending on serial port operations. Knowing very little about the USI hardware and only slightly more about the I2C protocol in general, I set out to master the I2C protocol, to make it my slave and command it to do my data transmissions. And that I did, and it worked well for the project. All up until I got my Raspberry Pi at least, because when I finally got around to playing with the Pi, I tried hooking up my I2C motor boards to its I2C port in an attempt to have a Pi-powered robot. Unfortunately, no matter what commands I sent, the Pi could not make communication happen. Since I had never validated my protocol beyond my own master code talking to my own slave code, I figured I wasn't implementing the protocol just right, and sat down to make it all work correctly. That I did, with the new code much more streamlined, organized, and understandable (comments galore for anyone who wants to learn!). Since my journey into the world of I2C was rough, I decided to post here for all to see, and to go into as much detail as I could to make I2C's functionality clear. In the next few steps I will talk about the USI hardware and how it works as both a master and a slave. I have also attached my USI code files. I want people to have a good USI implementation and I also want them to read how it works, knowing exactly what's going on is crucial when dealing with a complex, low-level system, so I've commented my files thoroughly. Step 5: ATTiny USI I2C Code Implementation - USI Hardware So, before we look at code, let's look at the datasheet. Specifically I'm looking at the ATTiny2313 datasheet as that's the chip I'm using, but the same USI hardware can be found in many different ATTiny models. Note that the output pins may be different between chips, but otherwise the hardware works the same way and has the same registers. The USI hardware has three pins: DO - Data Output, used for three-wire (SPI) communication mode only DI/SDA - Data Input/Serial Data, used as SDA in I2C configuration USCK/SCL - Clock, used as SCK in I2C configuration In addition, the USI hardware has three registers: USIDR - USI Data Shift Register - Shifts data in and out of the USI hardware USISR - USI Status Register - Has state flags and 4-bit counter (more on this below) USICR - USI Control Register - Has interrupt enables, clock modes, and software clock strobe functions 4-Bit Counter The 4-bit counter occupies the lower 4 bits of USISR and is used to time the overflow interrupts when operating in slave mode as well as to help generate SCK clock pulses in master mode. Being a 4-bit counter, it counts upwards from 0 to 15 before overflowing. Upon overflowing, it can trigger an interrupt (USI_OVERFLOW_vect, enabled by a bit in USICR). This is used for the USI slave state table to keep track of transmission as it switches between transmission states (more on this in the slave code section). When acting as a master, the 4-bit counter is used along with the clock strobe bit in USICR to generate the SCK clock. You set the counter to overflow in the number of clock pulses you wish to generate (generally 8 or 1, with 8 being a data transmission and 1 being an ACK/NACK transmission). Then, you loop until the counter overflows, continuously setting the clock strobe bit and performing a delay wait. More on this can be seen in the master code section. Two Wire Clock Control Unit (Start Condition Detector) The TWI Clock Control Unit is a module in the USI that monitors the SCK line for start and stop conditions. Its primary purpose is the start condition detector, which, when enabled, generates a USI_START_vect interrupt whenever it detects a valid start condition. This interrupt handler is the starting point for slave-mode USI I2C transmission handling, and must set up the 4-bit counter to overflow after the address transmission has occurred. From there on, the overflow interrupt manages the rest of that I2C message and resets the start condition detector for the next message. Read the Datasheet I won't go into detail on each of the bits in each of these registers, but if you're looking at writing some USI code it is essential that you read these sections of the datasheet. I recommend reading the whole Universal Serial Interface - USI section (pages 142-150 of the ATTiny2313 full datasheet). This will give you all the information you'll need in addition to what I've pointed out here. Step 6: ATTiny USI I2C Code Implementation - USI I2C Master The USI I2C Master (usi_i2c_master.c/h) library provides I2C master mode capabilities using the USI hardware. There are two important functions that the user should be familiar with. The first is the initialization function which sets up the SDA/SCL pins and USI hardware, and the other is the transmission function, which performs either a read or a write operation on an I2C message, returning 1 (true) if successful and 0 (false) if an error (received a NACK) occurred. A third function, the transfer function, is used by the transceiver function to send and receive data. The transfer function should not be used outside of the usi_i2c_master library. The transmission function takes two arguments. The first is a pointer to a data buffer in which to send or receive data from. It is assumed that the first byte in this buffer is the ADDRESS+R/W byte (upper 7 bits address, LSB is R/W). This byte, by protocol, is always transmitted and never received. The rest of the buffer will either be sent out or filled by received data according to the R/W bit (1 for read, 0 for write). The second argument is the total size of the buffer (including the address byte). Here's a brief example. Let's say we want to output the value 0x70 to the internal address 0x12 of the device with address 0x40. First, we must create a buffer to store our transmission: char i2c_transmit_buffer[3]; char i2c_transmit_buffer_len = 3; i2c_transmit_buffer[0] = (0x40 << 1) | 0 //Or'ing with 0 is unnecessary, but for clarity's sake this sets the R/W bit for a write. i2c_transmit_buffer[1] = 0x12; //Internal address i2c_transmit_buffer[2] = 0x70; //Value to write //Transmit the I2C message USI_I2C_Master_Start_Transmission(i2c_transmit_buffer, i2c_transmit_buffer_size); There you have it, message transmission complete! That was easy! If you want more information on the inner workings of the USI_I2C_Master code, just take a look inside the usi_i2c_master.c file where I've commented the states, transfer function, and other interesting sections. I've made use of one-line #define macros to make it more clear what each line's purpose is. In the next step, I will introduce the slave-mode code, which is significantly more complex but also easy to use from an end-user standpoint. I've taken a different approach on implementing the slave code that I haven't seen in any other tutorials, it's interesting and useful! Step 7: ATTiny USI I2C Code Implementation - USI I2C Slave Unlike the master code, the USI I2C Slave code (usi_i2c_slave.c/h) is implemented almost entirely using the USI interrupts. As mentioned earlier, the USI module has two interrupts, one generated upon detection of a START condition and the other based on the overflow of the 4-bit counter. The counter is crucial for the slave code to work correctly, and was not explained very well in tutorials and code I read. In the flowchart image I have noted numbers for each state in the logic. These numbers (8's, 1's, and 0's) are counter count values indicating how many ticks the counter should count before transitioning to the next state. As the counter is clocked using SCL clocks, these values tell how many SCL clock pulses must occur before the next state. In general, something that waits 8 clock pulses is waiting on transmission/reception of a data byte while something that waits 1 clock pulse is waiting on transmission/reception of an ACK/NACK. A few things wait 0 clocks, meaning that they instantaneously continue to the next state or are an expanded part of the previous state (in the case of Write or Read?). So, as an end-user, you probably are more interested in how to interface the library to your own code! This is easy, and here's why. I've done away with the receive/transmit buffers that were used in other USI I2C implementations (mainly those based on AVR312 app-note) and instead implemented the register bank protocol described at the beginning of this tutorial. The bank is stored as an array of pointers, not data values, so you must attach local variables in your code to memory addresses in the I2C register bank by setting the pointers to point to your variables. This means that your main-line code doesn't ever have to poll I2C buffers or handle data arrivals, the values are updated instantaneously whenever they arrive. It also allows program variables to be polled at any time by the I2C interface without affecting the main-line code (other than the delay due to interrupt). It's a pretty neat system. Let's again take a brief example. For example, let's say we have a very basic software PWM generator that is driving an LED. We want to be able to change the PWM value (a 16-bit value, just for the sake of learning about pointers) without making the main loop complicated. With the magic of asynchronous I2C slave, we can do just that! #include "usi_i2c_slave.h" //Define a reference to the I2C slave register bank pointer array extern char* USI_Slave_register_buffer[]; int main() { //Create 16-bit PWM value unsigned int pwm_val = 0; //Assign the pwm value low byte to I2C internal address 0x00 //Assign the pwm value high byte to I2C internal address 0x01 USI_Slave_register_buffer[0] = (unsigned char*)&pwm_val; USI_Slave_register_buffer[1] = (unsigned char*)(&pwm_val)+1; //Initialize I2C slave with slave device address 0x40 USI_I2C_Init(0x40); //Set up pin A0 as output for LED (we'll assume that whatever chip we're on has pin A0 available) DDRA |= 0x01; while(1) { PORTA |= 0x01; //Turn LED on for(unsigned int i = 0; i < pwm_val; i++) { PORTA &= ~(0x01); //Turn LED off } } } And there you have it! The main loop makes no reference to I2C at all, but upon sending a PWM value to the 16-bit location in I2C internal address 0x00/0x01, we can totally control the PWM of the LED! For added stability (to make sure only the pointer values you're using are available and to prevent stray pointers) I suggest you change the #define USI_SLAVE_REGISTER_COUNT to be the number of register pointers you need, no more, no less. When an access (read or write) is attempted on a register index outside of the range 0x00 to USI_SLAVE_REGISTER_COUNT - 1, nothing is written and zero is returned. Step 8: ATTiny USI I2C Code Implementation - Git the Code! To get (git) the code, head to my GitHub page! This code was written as part of my Senior Project Stepper Motor Controller, so you can check out my implementation of the motor controller using my I2C drivers. I also have a decent interrupt-driven USART serial driver in there you can use as well. Note that the names and functionality used in the I2C drivers may vary slightly due to bug fixes and updates that I implement. If it's anything serious I'll edit the tutorial, but for now it should be very accurate. Now that you're armed with the knowledge of I2C, you're ready to go out and talk to stuff! With I2C's bus design, you can connect a lot (theoretically up to 128, limited by address restrictions though) of devices to the network! Also, if you haven't got one yet, get yourself a Raspberry Pi, they're awesome. If you order one today, you might have it by the end of the year, but it'll be a very merry Christmas if that's the case. As far as I2C goes it's been a great help and I can't wait to build a robot around it. Be the First to Share Recommendations 22 Comments 3 years ago Hi Thank you for this tutorial, I have few questions: - How to specify the address of each slave? - How to know the address of the master? 6 years ago on Introduction Nice work! I've used the I2C slace code in order to be able to read logging messages from an ATtiny85 which doesn't come with a USART (after adding the appropriate pinout definitions to usi_i2c_slave.h) I read data using python on Raspberry Pi using smbus library. It works perfectly if I use the single byte method: bus.read_byte_data(DEVICE_ADDRESS, REG_ADDRESS) but didn't work when I tried to read a block of bytes in one call: data = bus.read_i2c_block_data(DEVICE_ADDRESS, REG_ADDRESS) which returns a list of 32 bytes - the 1st is correct, followed by 31 0xff s Not a problem, as reading bytes works fine, just wondered if there's some way to define the I2C registers in usi_i2c_slave.c to handle blocks of bytes(?) I've tried a couple of other I2C libs and yours is the only one to work for me with ATtiny85. Reply 6 years ago on Introduction I am trying to use an ATtiny85 as well with i2c tools on a raspberry pi. I have changed the pin definitions, but for some reason it will not show up when I run i2cdetect on the pi. I think it might be the clock speed, what is yours set at for the microcontroller? Reply 4 years ago I've read that the SDA & SCL lines need to be pulled up to improve odds of successful detection. I wasn't getting i2cdetect to work until I added pullups .. 470k Ohms Reply 6 years ago on Introduction Hi Alec Yes, I think I had to reduce the clock speed below about 40000 - I've got it set to 20000 (the default is 100000). The default can be configured by editing/creating a file /etc/modprobe.d/i2c_bcm2708.conf and adding a line options i2c_bcm2708 baudrate=20000 Reboot/Test: cat /sys/module/i2c_bcm2708/parameters/baudrate 20000 4 years ago I'm looking at the slave code. It looks like the main code that uses the slave code could be accessing the memory buffer that the ISR writes to. Shouldn't there be a mutual exclusion mechanism in place to prevent this? As an example, in your two byte PWM sample, say there are only two possible PWM values being sent by the master, 0x11 0x11 and 0x22 0x22. Even if the code read two bytes as a 16-bit, the underlying assembly could read 0x11, get interrupted as the incoming 0x22 0x22 is written by the ISR, and then continue to read the second byte as 0x22. So it would have read 0x11 0x22. Even if the architecture did atomic reads of 16-bit, it would still be an issue if the buffer was bigger, say 32 bytes, and the main code was only halfway through reading the bytes when the ISR wakes up and changes values. I'd like to use this code, so hopefully I'm missing something. 5 years ago God I hate that these wortheless pedantic instructibles with low information density end up at the top of Googles hit list and I end up clicking on them before reading that the site is Instructibles.com Reply 4 years ago This instructable was exactly what I needed. Google worked well and the instructable was great. Reply 5 years ago Nice job. 5 years ago on Introduction This is most excellent. Thanks for the Instructable. 6 years ago on Introduction I think the reason that the slave wouldn't send more than 1 byte at a time to the master is that the slave code always interprets the master's response as NACK even when it sends ACK. This can be fixed by changing in usi_i2c_slave.c case USI_SLAVE_SEND_DATA_ACK_CHECK: if(USIDR & 0x01) { So that it only test the LSB of USIDR - which is the 1bit that the master has just written to SDA for ACK (SDA low) or NACK (SDA high). I can now read multiple bytes correctly using the python smbus library. 6 years ago on Introduction Thanks. Very useful and good to follow. 7 years ago on Step 7 Thank you so much. I've used an I2C module before, but never the USI in the ATTiny's. Now I finally understand what the heck that 4-bit counter is for. I haven't looked at the code entirely, but I'm guessing you use the 4-bit counter overflow flag to check when the transfer is done. I've been staring at the datasheet all day, but now it finally makes sense! I will probably write my own libraries to get a good understanding of it, but I will base it heavily off of yours. Reply 7 years ago on Introduction You're welcome! I based my driver heavily off the Atmel app note for USI I2C, even though that one worked it was really hard to understand and I wrote mine to clean it up and figure out how it all works. Definitely try writing your own if you want to really understand how it works! Reply 7 years ago on Introduction Everyone on the inter webs kept telling me that the AVR app note had a major flaw, but no one cared to actually tell me what it was, and instead just insisted that I download Don Blake's code. Well I finally found someone to explain it for me. If anyone else is interested: It's always a good idea to try and write one. You will learn a lot! For instance, I learned that the USI code doesn't actually check that the start condition actually completed. I originally did it without the while loop at the beginning of the start vector. I didn't want my routine to use interrupts, so I didn't think it was necessary. I would only work once. Every subsequent read would only return 0x01. o_O 7 years ago on Step 6 I don´t unsderstand this line: i2c_transmit_buffer[0] = (0x40 << 1) | 0 //Or'ing with 0 is unnecessary, but for clarity's sake this sets the R/W bit for a write. Why do you make the displacement <<1?? Aren´t you sending 0x80?? and it´s a diferent address that you wanted... About the OR´ing with 0... if you want to put a 0 at the last bit (to write on the salve... I imagine), don´tn you need to make somethig like (address & 0xfe)?? In the contrary case, if you want to read from the slave, you need to put a 1 on the last bit, so (I think) you need make something like (address | 0x01)... or am I worng? Reply 7 years ago on Introduction The i2c slave address is shifted to the left by 1. That line sets the address to 0x40 (0b1000000, i2c addresses are 7 bits long) and then sets the R/W bit to zero (write mode). The or'ing with zero is pointless, I just did it for context, to show readers that the write bit is zero and the read bit is one (where I use | 1). Since the operation already shifts left by 1 the 0 bit will never actually be one, so the | 0 part can be removed. An optimizing compiler will do this for you. 8 years ago on Step 8 Thank you for making this instructable, I have the I2C Slave code running on an ATTiny 167 clocked at 8 MHz. It doesn't acknowledge it's address when the bus is running at 100kHz but it all works beautifully on a 5kHz bus. Have you any Idea why this is? Reply 7 years ago on Introduction Have you tried more intermediate speeds? My first guess is to assume you're running the attiny on the internal RC and it's pretty inaccurate, making more timing issues at a higher speed. (Non-ECE person here, just hobbyist) 7 years ago on Step 4 I have been trying to use your slave code to read the 2 byte ADC value from an ATtiny45. The first problem I found is the default clock of 8MHz is not fast enough to allow the ACK to take place before the clock edge. A 16MHz clock works with about 1uS to spare. The code at case USI_SEND_DATA needed 3 lines adding as follows: USISR = USI_SLAVE_CLEAR_START_USISR; PORT_USI |= (1 << PORT_USI_SDA); USI_SET_SDA_OUTPUT(); at case USI_SLAVE_SEND_DATA_ACK_WAIT you need to add USIDR = 0; after this the code works fine. So thanks for this code which is well written and very useful.
https://www.instructables.com/ATTiny-USI-I2C-The-detailed-in-depth-and-infor/
CC-MAIN-2021-21
refinedweb
5,460
67.49
by passing AC current through Quoteby passing AC current throughAnd where does this AC come from? To QuoteToYou are not producing AC. AC is alternating current, where the voltage changes from positive to negative 50 or 60 times per second. All you are doing is switching which way the current, at +5V, is flowing. an electric current that reverses its direction at regularly recurring intervals Pulsating dc and ac are the same, a variable flow of electrons. The primary difference is the "Reference"... If "AC" is "Referenced" from the most negative level them you could say "It''s Just pulsating DC. Whether it is sinusoidal, square rectangular (duty cycle not 50%) triangular.Come to think about the definition a little and you will see that the prime requirement for AC... The one Difference that sets AC apart from noise is just Periodicity.It is the periodicity that sets it apart and allows it to do useful and predictable work is it's periodicity.Noise can be called AC... Pink noise (audio) and White noise (Full Spectrum) and random impulse noise are AC but because of the lack of predictability, little real work can be done with them.If you put in place a device that passes AC only, a capacitor or a transformer will pass your "DC" very well. it will also filter the signal due to its reactance or response to an "AC" signal... again the Periodicity.As to the library it does produce a signal that makes the LED light up Yellow... So the difference is?Just the point of reference... Put it in the right place and your "DC" signal becomes "AC".Place a diode in series and you remove 1/2 of the DC signal... Just as a diode would with AC... and you have DC again... pulsating but of one polarity... The signal cannot pull down when the input goes to it's lowest point because the diode will not conduct in the reverse direction. #include "WProgram.h" #if defined(ARDUINO) && ARDUINO >= 100#include "Arduino.h"#else#include "WProgram.h"#endif Version 1.2 released with Arduino 1.0 support. Thanks PaulDriver for the patch! I also have a library (toneAC) that does "AC" to drive a speaker at almost twice the volume as the standard tone library. This is possible because I alternate the 5 volts between two pins. In my case, it's designed to be extremely fast, so I use the Arduino's PWM pins and timer 1. This also allows for perfect switching between the two pins without any programming slowing things down.As a bonus, my library can also drive a bicolor two pin LED as yours does (one of my example sketches included with the library controls a bicolor LED with a pot to adjust the cycle speed). You may want to check out my source. As toneAC is designed for ultra speed and accuracy, you must use the timer 1 controlled PWM pins. It also is totally driven totally by port registers for the fastest and smallest code. Looking at my library may assist you. I also have a NewTone library thats a modified version of toneAC but allows you to specify what pin you want to drive a speaker with. This also may assist you with your library.While writing library using port registers and timers may be a little more challenging at first, it's really not that hard once you do it a few times. And, the benefits are many. Very small code size, very fast, color switching and duty cycle can all be done in the background, no reason for delay statements which can kill a project, etc.Best of luck with your project!Tim
http://forum.arduino.cc/index.php?topic=116824.msg879275
CC-MAIN-2017-43
refinedweb
621
74.69
Introduction We have taken tour of the syntax and semantics of raw CIL up till now. In this article, we shall be confronted with the rest of implementation in the context of CIL programming such as how to build and consume *.dll file components using MSIL programming opcodes instruction set. Apart from that, we will see how to integrate exception handling related opcode instruction into IL code in order to handle unwanted thrown exception. Finally, we’ll come across with some unconventional methods of inline IL programming by integrating its opcodes into existing high level language source code. Building and Consuming *.DLLs files DLLs (Dynamic Linking Library) files are deemed to library components of business logics for future reusability. We have seen creation of DLL file components in numerous examples using Visual Studio IDE earlier, which isn’t rocket science at all. But it is very cumbersome to build dll’s through CIL grammar. Here the following code, defines two methods Hello() which simply displays a passed string over the screen and second method Addition() takes two integer values in order to calculate their sum as following: Building DLLs File .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly TestLib { } .module TestLib.dll //mention the final type of file .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 .corflags 0x00000001 // ILONLY .class public auto ansi beforefieldinit TestLib.Magic: nop IL_0007: nop IL_0008: nop IL_0009: ret } // end of method Magic::.ctor .method public hidebysig instance string Hello(string str) cil managed { .maxstack 2 .locals init ([0] string CS$1$0000) IL_0000: nop IL_0001: ldstr "Hello" IL_0006: ldarg.1 IL_0007: call string [mscorlib]System.String::Concat(string, string) IL_000c: stloc.0 IL_000d: br.s IL_000f IL_000f: ldloc.0 IL_0010: ret } // end of method Magic::Hello .method public hidebysig instance int32 Addition(int32 x, int32 y) cil managed { Magic::Addition } After you finish coding, compile this TestLib.il file using ILASM in order to generate its corresponding *.dll file as the following: ILASM.exe /dll TestLib.il And later, it is recommended you verify the generated CIL using the peverify.exe as the following: Consume DLLs File It’s time to consume the previously generated TestLib.dll file into a client executable Main.exe file. So create a new file as main.il and define appropriate external reference of mscorlib.dll and TestLib.dll file. Don’t forget to place TestLib.dll copy into the client project solution directory as the following: .assembly extern mscorlib // Define the Reference of mscorlib.dll { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly extern TestLib // Define the Reference of TesLib.dll { .ver 1:0:0:0 } .assembly TestLibClient { .ver 1:0:0:0 } .module main.exe // Define the final executable name .class private auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 8 .locals init ([0] class [TestLib]TestLib.Magic obj) //Init magic class obj IL_0000: nop IL_0001: newobj instance void [TestLib]TestLib.Magic::.ctor() // initialize magic class constructor IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldstr "Ajay" // Pass “Ajay” string in Hello method IL_000d: callvirt instance string [TestLib]TestLib.Magic::Hello(string) IL_0012: call void [mscorlib]System.Console::WriteLine(string) // print Hello method IL_0017: nop IL_0018: ldstr "Addition is:: {0}" IL_001d: ldloc.0 IL_001e: ldc.i4.s 10 // define x=10 IL_0020: ldc.i4.s 20 //define x=20 IL_0022: callvirt instance int32 [TestLib]TestLib.Magic::Addition(int32, int32) //call Addition() IL_0027: box [mscorlib]System.Int32 IL_002c: call void [mscorlib]System.Console::WriteLine(string, object) IL_0038: ret } } Main.il Finally, compile this program using ILASM.exe and you will notice that a main.exe file is created under the solution directory. It’s also recommended to verify the generated CIL code using peverify.exe utility. Now test the executable by running it directly from the command prompt. It will produce the desired output as the following: Exception Handling Sometimes during conversion between different data type, our program is unable to handle unexpected occurrences of strange errors and our program does not produce the desired result or may be terminated. The following example defines Byte type variable and assigning some value beyond its capacity. So it obvious that this program throws an exception related to over size as the following: .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly ExcepTest { .hash algorithm 0x00008004 .ver 1:0:0:0 } .module ExcepTest.exe .imagebase 0x00400000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 .corflags 0x00000003 // =============== CLASS MEMBERS DECLARATION =================== .class private auto ansi beforefieldinit test.Program extends [mscorlib]System.Object { .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 2 .locals init ([0] int32 x,[1] uint8 bVar) // init two variable x and bVar IL_0000: nop IL_0001: ldc.i4 2000 // assign x= 2000 IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: call uint8 [mscorlib]System.Convert::ToByte(int32) // convert integer to byte type (bVar=x) IL_000d: stloc.1 IL_000e: ldstr "Value=" IL_0013: ldloc.1 IL_0014: box [mscorlib]System.Byte IL_0019: call string [mscorlib]System.String::Concat(object, object) IL_001e: call void [mscorlib]System.Console::WriteLine(string) // print bVal IL_0023: nop IL_0024: ret } // end of method Program::Main } Now compile this code and run the executable file, the code is unable to handle the overflow size because the Byte data type can handle the size of data up to 255 and here, we are manipulating greater than 255 so our code throws the exception as the following: The previous program was not able to handle unexpected occurring errors during the program execution. In order to run the program in the appropriate order, we must have to include try/catch block. The suspicious code that might cause some irregularities should be placed in a try block and the thrown exception handled in the catch block as the following: .method private hidebysig static void Main(string[] args) cil managed { .entrypoint .maxstack 2 .locals init ([0] int32 x,[1] uint8 bVar) IL_0000: nop IL_0001: ldc.i4 0x7d0 IL_0006: stloc.0 .try { IL_0007: nop IL_0008: ldloc.0 IL_0009: call uint8 [mscorlib]System.Convert::ToByte(int32) IL_000e: stloc.1 IL_000f: ldstr "Value=" IL_0014: ldloc.1 IL_0015: box [mscorlib]System.Byte IL_001a: call string [mscorlib]System.String::Concat(object, object) IL_001f: call void [mscorlib]System.Console::WriteLine(string) IL_0024: nop IL_0025: nop IL_0026: leave.s IL_0038 } // end .try catch [mscorlib]System.Exception { IL_0028: pop IL_0029: nop IL_002a: ldstr "Size is overflow" IL_002f: call void [mscorlib]System.Console::WriteLine(string) IL_0034: nop IL_0035: nop IL_0036: leave.s IL_0038 } // end handler IL_0038: nop IL_0039: ret } After you applied the exception handling implementations in the code, now you need to compile it using ILASM and run the generated exe file. This time the try/catch block handle the thrown exception related to size overflow as following: Inline MSIL Code Typically, there isn’t a provision for IL Inline coding in .NET CLR. We can’t execute IL opcode instruction with high level language coding in parallel. In the following sample, we are creating a method which takes two integer type of arguments and later defines the addition functionality using IL coding instruction as: public static int Add(int n, int n2) { #if IL ldarg n ldarg n2 add ret #endif return 0; // place holder so method compiles } But a prominent developer, Mike Stall has made a tool called inlineIL which can execute IL code side by side with the existing C# code. In this process, we first compile our C# code using regular csc or vbc compiler in debug mode and generate a *.pdb file. The compiler won’t confuse with instruction defined in #if block and skipped by the compiler. csc %inputfile% /debug+ /out:%outputfile*.pdb% The original source code is diassembled, and the ILASM opcodes are extracted and injected into the disassembly code. The line number information for the injection comes from the PDB file which produced from first step as ildasm %*.pdb % /linenum /out=%il_output% Finally, the modified IL code is assembled using ILASM. The resulting assembly contains everything including the code defined in the ILAsm inserts as following ilasm %il_output% /output=%output_file *.exe% /optimize /debug Although, it does not make sense to integrate IL code into C# code file. This experiment is done just for a knowledge point of view. We must download the tool Mike Stall developed in order to see this implementation. Summary As you can see, IL opcode has directly opened various ways of new possibilities. We can drill down the opcode in order to manipulate it as per our requirements. In this article, we have learned how to build our own dll file component in order to consume it into a front end clients program, and protected code by applying exception handling. So up till now, we have obtained thorough understanding of IL grammar which is substantially required for .NET reverse engineering. Now it’s time to mess with hard core reverse engineering and as you will see in the forthcoming articles, how to manipulate .NET code in order to crack passwords, reveal serial keys and lots of other significant possibilities.
http://resources.infosecinstitute.com/net-reverse-engineering-3/
CC-MAIN-2016-44
refinedweb
1,536
51.24
Cayla makes easy creating web application with Ceylon. module my.app "1.0.0" { import cayla "0.2.3"; } import cayla { ... } object controllers { route("/") shared class Index() extends Controller() { shared actual default Response handle() => ok().body("Hello World"); } } shared void run() { value application = Application(controllers); application.run(); } > ceylon compile my.app ... > ceylon run my.app/1.0 started Applications are create via the Application objects that takes as argument a Ceylon declaration or an object that is scanned to discover the controllers: Application(`package my.controllers`) Application(controllers) Application can be started with Application.run or Application.start: runrun the application and blocks until the current process reads a line (like enter keystroke). startstarts the application asynchronously and returns a Promise<Runtime>providing a fine grained control over the application life cycle. Configuration is handled by the Config class. By default the appliation is bound on the 8080 port and on all available interfaces. Explicit config can be provided when the application is created: Application(`package my.controllers`, Config{port = 80;}); Controllers must extend the Controller interface, they can declare parameters which shall declares the String type, be shared and immutable. Such parameters are mapped toquery or path request parameters. route("/greeter") shared clas Greeter(String name) extends Controller() { shared actual default Response handle() => ok().body("Hello ``name``"); } route("/greeter/:name") shared clas Greeter(String name) extends Controller() { shared actual default Response handle() => ok().body("Hello ``name``"); } Path parameters can match /chars) declared with the :prefix like :name *prefix like *name +prefix like +name Controllers can be addressed using the redefined Controller.string method. In a controller the expression Greeter("Cayla") will produce the or the URL. Routing is declared with the route annotation. Valid controllers must have this annotation. route("/") shared class Index() extends Controller() { ... } Objects wrapping controllers can optionally be annotated with the route annotation: route("/products") object products { route("/") shared class Index() extends Controller() { ... } route("/cars") shared class Cars() extends Controller() { ... } } During an invocation Cayla dispatches the request to the Controller.handle method. This method should implement the controller behavior. It is also possible to override the Controller.invoke method instead that provides access to the RequestContext class that exposes Cayla objects. Both methods returns a Response object that is sent to the client via Vert.x The Response class is the base response, the Status class extends the response class to define the http status and the Body class extends the Status with a response body. Creating responses is usually done via the fluent API and the top level functions such as ok, notFound or error. return notFound().body("Not found!!!!"); By default a controller is bound to a route for all Http methods. This can be restricted by using annotations like get, post, head, put, etc… get route("/greeter") shared clas Greeter(String name) extends Controller() { shared actual default Response handle() => ok().body("Hello ``name``"); }
https://modules.ceylon-lang.org/repo/1/cayla/0.2.3/module-doc/index.html
CC-MAIN-2022-21
refinedweb
480
50.43
Remix is a new take on what it means to be a fullstack React framework, focusing on existing web standards and tying the frontend closely to the backend. This tight coupling is a breath of fresh air when you see how simple it is to load data into your React components or how to process data submitted from a form. In this article we will see Remix's power by creating a simple Feature Flag management system using Upstash Redis as the database. Full source code can be found here. Setup You will get a brand new Remix app by running npx create-remix@latest and choosing your preferred deployment environment. I went with Vercel but it should not make a difference for this tutorial. There are two ways you can connect to Upstash Redis: The first is through a TCP connection in which you can use any standard Redis client library that you are used to. The second is via Upstash's REST API. We will be going with the second option because it is available in all serverless environments, such as the Cloudflare Workers environment that Remix can be deployed to. Upstash has a package which mimics the actual Redis commands, making it easy to know which function to call. We now need a way to store two environment variables needed to connect to our Upstash Redis database. Remix doesn't come with development env var support out of the box, but it can be accomplished by adding dotenv as a development dependency. npm add --save-dev dotenv In our .env file (which should be added to .gitignore) we can set up two env vars required to connect to Upstash Redis. The @upstash/redis package automatically detects these so there is no need to connect within our code. These values can be found within the Upstash dashboard after creating a new Redis database. UPSTASH_REDIS_REST_URL="https://..." UPSTASH_REDIS_REST_TOKEN="..." We need to update our dev script to have dotenv pick up the env vars. The other scripts can stay the same. { "scripts": { "dev": "node -r dotenv/config node_modules/.bin/remix dev" } } Storing Feature Data Feature flags can get incredibly complex, with rollout plans to percentages of your userbase, enabled for specific groups of users, but they can also be as simple as "on" and "off". We will be storing our feature flags using the Hash data type that Redis provides. Our data will end up looking like the JSON below, where "1" is enabled/on and "0" is disabled/off". { "chart": "1", "graph": "0" } To access and manipulate this data we'll use four commands/functions provided by Redis: - hgetall to retrieve all keys (features) and values (enabled/disabled). - hset to enable or disable a specific feature flag. - hdel to delete a specific feature flag. - hmget to get multiple but specific feature flag values at once. Managing Features We will be building a page located at /features which is in charge of creating and managing (enable/disable/delete) existing features. We will go into detail about what AddFeature and FeatureList do when we discuss how to load data and then how to write data. // app/routes/features.tsx export default function Features() { return ( <div> <h1>Features</h1> <AddFeature /> <FeatureList /> </div> ); } Data Loaders A data loader is an exported function in Remix named loader which gets run on the server and returns data that is made available to our React component via a hook. We are starting with a page to create and manage feature flags, and in this case we want to return all the features. They'll be returned as an array of pairs: [ ["graph", true], ["chart", false] ] Starting with a TypeScript type definition, we'll then see a function called loadAllFeatures that uses the hgetall function imported from @upstash/redis. Because it returns data in a format that looks like ["graph", "1", "chart", "0"], we'll need to do some conversion and sorting to get it into the format our code is expecting. type LoaderData = { features: Array<[string, boolean]>; }; const loadAllFeatures = async () => { const { data } = await hgetall("features"); const features: Array<[string, boolean]> = []; for (let i = 0; i < data.length; i += 2) { features.push([data[i], data[i + 1] === "1"]); } return features.sort((a, b) => { if (a[0] > b[0]) return 1; if (a[0] < b[0]) return -1; return 0; }); }; The exported loader function itself will call the loadAllFeatures function, returning the features to be passed into the React component. export const loader: LoaderFunction = async (): Promise<LoaderData> => { // You would want to add authentication/authorization here const features = await loadAllFeatures(); return { features }; }; We'll cover the details of this React component later, but to show how you access the data returned from the loader function, you use a Remix hook called useLoaderData. const FeatureList = () => { const { features } = useLoaderData<LoaderData>(); return ( <ul> {features.map(([feature, active]) => ( <li key={feature}>{/* coming soon */}</li> ))} </ul> ); }; Form Actions We've seen how data is loaded, but at this stage we don't actually have any features in our feature flag database! Here is where form actions come into play. Data is processed in Remix by exporting a function named action. Much like loader, this is run on the server and it typically returns json data that the React component can access via another hook, or it can tell the browser to redirect to another page. The action function below actually handles four different types of actions, creating a feature, enabling/disabling a feature, and deleting a feature. We handle this with a switch statement that then calls the appropriate Redis function/command. export const action: ActionFunction = async ({ request }) => { // You would want to add authentication/authorization here const formData = await request.formData(); const feature = formData.get("feature") as string; const action = formData.get("_action") as string; if (!feature || feature.length === 0) { // This isn't currently displayed in our component return json({ error: "Please provide a feature" }); } switch (action) { case "create": case "enable": await hset("features", feature, 1); break; case "disable": await hset("features", feature, 0); break; case "delete": await hdel("features", feature); break; } return redirect("/features"); }; You'll notice that on success, I redirect to the same page the user is currently on. This essentially triggers a page reload, calling the loader function and updating what is displayed to the user. To add a new feature flag, the AddFeature component will use the Remix Form component that will submit the data to the action function we saw above. I specified that it should submit via the post method and also provided the replace prop so that it doesn't add a new page to the browser's history every time we create a feature flag. const AddFeature = () => { return ( <Form method="post" replace> <input type="hidden" name="_action" value="create" /> <input type="text" name="feature" required <button type="submit">Add</button> </Form> ); }; Once a feature has been created, we'll want to show all the current feature flags so they can be managed. Each feature flag actually displays two forms: One to enable/disable the feature flag, and a second to delete it. Note that there are two hidden fields: _action so that our action function knows what we are trying to do to the feature, and feature which sends the flag name we want to modify. const FeatureList = () => { const { features } = useLoaderData<LoaderData>(); return ( <ul> {features.map(([feature, active]) => ( <li key={feature}> <Form method="post" replace> <input type="hidden" name="_action" value={active ? "disable" : "enable"} /> <input type="hidden" name="feature" value={feature} /> <button type="submit" className="btn-naked"> {active ? "💪" : "🦾"} </button> </Form> <span>{feature}</span> <Form method="post" replace> <input type="hidden" name="_action" value="delete" /> <input type="hidden" name="feature" value={feature} /> <button type="submit">Delete</button> </Form> </li> ))} </ul> ); }; Using Features We have feature flags in our Upstash Redis database, but what good is that if we aren't toggling functionality on or off in our app based on these flags. We will use a loader function to load specific features from the database using hmget, and then a little data manipulation to get it into the right structure. If we want to load ["chart", "graph", "fake"] flags, Redis will return us ["1", "0", null]... keep in mind that if the flag doesn't exist, its value will be null, which I wanted to show by including the fake flag. type LoaderData = { features: Record<string, boolean>; }; const loadFeatures = async (keys: Array<string>) => { const { data } = await hmget("features", ...keys); const features = keys.reduce<Record<string, boolean>>((acc, key, index) => { acc[key] = data[index] === "1"; return acc; }, {}); return features; }; export const loader: LoaderFunction = async (): Promise<LoaderData> => { const features = await loadFeatures(["chart", "graph"]); return { features }; }; We can now access the loaded data in our component, again using Remix's useLoaderData hook. Then choose how the functionality of our website should change given whether a flag is currently enabled or disabled. export default function Index() { const { features } = useLoaderData<LoaderData>(); return ( <div> <h1>Dashboard</h1> {features.chart ? <h2>Chart</h2> : <h2>No Chart</h2>} {features.graph ? <h2>Graph</h2> : <h2>No Graph</h2>} </div> ); } Conclusion In this article we've seen how to use Upstash Redis to create a simple feature flag system in Remix, taking advantage of its data loader and form action server side functions. These allow us to keep the backend and frontend of a specific page tightly coupled, iterating quickly without the need to set up a separate GraphQL API and override standard form submission events on the frontend. Remix as we've seen leans in to web standards around how forms submit their data.
https://blog.upstash.com/redis-with-remix
CC-MAIN-2022-05
refinedweb
1,588
50.97
I am just starting to learn Java and I am using text pad when I try to compile an applet it gives me these errors and according to the book they should not be errors. Unless I am missing something? Here is the code and errors: /* Chapter 2: Welcome to My Day Programmer: Dickie Taylor Date: October 4, 2007 Filename: WelcomeApplet.java Purpose: This project displays a welcome message, the user's name, and the system date in a console application. */ import java.util.Date; import java.awt.*; import java.applet.*; public class WelcomeApplet { public void paint(Graphics g) { Date currentDate = new Date(); //Date constructor g.drawString("Welcome to my day!",200,70); g.drawString("Daily planner for Dickie Taylor",200,100); g.drawString(currentDate.toString(),200,130); Image smile; //declare an Image object smile = getImage( getDocumentBase(),"Smile.gif"); g.drawImage(smile,10,10,this); setBackground(Color.cyan); } } ERRORS are: C:\Java\Chapter 2\WelcomeApplet.java:23: cannot find symbol symbol : method getDocumentBase() location: class WelcomeApplet smile = getImage( getDocumentBase(),"Smile.gif"); ^ C:\Java\Chapter 2\WelcomeApplet.java:24: cannot find symbol symbol : method drawImage(java.awt.Image,int,int,WelcomeApplet) location: class java.awt.Graphics g.drawImage(smile,10,10,this); ^ C:\Java\Chapter 2\WelcomeApplet.java:25: cannot find symbol symbol : method setBackground(java.awt.Color) location: class WelcomeApplet setBackground(Color.cyan); ^ 3 errors Tool completed with exit code 1 Any help would be very much appreciated. Thank You, DLT What class is supposed to supply you the getImage, drawImage, and setBackground methods? import java.util.Date; import java.awt.*; import java.applet.*; You need to invoke a class's method directly. If the method is not static (with a static class you would invoke ClassName.methodName(arg)) you must have an instance of the class created and you must invoke that's instance's method. It looks to me that you are missing a big piece of this Applet. I am trying to simply create an applet that is going to have a graphic and says welome and another sentence and gives the system Date? Are you taking a class? Doesn't your text book have more information about how to build an Applet and to exploit the graphics environment? Take a look at the Java Tutorial on Applets at among the many resources available on the Internet. One of the first things you must do with your code is for your WelcomeApplet to be an "applet" by inheriting from java.awt.Applet. So, you must declare your class using: public class WelcomeApplet extends Applet this may give you access to the methods you want to use since those methods are members of the Applet class, either directly or inherited from the java.awt.Component class. Your operator (don't know if it's the right name) "g" should be dimensionalised. Like "Private String g;", but that seems to be missing. That "g" also needs to have the functions getImage, drawImage and setBackground. g is the Graphics environment of the Applet container some of the methods you've used are part of the Applet class... to make your code compile correct, just extend your class to the Applet class... Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?163883-error-Help!&p=487583
CC-MAIN-2017-34
refinedweb
549
58.28
Automatically create getters and setters When writing classes, I generally start with defining the private fields, then will use Eclipse to generate the public getters and setters. I like to Javadoc each field, but that Javadoc then needs to be repeated two more times (get and set), so I end up with needing to maintain 3 copies of the documentation. Generally, how important is it that we declare getters and setters? Why couldn't we simply declare fields as Read-Only or Read/Write and have the getters and setters generated automatically by Java? For example: <br /> public class Foo<br /> {<br /> /** Attribute that is not able to be changed, only defined by constructor, hence read-only. */<br /> @Get<br /> private String someReadOnlyAttribute;</p> <p> /** An attribute that is read/write. */<br /> @Get @Set<br /> private String attributeOne;</p> <p> /** Another read/write attribute. */<br /> @Get @Set<br /> private String attributeTwo;</p> <p> public Foo (final String someReadOnlyAttribute)<br /> {<br /> this.someReadOnlyAttribute = someReadOnlyAttribute;<br /> }<br /> }<br /> I do agree that sometimes there is value to defining an explicit getter or setter, so that ability needs to be preserved (also for backwards compatibility), but 90% of the time a standard shell is sufficient. Could something like this be considered for JDK 7? these do seem like useful annotations.. Quite frankly writting get/set code is boring. I'd extend the annotation to include visibility hints. I don't always want get/set to be public. if this code-generating annotation was created, would it make sense to have some options as what is generated. Probably common code patterns. Instead of just @Set Object thing produces: public void setThing(Object thing){ this.thing = thing; } Allow for event generation as well: @Set(PropertChangeEvent=true) produces: public void setThing(Object thing){ Object oldThing = this.thing; this.thing = thing; firePropertyChangeEvent("thing", oldThing, thing); } ----------- this might be a stretch... :( leouser How about just change JavaDoc so that getters and setters could inherit documentation from a field. This eliminates the duplication of documentation. > How about just change JavaDoc so that getters and > setters could inherit documentation from a field. > This eliminates the duplication of documentation. In fact you could add a generalised "{@include}" type tag in javadoc that would copy blocks of documentation from other objects. That way the refactoring process could just place a reference to the field documentation when creating getters and setters which wouldn't have to be changed when the field documentation was. I like the JavaDoc ideas! I'm trying to make a concerted effort to improve the level of documentation, and apply the DRY principle. I think ideally the situation would be: Given a statement 'foo.x', the VM... 1. First tries to find a 'getX()' method 2. Next tries to find a public 'x' member 3. Errors ...that way, we could all start off building our classes as mostly public members and there would be no penalty if we later wanted to swap one for a getter/setter instead. Of course, this requires the JavaBean convention actually be baked-in to the JVM, and would probably be a breaking change :( It's an interesting idea - though I don't think it really fits in as a suitable use for annotations (which are more at the "hint" level as far as the compiler is concerned. However I think it's going to be a bit disruptive of debugging - the creation of methods without source code. I know what you mean about commenting, though, it's irritating to have to maintain Javadocs on the field, the getter and the setter. Mind you refactoring tools could be a bit more helpful there. quote often you don't want "standard" getters and/or setters. And I've a deeply rooted distrust of code generators of any kind anyway, especially those that generate code I can't alter after it's been generated because it's either generated at a stage I've no control over or my changes are either ignored or cancelled out by the system after I make them (Netbeans and IBM take notice!).
https://www.java.net/node/660858
CC-MAIN-2015-35
refinedweb
682
54.42
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi, we had a buggy Jelly-Script which postet ten-thousands of comments on some issues. Deleting them manually is not possible, every reload of the issue takes a few minutes. The last chance i see is deleting them by a direct database-delete-statement. Did anyone delete comments like this before or does anyone know if there are dependencies? or has anyone a jelly-script which is able to delete comments through api? thanks & regards Deleting directly from the database is not recommended. But you can use the Script Runner plugin and the following script to delete all comments containing a specific text (in this case "Bla Bla Bla") in a specific issue (here TXS-561). String issueKey = 'TXS-561' IssueManager issueManager = ComponentAccessor.issueManager CommentManager commentManager = ComponentAccessor.commentManager MutableIssue issue = issueManager.getIssueObject(issueKey) List<Comment> comments = commentManager.getComments(issue) comments.each {comment -> if (comment.body.contains('Bla Bla Bla')) { commentManager.delete(comment) } } Henning Just wanted to say this worked like a charm for a comment spam issue I had. Thanks! Thx for your script... I have many issue with the same comment and I will delete this comment. How can I include alle issue keys in this script?I will bulk delete this Comment? Ok, but I can't include the issue keys in your script? for example String issueKey = 'xxx-685'; String issueKey = 'xxx-686' etc... or with another separator? Yes, you can. def issueKeys = ['xxx-456', 'aaa-333'] issueKeys.each{ issueKey -> MutableIssue ... } Thanks alot for this post @Henning Tietgens. This saved me a lot of work when cleaning-up the comments some spambot left on our JIRA instance over the weekend. I also took the time to write a quick How-To to apply your script to the JIRA instance: Hi @Henning Tietgens. I am on JIRA cloud and this script is giving me [x] errors to the left of all the imports at the top of your code before I even run it. The errors state "unable to resolve class com.atlassian.jira...(issue or component)" at each line (1-5). Am I missing something between the date of this post and now (a few years)? Thanks! Hi Daniel, this is a restriction of JIRA Cloud plugins. See ScriptRunner package import restrictions. On JIRA Cloud the plugin (and therefore your script) is not able to directly interact with the JIRA system (see Script Runner Migration Guide for details), instead the REST API has to be used. It should be possible to use{issueIdOrKey}/comment to accomplish the same thing as my script above, but I don't have a script ready for you. Henning Or clone the issue as cloning does not clone the comments. Then delete the original issue. Your options are very limited here. To avoid loss of history and data, you're basically down to two options - What Henning said - even the Jira CLI and Jelly can't delete the comments, the script runner pretty much is the only approach - As you said, hack the database. You will need to stop Jira, get a backup, remove lines from "jiraaction table", start Jira and then update the affected issues index (either with a global index, or a bulk edit or comment on the ones you've changed). I've had a similar problem in the past, and it is moderately safe as long as you do NOTHING else. But I never recommend database hacking, because it's so easy to get it wrong. It is not easy to put everything together, but with a little groovy scripting and JIRA Command Line Interface you could probably do it. --action renderRequest --request "/secure/DeleteComment.jspa?id=108212&commentId=48026&Delete=Delete" An easier alternative is available if you are really good at SQL against the JIRA database (and NOT OnDemand) to construct the right renderRequest (like above) for all the comments you need to remove. Then just use runFromSql to run all of them. As a simple administrator, without access to scripts etc, how do I delete all comments from a page? I've already copied page to retain snapshot with current comments. Confluence 5.3 This is a question about JIRA. You are asking about Confluence ... just create a new question so the answers will be for Confluence. I wrote a Jira Script Runner plugin Groovy script to delete Jira comment spam entered by a spambot that uses a username "Patrickmorton". See the source. You can use the Chrome developer tools to run JavaScript to access the JIRA API. More details are.
https://community.atlassian.com/t5/Jira-questions/Bulk-Delete-Comments/qaq-p/368877
CC-MAIN-2018-09
refinedweb
779
66.74
A simple Python package to profile CPU speed by computing the Fibonacci sequence Project description CPU Profile This is a simple package to measure CPU speed by calculating the time it takes to compute Fibonacci numbers. It is useful in contexts where CPU speed is unknown or can fluctuate, such as cloud function environments, and can serve as a rough measure of how long subsequent compute-intensive code will take to run. Installation pip install cpuprofile Usage from cpuprofile import profile_cpu # Calculate the CPU speed by computing Fibonacci numbers. elapsed_time = profile_cpu() # elapsed_time is ~0.18 (seconds) on a 2.5 GHz Intel Core i7 2015 Macbook Pro. # Or, a number can be specified to calculate the nth Fibonacci (default: 28). elapsed_time = profile_cpu(15) # 15th Fibonacci; takes around 0.0006 seconds elapsed_time = profile_cpu(35) # 35th Fibonacci; takes about 5 seconds Credit The minimalist approach of recursively calculating Fibonacci numbers as a way to profile the CPU is inspired by: - Booth, J. (2015). Not so incognito: Exploiting resource-based side channels in javascript engines (Undergraduate thesis, Harvard University). Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/cpuprofile/
CC-MAIN-2019-35
refinedweb
203
54.93
Introduction to Programming Languages/Interpreted Programs Interpreted Programs[edit] Interpreters execute programs in a different way. They do not produce native binary code; at least not in general. Instead, an interpreter converts a program to an intermediate representation, usually a tree, and uses an algorithm to traverse this tree emulating the semantics of each of its nodes. In the previous chapter we had implemented a small interpreter in Prolog for a programming language whose programs represent arithmetic expressions. Even though that was a very simple interpreter, it contained all the steps of the interpretation process: we had a tree representing the abstract syntax of a programming language, and a visitor going over every node of this tree performing some interpretation-related task. The source program is meaningless to the interpreter in its original format, e.g., a sequence of ASCII characters. Thus, like a compiler, an interpreter must parse the source program. However, contrary to the compiler, the interpreter does not need to parse all the source code before executing it. That is, only those pieces of the program text that are reachable by the execution flow of the program need to be translated. Thus, the interpreter does a kind of lazy translation. Advantages and disadvantages of interpretation over compilation[edit] The main advantage of an interpreter over a compiler is portability. The binary code produced by the compiler, as we have emphasized before, is tailored specifically to a target computer architecture. The interpreter, on the other hand, processes the source code directly. With the rise of the World Wide Web, and the possibility of downloading and executing programs from remote servers, portability became a very important issue. Because client web applications must run in many different machines, it is not effective for the browser to download the binary representation of the remote software. Source code must come instead. A compiled program usually runs faster than an interpreted program, because there are less intermediaries between the compiled program and the underlying hardware. However, we must bear in mind that compiling a program is a lengthy process, as we had seen before. Therefore, if the program is meant to be executed only once, or at most a few times, then interpreting it might be faster than compiling and running it. This type of scenario is common in client web applications. For instance, JavaScript programs are usually interpreted, instead of compiled. These programs are downloaded from a remote web server, and once the browser section expires, their code is usually lost. To change a program's source code is a common task during the development of an application. When using a compiler, each change implies a potentially long waiting time. The compiler needs to translate the modified files and to link all the binaries to create an executable program, before running that program. The larger is the program, the longer is this delay. On the other hand, because an interpreter does not translate all the source code before running it, the time necessary to test the modifications is significantly shorter. Therefore, interpreters tend to favour the development of software prototypes. Example: bash-script: Bash-script is a typical interpreter commonly used in the Linux operating system. This interpreter provides to users a command-line interface; that is, it gives users a prompt where they can type commands. These commands are read and then interpreted. Commands can also be grouped into a single file. A bash script is a file containing a list of commands to be executed by the bash shell. Bash is a scripting language. In other words, bash makes it very easy for the user to call applications implemented in other programming languages different than bash itself. A such script can be used to automatically execute a sequence of commands that the user often needs. The following lines are very simple commands that could be stored in a script file, called, for instance, my_info.sh: #! /bin/bash # script to present some information clear echo 'System date:' date echo 'Current directory:' pwd The first line ( #! /bin/bash) in the script specifies which shell should be used to interpret the commands in the script. Usually an operating system provides more than one shell. In this case we are using bash. The second line ( # script to present some information) is a comment and does not have any effect when the script is executed. The life cycle of a bash script is much simpler than the life cycle of a C program. The script file can be edited using a text editor such as vim. After that, it is necessary to change its permission in the Linux file system so that we can make it executable. A script call can be done by prefixing the file's name with its location in the filesystem. So, an user can run the script in a shell by typing "path/my_info.sh", where path indicates the path necessary to find the script: $> ./my_info.sh System date: Seg Jun 18 10:18:46 BRT 2012 Current directory: /home/IPL/shell Virtual Machines[edit] A virtual machine is a hardware emulated in software. It combines together an interpreter, a runtime supporting system and a collection of libraries that the interpreted code can use. Typically the virtual machine interprets an assembly-like program representation. Therefore, the virtual machine bridges the gap between compilers and interpreters. The compiler transforms the program, converting it from a high-level language into low-level bytecodes. These bytecodes are then interpreted by the virtual machine. One of the most important goals of virtual machines is portability. A virtualized program is executed directly by the virtual machine in such a way that this program's developer can be oblivious to the hardware where this virtual machine runs. As an example, Java programs are virtualized. In fact, the Java Virtual Machine (JVM) is probably the most well-known virtual machine in use today. Any hardware that supports the Java virtual machine can run Java programs. The virtual machine, in this case, ensures that all the different programs will have the same semantics. A slogan that describes this characteristic of Java programs is "write once, run anywhere". This slogan illustrates the cross-plataform benefits of Java. In order to guarantee this uniform behaviour, every JVM is distributed with a very large software library, the Java Application Program Interface. Parts of this library are treated in a special way by the compiler, and are implemented directly at the virtual machine level. Java [threads], for instance, are handled in such a way. The Java programming language is very popular nowadays. The portability of the Java runtime environment is one of the key factors behind this popularity. Java was initially conceived as a programming language for embedded devices. However, by the time Java was been released, the World Wide Web was also making its revolutionary début. In the early 90's, the development of programs that could be downloaded and executed in web browsers was in high demand. Java would fill up this niche with the Java Applets. Today Java applets felt out of favour when compared to other alternatives such as JavaScript and Flash programs. However, by the time other technologies begun to be popular in the client side of web applications, Java was already one of the most used programming languages in the world. And, many years past the initial web revolution, the world watches a new unfolding in computer history: the rise of the smartphones as general purpose hardware. Again portability is at a premium, and again Java is an important player in this new market. The Android virtual machine, Dalvik is meant to run Java programs. Just-in-Time Compilation[edit] In general a compiled program will run faster than its interpreted version. However, there are situations in which the interpreted code is faster. As an example, the shootout benchmark game contains some Java benchmarks that are faster than the equivalent C programs. The core technology behind this efficiency is the Just-in-Time Compiler, or JIT for short. The JIT compiler translates a program to binary code while this program is being interpreted. This setup opens up many possibilities for speculative code optimizations. In other words, the JIT compiler has access to the runtime values that are being manipulated by the program; thus, it can use these values to produce better code. Another advantage of the JIT compiler is that it does not need to compile every part of the program, but only those pieces of it that are reachable by the execution flow. And even in this case, the interpreter might decide to compile only the heavily executed parts of a function, instead of the whole function body. The program below provides an example of a toy JIT compiler. If executed correctly, the program will print Result = 1234. Depending on the protection mechanisms adopted by the operating system, the program might not executed correctly. In particular, systems that apply Data Execution Prevention (DEP), will not run this program till the end. Our "JIT compiler" dumps some assembly instructions into an array called program, and then diverts execution to this array. #include <stdio.h> #include <stdlib.h> int main(void) { char* program; int (*fnptr)(void); int a; program = malloc(1000); program[0] = 0xB8; program[1] = 0x34; program[2] = 0x12; program[3] = 0; program[4] = 0; program[5] = 0xC3; fnptr = (int (*)(void)) program; a = fnptr(); printf("Result = %X\n",a); } In general a JIT works in a way similar to the program above. It compiles the interpreted code, and dumps the result of this compilation, the binary code, into a memory array that is marked as executable. Then the JIT changes the execution flow of the interpreter to point to the newly written memory area. In order to give the reader a general picture of a JIT compiler, the figure below shows Trace Monkey, one of the compilers used by the Mozilla Firefox browser to run JavaScript programs. TraceMonkey is a trace based JIT compiler. It does not compile whole functions. Rather, it converts to binary code only the most heavily executed paths inside a function. TraceMonkey is built on top of a JavaScript interpreter called SpiderMonkey. SpiderMonkey interprets bytecodes. In other words, the JavaScript source file is converted to a sequence of assembly-like instructions, and these instructions are interpreted by SpiderMonkey. The interpreter also monitors the program paths that are executed more often. After a certain program path reaches an execution threshold, it is translated to machine code. This machine code is a trace, that is, a linear sequence of instructions. The trace is then transformed in native code by nanojit, a JIT compiler used in the Tamarin JavaScript engine. Once the execution of this trace finishes, either due to normal termination or due to an exceptional condition, control comes back to the interpreter, which might find other traces to compile.
https://en.wikibooks.org/wiki/Introduction_to_Programming_Languages/Interpreted_Programs
CC-MAIN-2015-32
refinedweb
1,816
54.73
CaptureMedia Here is our work for capturing media (@techteej and @tony) from 2 other threads and @techteej's Speech project, tidied up, wrapped in a class, closing the server and presented in a popover sized to fit the iOS pop up. The code uses a chunk from @omz's File Transfer script. Only tested on an iPad mini (original) and the latest iOS 7 (see below), can't vouch for others. # see version 2.1 Edit 2.1: New version posted Edit 2.0: New public interface attributes of: version, source, message and file name New compatibility testing in preparation for release of IOS 8 New close button in base class to prompt user action after cancel New sub class example: MyCaptureMedia Update: better fix for programmatic close of popover Edit 1.0: Notes for GitHub users regarding the items removed there: The _make_xxxmethods are according to @ccc's comments on best practices.... "Each ui element that gets added as a subview to your ui.View should have its own make_xxx()method." The methods did load and layout are supplied as a provision for subclasses of CaptureMedia. Did load... gives the subclass the opportunity to add to or modify the ui of the class before it's presented, perhaps to make the WebView visible or leave it hidden but add extra buttons, etc. Layout gives the subclass the opportunity to change the size of the popover or adjust it for orientation changes etc. The function of the def log_messageis to suppress the default log messages to the console. Updated source to version 2.0 p.s. I'm working on adding in a settings button and my SettingsSheet class for a switch to turn warnings on/off. @tony I have to test this on an iOS 7 iPad, which I don't see very often (it's a relatives) so good luck! Hopefully @ccc will help you. I can do what I can when I get the iOS 7 iPad. capture_media generates an error on line 115 on my ipad air ios7.... any fix? Looks like you should replace self._f with os.path.split(__file__)[1]. You might also want to try one of the older versions (github history) since it seems like people checked in work without testing. @JonB thanks. i've replaced the self._f at 2 locations, but there are still errors. Which version in the history would your recommend? - Webmaster4o Where is a working link?
https://forum.omz-software.com/topic/2026/capturemedia/22
CC-MAIN-2022-33
refinedweb
410
73.88
I prepared this simple program in hopes that it will help explain pointers to a 2nd semester C++ programming class. Do you see anything inaccurate or particularly confusing in any of my comments? I'm a little worried about this line in particular:Anything wrong with that?Anything wrong with that?Code: // It also stores an int** pointer to the 2-d array itself, // which holds the beginning address of the block of // int* pointers. Thanks for looking. Code: #include <iostream> using namespace std; int main () { int i,j; int iarr[4][2] = {{1,2},{3,4},{5,6},{7,8}}; // When we declare a 2-dimensional int array, the compiler: // allocates a contiguous block of memory in which to // store the requested number of ints. // It also allocates another contiguous block of memory // NO // in which it stores int* pointers to the 1-dimensional // arrays representing the "rows" (the last dimension) // of the int array. // It also stores an int** pointer to the 2-d array itself, // NO // which holds the beginning address of the block of // int* pointers. // code deleted ... return 0; }
https://cboard.cprogramming.com/cplusplus-programming/113822-pointer-school-printable-thread.html
CC-MAIN-2017-30
refinedweb
184
61.26
a logical controlling whether all symbols are resolved (and relocated) immediately the library is loaded or deferred until they are used. This control is useful for developers testing whether a library is complete and has all the necessary symbols, and for users to ignore missing symbols. Whether this has any effect is system-dependent. It is ignored on Windows. - … other arguments for future expansion. See section ‘Windows’ below. - symbol a character string giving a symbol name. - PACKAGE if supplied, confine the search for the nameto the DLL given by this argument (plus the conventional extension, .so, .sl, .dll, …). This is intended to add safety for packages, which can ensure by using this argument that no other package can override their external symbols. This is used in the same way as in .C, .Call, .Fortranand .Externalfunctions. - type The type of symbol to look for: can be any ( "", the default), "Fortran", "Call"or "External". Details The objects dyn.load loads are called ‘dynamically loadable libraries’ (abbreviated to ‘DLL’) on all platforms except macOS, which uses the term for a different sort of object. On Unix-alikes they are also called ‘dynamic shared objects’ (‘DSO’), or ‘shared objects’ for short. (The POSIX standards use ‘executable object file’, but no one else does.) See ‘See Also’ and the ‘Writing R Extensions’ and ‘R Installation and Administration’ manuals for how to create and install a suitable DLL. Unfortunately a very few platforms (e.g., Compaq Tru64) do not handle the PACKAGE argument correctly, and may incorrectly find symbols linked into R. The additional arguments to dyn.load mirror the different aspects of the mode argument to the dlopen() routine on POSIX systems. They are available so that users can exercise greater control over the loading process for an individual library. In general, the default values are appropriate and you should override them only if there is good reason and you understand the implications. The local argument allows one to control whether the symbols in the DLL being attached are visible to other DLLs. While maintaining the symbols in their own namespace is good practice, the ability to share symbols across related ‘chapters’ is useful in many cases. Additionally, on certain platforms and versions of an operating system, certain libraries must have their symbols loaded globally to successfully resolve all symbols. One should be careful of the potential side-effect of using lazy now argument as FALSE. If a routine is called that has a missing symbol, the process will terminate immediately. The intended use is for library developers to call with value TRUE to check that all symbols are actually resolved and for regular users to call with FALSE so that missing symbols can be ignored and the available ones can be called. The initial motivation for adding these was to avoid such termination in the _init() routines of the Java virtual machine library. However, symbols loaded locally may not be (read probably) available to other DLLs. Those added to the global table are available to all other elements of the application and so can be shared across two different DLLs. Some (very old) systems do not provide (explicit) support for local/global and lazy/eager symbol resolution. This can be the source of subtle bugs. One can arrange to have warning messages emitted when unsupported options are used. This is done by setting either of the options verbose or warn to be non-zero via the options function. There is a short discussion of these additional arguments with some example code available at. External code must not change the floating point control word, but many DLLs do so. Common changes are to set it to use 53 bit precision instead of R's default 64 bit precision, or to unmask some exceptions. dyn.load detects such changes, and restores R's control word to its default value of hex 8001F. This may cause the DLL to malfunction; if so, it should be rewritten to save and restore the control word itself. If warn.FPU is set to TRUE using the options function, a warning will be printed. (If the warning says that the control word was changed from some other value than 8001F, please report the circumstances to the Windows maintainers: that probably indicates an internal bug.) Value The function dyn.load is used for its side effect which links the specified DLL to the executing R image. Calls to .C, .Call, .Fortran and .External can then be used to execute compiled C functions or Fortran subroutines contained in the library. The return value of dyn.load is an object of class DLLInfo. See getLoadedDLLs for information about this class. The function dyn.unload unlinks the DLL. Note that unloading a DLL and then re-loading a DLL of the same name may or may not work: on Solaris it uses the first version loaded. is.loaded checks if the symbol name is loaded and searchable and hence available for use as a character string value for argument .NAME in .C or .Fortran or .Call or .External. It will succeed if any one of the four calling functions would succeed in using the entry point unless type is specified. (See .Fortran for how Fortran symbols are mapped.) Note that symbols in base packages are not searchable, and other packages can be so marked. The ‘standard mechanisms for loading DLLs’ include a search order for where a DLL is found (if not given as an absolute path, which is preferred), and of where its dependent DLLs will be found. This search path depends on the version of Windows and its security settings, but for versions since Windows XP SP1 it is The directory from which the application was launched. The various system directories, e.g. c:/Windows/system32, c:/Windows/systemand c:/Windows. The current directory. Along the search path for executables given by the environment variable PATH. Packages often want to supply dependent DLLs in their libs directory, and do this by setting the PATH variable ( library.dynam does that automatically in recent versions of R), but the DLL search order means that DLLs in the launch directory and in system directories will be preferred. On Windows XP SP1 and later there is a way to modify the search order. If argument DLLpath is supplied to dyn.load, the latter makes use of the Windows system call SetDllDirectory to insert the value of DLLpath in second place, and removes the current directory, for the duration of that dyn.load call. (Note that only one directory can be inserted in this way.) Users have been confused by messages like error: unable to load shared object '.../library/rJava/libs/x64/rJava.dll': LoadLibrary failure: The specified module could not be found. The final line is a Windows (not R) diagnostic: the ‘module’ that could not be found is not rJava.dll but something else Windows is looking for (here most likely Java DLLs): if you are lucky there will be a dialog box with more details. # }
https://www.rdocumentation.org/packages/base/versions/3.5.1/topics/dyn.load
CC-MAIN-2019-04
refinedweb
1,170
63.7
These days, automation has found itself a place in every trend of Business and Development. And one such automation deals with automated online conversational entities. The idea behind this article is to deploy a Chat Bot in an ASP.NET website (via a Widget) that is not connected to any online bot API services and is directly hosted within the web app itself. So without further adieu, let's get started. Let's create an ASP.NET website that will contain the chat bot widget. For this, let us follow the steps below: BotWebsite style="height: 334px; width: 600px" alt="Image 2" data-src="" class="lazyload" data-sizes="auto" data-> style="height: 485px; width: 600px" alt="Image 3" data-src="" class="lazyload" data-sizes="auto" data-> Next, we'll add a Web Form to the project. This Web Form will be our default web page to which we'll later add our chat bot widget. style="height: 325px; width: 600px" alt="Image 4" data-src="" class="lazyload" data-sizes="auto" data->.Bot.Channels This will add a reference to the Syn.Bot.Channels library that we will be making extensive use of in this tutorial. The library we've just imported will provide us with the following crucial elements for our Automated Chat bot. Syn.Bot.Channels WidgetChannel Every time a Chat Request is sent to our Chat bot widget, the message will be passed as parameters to a URL that will point to a Web Form in our Project. The Web Form (containing the backed Bot system) will then process the message part and return a bot response with the proper headers. The same URL will also serve the purpose of sending the required JavaScripts, CSS and HTML elements to the browser whenever the Default.aspx page is loaded. using System; using System.Web; using System.Web.UI; using Syn.Bot.Channels.Testing; using Syn.Bot.Channels.Widget; using Syn.Bot.Oscova; namespace BotWebsite { public partial class BotService : Page { private static WidgetChannel WidgetChannel { get; } private static OscovaBot Bot { get; } static BotService() { Bot = new OscovaBot(); WidgetChannel = new WidgetChannel(Bot); //Add the pre-built channel test dialog. Bot.Dialogs.Add(new ChannelTestDialog(Bot)); //Start training. Bot.Trainer.StartTraining(); var websiteUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); WidgetChannel.ServiceUrl = websiteUrl + "/BotService.aspx"; WidgetChannel.ResourceUrl = websiteUrl + "/BotResources"; WidgetChannel.WidgetTitle = "Our Smart Bot!"; WidgetChannel.LaunchButtonText = "Ask"; WidgetChannel.InputPlaceHolder = "Ask your query here..."; } protected void Page_Load(object sender, EventArgs e) { WidgetChannel.Process(Request, Response); } } } Time to demystify the above code. We start by using the static constructor for the BotService page object. Inside the static constructor, we create and initialize a new OscovaBot instance. The static constructor is opted to ensure that our WidgetChannel object will be initialized only once per session. BotService OscovaBot WidgetChannel ServiceUrl ResourceUrl WidgetTitle InputPlaceHolder LaunchButtonText protected void Page_Load(object sender, EventArgs e) { WidgetChannel.Process(Request, Response); } This is where the magic happens. Every time the BotService.aspx page is about to load the page, Request and Response objects are passed to the WidgetChannel as arguments. Request Response The agent then processes the Request and returns a Response with a proper header. These responses include (but are not limited to): The following line however, adds a pre-built Channel testing dialog that has the following in-built test commands ready: //Add the pre-built channel test dialog. Bot.Dialogs.Add(new ChannelTestDialog(Bot)); The chat widget that will be displayed on our web page uses certain images and apparently, we'll have to import a few image files into our Project. The BotResource folder now has all the required image files. Now that our project is ready, there's this one last thing that we'll have to do to fire up our chatbot. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BotWebsite.Default" %> <!DOCTYPE html> <html xmlns=""> <head runat="server"> <title>My Website with a Bot</title> </head> <body style="background-color: #1d1f21"> <form id="form1" runat="server"> <div> </div> <script type="text/javascript"> (function () { var scriptElement = document.createElement('script'); scriptElement.type = 'text/javascript'; scriptElement.async = false; scriptElement.src = '/BotS BotService.aspx upon receiving the aforementioned parameter will return the JavaScript to the browser that will automatically add a Style Sheet along with the HTML elements that make up the cosmetics of your Chat bot widget. ServiceUrl Script Get Interestingly, we are done with our coding, copying, extracting and what not. We'll go ahead and run the project. To do so, press F5 and you should see the Chat Bot Widget. If for some reason, you don't see the widget, then refresh the page. style="height: 468px; width: 640px" alt="Image 5" data-src="" class="lazyload" data-sizes="auto" data-> Congratulations! You are ready to test the bot. To test the bot, try saying ping or quick reply message and you should receive a response. So we've finally hit the million dollar question. As the NuGet package we've imported into our Project is centered around Workspace Bot project. We'll have to make use of Oryzer Studio for development of the Knowledge Base and later export the project into our project's BotResources folder. For this, I've painstakingly put together a separate article on Creating an On-Premise Offline Bot in C# using Oscova. You'll have to go through the article and create a simple knowledge base for the Bot using Oryzer Studio. Once you've created your Knowledge Base, there's one nifty little trick you'll have to do. Every knowledge base project file you export using Oryzer Studio gets suffixed with the .west extension. Since access to unknown extensions is forbidden by default in an ASP.NET environment, you can either add that extension to your ASP.NET environment (via IIS) or you'll have to rename the extension to .txt or json. To do so (while saving your Knowledge Base), enclose the name of your Package (with the .txt or json extention) within double quotes and click Save. style="height: 300px; width: 600px" alt="Image 6" data-src="" class="lazyload" data-sizes="auto" data-> Once you've exported the Workspace project, right click the BotResource folder (in Visual Studio) Add->Existing Item.. and select the exported file. Then using our example code, you can change the first 2 lines in the static constructor to: Bot = new OscovaBot(); Bot.ImportWorkspace("Path to File"); While trying to disect the cosmetics behind the Chat Widget, in an attempt to check if any external resources were being used by the Virtual Chat Agent, I learnt that the Chat Bot Widget uses pure JavaScript and has multiple placeholder values within double {{}} curly brackets. You can also extract the internal script by calling WidgetChannel.ExportResources("Directory-Path-Here"); You may want to tinker around the code for customization. WidgetChannel.ExportResources("Directory-Path-Here"); The knowledge base I've used in this article is a pre-built testing dialog. It just lets the developer test how certain types of responses are displayed within the chat panel. On a side note, I ain't an ASP.NET pro and I firmly believe that there's gotta be a better approach than using a Web Form as the service URL. WCF would probably be a better way to go about? Either way, I'd rather stick with a simpler approach instead of introducing a complex WCF service that might not work as expected for many readers. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) Bot = new OscovaBot(); Bot.ImportWorkspace("Path to File"); ExportResources() UseExternalResource true const newUserId = Math.floor(Math.random() * 99999999); Resources Syn Oryzer Studio OscovaBot.Logger.LogReceived General News Suggestion Question Bug Answer Joke Praise Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
https://www.codeproject.com/Articles/871501/Adding-a-Self-Hosted-Chatbot-to-an-ASP-NET-Website
CC-MAIN-2021-39
refinedweb
1,314
57.87
Concert.js is an event library for JavaScript and Node.js that implements the observer pattern (a.k.a publish/subscribe). This is a useful pattern for creating decoupled architectures, event driven systems and is one key element in the Model-View-Controller pattern. Concert.js similar to Node's EventEmitter and Backbone.Events, but independent, minimal and light-weight. on, once, offand trigger. on, onceor offon the child instances. Eliminate an awful lot of computation by setting your event listeners on your class's prototype. Read more on inheritable observables. oncefunction to listen to an event only once and then remove the listener automatically. obj.addEventListener = Concert.on. allevent for catching all triggered events. obj.on({change: onChange, save: onSave}) change:name. Object.getOwnPropertySymbols. npm install concert Concert.js doesn't yet have a build ready for the browser, but you might be able to use Browserify to have it run there till then. To add events to any object of your choice, just mix Concert's functions to your object: var Concert =var music = {}for var name in Concert musicname = Concertname Then use on and trigger to add listeners and trigger events: musicmusic If you're using Underscore.js or Lo-dash, you can use _.extend to mix Concert in: _ Mix Concert in to your class's prototype to make each instance observable. {}_ Then you can listen to and trigger events on each instance. var music =music Because there are no limits to event names, you can create faux namespaces by adding a separator, e.g :, to event names. Then trigger both the specific and general version in your application code and you're good to go. This happens to be also what Backbone.Model does for its change events. modelmodel { thissong = song }_Musicprototype { this }Musicprototype Once you initialize your object, all of the event listeners will be ready without having to call a bunch of ons and onces in the constructor. This pattern saves you from an awful lot of unnecessary computation. Ensure the third argument, the listener's context, remains undefined when calling Music.prototype.on. The listener's context will then be set to any particular instance on which trigger was called. var music = "On Broadway"music // => Will log "Playing On Broadway.". You can then add listeners without worrying you'll change every instance in the system (as you would when you'd use Node.js's EventEmitter or Backbone's Events). var jam = "The Way It Is"jamjammusic // => Will log "Jamming The Way It Is.".var classic = "Tubular Bells"classic // => Will still log "Playing Tubular Bells.". If you'd like to use a single listener for multiple events, but need a way to still differentiate between events, make use of Concert.js's support for binding arguments: var song = "The Way It Is"songsong Your onStartOrStop function will then be called in the context of song with its first argument as either "play" or "stop". Any additional arguments given to trigger will come after the bound arguments. For extended documentation on all functions, please see the Concert.js API Documentation. Concert.js is released under a Lesser GNU Affero General Public License, which in summary means: For more convoluted language, see the LICENSE file. Andri Möll typed this and the code. Monday Calendar supported the engineering work. If you find Concert.js needs improving, please don't hesitate to type to me now at andri@dot.ee or create an issue online.
https://www.npmjs.com/package/concert
CC-MAIN-2018-09
refinedweb
581
58.99
New features in Python 3.6¶ Python 3.6 was released in December 2016. As of mypy 0.510 all language features new in Python 3.6 are supported. Syntax for variable annotations (PEP 526)¶ Python 3.6 feature: variables (in global, class or local scope) can now have type annotations using either of the two forms: from typing import Optional foo: Optional[int] bar: List[str] = [] Mypy fully supports this syntax, interpreting them as equivalent to foo = None # type: Optional[int] bar = [] # type: List[str] An additional feature defined in PEP 526 is also supported: you can mark names intended to be used as class variables with ClassVar. In a pinch you can also use ClassVar in # type comments.) and comprehensions (PEP 530)¶ Python 3.6 allows coroutines defined with async def (PEP 492) to be generators, i.e. contain yield expressions, and introduces a syntax for asynchronous comprehensions. Mypy fully supports these features, for example: from typing import AsyncIterator async def gen() -> AsyncIterator[bytes]: lst = [b async for b in gen()] # Inferred type is "List[bytes]" yield 'no way' # Error: Incompatible types (got "str", expected "bytes") New named tuple syntax¶ Python 3.6 supports an alternative syntax for named tuples. See Named tuples.
http://mypy.readthedocs.io/en/latest/python36.html
CC-MAIN-2017-26
refinedweb
205
58.58
Tollfree in the US: 877-421-0030 Alternate: 770-615-1247 Access code: 173098# Full list of phone numbers Call Time: 8:00 AM Pacific; 11:00 AM Eastern; 1500 UTC I did receive query about JSDT ... IP Staff surprised they were releasing/graduating. (remember to communicate that seperately, next time) Still not listed on what's new page. They said we would be once IP docs approved. This is a request to have a move review. June 8 meeting for questions and discussion, and the PMC will make a decision/position within a few weeks after that. Related information and links: Konstantin presented the reasons he'd like the Faceted project code outside of WTP. Partially for appearance and visibility as a generally useful framework, not specific to webtools. Broaden appeal, broaden adoption. He was pretty direct that the move was to have independent governance, that in his view of open source development, the individual person who works on some framework code should have final say in what they do with that code (that they could not be vetoed by other committers in the project). He sees the framework's 2.x code as a fresh start, with his own API Policy (not WTP's) which would include removing all the currently deprecated API The current API would be renamed to its own package namespace. (The current/continued 1.x stream would keep same namespace and API as it has now, and he'd try to maintain compatibility, having the old code call out to the new code.) The new v2 framework would offer some new UI work. clean API (no deprecated API). No "core api" additions or concepts were mentioned. He said there were no other adopters, beyond WTP. Some recent discussions came from PDT (who prereq WTP). He has discussed with CDT, but Doug said "interesting, but no time or people to do right now". Konstantin would also like to pitch to PDE team, if he had independent project. As to why "more efficient" to do both old and new code in one project, he mentioned then they could have a common build. He acknowledged the incubating state of current Faceted Project project, and thought it would not take much to get graduated. (He mentioned work on build). He acknowledged there was not much community in the new Incubating project,, in terms of adoption, mailing lists, newsgroups, bugzilla, which he attributes to the "chicken and egg" phenomena. When asked about having other committers in the new project, he said he would like very much if others made substantial contributions to the code (but no one has so far, and no one has shown much interest). He said he could not think of any alternatives, such as (my offhand suggestion) having a sub-sub-project of WTP's Common Tools project would not solve the governance problem, he said. Overall, I think the meeting/discussion accomplished what it should have (increased our understanding, give him a chance to explain). Back to meeting list. Please send any additions or corrections to David Williams. Back to the top
http://www.eclipse.org/webtools/development/pmc_call_notes/pmcMeeting.php?meetingDate=2010-06-08
CC-MAIN-2015-18
refinedweb
518
72.05
Hi, I would like to derive a class from pugi::xml_node to add more functionality to the class. I get stuck when I try to append a child because pug::xml_node append_child return pugi::xml_node (not a pointer). This is what I've tried, but it failes to compile. Code: PugiXmlNode PugiXmlNode::appendChild(std::string name) { return (PugiXmlNode) (append_child(name.c_str())); } Is there any way to do this? W. PugiXmlNode PugiXmlNode::appendChild(std::string name) { return (PugiXmlNode) (append_child(name.c_str())); } Originally Posted by woomla Hi, I would like to derive a class from pugi::xml_node to add more functionality to the class. First, does this pugi class have a virtual destructor? If not, then the intentions of the author of pugi is that it is not to be derived from. The class is meant to be used as a component within a larger framework, and not to be derived from or "tinkered with" by extending it. If I give you a 6 foot ladder, and then you glue on an extra 2 rungs to this ladder, don't blame me if the ladder collapses when you step on those extra two rungs. That's what you're doing when you attempt to extend a class that isn't meant to be extended. In this case, you should be creating a class that uses a pugi object, or create wrapper functions that manipulates the object. If the pugi class does have a virtual destructor, then you should investigate the valid, proper ways to add functionality (usually there would be virtual functions in the public or protected area of the class). The reason for the virtual destructor is to make sure that if the class is used polymorphically, where the base class pointer may be used to destroy the object, then the destructors are called without undefined behaviour occurring. In other words, a virtual destructor guarantees that any usage at all of a derived object will work correctly with respect to destruction. Without a virtual destructor, the class is opened up to all sorts of problems if the coder happens to use the derived class in a polymorphic fashion. Edit: I took a look at this pugi class. The xml_node class does not have a virtual destructor, therefore derivation is not intended for this object. Other objects do have virtual destructors, so the authors are or should be fully aware of why they did not place a virtual destructor in the xml_node class. Regards, Paul McKenzie Last edited by Paul McKenzie; December 10th, 2012 at 03:28 PM. Thanks for this excellent, easy to understand answer! Forum Rules
http://forums.codeguru.com/showthread.php?530609-Derive-from-pugi-xml_node&p=2095501
CC-MAIN-2014-49
refinedweb
436
60.75
Snapshot A view of an object at a point in appropriate date. If Bi-temporality is present, then you'll need both actual and record dates. Snapshots are a view to help accessing, so in most cases they should be immutable. An exception to this is where you might update a snapshot and then apply it back to the real object as at some date. This is not something that I'd do very often, and usually only when working with an external system that isn't aware of temporality. When to Use It Temporality adds a good bit of complexity to a design and there are times when you don't want to take that into account. Maybe you are in a context where the you want to do a good bit of work with respect to a particular timepoint and you don't want to keep reminding the system which timepoint you're dealing with. Or maybe you are linking to a system that doesn't understand temporality. Then you can take a snapshot for use with that system. Further Reading This pattern was crystalized for me when collaborating with Andy Carlson on our plop paper . Example: Implementing Snapshot (Java) Putting together a snapshot is really quite straightforward. The key is to use delegation so that the snapshot acts as an adaptor on the underlying object. Figure 1: Using delegation to implement a snapshot class Customer... private TemporalCollection addresses = new SingleTemporalCollection(); public Address getAddress(MfDate date) { return (Address) addresses.get(date); } public Address getAddress() { return getAddress(MfDate.today()); } public void putAddress(MfDate date, Address value) { addresses.put(date, value); } class CustomerSnapshot... private Customer base; private MfDate validDate; public CustomerSnapshot (Customer base, MfDate validDate) { this.base = base; this.validDate = validDate; } public Address getAddress() { return base.getAddress(validDate); } Notice in this case that you create a snapshot by calling the constructor on the CustomerSnapshot supplying the customer and the actual date. You can also do this by calling a createSnapshot(Date) method on the Customer. Using the constructor allows you to avoid a dependency from the Customer to its snapshot.
https://martinfowler.com/eaaDev/Snapshot.html
CC-MAIN-2021-04
refinedweb
350
56.96
0 Members and 1 Guest are viewing this topic. I've compiled a new version of this for r5583 (112.2.2), please test.It works only on OSX 10.7 (Lion). The app bundle includes pak64, you can add other paksets by right-clicking on the app bundle, selecting "show package contents" and then copying your pakset into Contents/MacOS/ (equivalent to the simutrans/ folder on other platforms).Please let me know if you have any problems with it. It's still fairly new/crude but should have all the basic functionality. The source has been available on Github for a while, here: What? Colourspace looks fine to me. hehehe Question - does makeobj store the image data in pak files internally as 24bits (e.g. 8 bits for R, 8 bits for G, 8 bits for B) or as RGB565/1555? /** * Transform a 24 bit RGB color into the system format. * @return converted color value * @author Hj. Malthaner */unsigned int get_system_color(unsigned int r, unsigned int g, unsigned int b){#ifdef USE_16BIT_DIB return ((r & 0x00F8) << 8) | ((g & 0x00FC) << 3) | (b >> 3);#else return ((r & 0x00F8) << 7) | ((g & 0x00F8) << 2) | (b >> 3); // 15 Bit#endif} /* from here code for transparent images */typedef void (*blend_proc)(PIXVAL *dest, const PIXVAL *src, const PIXVAL colour, const PIXVAL len);// different masks needed for RGB 555 and RGB 565#define ONE_OUT_16 (0x7bef)#define TWO_OUT_16 (0x39E7)#define ONE_OUT_15 (0x3DEF)#define TWO_OUT_15 (0x1CE7)static void pix_blend75_15(PIXVAL *dest, const PIXVAL *src, const PIXVAL , const PIXVAL len){ const PIXVAL *const end = dest + len; while (dest < end) { *dest = (3*(((*src)>>2) & TWO_OUT_15)) + (((*dest)>>2) & TWO_OUT_15); dest++; src++; }}etc... This looks very interesting. Would it be possible to do an Experimental version of this? Of course it's possible, all it would take is someone to do the work to port it over. In fact given that it doesn't modify the game files at all (except the makefile) so long as experimental has not changed the simsys interface it'd be a drop-in addition. @james, just wait and rely on FOSS. Once it works for standard, there will be desire by people having macs to have experimental on it too, chances aren't bad at least one of them will do it. If not, as soon as people start to pester you about doing it, a sollution should be found.....
http://forum.simutrans.com/index.php?PHPSESSID=dfbbqfkpku62a7e20k53bpvu91&topic=8783.0;all
CC-MAIN-2017-34
refinedweb
392
70.94
It’s just data As a human reading the feed, I thought it was pretty obvious what it meant, but I am not convinced this is significant. Programs that read feeds need to understand it and that would require a level of cooperation that seems to be missing from RSS.Posted by Bruce Loebrich at The point was that one of Dave's fundamental principles for RSS 2.0 is that you should be able to understand what an element is just by looking at it, i.e. that the meaning of elements should be self-evident. FWIW, I agree with this principle, but different people may have very different views on what's self-evident. It's difficult for me to judge this sort of thing, since I've been mired in XML syntax for years. As have most of the people who are participating in this discussion. We talk about the "average user". I want to hear from some. Well, I figured it out, but I've been watching the action as it unfolded, so I probably shouldn't be included in the sample. The meaning doesn't exactly leap to the eye, I must admit. That makes a lot of sense. I'm pretty sure I fall into the "average user" category. I can't imagine it is anything but self-evident as a first guess to anybody that has had even a brief introduction to RSS.Posted by Bruce Loebrich at Dorothea, with all due respect, you are a markup goddess. Your opinion is always most welcome, but you're not a representative sample of the population we're trying to test here.Posted by Mark at Seemed pretty straightforward to interpret from my perspective. I don't run screaming from the room when I see something that resembles code, but otherwise I would rate myself as an "average user" in this context (or "above average" if we're talking about Lake Woebegon).Posted by Jim McGee at I guessed correctly, having read Mark's example first and then clicked through to the other things he linked. I'm ok with XML and have been reading many of Mark's posts about RSS, so I don't know if I'm an "average" enough user or not. Are you looking for non-technical people, or just people who aren't "geeky" enough to have signed up for the RSS listserve? Jason PS: I love you geeks who have signed up for it, because you guys do all the hard work and I reap the rewards by just pasting the RSS templates that people like Mark write into my Movable Type templates panel and save them. Oh, and I'm a geek to, just not an RSS Geek. Yes. Useful. Makes sense. I just threw my feed into the root of my site (and others do I'm sure). One day I will move it and.. yes yes.. especially useful for blogfolk who move to a TLD. Exactly.Posted by why the lucky stiff at I am familiar w/ XML and namespaces, and I have a rudimentary understanding of the purpose and constructs of RDF. Given all those things, I thought the purpose was obvious. Of course, a high percentage of RSS feeders (and certainly a higher percentage of the web-going populace) wouldn't have that previous knowledge to go on. I'm comfortable with HTML and CSS, but I've never touched RSS. I figured it out.Posted by Stephanie at I had to read it over twice, but did indeed figure out what it means within 45 seconds (and I haven't looked at a lot of RSS). Interesting how our eyes process URLs -- I initially was convinced that both of the URLs were the same. Michael: yeah, Bill had the same problem. I could have picked a better example (Sam's URLs for instance, which are quite different), but this is a real-life scenario. I really did have a weblog at weblogger.com before I moved to my own domain, and when I moved, people really did complain about having to update their subscriptions manually.Posted by Mark at I indeed made the mistake of misreading the two URLs. The question of being able to look at an element and understand it's purpose seems tempting. On one level it's perhaps even compelling. But what happens when you later determine your overly simplistic naming of the element impairs it's growth? NewLocation? What's new about it? What's next, OldLocation? It's just a location and it might have modifying attributes on it. Thus anything looking for locations (resources) can find all occurences of resources and THEN decide about understanding the modifiers. The modifiers could be even more detailed than what I've suggested here. Attributes for checksum, signing, labelling and who knows what else could be associated with this resource URL. T he delightful advantage to a framework is you don't have to jam it all into this particular element. You could, if you wanted, put additional modifiers in other Description element(s) and build from there. If your application doesn't care about building more data on top of the resource URL then fine, just ignore it; that's the way XML works. But if it does, well, using a framework would help avoid painting yourself into various corners. The RDF folks have put a lot of thinking into their work. And from the mailing list archives it's apparent they've already wrestled with many of these issues and have gotten themselves both into and back out of a lot of 'painted corners' along the way. As Jason points out, it's nice to be able to make use of the efforts from other standards. I agree with Bill here. This syntax is not the "simplest" syntax possible, in the sense that you *could* accomplish the same short-term goal with fewer bytes. But it does build on some good prior art. The RSS community has not totally standardized on this sort of syntax (there are some examples in older modules where a URL was not put into rdf:resource, but it appears that these were growing pains and/or simple mistakes, and are being corrected), but I think that's the direction the community is moving, and I think standardizing on these sorts of rules helps everybody. Future RSS module developers will appreciate it if we can hammer out this stuff now and write up a "So you want to write an RSS module" intro guide. That said, this experiment was a kind of reality check. Standardizing on a syntax that is *too* complex helps no one. I wanted to see if this syntax was too complicated for non-RSS-geeks to grok. Based on comments so far, it seems that this syntax is not too complex. Normal people seem to get it just by looking at it. That's a good thing. I've looked at RSS a little, but I've never spent much time with it. I figured it out.Posted by Jeff at Is this actually the usability test you need to do? I wouldn't think that human-parsing of a correctly written element would be nearly as important as sitting someone down with the documentation and a test situation ('your old feed is here, in this format, your new feed is here, in this format, you (can|can't) edit .htaccess on the old server, what do you put where?') and seeing what they produce. One hopes Bill's backward attributes in 7.3 and 7.4 won't turn out to be a common error.Posted by Phil Ringnalda at It seems pretty straightforward. I thought to myself: "Oh, it's a kind of a redirect so that the subscriber gets the RSS feed from diveintomark.org instead of the weblogger address." And I know very little about RSS syntax.Posted by Jonathon Delacour at Phil, this is a reaction to D has stated that RDF is too hard for users to understand, and has therefore come to the conclusion that we can not use any syntax that looks remotely like RDF. I state it this way because this *is not RDF*. RDF is a complex integrated framework of semantic statements. This is the letters "r", "d", and "f" in an attribute of an element. The presence of those letters does not appear to cause normal users to flee the scene screaming. The advantage of using the letters "r", "d", and "f" in this way is that developers who *do* care about RDF can use this *exact same syntax* in their documents. Then RDF-aware news aggregators (of which there are, um, none, at least not in the end user space, but there are some private parsers that people have built, and who knows, maybe there will be more in the future) -- anyway, RDF-aware parsers can do whatever it is they do. Meanwhile, non-RDF-aware aggregators (which would be, um, everyone) can parse this syntax just fine, and they won't have to support 2 different syntaxes (one for RSS 1.0, one for RSS 2.0) that really just accomplish the same thing. The point of adding namespaces to RSS 2.0 was *so we take advantage of this work* that has already been done by others. It's good work. It's prior art. Respect it. That doesn't mean "you have to do it the RDF way" all the time, but if there's a good case for using syntax that RDF people could accept verbatim, and that syntax doesn't cause people to run screaming from the room, then we should use it. Posted by Mark Um, that was supposed to be "Dave", not "D". I assume we can figure that out. Phil, to your other point: people will learn how to do this by (a) reading a HOWTO document that gives examples, or (b) looking at a feed that already does it. Most likely (b). This is why I phrased my example the way I did, because it mimics real-world learning conditions. If, for instance, I had written my own RSS parser (which knows nothing of RSS redirection) and was subscribing to diveintomark.weblogger.com/xml/rss.xml and one day the updates stopped coming, I would go to the feed manually and try to find out what happened. At that moment, the syntax must be instantly understandable and human-readable. These requirements are important, and often ignored by developers. Dave keeps hammering on this point, and he's absolutely right. Syntax that isn't understandable by humans is worse than worthless, it's cruel. At that crucial moment when things go wrong, it taunts them with the knowledge that something important is being said, but they're too fucking stupid to figure out what it is. Judging by the comments left here by others, I think we've established that this syntax satisfies these important requirements. Normal people looked at it and said "hey, I bet the feed moved over there". And they were right. > but you're not a representative sample > of the population we're trying to test > here. I'm sure it's a representative sample of the population who is reading Mark's weblog *and* paying attention to posts about odd technical things like this. :-) FWIW, I thought the example was very obvious. - ask I thought I had worked out correctly what it meant, and I was right, but I wouldn't necessarily say that it was obvious; the "admin:feedLink" bit confused me slightly. Still, I think that anyone who is going to actually be reading RDF files at all, as opposed to using them to subscribe to a feed but not knowing anything about them, will be able to work it out.Posted by sil at Mark, hopefully you'll forgive me if I don't promote the letters R, D and F, which I think stand for Reality, Distortion and Field.Posted by Dave Winer at I am comfortable with CSS and HTML and programming and Unix system administration, but have never seen an RSS feed. I figured it out easily enough. The point about closing the loop using both isReplacedBy and replaces is a good one -- I'd very happily delegate that decision to an aggregator, if the switchover were properly logged somewhere so I could go find out what happened if something breaks.Posted by Peter Herndon at I'm another "RSS output comes free with MT, so I may as well play with it" type. The syntax is obvious enough. Not being an RDF holy-warrior, however, I'll toss out a couple (perhaps obvious) questions/suggestions. Is there some reason that one couldn't come up with human readable comments embedded in the XML instead of trying to make everything human-readable (commendable, but perhaps impossible). While we're fixing inabilities of the average blogger to do server-based functions, how about some way to embed referer and logging in their feed? Most bloggers don't have access to "real" web logs and use a logging service like extremetracking.com for their sites. Knowing who is pulling a RSS feed and how often shouldn't be any harder. Mark Pilgrim's suggestion of an RSS redirect that allows folks who don't have the ability to do .htaccess sorts of... [more] Trackback from Way.Nu I'm no RSS holy-warrior, but the example seemed very straightforward. Is there a reason that embedding a human-readable comments element inside RSS is anathema? While you're solving problems such as redirects that the average blogger can't fix without some server expertise, how about some mechanism for tracking RSS feed usage? I'm currently grepping my server logs to see how many people pull my RSS (too lazy to install a log tracking tool when a server-based tool like extremetracking.com is so easy to use). Heh. Ask identifies the narrow population sample in this test :-) Looks pretty straightforward though: "This thing here is replaced by that thing there." <doSomething>withThatThing</doSomething> seems simple because we've become used to markup. Speaking of usability testing, Sam, after the 29th comment is submitted, there's an issue. Here's what I see: click submit; form submits; I'm returned to; comment does not appear in. Posted by Will Cox Hi! Hello Mark, miss me yet? I've been reading Mark's weblog, and I thought I'd throw my two cents in. I have yet to even bother to dive into XML or RSS. Hell I barely even know what RSS is, other than its some kind method for news aggregators to read websites... what the hell is a news aggregator? I'd like to think I'm pretty damn good with SQL but since I know nothing about XML, I think I qualify as an average user. Well, maybe even a novice. Anyway. I looked at this code fragment Mark gave out. Okay, correct me if I'm wrong, but it looks like your are redirecting or replacing one RSS feed with another RSS feed right? Particularly one that is outdated because its not an updated resource. Is this newbie right? Did I give you what you want? Hope I helped. I thought it was rather obvious, also. To me, this means a number of possibilities are true: 1. Computers will never get it - not complicated enough. 2. Computers will get it - They're controlled by people, and people can get it. 3. People will never get it - too obvious. 4. People will get it - only geeks want to make things more complicated than they are. 5. I'm not part of the "average users" - I understand HTML, CSS, and can hack a Perl program that someone else gave me, so RSS shouldn't be a problem. 6. I am an average user - I know nothing about XML or RSS (questioning how to spell them on many occasions), use the web only for email and HTTP content, and enjoy reading more than creating. 7. I shouldn't have posted this comment. I figured it out, and I have barely scratched XML. I had to look twice to see the difference between URLs, but it was pretty straightforward once I saw it. I'm a knowledgeable computer user, but about as average as you can get for XML stuff, so there's one for the sample.Posted by Dave M. at Yes, the example is understandable (however, I've been following the topic over the last week, so I'm not very representative), but it is quite ugly. A tag citing 3 different namespaces? It reminds me of Microsoft Word 2000's HTML output. It makes a human programmer looking at it think he needs to learn 3 new schemas. So, if the real meaning of "rdf:" here in the context of RSS2 is "the letters r, d and f", you're not making the implementer feel dumb: you're actually lying to him. - Dotan Seemed straightforward to me as an average user-who-happens-to-be-a programmer-but-is-not-involved-enough-in-this-particular-domain-to-comment-substantively. Just in case that's the demographic you were worried about. :-)Posted by Larry O'Brien at I do know HTML. I don't really know anything about RSS. That "isReplacedBy=" is a pretty obvious giveaway for anyone who can read English, though.Posted by Adam Rice at
http://www.intertwingly.net/blog/922.html
crawl-002
refinedweb
2,940
72.46
Homework Homework Questions? Ask a Tutor for Answers ASAP I have an hour left; 1. (TCO 4) What is the bit pattern in data after the following statements execute?unsigned int data = 10;data = data | 0x0B;data = data << 1; (Points : 7) 0x314 0x154 0x342 0x1562. (TCO 4) What is the value of data after the following code executes?unsigned char data = 0xA5;data = data & 0xF0; (Points : 7) 0xA0 0xF0 0xF5 0x5A3. (TCO 4) What is wrong with the following switch statement?switch(x){case 0:cout << x;case 2:cout << 2 / x;break;default:cout << “error”;break;} (Points : 7) The value of x could be something other than 1 or 2. There is no break statement for case 1. There is no semicolon after the closing bracket. All of the above4. (TCO 4) A variable declared before and outside all function blocks (Points : 7) is visible only in main. is visible to all functions. is visible to all functions except main. is not visible to any functions.5. (TCO 4) C++ selection statements include(Points : 7) for, while, do-while. cout and cin. if, if-else, if-else if, switch. #include and using namespace std;.6. (TCO 4) Which operation in the following expression will be performed first?c = a++ / b + 5; (Points : 7) a a/b assignment to c b + 57. (TCO 4) How many elements does the following array contain?double data [100] [500]; (Points : 7) 500 100 600 50,0008. (TCO 4) The code below computes the length of a C-style string. What should the value of FLAG be?char name[20]= "Lancilot";int length=0;while(name[length] != FLAG){length = length+1;}cout << length << endl; (Points : 7) ‘\0’20 NULL 09. (TCO 4) Given the following code to fill an array,int;int data[100];for(int i = 0; i <= X; i++) data = i;what should the value of X be? (Points : 7) 100 101 99 i10. (TCO 4) Given the following code fragment, what is the data type of thisStudent?struct student{string name;double gpa;};student thisStudent; (Points : 7) string const pointer to student student double11. (TCO 4) Which of the following is an invalid declaration to overload the following function?double foo(int); (Points : 7) double foo(double); int foo(int); double foo(double *): double foo(int *);12. (TCO 4) Which of the following statements call the following function correctly? int MultiplyValues (int, int); (Points : 7) int a = MultiplyValues (int x, int y); int a = MultiplyValues (10, 20); double d = MultiplyValues (int 10, int 20); All of the above13. (TCO 4) What is the output of the following code?void func(int x[ ]){x[0] = x[0] * 3;x[1[ = x[1] * 3;x[2] = x[2] * 3;}void main (){int x[ ] = {1, 2, 3};func(x);cout << x[0] << “ “ << x[1] << “ “ << x[2] << endl;} (Points : 7) 1 2 3 3 4 5 3 6 9 3 3 314. (TCO 4) Which of the following function definitions uses pass-by-values? (Points : 7) int myFunc( int * x, int * y ); int myFunc( int x, int y ) ; int myFunc( int & x, int & y ) ; int myFunc( int @ value1, int @ value2 ) ;15. (TCO 4) Which of the following is called automatically each time an object is created? (Points : 7) Compiler Builder Constructor Destructor16. (TCO 4) Creating one class from another in a parent/child hierarchy is an example of (Points : 7) encapsulation. polymorphism. inheritance. abstraction.17. (TCO 4) A Distance class has two private members, ‘feet’, of type int, and ‘inches’, of type double. Which prototype correctly declares the copy constructor for such class? (Points : 7) Distance Distance(const Distance &); Distance(const Distance &); int Distance(int, double); Distance(feet, inches);18. (TCO 4) Composition is typically an example of (Points : 7) a “has a” relationship. an “is a” relationship. a “uses a” relationship. a “is used” relationship.19. (TCO 4) What is the name of a member function of a class that only accesses the value(s) of member variable(s) and does not modify the value(s)? (Points : 7) Set Private Member Accessor20. (TCO 4) A derived class is typically an example of (Points : 7) a “has a” relationship. an “is a” relationship. a “uses a” relationship. a “is used” relationship.21. (TCO 4) When writing a class, the compiler automatically creates some support functions for the class. What are some of these functions? (Points : 7) Assignment operator function Copy constructo Assignment operator and copy constructor None of the above 22. (TCO 4) Given the definition of some class called Employee, which of the following correctly dynamically allocates an array of 20 Employee objects? Employee * myData = new Employee[20]; Employee myData[20] = new Employee[20]; Employee = myData[20]; Employee array = new Employee[20]; 23. What is the output of the following code snippet?int value = 10;int * iptr = &value;*iptr = 5;Cout << *iptr << “ “ << value; 5 5 10 10 5 10 10 5 24. What is the output of the following code snippet?int *p;int *q;p = new int;*p = 43;q = p;*q = 52;p = new int;*p = 78;q = new int;*q = *p;cout << *p << " " << *q << end1 4352 5278 7878 7852
http://www.justanswer.com/homework/7f7j1-1-tco-4-bit-pattern-data-following.html
CC-MAIN-2017-22
refinedweb
858
67.96
Usually attributes of your Angular controllers are not namespaced. But you can namespace them. But you might not want to. Angular Controllers Usually Attach Attributes to Scope Usually attributes in an Angular controller, such as functions and variables, are attached to the $scope object. That looks like this: angular.module('myapp').controller 'MyCtrl', ($scope) -> $scope.myVar = 'myVal' $scope.myFn = -> console.log 'does stuff' Then in my template I don’t know, nor do I need to know, where the attribute comes from. I just reference it in my-app.jade: html(ng-app="myapp") body(ng-controller="MyCtrl") h1 My Var: {{myVar}} button(ng-click="myFun()") Does Stuff Namespaced Angular Controller Attributes In this simple example, this is no big deal. But as your app grows in complexity with many, nested controllers and templates, it can become difficult to read the code. If you have common function names, it might be hard to tell which controller’s function is referenced in your templates. To make this less of a problem and the code more clear, you might namespace your controller attributes in the template. To do this, you can write your controllers to attach attributes to the controller instead of scope and then put the controller itself on scope. That looks like this: angular.module('myapp').controller 'MyCtrl', ($scope) -> @myVar = 'myVal' @myFn = -> console.log 'does stuff' $scope.MyCtrl = @ Then your template changes to look like this: html(ng-app="myapp") body(ng-controller="MyCtrl") h1 My Var: {{MyCtrl.myVar}} button(ng-click="MyCtrl.myFun()") Does Stuff It’s kind of nice for the reasons stated above. I saw this strategy referenced on the Interwebs at one point and thought it seemed like a good idea. Why You Might Avoid This Maybe you love the idea. Maybe you don’t. I thought I did. I have been writing controllers this way for a while. Now I don’t. Here’s why: 1. It Makes Templates Less Reusable It’s quite probable that I’ll have templates that I don’t want permanently attached to a specific controller. An example I ran into recently was on a profile page. I had two pages to show profiles: one for my profile and one for an arbitrary person in the system. They looked the same in the UI. They had the same basic functions. But the source of data for the variables and the implementation of the functions was different in the two scenarios. Thus, I had to refactor to remove the namespacing to be able to reuse the template across pages. 2. It’s More Typing It’s silly. It adds up. The less superfluous typing I can do, the more I consider that solution. 3. The Creators Don’t Do It I haven’t seen this strategy featured in official tutorials, guides, or API examples. Not that the Angular d00ds have all the ideas or do everything right – it just isn’t a pattern I see widely accepted or used. These days, I don’t namespace my controller attributes, and I don’t recommend it. So what do you think? Do you write your controllers this way? Good idea? Bad idea? What are some alternative methods you’ve found to balance template reuse with readability?
https://jaketrent.com/post/namespacing-angular-controller-attributes
CC-MAIN-2021-04
refinedweb
543
68.06
import flash movie into asp.net Discussion in 'ASP .Net' started by bushi, May 25, 2007. Another flash question - jpegs in flash movie acting oddly.Jim Higson, Sep 21, 2004, in forum: HTML - Replies: - 1 - Views: - 693 - Jim Higson - Sep 21, 2004 Flash movie in c# asp.net (aspx) file help...trint, May 14, 2007, in forum: ASP .Net - Replies: - 6 - Views: - 893 - Alexey Smirnov - May 14, 2007 Problem with Flash Movie not loading in ASP page.MN, Feb 16, 2005, in forum: ASP General - Replies: - 3 - Views: - 248 - Bob Barrows [MVP] - Feb 16, 2005 Preloading a movie while playing another movie, Oct 11, 2005, in forum: Javascript - Replies: - 3 - Views: - 267 - Jambalaya - Oct 12, 2005
http://www.thecodingforums.com/threads/import-flash-movie-into-asp-net.509444/
CC-MAIN-2015-48
refinedweb
116
84.37
Whenever we compile any code, the output that we get is an executable file, which we generally don’t bother about. We execute it on our desired target. If it is an embedded system, we flash it to the target device and run it. Usually, this executable file is the ELF (Executable and Linkable Format) file. In this article we will analyse the compilation process as well as ELF. To begin with, there are many compilation stages so let us look at them more closely. Compilation stages To understand the stages of compilation, let us write a simple program and compile it. For compilation purposes, we will use the GCC open source compiler. So, let us consider a file study.c that contains the following program: #include <stdio.h> #define NUMBER_1 1 #define NUMBER_2 2 int main(void) { int a,b,c; a = NUMBER_1; b = NUMBER_2; c = a + b; printf("Output: %d\r\n", c); return 0; } We use the following command to compile this study.c programming file: gcc study.c -o study Note: GCC or other tools mentioned in this article need to be installed before they are used. The above command compiles ‘study.c’ and produces an executable file,‘study’. Type the following command to see the file type of this executable: file study Output: study: ELF 64-bit LSB shared object, x86-64 From the output, it can be seen that the file format of the executable study is ELF. What GCC has done is, it has passed study.c through the following stages of compilation to convert the study.c file to a final executable: - Pre-processing - Compiling (assembly file creation) - Assembler (object file creation) - Linking (links all object files to create an executable) So, let’s explore each stage to understand how each process works in compilation. Pre-processing This is the first stage of compilation in which the source code is processed. The following high-level tasks are done at the pre-processing stage: - Removal of comments from source code - Expanding #include files - Macro expansion - Conditional compilation Now let’s try to pre-processed our study.c file and look at its output. The following is the command by which we can restrict the compiler to just pre-process the study.c file and generate the pre-processed file instead of the executable: gcc -E study.c -o study.i Here, study.i is the pre-processed file. Open the study.i file, and you should see the following contents: [lines omitted for brevity] extern void funlockfile (FILE *__stream) __attribute__ ((__nothrow__ , __leaf__)); # 868 "/usr/include/stdio.h" 3 4 # 2 "study.c" 2 # 6 "study.c" int main(void) { int a,b,c; a = 1; b = 2; c = a + b; printf("Output: %d\r\n", c); return 0 } From the study.i file, it can be seen that the statement #include <stdio.h> has been replaced by the contents of the stdio.h file. Macros NUMBER_1 and NUMBER_2 are not present in the output. Besides, wherever these macros were used, their values are replaced by macro values. So a = NUMBER_1 is replaced by a = 1. In this compilation stage, any line that starts with # is interpreted as a pre-processing command. These commands have their own language format (which is not discussed in detail here since online sources describe it in detail). Note: Try to write different macros and conditional compilation commands in the code, then run the provided pre-processing command and see the output in order to understand pre-processing in detail. Compilation What this stage is called is confusing, as it converts pre-processed code into assembly code. In this stage, all programming symbols are converted to assembly instructions, which are native to the target processor architecture. This is also the stage where inline assembly code in high-level programming languages is processed. Now let’s compile our study.c file and produce the equivalent assembly instruction file. The following command restricts the compiler to convert the study.c file to an assembly file. gcc -S study.c -fverbose-asm -o study.s After running the above command, open the study.s file, which contains the assembly equivalent of the program. This file will also show assembly code generated for each line of C code that we have written. Using this, you can understand how assembly instructions and C programming syntax are related. Note: Modify the above program and run the above command to see how assembly instructions are generated for different C syntaxes. Assembling This stage is used to convert assembly instructions to machine code or object code. This object code is the actual machine instructions that run on the target processor. This is the first stage in which the ELF file is generated. The output file is known as an object file which has an extension .o and has the file format ELF. This file cannot be directly executed, but needs to be linked using Linker, which is the final stage of compilation. To convert our study.c file to an object file, we will use the following command: gcc -c study.c -o study.o study.o cannot be directly opened as it is a binary file. To open this file, we can use binary utilities. ELF files and binary utilities To understand the final stage of compilation, which is linking, and to visualise how ELF files are structured, we need to understand object files, particularly ELF files. We were able to generate object files in the previous stage, but we were not able to open them. To open this file, we need to understand the structure of an object file. ELF object files contain five kinds of information: - ELF header - Section header and different sections - Program header and different program sections - Object code - Debugging information ELF header All ELF object files start with the ELF header. It is in binary but has the following data structure format: # define EI_NIDENT 16: This variable marks the file as an ELF object file and provides information about the object file. e_type: This member determines the object file type. e_machine: This member specifies the architecture for which this ELF is compiled. e_version: This member provides information about the version of the ELF object file. e_entry: This is the entry point or the start address of the program. e_phoff: This member provides offset from the ELF header at which the program header is present. e_shoff: This member provides offset from the ELF header at which the section header is present. e_flags: This member holds processor specific tags. e_ehsize: This member holds the ELF header size in bytes. e_phentsize: This member holds the size in bytes of one entry in the file’s program header table. e_phnum: This member holds the number of entries in the program header table. e_shentsize: This member holds a section header’s size in bytes. e_shnum: This member holds the number of entries in the section header table. To read the ELF header of our object file,‘study’, we will use a binary utility tool called readelf. The following is the command to read the ELF header of any object file: readelf -h study The output is seen in Figure 1. As can be seen from the ELF header, the object file format is ELF64. The object file is Little Endian. The ELF file is built for an x86-64 bit machine. There are two important pieces of information present in the ELF header. One is the ELF program header part and the other is the ELF section header part. ELF sections When a program is compiled, different things are generated after compilation. I have grouped these into raw groups as shown below: - Binary executable code - Code for initialised variables - Code for uninitialised variables - Constant strings - Information about the variable and function names used in the program - Debugging information There could be other information but I will only discuss what has been mentioned here. These groups are combined and they are provided specific names. Compilers generally have common names for these mentioned groups. All binary executable code goes into the .text section, all initialised variables are grouped in the .data section, all uninitialised variables are grouped in the .bss section, all constant strings are grouped in .shstrtab section, all variable and function names go in .symtab (which is called the symbol table) and all debug information is grouped in the .debug section. All this information is put in the section part of the ELF file. The location of the section header in an ELF file is provided by the e_shoff variable, which is present in the ELF header. e_shoff provides the offset at which the ELF section header is present in the ELF file. e_shnum is the number of section header entries in the ELF file and the size of each entry is e_shentsize. Use the following command to see all the sections that are present in our study.c example: readelf -S study From the output, it can be seen that there are .text, .data, .bss, .symtab and .shstrtab sections. To check the code that is present in .text, use the following command: objdump -d study This will dump all the code that is present in our study.c example. Try experimenting with objdump, hd and readelf commands to analyse each section of the ELF file. Modify the program, compile it and see how different information in the section changes. So how does the compiler come to know where to put each section in the final ELF. This is where the linker comes in. Linkers use a file known as the linker descriptor file. This contains information about all the memory in the target machine (Flash, RAM, QSPI, SDRAM, etc) with its starting address and size. It also contains information about the different sections that should be present in the final ELF file and where each section should be loaded in the target machine. The following is a simple linker descriptor file: MEMORY { FLASH (rx) : ORIGIN = 0x0, LENGTH = 0x020 RAM (rwx) : ORIGIN = 0xA0, LENGTH = 0x00A0000 /* 640K */ } ENTRY(Reset_Handler) SECTIONS { . = 0x0000; .text : { *(.text) } . = 0xA0; .data : { *(.data) } .bss : { *(.bss) } } The above linker script file informs linker about the following: - The system has two memories — Flash and RAM. - Put all executable code that is present in the .text section at the address 0x00000 in the target machine. - Put all data (.data and .bss) starting at address 0xA0. ELF program header The program header in the ELF specifies which section of the ELF file goes to a particular memory location. The program header location in the ELF file is provided by the e_phoff variable present in the ELF header. e_phoff provides the offset at which the ELF program header is present in the ELF file. e_phnum is the number of program header entries in the ELF file and the size of each entry is e_phentsize. Use the following command to see the program header information of our study.c example: readelf -l study Linker This is the final stage of compilation. In this stage, the final executable ELF is generated. Linker takes all object files generated for each programming file in previous stages as inputs. It also takes a linker descriptor file as input. Linker combines sections from all object files into one final ELF. It instructs the linker descriptor file as to what addresses are to be provided for each section. It also resolves the symbols used by each object file. If any symbol is not defined, then linker gives an error. These are the stages by which a final executable is generated. In the case of ARM and other microcontroller platforms, Hex files are present. These are generated from ELF files using the following command: objcopy -O -ihex study study.hex Program execution If you execute any C program, then main() is always the entry point. This is because a startup code is always linked to your original program by linker. This startup code consists of a startup function, which usually is __start or Reset_handler. This is placed at the address that the processor will execute at boot. This function calls the main() function, which is the starting point of the application. Generally, in embedded systems, there is a startup.s file which contains a vector table where the Reset_Handler function is placed, which the controller executes at startup. This Reset_Handler will copy all initialised variables to RAM, and then initialise all the memory used by the BSS section to zero. This Reset_Handler will then call the main() function. This is how an application is compiled and executed.
https://www.opensourceforu.com/2020/02/understanding-elf-the-executable-and-linkable-format/
CC-MAIN-2022-21
refinedweb
2,100
65.83
I'm trying to test some of my custom tools, written for a ArcCatalog python addin. This is my first attempt to use Pro, without the convenience and the power we have with ArcCatalog (but hoping the idea: Add Stand Alone Data Catalog Like ArcCatalog to ArcGIS Pro will still happen so that this isn't as critical a test ....please vote up the idea! ). I have several blahUtils.py type scripts to separate/organize my common functions. These are located in my Scripts folder in my addin file structure and I import into my tools/scripts using from blahUtils import * from moreBlahUtils import * # etc... rather than in a library in the python folder....that is, keep the addin all together. This structure works well in ArcCatalog running is as an built/installed addin or from the Toolbox/Tool used to create the addin. Putting aside the differences between Python 2.x and 3.x for the time being, how would I import the utility python scripts within my main tool script? I have read thru Importing ArcPy—ArcPy Get Started | ArcGIS Desktop and Python migration from 10.x to ArcGIS Pro—ArcPy Get Started | ArcGIS Desktop (no, I have not run the 2to3 tool yet) but those seem to refer to fairly standard modules. I would like to keep my scripts in the folder structure for my toolbox (i.e. the addin structure) if possible. The error I am getting Traceback (most recent call last): File "\\<server>\c$\Users\<user>\_MyPyAddins\dwcUpdateMasterFGDB\Install\scripts\01-CopyDWCMasterSDEtoFGDB.py", line 47, in <module> from ADFGUtils import * File "\\<server>\c$\Users\<user>\_MyPyAddins\dwcUpdateMasterFGDB\Install\scripts\ADFGUtils.py", line 134 self.__dict__ = self""" ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 188-189: truncated \UXXXXXXXX escape Failed to execute (01-CopyDWCMasterSDEtoFGDB). Is basically telling me it can not find the first custom script from ADFGutils import * I am trying to import. Any suggestions on where I need to put these and how I would refer to them? Again, I prefer to keep in the same folder with/near my toolbox. Thanks. tagging Python Python AddIns For the purposes of closing this thread, below is one way to add a single custom mod which is stored in same folder as the script that is running. This is how my python addins are setup, so that is what I am testing. Posting here in case others are trying to do the same. I will start another post with this as a starting point, but hopefully to make it a bit more dynamic. (I will come back and add a link to that once posted.) This is a cut and paste from a large working tool...if something doesn't make sense, let me know... hope this is helpful to someone.
https://community.esri.com/thread/193592-import-custom-arcpy-modules-in-pro-14-from-python-addin-structure
CC-MAIN-2019-13
refinedweb
469
65.93
I'm trying to write a vending machine program so far I've been able to do everything except add drinks. Code: public class VM{ public VM(int price) { Cost= Price; String vend [][] = new String [2][2]; drinks= new ArrayList(); } } I'm trying to write addDrink() method, but have not been able to. I'm trying to use something like drink.add(new vend(Drink_variable)), but haven't been able to. I've been reading many books but all the examples there write something else. e.g.drink.add(new vend(price p)). Its driving me mad. I have no where to turn to. Reading books are not helping. I have no one I can ask help for. People just don't care. Probably this post that I'm writing right now will be of no use, since I won't get any useful feedback. It's easy to say write a for loop, declare an object, write a class for this or that. But I haven't been able to implement this. If I could see at least a similar example may I can learn something. I don't know how I can add an item to an array. So everytime I call the addDrink method the list of Drinks in the array should increase. So when I display them I can see a list of the drinks I've added. And also, I should be able to determine its price and slot(eg A1) when adding. If someone can write an example of just the add method to a vending machine that will be very helpful. I can send you the full code that I have done so far if you want. I would appreciate any feedback. Regards, John public class VM{ public VM(int price) { Cost= Price; String vend [][] = new String [2][2]; drinks= new ArrayList(); } } How are you representing the drink objects? I assume you would have an instance of a class or a structure which has a price and slot component Use a vector rather than an array for each of your slots ... it grows ... you can query its size, you can use the Vector class' add and remove methods, etc. Forum Rules Development Centers -- Android Development Center -- Cloud Development Project Center -- HTML5 Development Center -- Windows Mobile Development Center
http://forums.devx.com/showthread.php?164906-Java-Vending-Machine-Program&p=490759
CC-MAIN-2015-06
refinedweb
384
82.85
You already know what nested functions are. Closures can be viewed as the most useful application of nested functions. Before starting with closures, let’s talk a bit about nested functions. We know that a nested function is a function which is defined inside another function. Let’s look at a simple program having a nested function. def outer(x): def inner(): print(x) inner() outer("Hey there!") The function inner() is defined inside the function outer(), and so inner() is a nested function. We called outer() by passing "Hey there!" as the argument. Thus, its parameter x got the value "Hey there!". Since a nested function can access the variable defined in the function in which it is created, we printed the value of x inside the nested function inner(). Look at another example. def outer(x): def inner(): print("This is the inner function") return x return inner() print(outer("Hey there!")) The statement return inner() inside the outer() function calls the inner() function and returns the value returned by the inner() function. Inside the inner() function, the value of x is returned. So this was just a recap of nested functions. Let’s now talk about closures. Closures in Python In the last example, the outer() function returned the value returned by the nested inner() function. What if you want to return the entire functionality of the inner() function from the outer() function? Yes, we can do so by replacing return inner() by return inner in the outer() function. return inner() will call the inner() function and then return the value returned by the inner() function, whereas return inner will return the entire inner() function. This is demonstrated in the following example. def outer(x): def inner(): print("This is the inner function") print(x) return inner # returning inner function func = outer("Hey there!") print(type(func)) func() When the outer() function is called with the argument "Hey there!", it returns the inner() function instead of calling it. The returned inner() function is assigned to the variable func. Thus, func stores the inner() function and hence printing type(func) displayed <class 'function'>. Therefore, func now has all the functionalities of the inner() function and thus behaves as a function. On calling the function func(), the string "This is the inner function" and the value of x ("Hey there!") got printed. We got the same output which we would have got on calling inner(). But wait, x was a variable defined in the outer() function but the outer function has already finished executing, then how does func() remember the value of x? This is exactly what a closure does. A closure is a technique that binds (attaches) some data to the code. When the outer() function returned the inner() function, it attached the value of the variable x with the code of the inner() function and then returned the inner() function. Thus, we have a closure in the above program. This value attached to the code is remembered even when the function in which it was defined is no longer executing. Therefore, on calling func(), the value of x got printed even when the outer function was not getting executed, because the value of x is attached to the code returned by the outer() function and assigned to func. Hope you understood the concept of closures. Summing up, a closure is a technique in which a function returns its nested function after attaching some data (value of x in the above example) to the code of the nested function. This returned function is assigned to some variable ( func in the above example) which can be used to execute the code of the assigned function whenever called, while also remembering the data attached. In the above example, let’s see what would happen if we delete the outer() function after returning the inner() function. def outer(x): def inner(): print("This is the inner function") print(x) return inner # returning inner function func = outer("Hey there!") del outer # deleting outer function func() After assigning the returned inner() function to the variable func, the outer() function is deleted by writing del outer. Then on calling func(), we are still getting the output. So, even after deleting the original function, the returned function is still giving the output. Or, we can say that func() remembers the context (functionality, variables defined, etc) of the deleted function. Look at another example. def outer(): x = "Hey there!" def inner(): print("This is the inner function") print(x) return inner # returning inner function func = outer() func() This is similar to the previous examples. Here also, the inner() function is using the variable x defined inside the outside function. Let’s see another example in which a closure is used. def outer(x): def inner(y): print(x + y) return inner func = outer(10) func(5) Before reading the explanation, try to understand what is happening in this program. The outer() function is called by passing 10 as argument, making its parameter x equal to 10. It returns its nested function inner() and assigns it to the variable func. So, func stores the inner() function with x equal to 10. Then the func() function is called by passing 5 as argument by writing func(5), thus making its parameter y equal to 5. Inside the body of func(), the sum x + y is printed. We can also obtain the above result as follows. def outer(x): def inner(y): return x + y return inner func = outer(10) print(func(5)) In the next example, we are returning the sum of the elements of a list. def outer(): sum = 0 def inner(mylist): nonlocal sum for num in mylist: sum = sum + num return sum return inner # returning inner function func = outer() mylist = [1, 2, 3, 4, 5, 6] print(func(mylist)) Try to understand the above code yourself. If you have, that means you have understood closures. So we have seen different examples of closures. But when should we use closures? Let’s find the answer to it in the next section. Significance of Closures The first benefit of closures is that we can execute the functionality of the nested function anytime even after its outer function is not executing. When we have only one or two (preferably one) methods in a class, then also it is better to use closures instead of class. Assume that we have the following class with a single method print_message() inside it. class CreateMessage: def __init__(self, msg): self.msg = msg def print_message(self, name): print("Hi", name) print(self.msg) message = CreateMessage("Welcome to the Python course") print("Printing 1st message----") message.print_message("John") print("Printing 2nd message----") message.print_message("Sam") We created an object message of the class CreateMessage by passing the value "Welcome to the Python course" to the msg parameter of the constructor. Thus, in the constructor, self.msg = msg made the attribute msg equal to "Welcome to the Python course". Then we used the message object to call the print_message() method with different arguments every time. Note that we used a class here to store a single method print_message() because we also wanted to store some data (msg) which is used in the method. So according to you, is it a good decision to create a class for a single method just because we want to store some additional data? No, it isn’t. For such scenarios, we can use closures instead. Let’s see how. def create_message(msg): def print_message(name): print("Hi", name) print(msg) return print_message message = create_message("Welcome to the Python course") print("Printing 1st message----") message("John") print("Printing 2nd message----") message("Sam") We defined a function create_message() with a nested function print_message(). When the create_message() function is called, we create a closure by returning the nested function print_message() to a variable message. So, the variable message now stores the functionality of the function print_message() with the value of the variable msg as "Welcome to the Python course". Now whenever the function message() is called, it implements the functionality of print_inner(). We got the same result as in the previous example having class. Thus, we were able to use closures instead of class when it has just one method. Look at another example. class CreateMessage: def __init__(self, msg): self.msg = msg def print_message(self, name): print("Hi", name) print(self.msg) print("Object 1----") message1 = CreateMessage("Welcome to the Python course") print("Printing 1st message----") message1.print_message("John") print("Printing 2nd message----") message1.print_message("Sam") print("Object 2----") message2 = CreateMessage("Welcome to the C# course") print("Printing 1st message----") message2.print_message("Maria") print("Printing 2nd message----") message2.print_message("Peter") Suppose the students John and Sam want to learn Python and Maria and Peter want to learn C#. For that, in the above example, we created an object message1 with attribute msg equal to "Welcome to the Python course", and an object message2 with msg equal to "Welcome to the C# course". This can be implemented using closures as follows. def create_message(msg): def print_message(name): print("Hi", name) print(msg) return print_message print("Variable 1----") message1 = create_message("Welcome to the Python course") print("Printing 1st message----") message1("John") print("Printing 2nd message----") message1("Sam") print("Variable 2----") message2 = create_message("Welcome to the C# course") print("Printing 1st message----") message2("Maria") print("Printing 2nd message----") message2("Peter") Here the variables message1 and message2 store the code of the print_message() function with the values of msg equal to "Welcome to the Python course" and "Welcome to the C# course" respectively. If the number of methods or the number of attributes in a class increase, then go for class. But for a single method and a few attributes, using closures is a better option because it is faster. However, the choice is yours. Closures are also used for creating decorators. We will read about decorators in the next chapter. So this was all about closures. We looked at different examples of closures and also discussed its significance. Make yourself comfortable in closures by practicing more questions on it and feel free to ask your doubts in the discussion section.
https://www.codesdope.com/course/python-closures/
CC-MAIN-2022-40
refinedweb
1,696
64.51
The popularity of declarative markup languages has gradually increased since the initial release of HTML. This shouldn't come as a surprise to anyone given that markup languages let information be presented to end users without requiring any knowledge of a programming language. For years HTML has served as the declarative language of choice for presenting information to end users through a browser and it certainly isn't going anywhere in the near future. However, new declarative languages such as Extensible Application Markup Language (XAML) have emerged, providing an alternate means for displaying data in more rich and engaging ways than HTML is capable of doing. In this article, I introduce the XAML language and describe several ways it can be used in Silverlight applications. The topics covered will focus on functionality available in Silverlight 1.0. Future articles will introduce new XAML features available in Silverlight 2.0. What Is XAML? Extensible Application Markup Language (XAML) was originally created for the Windows Presentation Foundation (WPF) technology released with .NET 3.0. WPF and XAML provide a way to integrate designers into the application development process and create rich and interactive desktop (and even Web) applications that can bind to a variety of data sources. The release of Silverlight 1.0 brought XAML to the world of rich internet application development. Silverlight exposes a subset of the XAML language found in WPF that can be run directly in the browser once the Silverlight plug-in has been installed. So what exactly is XAML and why should you learn it? If you have any background in HTML, then you'll quickly learn that XAML is like HTML is many ways (although XAML follows the rules defined in the XML specification which means that it's stricter than standard HTML). For example, HTML relies heavily on <div> elements to position child objects. Although XAML doesn't provide a <div> element, other elements such as <Canvas> can be used to accomplish the same type of task. If you've already learned HTML then you'll find that learning XAML is similar although XAML is capable of doing many more things from animating and transforming objects to dynamically displaying shapes with custom gradients. HTML can only do so much on its own which is why additional features such as JavaScript on the client-side and dynamic programming languages on the server-side have been created over the years. In Silverlight, 1.0 XAML relies on JavaScript in cases where dynamic events need to be raised and handled. Silverlight 2.0 ups the ante by adding support for several languages including VB.NET and C#. Throughout the rest of this article I introduce several key aspects of XAML and demonstrate how you can use XAML elements and attributes in Silverlight applications. Handling Layout in Silverlight As mentioned previously, Silverlight 1.0 provides a Canvas element that acts as a container for child objects much like div elements act as containers in HTML. The Canvas element can be used to organize objects and define where and how the objects should be displayed. Silverlight 1.0 applications have a root Canvas element defined that includes a special XML namespace (see Listing One). This Canvas acts as the parent for all other objects placed into a Silverlight application. <Canvas xmlns=""> </Canvas> Additional Canvas elements can be nested inside of the root Canvas element as well. This is especially useful when your application has several different visual sections such as a header, content area and footer. By using different Canvas elements you can group related child controls quite easily. Listing Two shows an example of a nested Canvas element. <Canvas xmlns=""> <Canvas Canvas. <!-- Child content goes here --> </Canvas> </Canvas> Notice that it defines the height and width as well as where the child canvas should be positioned relative to its parent container. The Canvas.Left and Canvas.Top attributes are referred to as "attached properties" in the world of XAML programming. Their values are relative to the parent. In this case the child Canvas will be positioned 10 pixels from the left and 10 pixels from the top of the parent container. By using Canvas elements appropriately within a Silverlight application you can easily position shapes, media, and text, and show/hide groups of objects easily.
http://www.drdobbs.com/windows/getting-started-with-xaml-in-silverlight/206905307?pgno=1
CC-MAIN-2014-41
refinedweb
717
53.81
The only problem with hand picking the JARs you want or need from JWSDP is the license of course... Not that you cannot do it, you just have to be very careful you are not violating SUN's license. For the runtime, the JWSDP doc clearly states all the JARs that need to be redistributed for JAXB (not to run per se, but to obey the license terms). I was told people on the JAXB forums have asked for a separate JAXB redistributable pack, and that SUN was working on it... --DD -----Original Message----- From: Jacob Kjome [mailto:hoju@visi.com] Sent: Wednesday, April 02, 2003 1:25 PM To: Ant Users List Subject: RE: Anyone got any workaround ideas on the broken Jaxb stuff? Just a little update. The example I showed below was based on the JAXB beta. For the 1.0, you can make the following modifications without having to "conserve the JWSDP layout for this to work correctly" as Dominique mentioned.... Change: <jaxb destDir="${src.home}" readOnly="true" strictValidation="true" xjcjar="${web.home}/WEB-INF/jars/jaxb/jaxb-xjc.jar"> To: <jaxb destDir="${src.home}" readOnly="true" strictValidation="true"> <classpath refid="build.classpath" /> This assumes you have a directory in your build containing the jaxb-*.jar files + the jax-qname.jar file. You don't need to have any of the dom, sax, namespace, or xercesImpl jars in that directory nor do you have to add anything to the JAVA_HOME/jre/lib/endorsed directory (except for maybe xalan of which I have the latest version from the apache site in there currently). All this is already present in the default Ant environment. The only one I have a question about is the namespace jar of which I don't think the libraries are present in the default Ant environment? Not sure if the classes in that jar are not actually used by JAXB or if they just aren't used in compilation because the JAXB task is able to successfully compile schema's without it. Anyway, the reason for ignoring the classpath using the xjcjar was more apparent when using the JAXB beta because the xerces version it included clashed a bit with the xerces that came with JAXB. Doesn't seem to be a problem now because JAXB now works with the latest Xerces. Jake At 10:25 AM 4/2/2003 -0600, you wrote: >Additionally, this post by Dominque Devienne might help a bit... > > >And here are my targets using the JAXB task.... > > <!-- specify location of jar file in a properties file --> > <property name="jaxbtask.jar" > > > <path id="build.classpath"> > ... > ... > ... > <pathelement location="${jaxbtask.jar}"/> > <fileset > > <include name="jaxb-*.jar"/> > <include name="jax-qname.jar"/> > </fileset> > </path> > > <target name="compile.jaxb.task" depends="prepare" > > > <!-- Compile Java classes as necessary --> > <mkdir dir="${build.home}/WEB-INF/classes"/> > <javac > > <classpath> > <pathelement > > </classpath> > </javac> > > </target> > > <target name="jar.jaxb.task" depends="compile.jaxb.task" > > > <jar > > <fileset dir="${build.home}/WEB-INF/classes"> > <include name="com/lgc/buildmagic/**/*.class" /> > </fileset> > </jar> > > </target> > > <target name="jaxb" depends="jar.jaxb.task" > > > <taskdef > > <classpath refid="build.classpath" /> > </taskdef> > > <jaxb destDir="${src.home}" > > <schemas dir="${src.schema.home}" includes="**/*.xsd" /> > <!-- Custom mapper to deduce the target package name: > For example, schema com/lgc/infra/acme/doc-files/tools.xsd > yields package name com.lgc.infra.acme.generated.tools > --> > <targetPackageMapper type="regexp" > > </jaxb> > </target> > > <target name="clean.jaxb.generated"> > <delete includeEmptyDirs="true" quiet="true"> > <fileset dir="${src.home}" includes="**/generated/**" /> > </delete> > </target> > > > >This has been tested to work under Ant-1.5.1, Ant-1.5.2, and Ant-1.5.3beta. > >Jake > > >At 12:09 PM 4/2/2003 +0200, you wrote: >>I am using the alternative implementation from >> without any >>problems. >> >> > -----Original Message----- >> > From: webhiker [mailto:webhiker@tiscali.fr] >> > Sent: Wednesday, April 02, 2003 11:22 AM >> > To: Ant Users List >> > Subject: Anyone got any workaround ideas on the broken Jaxb stuff? >> > >> > >> > Just wondering if anyones found a decent fix for the silly parser >> > dependancies of the xjc task (com.sun.tools.xjc.XJCTask) >> > which requires >> > manually setting ANT_OPTS to contain a special >> > -Djava.endorsed.dirs to >> > find it's xalan.jar and xerces.jar rubbish. >> > >> > Is there no other way to set the endorsed dirs from within >> > the build.xml >> > file? I think the problem is from the fact that the xjc task >> > is in the >> > same JVM as Ant, and thus the endorsed dirs cannot be modified. >> > >> > I'd appreciate any intelligent workarounds. >> > >> > WH >> > >> > >> > --------------------------------------------------------------------- >> > To unsubscribe, e-mail: user-unsubscribe@ant.apache.org >> > For additional commands, e-mail: user-help@ant.apache.org >> > >> >> >>--------------------------------------------------------------------- >>To unsubscribe, e-mail: user-unsubscribe@ant.apache.org >>For additional commands, e-mail: user-help@ant.apache.org
http://mail-archives.apache.org/mod_mbox/ant-user/200304.mbox/%3CD44A54C298394F4E967EC8538B1E00F1D2BE16@lgchexch002.lgc.com%3E
CC-MAIN-2015-14
refinedweb
782
51.85
Monadic fixpoints. For a detailed discussion, see Levent Erkok's thesis, Value Recursion in Monadic Computations, Oregon Graduate Institute, 2002. class Monad m => MonadFix m where Source Monads having fixed points with a 'knot-tying' semantics. Instances of MonadFix should satisfy the following laws: mfix (return . h) = return (fix h) mfix (\x -> a >>= \y -> f x y) = a >>= \y -> mfix (\x -> f x y) mfix (liftM h . f) = liftM h (mfix (f . h)), for strict h. mfix (\x -> mfix (\y -> f x y)) = mfix (\x -> f x x) This class is used in the translation of the recursive do notation supported by GHC and Hugs. mfix :: (a -> m a) -> m a Source The fixed point of a monadic computation. mfix f executes the action f only once, with the eventual output fed back as the input. Hence f should not be strict, for then mfix f would diverge. fix :: (a -> a) -> a Source fix f is the least fixed point of the function f, i.e. the least defined x such that f x = x. For example, we can write the factorial function using direct recursion as >>> let fac n = if n <= 1 then 1 else n * fac (n-1) in fac 5 120 This uses the fact that Haskell’s let introduces recursive bindings. We can rewrite this definition using fix, >>> fix (\rec n -> if n <= 1 then 1 else n * rec (n-1)) 5 120 Instead of making a recursive call, we introduce a dummy parameter rec; when used within fix, this parameter then refers to fix' argument, hence the recursion is reintroduced. © The University of Glasgow and others Licensed under a BSD-style license (see top of the page).
https://docs.w3cub.com/haskell~8/libraries/base-4.12.0.0/control-monad-fix/
CC-MAIN-2020-24
refinedweb
282
69.82
debug - Perl pragma for debugging and logging of debug lines. package Foo; # start by embedding calls to # debug::log inside your module # of package. # use the pragma use debug; sub bar { # call debug::log if you have # something to say, but don't # forget "if DEBUG" debug::log("entering Foo::bar") if DEBUG; print "foo"; # you can also call it with the # object '->' syntax if you like. debug->log("leaving Foo::bar") if DEBUG; } 1; # then in your main script, you # can do one of the following things # use your module use Foo; # turn debug on for the Foo package (at compile-time) use debug qw(Foo); # you can also do it this way (at run-time) debug->on("Foo"); # now comes your code ... Foo::bar(); # your would then look like this: debug-log + entering Foo::bar foo debug-log + leaving Foo::bar The debug pragma provides a very simple way of turning on and off your debugging lines, as well as a very flexible way of logging those lines to literally anywhere you want. You need to register a module for debugging by placing use debug at the top of you module. Then you can embed calls to debug::log within your code making sure to surround them with conditional checks for the value of the DEBUG constant. See the SYNOPSIS section for an example. After that you can turn the debugging on and off from any other module or namespace. You can do this one of 2 ways: # compile-time way use debug qw(Foo Bar Baz); # add as many modules as you like # run-time way debug->on qw(Foo Bar Baz); # add as many modules as you like Now comes the debug log filters. If you do nothing else, your debug lines will look like the example in the SYNOPSIS section. But you can change that very easily. By changing the default log filter with (what else) the set_default_log_filter function. Here is an example: debug::set_default_log_filter(sub { print STDERR "debugging : ", @_ }); This will send all the debug::log calls to STDERR and prepend the string "debugging : " to them all. Any anyonomous subroutine or subroutine reference will do. But the default filter is not the only one you can change, you can also assign a specific filter for each package you are debugging. Here is an example: debug::set_log_filter(Foo => sub { print "Debugging Foo >> ", @_ }); This log filter will only be called from the Foo package. And just as you can add them, you can take them away. Use the remove_log_filter function. Again, an example: debug::remove_log_filter("Foo"); All debug::log calls in Foo will now go through the default log filter again. A debug log filter which prints the name of package it was called in. sub my_calling_package_filter { print "debugging -> ", (caller(1))[0], " : ", @_, "\n"; } debug->set_log_filter(Foo => \&my_calling_package_filter); A debug log filter to convert things to HTML. sub my_HTML_log_filter { # first we need to join the arguements into a single string my $output = join "" => @_; # then we replace any \n (newlines) with an HTML <BR> tag $output =~ s/\n/\<BR\>/g; # then we replace any tabs with 4 " "s $output =~ s/\t/\ \;\ \;\ \;\ \;/g; # then we wrap the output in <P> tags and return it return "<P>$output</P>"; } debug->set_log_filter(Foo => \&my_HTML_log_filter); A debug log filter which will print a basic date stamp. debug->set_log_filter(Foo => sub { "[" . localtime() . "]: ", @_ } ); Here is a filter which appends to a file. sub append_to_file { open LOG, ">>", "/tmp/debug.log"; print LOG "debug->log : ", @_; close LOG; } debug->set_log_filter(Foo => \&append_to_file); This will turn debugging on for all the packages given in the @packages arguement. This will turn debugging off for all the packages given in the @packages arguement. This will return true (1) if debugging is on for that module and false (0) otherwise. An array of strings and variables ( @statements) which will be logged. These values are fead through either the current default log filter or the one assigned specifically to the current package. The $log_filter argument is expected to be a subroutine reference, and if it is not, an exception is thrown. For information about how to create the log filters see the above sections. This assigns a specific $log_filter to a particular $package, from then on all debug-log()> calls from within that package will go through this filter. The $log_filter argument is expected to be a subroutine reference, and if it is not, an exception is thrown. For information about how to create the log filters see the above sections. This will remove the log filter for the specific $package, thereby returning it to using the default log filter. This module exports two functions: This is just a boolean flag, so that you can write: debug->log("This line should work") if DEBUG; This is a lazily loaded Data::Dumper::Dumper wrapper. Why? Well, to start with, someone suggested it to me (see ACKNOWLEDGEMENTS), and secondly I realized how many times I have done this: use Data::Dumper; debug->log(Dumper(\%strucutre)) if DEBUG; And how much nicer it would be if I could do this: debug->log(Dumper(\%strucutre)) if DEBUG; The reason we lazily load Data::Dumper is that it will take up a lot of memory, so we don't load it unless we absolutely have to. If you do not have Data::Dumper installed (for some strange reason), this function will basically return undef. None that I am aware of. Of course, if you find a bug, let me know, and I will be sure to fix it. This module has been used in several production sites for over 2 years now without incident, the code released here has only been slightly modified, and documentation and tests added. I use Devel::Cover to test the code coverage of my tests, below is the Devel::Cover report on this module test suite. ------------------------ ------ ------ ------ ------ ------ ------ ------ File stmt branch cond sub pod time total ------------------------ ------ ------ ------ ------ ------ ------ ------ debug.pm 100.0 96.4 n/a 100.0 100.0 100.0 99.3 ------------------------ ------ ------ ------ ------ ------ ------ ------ Total 100.0 96.4 n/a 100.0 100.0 100.0 99.3 ------------------------ ------ ------ ------ ------ ------ ------ ------ This module uses an all lowercase name, which is considered "wrong" by the perl-5-porters group. The idea is that all lowercase names are reserved for pragmas they create and which implement functionality missing in perl itself. I can understand their logic, and do not think that they are in the wrong in that stance. However, I do prefer to name my pragmas with lowercase names as well. That all said, I am making the choice to keep the lowercase name, and it is your choice as the user whether you want to use my module or not. I may be forcing my module to a life of obscurity by doing this, but so be it. This module provides a simple flexible and lightweight means of logging your debug calls. If you have more sophisticated debugging/logging needs I suggest you look at Log::Log4Perl. While I have never used it myself, I have heard many good things about it. Data::Dumper::Dumpertrick. stevan little, <stevan@iinteractive.com> This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/debug/lib/debug.pm
CC-MAIN-2016-22
refinedweb
1,207
60.45
Scala and Evaluation Strategy. No doubt there are some quirkiness, but everything about Scala makes sense. It sort of reminds me of C++ in the sense that the half of what people consider the language is implemented as library, and the actual language syntax provides extension points so that such libraries can be implemented. So, in C++, third party can create classes that feels and acts like built-in data types by using operator overloading, friend functions, copy constructors, and stream library, etc. It also meant that it has a steep learning curve just to write a class that act in native way. In my case, I've only started to understand the language after taking several lectures at college, reading Deitel and Deitel from cover to cover, reading Effective C++, and reading and writing lots of code. In contrast to C++, Java took a refreshing approach by taking away all that extensibility stuff, and providing bare bones in exchange of garbage collector, cross-platform virtual machine, and concurrency monitor. Initially Java didn't have generics. Some may not be aware of synchronized keyword, but people usually quickly get Java. The simplicity of Java the language and its familiarity helped spread it from academia to enterprise and mobile phones. Scheme is simple too, in the sense that it has few parts, but it's alien from C++ or any practical usage. Enough about them. The one of the amazing features of Scala is by-name parameters. Here's from the language spec: Syntax: ParamType ::= '=>'. Example4.6.1 The declaration def whileLoop (cond: => Boolean) (stat: => Unit): Unit indicates that both parameters of whileLoop are evaluated using call-by-name. What does this all mean, and how do you call it? var i = 0 whileLoop(i < 10) { println(i) i += 1 } // whileLoop given sufficient implementation of whileLoop, the above code produces the expected output of scala> whileLoop(i < 10) { | println(i) | i += 1 | } // whileLoop 0 1 2 3 4 5 6 7 8 9 This is not a normal method invocation you've seen in C++ or Java. This is not even lazy evaluation. In a normal invocation, i < 10 would evaluate to true because 0 < 10 and it'll forever execute the block, even if we accept that the code between curly braces somehow passed itself into whileLoop, which is a feature we've seen in language like Ruby, which gets it from Smalltalk. For both parameters of whileLoop, a function value is generated and passed into the whileLoop method. In other words, (cond: => Boolean) is a syntactic sugar that automatically generates (() => i < 10) out of (i < 10), which effectively mimics the delay of evaluation until it's applied later. I was wondering what's the general term for this concept is. According to Wikipedia, the concept of determining when to evaluate an expression is named evaluation strategy, and this one is called. Another genius of the Scala is the idea of infix operator notation. It's a notation, not an operator. In a way, there are no operators; they are all methods, and methods that take arguments are all operators too. Well, technically there are still operators because of precedence and associativity issues, but basically anyone can create a method that acts like operators. For example, 1 + 2 is a syntactic sugar for (1).+(2). All of these extension points allows libraries to implement feature that feels as if it's a native, built-in feature. A prime example is the combinator parser feature, which Scala ships with. According to Programming in Scala, here's the definition of ~ and | as a method of class Parser: def ~ (q: => Parser[T]) = new Parser[T~U] { def apply(in: Input) = p(in) match { case Success(x, in1) => q(in1) match { case Success(y, in2) => Success(new ~(x, y), in2) case failure => failure } case failure => failure } } def | (q: => Parser[T]) = new Parser[T] { def apply(in: Input) = p(in) match { case s1 @ Success(_, _) => s1 case failure => q(in) } } The details seem complicated, but the point is that the parameters are using by-name parameters because it's preceded by =>. Now a parser can be written as follows: def parens = floatingPointNumber | "("~parens~")" This is the Scala magic. By delaying the evaluation till the very end, parens allows itself to be self-referential. It's tricky, yet from the user of the combinator parser, it feels natural. This is the way of writing out a grammar in BNF. Using just the cards dealt to everybody else, Scala demonstrates a great example of language extension that feels like it's part of the language. There's of course the pattern matching that's happening here, but by-name parameter essentially enables metaprogramming on Scala, treating Scala code itself as chunks of code, or a sequence of symbols.
http://eed3si9n.com/scala-and-evaluation-strategy
CC-MAIN-2014-41
refinedweb
802
59.23
Library An Introduction to Tkinter Methods ::: Back Next The Text widget supports the standard Tkinter Widget interface, plus the following methods: Insert text at the given position (typically INSERT or END). If you provide one or more tags, they are attached to the new text. If you insert text on a mark, the mark is moved according to its gravity setting. Delete the character (or embedded object) at the given position, or all text in the given range. Any marks within the range are moved to the beginning of the range. Return the character at the given position, or all text in the given range. Return a list of widget contents at the given position, or for all text in the given range. This includes tags, marks, and embedded objects. Not implemented in Python 1.5.2 and earlier. If necessary, scroll the text widget to make sure the text at the given position is visible. The see method scrolls the widget only if the given position isn't visible at all, while yview always scrolls the widget to move the given position to the top of the window. Return the "line.column" index corresponding to the given index. Compare the two positions, and return true if the condition held. The op argument is one of "<", "<=", "==", ">=", ">", or "!=" (Python's "<>" syntax is not supported). The following methods are used to manipulate builtin as well as user-defined marks. Move the mark to the given position. If the mark doesn't exist, it is created (with gravity set to RIGHT). You also use this method to move the predefined INSERT and CURRENT marks. Remove the given mark from the widget. You cannot remove the builtin INSERT and CURRENT marks. Return the line/column position corresponding to the given mark (or any other index specifier; see above). Return the current gravity setting for the given mark (LEFT or RIGHT).. Return a tuple containing the names of all marks used in the widget. This includes the INSERT and CURRENT marks (but not END, which is a special index, not a mark). The Text widget allows you to embed windows into the widget. Embedded windows occupy a single character position, and moves with the text flow. Insert a widget at the given position. You can either create the widget (which should be a child of the text widget itself) first, and insert it using the window option, or provide a callback which is called when the window is first displayed. Table 42-2. Text Window Options Option Type Description align constant Defines how to align the window on the line. Use one of TOP, CENTER, BOTTOM, or BASELINE. The last alignment means that the bottom of the window is aligned with the text baseline - that is, the same alignment that is used for all text on the line). create callback This callback is called when the window is first displayed by the text widget. It should create the window (as a child to the text widget), and return the resulting widget instance. padx, pady distance Adds horizontal (vertical) padding between the window and the surrounding text. Default is 0 (no padding). stretch flag If zero (or OFF), the window will be left as is also if the line is higher than the window. If non-zero (or ON), the window is stretched to cover the full line (in this case, the alignment is ignored). window widget Gives the widget instance to insert into the text. Return the line/column position corresponding to the given window (or any other index specifier; see above). Remove the given window from the text widget, and destroy it. Return the current value of the given option. If there's no window on the given position, this method raises a TclError exception. Modifies one or more options. If there's no window on the given position, this method raises a TclError exception. Return a tuple containing all windows embedded in the text widget. In 1.5.2 and earlier, this method returns the names of the widgets, rather than the widget instances. This will most likely be fixed in future versions. Here's how to convert the names to a list of widget instances in a portable fashion: windows = text.window_names() try: windows = map(text._nametowidget, windows) except TclError: pass The Text widget allows you to embed images into the widget. Embedded images occupy a single character position, and moves with the text flow. Note that the image interface is not available in early version of Tkinter (it's not implemented by Tk versions before 8.0). For such platforms, you can display images by embedding Label widgets instead. image_create(index, options...). Insert an image at the given position. The image is given by the image option, and must be a Tkinter PhotoImage or BitmapImage instance (or an instance of the corresponding PIL classes). This method doesn't work with Tk versions before 8.0. Table 42-3. Text Image Options Defines how to align the image on the line. Use one of TOP, CENTER, BOTTOM, or BASELINE. The last alignment means that the bottom of the image is aligned with the text baseline -- that is, the same alignment that is used for all text on the line). image Gives the image instance to insert into the text. name string Gives the name to use when referring to this image in the text widget. The default is the name of the image object (which is usually generated by Tkinter). Adds horizontal (vertical) padding between the image and the surrounding text. Default is 0 (no padding). index(image). Return the line/column position corresponding to the given image (or any other index specifier; see above). delete(image). Remove the given image from the text widget, and destroy it. image_cget(index, option). Return the current value of the given option. If there's no image on the given position, this method raises a TclError exception. Not implemented in Python 1.5.2 and earlier. image_config(index, options...), image_configure(index, options...). Modifies one or more options. If there's no image on the given position, this method raises a TclError exception. Not implemented in Python 1.5.2 and earlier. image_names(). Return a tuple containing the names of all images embedded in the text widget. Tkinter doesn't provide a way to get the corresponding PhotoImage or BitmapImage objects, but you can keep track of those yourself using a dictionary (using str(image) as the key). This method is not implemented in Python 1.5.2 and earlier. The following methods are used to manipulate tags and tag ranges. tag_add(tag, index), tag_add(tag, start, top). Add tag to the character at the given position, or to the given range. tag_remove(tag, index), tag_remove(tag, start, stop). Remove the tag from the character at the given position, or from the given range. The information associated with the tag is not removed (not even if you use tag_remove(1.0, END)). tag_delete(tag), tag_delete(tags...). Remove the given tags from the widget. All style and binding information associated with the tags are also removed. tag_config(tag, options...), tag_configure(tag, options...). Set style options for the given tag. If the tag doesn't exist, it is created. Note that the style options are associated with tags, not text ranges. Any text having a given tag will be rendered according to its style options, even if it didn't exist when the binding was created. If a text range has several tags associated with it, the Text widget combines the style options for all tags. Tags towards the top of the tag stack (created later, or raised using tag_raise) have precedence. tag_cget(tag, option). Get the current value for the given option. tag_bind(tag, sequence, func), tag_bind(tag, sequence, func, "+"). Add an event binding to the given tag. Tag bindings can use mouse- and keyboard-related events, plus <Enter> and <Leave>. If the tag doesn't exist, it is created. Usually, the new binding replaces any existing binding for the same event sequence. The second form can be used to add the new callback to the existing binding. Note that the new bindings are associated with tags, not text ranges. Any text having the tag will fire events, even if it didn't exist when the binding was created. To remove bindings, use tag_remove or tag_unbind. tag_unbind(tag, sequence). Remove the binding, if any, for the given tag and event sequence combination. tag_names(). Return a tuple containing all tags used in the widget. This includes the SEL selection tag. tag_names(index). Return a tuple containing all tags used by the character at the given position. tag_nextrange(tag, index), tag_nextrange(tag, start, stop). Find the next occurence of the given tag, starting at the given index. If two indexes are given, search only from start to stop. Note that this method looks for the start of a range, so if you happen to start on a character that has the given tag, this method will return that range only if that character is the first in the range. Otherwise, the current range is skipped. tag_prevrange(tag, index), tag_prevrange(tag, start, stop). Find the next occurence of the given tag, starting at the given index and searching towards the beginning of the text. If two indexes are given, search from start to stop. As for nextrange, this method looks for the start of a range, beginning at the start index. So if you start on a character that has the given tag, this method will return that range unless the search started on the first character in that tag range. tag_lower(tag), tag_lower(tag, below). Move the given tag to the bottom of the tag stack (or place it just under the below tag). If multiple tags are defined for a range of text, options defined by tags towards the top of the stack have precedence. tag_raise(tag), tag_raise(tag, above). Move the given tag to the top of the tag stack (or place it just over the above tag). tag_ranges(tag). Return a tuple with start- and stop-indexes for each occurence of the given tag. If the tag doesn't exist, this method returns an empty tuple. Note that the tuple contains two items for each range. To manipulate the selection, use tag methods like tag_add and tag_remove on the SEL tag. There are no selection-specific methods provided by the Text widget. But if you insist, here's how how to emulate the Entry widget selection methods: def selection_clear(text): text.tag_remove(SEL, 1.0, END) def selection_from(text, index): text._anchor = index def selection_present(text): return len(text.tag_ranges(SEL)) != 0 def selection_range(text, start, end): text.tag_remove(SEL, 1.0, start) text.tag_add(SEL, start, end) text.tag_remove(SEL, end, END) def selection_to(text, index): if text.compare(index, "<", text._anchor): selection_range(text, index, text._anchor) else: selection_range(text, text._anchor, index) The following methods only work if the text widget is updated. To make sure this is the case, call the update_idletasks method before you use any of these. bbox(index). Returns the bounding box for the given character, as a 4-tuple: (x, y, width, height). If the character is not visible, this method returns None. dlineinfo(index). Returns the bounding box for the line containing the given character, as a 5-tuple: (x, y, width, height, offset). The last tuple member is the offset from the top of the line to the baseline. If the line is not visible, this method returns None. The Text widget doesn't contain any builtin support for printing. To print the contents, use get or dump and pass the resulting text to a suitable output device. If you have a Postscript printer, you can use PIL's PSDraw module. search(pattern, index, options...). Search for text in the widget. Returns the first matching position if successful, or an empty string if there was no match. Table 42-4. Text Search Options forwards, backwards Search from the given position towards the end of the buffer (forwards), or the beginning (backwards). Default is forwards. exact, regexp Interpret the pattern as a literal string (exact), or a Tcl-style regular expression (regexp). Default is exact. nocase Enable case-insensitive search. Default is case sensitive. stopindex index Don't search beyond this position. Default is to search the whole buffer, and wrap around if the search reaches the end of the buffer. To prevent wrapping, set stopindex to END when searching forwards, and 1.0 when searching backwards. count variable Return the length of the match in the given variable. If given, this variable should be a Tkinter IntVar. These methods are used to scroll the text widget in various ways. The scan methods can be used to implement fast mouse pan/roam operations (they are bound to the middle mouse button, if available), while the xview and yview methods are used with standard scrollbars. scan_mark(x, y), scan_dragto(x, y). scan_mark sets the scanning anchor for fast horizontal scrolling to the given mouse coordinate. scan_dragto scrolls the widget contents sideways according to the given mouse coordinate. The text is moved 10 times the distance between the scanning anchor and the new position. xview(), yview(). Returns a tuple containing two values; the first value corresponds to the relative offset of the first visible line (column), and the second corresponds to the relative offset of the line (column) just after the last one visible on the screen. Offset 0.0 is the beginning of the text, 1.0 the end. xview(MOVETO, offset), yview(MOVETO, offset). Adjust the text widget so that the given offset is at the left (top) edge of the text. Offset 0.0 is the beginning of the text, 1.0 the end. These methods are used by the Scrollbar bindings when the user drags the scrollbar slider. The MOVETO constant is not defined in Python 1.5.2 and earlier. For compatibility, use the string "moveto" instead. xview(SCROLL, step, what), yview(SCROLL, step, what). Scroll the text widget horizontally (vertically) by the given amount. The what argument can be either UNITS (lines, characters) or PAGES. These methods are used by the Scrollbar bindings when the user clicks at a scrollbar arrow or in the trough. These constants are not defined in Python 1.5.2 and earlier. For compatibility, use the strings "scroll", "units", and "pages" instead. yview_pickplace(index). Same as see, but only handles the vertical position correctly. New code should use see instead.
http://www.pythonware.com/library/tkinter/introduction/x8369-methods.htm
crawl-002
refinedweb
2,431
67.55
NetCDF reader called He's posted the code and some more usage information on Github too: Karim goes into detail on the ideas behind the library on his blog. But be careful, the examples on the blog aren't as current as the ones on Github: As a quick test I installed pyncf using pip directly from Github: pip install I then downloaded the sample time series orthogonal point data NetCDF sample file from here: The actual link to the netcdf file is here: /thredds/fileServer/testdata/netCDFTemplateExamples/timeSeries/BodegaMarineLabBuoy.nc What's nice about these NOAA samples is that they have a plain-text CDL (Common Data Language) version as well that let's you see what's in the file when you're experimenting with an API like this: First, I imported the library and created a NetCDF object from the sample file: import pyncf nc = pyncf.NetCDF(filepath="BodegaMarineLabBuoy.nc")Then I created a variable to hold the header dictionary: header = nc.headerThe header metadata contains a variety of summary data as nested dictionaries and list. We can access the product description by traversing that structure: header["gatt_list"][1]["values"] 'These seawater data are collected by a moored fluorescence and turbidity instrument operated at Cordell Bank, California, USA, by CBNMS and BML. Beginning on 2008-04-23, fluorescence and turbidity measurements were collected using a Wetlabs ECO Fluorescence and Turbidity Sensor (ECO-FLNTUSB). The instrument depth of the water quality sensors was 01.0 meter, in an overall water depth of 85 meters (both relative to Mean Sea Level, MSL). The measurements reflect a 10 minute sampling interval.' The time values in this dataset are stored as epoch seconds. I accessed those and then converted the first and last into readable dates to see exactly what period this dataset spans: import time t = nc.read_dimension_values("time") print time.ctime(t[0]) 'Mon Jul 28 12:30:00 2008' print time.time(t[-1]) 'Wed Sep 10 10:31:00 2008'The pyncf codebase is considered an alpha version and is currently read only, but what a great addition to your pure Python geospatial toolbox! I wish this library was available when I updated "Learning Geospatial Analysis with Python"! Thank you for sharing the post! Glad to hear the information. imgrum
http://geospatialpython.com/2016/04/pure-python-netcdf-reader.html
CC-MAIN-2018-51
refinedweb
383
52.09
I found a solution that is working for me: 1. Custom Inventory Field - Build a custom inventory field in you K1000 by going to "Inventory", "Software" and then select "New" from the "Choose Action"-menu. - Enter a name for your field, "Server roles and features" e.g. - Select all operating systems that this field should be evaluated on by holding the CTRL-key and clicking each of the required entries. In our case it makes sense to select Windows Server OS only since the query won't work on any Windows client OS. In my tests I found this one works on Windows Server 2008 R2 and above. If you need to support Windows Server 2008 Non-R2 (but not older!), see the alternative command in the next step. IMPORTANT: If new Windows Server OS come into your K1000's managed device inventory make sure you come back here and enable these new server OS as well - the K1000 won't do that for you! - In the field "Custom Inventory Rule" enter the following: ShellCommandTextReturn(%windir%\SysNative\WindowsPowerShell\v1.0\powershell -NoLogo -NonInteractive -NoProfile -Command "Get-WindowsFeature | where-object {$_.Installed -eq $True} | foreach {$_.Name}") If you need to support Windows Server 2008 Non-R2 enter the following command INSTEAD. According to Microsoft, this query method is deprecated since Windows Server 2012 - on my 2012 and 2012 R2 servers this is working anyway. So here is the "old school" command: ShellCommandTextReturn(wmic /namespace:\\root\CIMV2:Win32_ServerFeature PATH Win32_ServerFeature Get Name) - After running inventory on your server(s), you should now have a custom inventory field (in the "Software" section) showing you all installed roles and features of the server. 2. Smart Label When the custom inventory field is available and working we can use the smart label editor to build filters on that. - First of all, you need to identify the "core" role name(s) of the roles you are looking for. Note that a roles "Display Name" may be localized, that's why I suggest to use the "Name" field instead to make this one work on all machines. To find out what your roles name is open a PowerShell command line on one of your servers and run the following command: Get-WindowsFeature | where-object {$_.Installed -eq $True} | ft DisplayName,Name This will give you a list of "Name" and "DisplayName" side-by-side. In my case, I want to see the servers with "Remotedesktop-Sitzungshost" (German for the RDS Session Host) - that roles name is "RDS-RD-Server". If you used the "old school" command above you need to check the names listed by the WMIC command instead. - Now open a smart label editor in your "Inventory" "Device" overview and select your new custom inventory field from above in the list of available fields. Switch the operator to "contains" and enter your desired role name in the right field. Test your label configuration. If everything is OK, enter a name for your smart label, hit "Save" - and you're done! You can also define combinations, e.g. "contains RDS-RD-Server AND contains RDS-Web-Access" to find your RemoteApp host etc. - Wait for the next inventory to run to see your label getting populated! Another nice idea to use this field is in reports. You could create a report that shows all servers having the role "Desktop-Experience" installed or not having .NET-Framework 3.5 installed (choose "does not contain" as operator and "NET-Framework-Features" as role name!) If you want to use this for your client machines, please note the PowerShell query is different. We need to use the Win32_OptionalFeature-class here. The PowerShell command would be Get-WmiObject -query 'select * from win32_optionalfeature where installstate=1' | foreach {$_.Name} then, so you could use the following custom inventory command: Get-WmiObject -query 'select * from win32_optionalfeature where installstate=1' | foreach {$_.Name} then, so you could use the following custom inventory command: ShellCommandTextReturn(%windir%\System32\WindowsPowerShell\v1.0\powershell -NoLogo -NonInteractive -NoProfile -Command "Get-WmiObject -query 'select * from win32_optionalfeature where installstate=1' | foreach {$_.Name}")
https://www.itninja.com/blog/view/show-and-use-windows-server-roles-and-features-in-your-k1000
CC-MAIN-2020-34
refinedweb
683
54.83
The Type System The CLR has its own set of concepts and techniques for packaging, deploying, and discovering component code. These concepts and techniques are fundamentally different from those used by technologies such as COM, Java, or Win32. The difference is best understood by looking closely at the CLR loader, but first one must look at how code and metadata are actually packaged. Modules Defined Programs written for the CLR reside in modules. A CLR module is a byte stream, typically stored as a file in the local file system or on a Web server. As shown in Figure 2.1, a CLR module uses an extended version of the PE/COFF executable file format used by Windows NT. By extending the PE/COFF format rather than starting from scratch, CLR modules are also valid Win32 modules that can be loaded using the LoadLibrary system call. However, a CLR module uses very little PE/COFF functionality. Rather, the majority of a CLR module's contents are stored as opaque data in the .text section of the PE/COFF file. Figure 2.1: CLR Module Format CLR modules contain code, metadata, and resources. The code is typically stored in common intermediate language (CIL) format, although it may also be stored as processor-specific machine instructions. The module's metadata describes the types defined in the module, including names, inheritance relationships, method signatures, and dependency information. The module's resources consist of static read-only data such as strings, bitmaps, and other aspects of the program that are not stored as executable code. The file format used by CLR modules is fairly well documented; however, few developers will ever encounter the format in the raw. Even developers who need to generate programs on-the-fly will typically use one of the two facilities provided by the CLR for programmatically generating modules. The IMetaDataEmit interface is a low-level COM interface that can be used to generate module metadata programmatically from classic C++. The System.Reflection.Emit namespace is a higher-level library that can be used to generate metadata and CIL programmatically from any CLR-friendly language (e.g., C#, VB.NET). The CodeDOM works at an even higher layer of abstraction, removing the need to know or understand CIL. However, for the vast majority of developers, who simply need to generate code during development and not at runtime, a CLR-friendly compiler will suffice. The C# compiler (CSC.EXE), the VB.NET compiler (VBC.EXE), and the C++ compiler (CL.EXE) all translate source code into CLR modules. Each of the compilers uses command-line switches to control which kind of module to produce. As shown in Table 2.1, there are four possible options. In C# and VB.NET, one uses the /target command-line switch (or its shortcut, /t) to select which option to use. The C++ compiler uses a combination of several switches; however, one always uses the /CLR switch to force the C++ compiler to generate CLR-compliant modules. The remainder of this discussion will refer to the C# and VB.NET switches, given their somewhat simpler format. Table 2.1 Module Output Options The /t:module option produces a "raw" module that by default will use the .netmodule file extension. Modules in this format cannot be deployed by themselves as stand-alone code, nor can the CLR load them directly. Rather, developers must associate raw modules with a full-fledged component (called an assembly) prior to deployment. In contrast, compiling with the /t:library option produces a module that contains additional metadata that allows developers to deploy it as stand-alone code. A module produced by compiling with /t:library will have a .DLL file extension by default. Modules compiled with /t:library can be loaded directly by the CLR but cannot be launched as an executable program from a command shell or the Windows Explorer. To produce this kind of module, you must compile using either the /t:exe or the /t:winexe option. Both options produce a file whose extension is .EXE. The only difference between these two options is that the former assumes the use of the console UI subsystem; the latter option assumes the GUI subsystem. If no /t option is specified, the default is /t:exe. Modules produced using either the /t:exe or the /t:winexe option must have an initial entry point defined. The initial entry point is the method that the CLR will execute automatically when the program is launched. Programmers must declare this method static, and, in C# or VB.NET, they must name it Main. Programmers can declare the entry point method to return no value or to return an int as its exit code. They can also declare it to accept no parameters or to accept an array of strings, which will contain the parsed command-line arguments from the shell. The following are four legal implementations for the Main method in C#: static void Main() { } static void Main(string[] argv) { } static int Main() { return 0; } static int Main(string[] argv) { return 0; } These correspond to the following in VB.NET: shared sub Main() : end sub shared sub Main(argv as string()) : end sub shared function Main() : return 0 : end function shared function Main(argv as string()) return 0 end function Note that these methods do not need to be declared public. Programmers must, however, declare the Main method inside a type definition, although the name of the type is immaterial. The following is a minimal C# program that does nothing but print the string Hello, World to the console: class myapp { static void Main() { System.Console.WriteLine("Hello, World"); } } In this example, there is exactly one class that has a static method called Main. It would be ambiguous (and therefore an error) to present the C# or VB.NET compiler with source files containing more than one type having a static method called Main. To resolve this ambiguity, programmers can use the /main command-line switch to tell the C# or VB.NET compiler which type to use for the program's initial entry point.
http://www.informit.com/articles/article.aspx?p=30601&amp;seqNum=7
CC-MAIN-2017-26
refinedweb
1,021
55.44
Uncertainty in polynomial roots - Part II Posted July 06, 2013 at 03:31 PM | categories: data analysis, uncertainty | tags: | View Comments We previously looked at uncertainty in polynomial roots where we had an analytical formula for the roots of the polynomial, and we knew the uncertainties in the polynomial parameters. It would be inconvenient to try this for a cubic polynomial, although there may be formulas for the roots. I do not know of there are general formulas for the roots of a 4th order polynomial or higher. Unfortunately, we cannot use the uncertainties package out of the box directly here. import uncertainties as u import numpy as np)) print np.roots([A, B, C]) >>> >>> >>> >>> >>> >>> >>> >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\Users\jkitchin\AppData\Local\Enthought\Canopy\User\lib\site-packages\numpy\lib\polynomial.py", line 218, in roots p = p.astype(float) File "c:\Users\jkitchin\AppData\Local\Enthought\Canopy\User\lib\site-packages\uncertainties\__init__.py", line 1257, in raise_error % (self.__class__, coercion_type)) TypeError: can't convert an affine function (<class 'uncertainties.Variable'>) to float; use x.nominal_value To make some progress, we have to understand how the numpy.roots function works. It constructs a Companion matrix, and the eigenvalues of that matrix are the same as the roots of the polynomial. import numpy as np c0, c1, c2 = [-0.99526746, -0.011546, 1.00188999] p = np.array([c2, c1, c0]) N = len(p) # we construct the companion matrix like this # see # for this code. # build companion matrix and find its eigenvalues (the roots) A = np.diag(np.ones((N-2,), p.dtype), -1) A[0, :] = -p[1:] / p[0] print A roots = np.linalg.eigvals(A) print roots [[ 0.01152422 0.99338996] [ 1. 0. ]] [ 1.00246827 -0.99094405] This definition of the companion matrix is a little different than the one here, but primarily in the scaling of the coefficients. That does not seem to change the eigenvalues, or the roots. Now, we have a path to estimate the uncertainty in the roots. Since we know the polynomial coefficients and their uncertainties from the fit, we can use Monte Carlo sampling to estimate the uncertainty in the roots. import numpy as np import uncertainties as u c, b, a = [-0.99526746, -0.011546, 1.00188999] sc, sb, sa = [ 0.0249142, 0.00860025, 0.00510128] NSAMPLES = 100000 A = np.random.normal(a, sa, (NSAMPLES, )) B = np.random.normal(b, sb, (NSAMPLES, )) C = np.random.normal(c, sc, (NSAMPLES, )) roots = [[] for i in range(NSAMPLES)] for i in range(NSAMPLES): p = np.array([A[i], B[i], C[i]]) N = len(p) M = np.diag(np.ones((N-2,), p.dtype), -1) M[0, :] = -p[1:] / p[0] r = np.linalg.eigvals(M) r.sort() # there is no telling what order the values come out in roots[i] = r avg = np.average(roots, axis=0) std = np.std(roots, axis=0) for r, s in zip(avg, std): print '{0: f} +/- {1: f}'.format(r, s) -0.990949 +/- 0.013435 1.002443 +/- 0.013462 Compared to our previous approach with the uncertainties package where we got: : -0.990944048037+/-0.0134208013339 : 1.00246826738 +/-0.0134477390832 the agreement is quite good! The advantage of this approach is that we do not have to know the formula for the roots of higher order polynomials to estimate the uncertainty in the roots. The downside is we have to evaluate the eigenvalues of a matrix a large number of times to get good estimates of the uncertainty. For high power polynomials this could be problematic. I do not currently see a way around this, unless it becomes possible to get the uncertainties package to propagate through the numpy.eigvals function. It is possible to wrap some functions with uncertainties, but so far only functions that return a single number. There are some other potential problems with this approach. It is assumed that the accuracy of the eigenvalue solver is much better than the uncertainty in the polynomial parameters. You have to use some judgment in using these uncertainties. We are approximating the uncertainties of a nonlinear problem. In other words, the uncertainties of the roots are not linearly dependent on the uncertainties of the polynomial coefficients. It is possible to wrap some functions with uncertainties, but so far only functions that return a single number. Here is an example of getting the nth root and its uncertainty. import uncertainties as u import numpy as np @u.wrap def f(n=0, *P): ''' compute the nth root of the polynomial P and the uncertainty of the root''' p = np.array(P) N = len(p) M = np.diag(np.ones((N-2,), p.dtype), -1) M[0, :] = -p[1:] / p[0] r = np.linalg.eigvals(M) r.sort() # there is no telling what order the values come out in return r[n] # our polynomial coefficients and standard errors)) for result in [f(n, A, B, C) for n in [0, 1]]: print result -0.990944048037+/-0.013420800377 1.00246826738+/-0.0134477388218 It is good to see this is the same result we got earlier, with a lot less work (although we do have to solve it for each root, which is a bit redundant)! It is a bit more abstract though, and requires a specific formulation of the function for the wrapper to work. Copyright (C) 2013 by John Kitchin. See the License for information about copying.
http://kitchingroup.cheme.cmu.edu/blog/2013/07/06/Uncertainty-in-polynomial-roots-Part-II/
CC-MAIN-2017-22
refinedweb
908
58.28
Programming Mac OS X with Cocoa for Beginners/Adding finesse So far we have built a fairly crude drawing program, but one that is starting to look like a real application. We have covered many of the core principles of Cocoa that you'll need to write any application. If you look at how much code we've actually written, it's not that much, yet our application is already quite functional. In this section, we'll look at adding finesse - those touches that separate real, well-designed and implemented applications from those lesser amateur efforts we've no doubt all seen. Undo[edit] The first thing to tackle is Undo. A real application should allow almost all actions to be undoable, in the spirit of forgiveness of the user. Without Undo, your application is likely to be discarded in favour of another one that has it, as punishing the user for mistakes, or not allowing them to experiment is a cardinal design sin! Undo is traditionally one of the "hard" parts of implementing an application. Cocoa helps us massively here, and so Undo is not so hard. Usually, adding Undo as an afterthought is not a good idea - you need to design your application from the ground up to cope with the undo task. So far we have not mentioned Undo, but we have in fact designed our application to allow it to be added easily. The principle of Undo is straightforward - whenever we do anything to change the state of the data model, the previous state is recorded so it can be put back. We can record this previous state in different ways, either just record the whole state, or parts of it along with tags to tell us what was changed, or we can record actions and perform the opposite action to implement Undo. We'll be using a combination of these things. Cocoa automatically combines several undoable "recordings" into one Undoable action for each event, which really makes life very simple for us - we simply need to make sure the recording happens at each editable point of interest. We'd like the following to be undoable: - adding new objects - deleting objects - changing the position or size of an object - changing the stroke and fill colours - changing the stroke width Note that we could also make the selections themselves undoable, but in this exercise we won't do this. In Cocoa, the object responsible for handling Undo is the undo manager. It is embodied in the class NSUndoManager. The way it works is by storing invocations. We already discussed how Objective-C uses runtime binding of class methods. An invocation is just a stored description of a method call. When the invocation is "replayed" the stored method call is actually made. The invocation not only records the target and method to be called, but also all of the method's parameters at the time the invocation was recorded. Thus we can create an invocation which when called, will undo the current action we are performing. Both the action and the invocation to undo the same action are created at the same time. First let's add the code for undoing adding and deleting objects. Here is the modified code in MyDocument.m for addObject and removeObject: - (void) addObject:(id) object { if(![_objects containsObject:object]) { [[self undoManager] registerUndoWithTarget:self selector:@selector(removeObject:) object:object]; [_objects addObject:object]; [_mainView setNeedsDisplayInRect:[object drawBounds]]; } } - (void) removeObject:(id) object { if([_objects containsObject:object]) { NSRect br = [object drawBounds]; [[self undoManager] registerUndoWithTarget:self selector:@selector(addObject:) object:object]; [self deselectObject:object]; [_objects removeObject:object]; [_mainView setNeedsDisplayInRect:br]; } } We obtain an undo manager by calling [self undoManager]. Every document has its own undo manager instance already set up, we just need to use it. We then use the registerUndoWithTarget:selector:object: method to build an invocation that the undo manager stores. When we add an object, we build an invocation to removeObject. When we remove an object, be build an invocation to addObject. In other words, we record the OPPOSITE of what we are doing. We have also added code here to refresh the main view when the objects come and go, so that we can see the effect that our actions have. Compile and run the project. Create some shapes. Now Undo them. You'll find you can Undo and Redo as many actions as you want - everything works as you would expect for the Undo command. Not bad for just two lines of code! Note that when Undo is performed, it calls, say removeObject, which in turn records another addObject undo action. This is how redo works - NSUndoManager knows the context it is called in, so can add tasks to the appropriate stack. Now let's make editable actions Undoable. For this, we'll need to add code to WKDShape, and at present shapes don't have an undomanager, nor do they know anything about the document they are part of, so they can't obtain one. So the first thing we need to do is to provide a way to allow shapes to obtain an appropriate undo manager. In WKDShape.h, add a data member to the class called _owner, typed as NSDocument*. Add accessor methods setOwner: and owner. In the .m file, add the implementation: - (void) setOwner:(NSDocument*) doc { _owner = doc; } - (NSDocument*) owner { return _owner; } In MyDocument.m, add a line to addObject that calls setOwner with self - this makes sure that whenever an object is added to a document, the object is updated with which document it belongs to. Note that since everything that ever adds an object to a document calls this method, including paste for example, this information is always up to date. This is a strong design principle - always try to minimise the number of places in your code that change the data model by factoring code into a few key methods. Then you can add code to those methods in the knowledge that they will always be called, and nothing can get in "through the back door". If we hadn't done this, implementing Undo would be very much harder than it has been so far. Now we have a way for a WKDShape to obtain its owning document's undoManager, we can implement undo easily. - (void) setFillColour:(NSColor*) colour { [[[self owner] undoManager] registerUndoWithTarget:self selector:@selector(setFillColour:) object:_fillColour]; [colour retain]; [_fillColour release]; _fillColour = colour; [self repaint]; } Here, we don't set up the undo using a different method, we use the same method, but with the OLD value of the colour. When the undo command is called, it calls this same method, passing back the original colour. The code for the stroke colour is identical. The case for the stroke width is slightly more involved, because the undo manager doesn't directly store simple scalar values such as a float. Instead we need to pack the value up into an object. Cocoa provides a simple class for doing just this - NSNumber. As we need to be able to call a method that takes an object parameter, we must now create one. We'll refactor the code so that all the calls to set the stroke width now go through it. - (void) setStrokeWidth:(float) width { [[[self owner] undoManager] registerUndoWithTarget:self selector:@selector(setStrokeWidthObject:) object:[NSNumber numberWithFloat:_strokeWidth]]; _strokeWidth = width; [self repaint]; } - (void) setStrokeWidthObject:(NSNumber*) value { [self setStrokeWidth:[value floatValue]]; } Don't forget to add the method setStrokeWidthObject: to your class declaration. Now if anyone calls setStrokeWidth, the old value is turned into an NSNumber object and used to build the undo invocation on setStrokeWidthObject: When Undo is called, setStrokeWidthObject: unpacks the encapsulated value and calls setStrokeWidth:, so everything works correctly. Compile and go to test that changing properties using the inspector is now fully undoable. They should be! Notice how Cocoa has separated each editing action into different Undo commands for you. If you drag around in the colour picker for example, the colour of the object will change many, many times until you stop dragging. But only one Undo command is needed to put back the previous colour - it doesn't visibly "replay" all of the individual intermediate colours. There is one thing that isn't so great now however. If we Undo an editing change, the Inspector doesn't change! If we think about it, it's obvious why - previously we only set up the inspector to respond to selection changes which also set up the state of the controls. After that the inspector changes the object's state so they were always in "synch". Undo isn't changing the selection state, but it is changing the object's state behind the inspector's back, so we need to tell the inspector to resynch when this occurs. To do this we need to add a new notification that the inspector can respond to. This is very similar to the "repaint" notification - in fact it would be possible to use that one in this case, but since semantically it does have a different meaning, it is good practice to make it a separate notification. If later you extended the design you might find combining the notifications led to awkward problems. So create a new notification name and a method for sending it. I called it resynch. Call this method from every place that the object state can be changed from - setFillColour:, setStrokeColour:, setStrokeWidth: In the inspector, create a new responder method - I called it resynch: - taking a single NSNotification parameter. Subscribe to the resynch notification in the awakeFromNib method as before. The resynch: method looks like: - (void) resynch:(NSNotification*) note { WKDShape* shp = (WKDShape*)[note object]; if ( shp == editShape ) [self setupWithShape:shp]; } As you can se, it's very simple - we find out which object was changed. If it's the one we are in fact currently editing, we simply call our setup method so that the control states match the object's state. Compile and run again to verify that this time, Undoing an edit operation also reflects the change in the Inspector. Finally, we need to Undo moves and resizes of the object. By factoring all of this information through the setBounds: method, we have just one place to add the undo recording to. As with setStrokeWidth, we'll need to use an NSValue object to store the old rect. Here's the refactored and modified code in WKDShape: - (void) setBounds:(NSRect) bounds { [self repaint]; [[[self owner] undoManager] registerUndoWithTarget:self selector:@selector(setBoundsObject:) object:[NSValue valueWithRect:[self bounds]]]; _bounds = bounds; [self repaint]; [self resynch]; } - (void) setBoundsObject:(id) value { [self setBounds:[value rectValue]]; } - (void) setLocation:(NSPoint) loc { NSRect br = [self bounds]; br.origin = loc; [self setBounds:br]; } - (void) offsetLocationByX:(float) x byY:(float) y { NSRect br = [self bounds]; br.origin.x += x; br.origin.y += y; [self setBounds:br]; } - (void) setSize:(NSSize) size { NSRect br = [self bounds]; br.size = size; [self setBounds:br]; } Compile and run... create a shape and move it. Now Undo. Is the action undoable in the way you expected? No, it's not. The action is undoable, but unlike the colour case, each individual small amount of motion has been recorded as a separate Undo task. The Undo manager has failed to group the motions into one big single action. Why is that? NSUndoManager groups all undo actions that occur within a single event. However, dragging an object consists of multiple events. We can't change that, but we can change the way that the undo manager groups things by giving it some hints. In WKDDrawView.m, in the method mouseDown:, add the following line at the top of the method: [[[self delegate] undoManager] beginUndoGrouping]; and in the mouseUp: method, add the following line at the bottom of the method: [[[self delegate] undoManager] endUndoGrouping]; This will fix the problem - compile and run to verify. What this does it do tell the undo manager to group any undo recording it receives from now until the call to endUndoGrouping. We beging grouping on a mouse down, and end on a mouse up, so all the actions that occur during the drag will end up in the same group, and will be replayed under the single Undo command. Each individual offset of the shape is still recorded, but when played back the entire move is replayed so the effect for the user is the expected behaviour. Finally, you'll probably have noticed that the menu command only shows a generic "Undo". It would be nice if we could give our users a more meaningful indication of what the Undo operation will accomplish. To do this, we pass a string to the undo manager which is uses to build the menu command text. Whatever was the most recent string it received in a group will be the one used. The method is NSUndoManager's setActionName: method. For now we will just hard-code the strings for each action - in a real app we'd need to allow this to be localizable. In WKDShape, this is straightforward. For example, in setFillColour, add: [[[self owner] undoManager] setActionName:@"Change Fill Colour"]; just after the current undo recording operation. For all similar state changes, you can add a line with a string indicating the thing actually changed. Remember that the user will see this; you don't need to include "Undo" or "Redo". To distinguish between resizing and moving a shape, you can include this line in the appropriate routines - they don't need to go directly in setBounds: also, don't forget the code where a handle is dragged interactively - mouseDragged: The MyDocument changes are similar with one small kink - because we are using the 'opposite' method approach, we need to tell apart the case of undo/redo and a normal call and make sure we only update the string if we were called normally - i.e. not from an undo invocation. To do this, we use: if (! [[self undoManager] isUndoing] && ! [[self undoManager] isRedoing]) [[self undoManager] setActionName:@"Delete Object"]; Run again to check that everything works as expected. As a bonus, you'll notice that now, changes to the document automatically result in you being asked if you want to save changes when you quit or close a document. This is because by recording undo tasks, you are also notifying the document that its state is different from the disk file. Previously, it had no way to tell. Cocoa now steps in and adds that small piece of functionality for you "for free". Neat! Further exercises: - Add the ability to undo selection changes. This will often result in a more usable application in practice. Printing[edit] Real applications should print. Again, in a traditional Mac application, adding the ability to print was usually hard work, and very often added as an afterthought, making it harder still! Cocoa is much easier, since there is no major difference between its on-screen graphics model and the printing model. In fact we already have most of the code written. Printing is handled by an object called an NSPrintOperation, working in conjunction with an NSView. The view draws the content to the paper. For our simple exercise, we need very little code, since the default pagination scheme of tiling across pages is adequate. As you might imagine Cocoa provides numerous alternative approaches, but these are rather beyond the scope of just getting basic printing working. As we have a document-based application, we use the printDocument: action method to get things going. Here's the code: - (IBAction) printDocument:(id) sender { NSPrintOperation *op = [NSPrintOperation printOperationWithView:_mainView printInfo:[self printInfo]]; [op runOperationModalForWindow:[self windowForSheet] delegate:self didRunSelector: @selector(printOperationDidRun:success:contextInfo:) contextInfo:NULL]; } We create an NSPrintOperation, passing it our main view which will render the drawing. Once we have this, we then just run it using a sheet dialog. That takes care of the rest. The sheet requires a completion routine, but in this case we don't need it to actually do anything, so we simply provide it as an empty method: - (void) printOperationDidRun:(NSPrintOperation*) printOperation success:(BOOL)success contextInfo:(void *)info { } Don't forget to add this to your class definition. That's it! Compile and run it and you'll find that you can print out your drawings. There's one thing that isn't so great here, and this is that it prints the selection handles. Really, we don't need to see these handles when a drawing is printed, so we'll now just modify the main view drawing code so that it doesn't bother to render these when it's printing. This turns out to be very simple: while( shape = [iter nextObject]) { if ( NSIntersectsRect( rect, [shape drawBounds])) [shape drawWithSelection:[selection containsObject:shape] && [NSGraphicsContext currentContextDrawingToScreen]]; } This is the main loop inside our view's drawRect: method. We just add a check whether the current graphics context is drawing to the screen. If not, it must be drawing to the printer, so the objects are rendered without the handles, regardless of their selection state. Menu item maintenance[edit] We have seen how Cocoa automatically enables menu items that can find a target in the current context. That's pretty neat, but not always enough. For example, when we implemented Cut and Paste, we found these commands always enabled even if there was no selection to cut, or nothing on the clipboard we could paste. We'll now see how we deal with that. Whenever a menu is displayed, the target is given a chance to overrule the normal enabling behaviour. It does this by implementing a method called validateMenuItem: which is called for each item. You can return YES to enable the item, NO to disable it. So in MyDocument, we add: - (BOOL) validateMenuItem:(NSMenuItem*) item { SEL act = [item action]; if ( act == @selector(cut:) || act == @selector(copy:) || act == @selector(delete:)) return ([[self selection] count] > 0 ); else if ( act == @selector(paste:)) { NSPasteboard* cb = [NSPasteboard generalPasteboard]; NSString* type = [cb availableTypeFromArray:[NSArray arrayWithObjects:@"wikidrawprivate", nil]]; return ( type != nil ); } else return YES; } As here, it's a good idea to compare the action selectors to determine which action the menu item is targetting, instead of looking at the menu item strings or position. An alternative would be to use the item's tag, but that would require that you carefully set these up in IB. By using the selector, you are immune from text and positional changes you might make to the menu - as long as it remains targetted at the same action method, it will behave correctly with respect to what that method actually achieves. Here, if the item is targetting the cut, copy or delete methods, we see if there are any items in the selection array. If so, we enable the item, otherwise we disable it. For the paste case, we peek at the pasteboard to see if it has data of type 'wikidrawprivate' available - if so we can paste, so we enable that item. You can implement a similar method in any target of a menu command so finely control the enabling of a menu item. You can also use the opportunity to change the text of a menu item to reflect some information you have in your data model if you like.
http://en.wikibooks.org/wiki/Programming_Mac_OS_X_with_Cocoa_for_Beginners/Adding_finesse
CC-MAIN-2014-52
refinedweb
3,206
52.29
NAME kill - send signal to a process SYNOPSIS #include <sys/types.h> #include <signal.h> int kill(pid_t pid, int sig); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): kill(): _POSIX_C_SOURCE || _XOPEN_SOURCE DESCRIPTION The kill() system call can be used to send any signal to any process group or process. If pid is positive, then signal sig is sent -pid. If sig is 0, then no signal is sent, but error checking is still performed.(2)ed for. CONFORMING TO SVr4, 4.3BSD, POSIX.1-2001 NOTES The only signals that can be sent to process ID 1, the init process, are those for which init has explicitly installed signal handlers. This is done to assure the system is not brought down accidentally. effective user ID of the receiver. The current rules, which conform to POSIX.1-2001, were adopted in kernel 1.3.78. processes for which the caller had permission to signal. SEE ALSO _exit(2), killpg(2), signal(2), sigqueue(2), tkill(2), exit(3), capabilities(7), credentials(7), signal(7) COLOPHON This page is part of release 2.77 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.ubuntu.com/manpages/hardy/man2/kill.2.html
CC-MAIN-2015-22
refinedweb
204
67.86
In multithreading when multiple threads are working simultaneously on a shared resource like a file(reading and writing data into a file), then to avoid concurrent modification error(multiple threads accessing same resource leading to inconsistent data) some sort of locking mechanism is used where in when one thread is accessing a resource it takes a lock on that resource and until it releases that lock no other thread can access the same resource. In the threading module of Python, for efficient multithreading a primitive lock is used. This lock helps us in the synchronization of two or more threads. Lock class perhaps provides the simplest synchronization primitive in Python. Primitive lock can have two States: locked or unlocked and is initially created in unlocked state when we initialize the Lock object. It has two basic methods, acquire() and release(). Following is the basic syntax for creating a Lock object: import threading threading.Lock() Lock objects use two methods, they are: acquire(blocking=True, timeout=-1)method This method is used to acquire the lock. When it is invoked without arguments, it blocks until the lock is unlocked. This method can take 2 optional arguments, they are: Falsewill not block the thread if the lock is acquired by some other thread already and will return Falseas result. If you provide the value for this blocking flag as Truethen the calling thread will be blocked if some other thread is holding the lock and once the lock is released then your thread will acquire the lock and return True. release()method It is used to release an acquired lock. If the lock is locked, this method will reset it to unlocked, and return. Also this method can be called from any thread. When this method is called, one out of the already waiting threads to acquire the lock is allowed to hold the lock. Also, it throws a RuntimeError if it is invoked on an unlocked lock. Below we have a simple python program in which we have a class SharedCounter which will act as the shared resource between our threads. We have a task method from which we will call the increment() method. As more than one thread will be accessing the same counter and incrementing its value, there are chances of concurrent modification, which could lead to inconsistent value for the counter. Takeaways from the code above: acquire()method and then access a resource, what if during accessing the resource some error occurs? In that case, no other thread will be able to access that resource, hence we must access the resource inside the tryblock. And inside the finallyblock we can call the release()method to relase the lock. counter. /python/python-threading-lock-object
https://www.studytonight.com/python/python-threading-lock-object
CC-MAIN-2021-10
refinedweb
456
67.99
WebNano - A minimalistic PSGI based web framework. version 0.007 A minimal WebNano application can be an app.psgi file like this: { package MyApp; use base 'WebNano'; 1; } { package MyApp::Controller; use base 'WebNano::Controller'; sub index_action { my $self = shift; return 'This is my home'; } 1; } my $app = MyApp->new(); $app->psgi_app; You can then run it with plackup. A more practical approach is to split this into three different files. Every WebNano application has at least three parts - the application class, at least one controller class and the app.psgi file (or something else that uses Plack::Runner run the app). The application object is instantiated only once and is used to hold all the other constant data objects - like the connection to the database, a template renderer object (if it is too heavy to be created per request) and general stuff that is too heavy to be rebuilt with each request. In contrast the controller objects are recreated for each request. The dispatching implemented by WebNano::Controller is a simple namespace matching of HTTP request paths into method calls as in the following examples: '/page' -> 'MyApp::Controller->page_action()' '/Some/Very/long/pa/th' -> 'MyApp::Controller::Some::Very->long_action( 'pa', 'th' ) The dispatching to methods inside a controller is always available - to get actions dispatched to controllers in subdirs you need to override the search_subcontrollers method and make it return a true value: sub search_subcontrollers { 1 }. Usually in your root controller should do that. Other controllers also can do it as well - but only if they do not do their own dispatching to sub-controllers. If a controller has custom dispatching then you should leave the default search_subcontrollers to avoid intruducing possible security risks from the automatic dispatching which could bypass your controller's logic. Additionally if the last part of the path is empty then index is added to it - so / is mapped to index_action and /SomeController/ is mapped to MyApp::SomeController->index_action. You can override the _action suffix with the url_map controller attribute which maps URLs to functions just like the run_modes attribute in CGI::Application: $self->url_map( { 'mapped url' => 'mapped_url' } ); or a list of approved methods to be dispached by name: $self->url_map( [ 'safe_method' ] ); More advanced dispatching can be done by overriding the local_dispatch method in the Controller class: around 'local_dispatch' => sub { my( $orig, $self ) = @_; my( $id, $method, @args ) = @{ $self->path }; $method ||= 'view'; if( $id && $id =~ /^\d+$/ && $self->record_methods->{ $method } ){ my $rs = $self->app->schema->resultset( 'Dvd' ); my $record = $rs->find( $id ); if( ! $record ) { my $res = $self->req->new_response(404); $res->content_type('text/plain'); $res->body( 'No record with id: ' . $id ); return $res; } return $self->$method( $record, @args ); } return $self->$orig(); }; This example checks if the first part of the path is a number - if it is it uses it to look for a Dvd object by primary key. If it cannot find such a Dvd then it returns a 404. If it finds that dvd it then redispatches by the next path part and passes that dvd object as the first parameter to that method call. Note the need to check if the called method is an allowed one. If the first part of the url is not a number - then the request is dispatched in the normal way. More examples you can find in the examples subdir. The primary design goal here is to provide basic functionality that should cover most use cases and offer a easy way to override and extend it for special cases. In general it is easy to write your own dispatcher that work for your limited use case - and here you just need to do that, you can override the dispatching only for a particular controller and you don't need to warry about the general cases. If you need to build a heavy structure used in the controller you can always build it as an application attribute and use it in the controller as it has access to the application object. However, since all the controller's work is done in the request scope (i.e. creating the request) - then it makes sense that the whole object should live in that scope. This is the same as Tatsumaki handlers (and probably many non-Perl frameworks), but different from Catalyst. There is a tendency in other frameworks to add interfaces to any other CPAN library. With WebNano the goal is to keep it small, both in code and in its interface. Instead of adding new interfaces for things that can be used directly, but WebNano tries to make direct usage as simple as possible. A WebNano script is a PSGI application so you can immediately use all the Plack tools. For example to use sessions you can add following line to your app.psgi file: enable 'session' Read Plack::Middleware::Session about the additional options that you can enable here. See also Plack::Builder to read about the sweetened syntax you can use in your app.psgi file and to find out what other Plack::Middleware packages are available. The same goes for MVC. WebNano does not have any methods or attributes for models, not because I don't structure my web application using the 'web MVC' pattern - but rather because I don't see any universal attribute or method of the possible models. Users are free to add their own methods. For example most of my code uses DBIx::Class - and I add these lines to my application: has schema => ( is => 'ro', isa => 'DBIx::Class::Schema', lazy_build => 1 ); sub _build_schema { my $self = shift; my $config = $self->config->{schema}; return DvdDatabase::DBSchema->connect( $config->{dbi_dsn}, $config->{user}, $config->{pass}, $config->{dbi_params} ); } then I use it with $self->app->schema in the controller objects. As to Views - I've added some support for two templating engines for WebNano, but this is only because I wanted to experiment with 'template inheritance'. If you don't want to use 'template inheritance' you can use Template::Tookit directly in your controller actions or you can use directly any templating engine in your controller actions - like $self->app->my_templating->process('template_name' ) or even $self->my_templating->process( ... ) as long as it returns a string. You can use the original "Delayed_Reponse_and_Streaming_Body" in PSGI The streaming_action method in t/lib/MyApp/Controller.pm can be used as an example. soon on CPAN. Example: around 'local_dispatch' => sub { my $orig = shift; my $self = shift; if( !$self->env->{user} ){ return $self->render( template => 'login_required.tt' ); } $self->$orig( @_ ); }; local_dispatch is called before the controll is passed to child controllers, so if you put that into the MyApp::Controller::Admin controller - then both all local actions and actions in child controllers (for example MyApp::Controller::Admin::User) would be guarded agains unauthorized usage. This is a method which returns a subroutine reference suitable for PSGI. The returned subrourine ref is a closure over the application object. This method is deprecated - use psgi_app instead. Experimental. Application method that acts as the PSGI callback - takes environment as input and returns the response. Nearly every web application uses some templating engine - this is the attribute to keep the templating engine object. It is not mandatory that you follow this rule. If set prints out some debugging information to stdout. By default checks if $ENV{PLACK_ENV} eq 'development'. WebNano::Renderer::TT - Template Toolkit renderer with template inheritance WebNano::Controller::CRUD (experimental), - example blog engine using WebNano See Makefile.PL None reported. No bugs have been reported. Please report any bugs or feature requests to bug-webnano@rt.cpan.org, or through the web interface at. Jeff Doozan Zbigniew Lukasiak <zby@cpan.org> This software is Copyright (c) 2010 by Zbigniew Lukasiak <zby@cpan.org>. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible)
http://search.cpan.org/~zby/WebNano-0.007/lib/WebNano.pm
CC-MAIN-2016-26
refinedweb
1,293
52.9
I feel so dumb for not being able to figure this out. Maybe it's because I'm sick, but for some reason, I just can't get this program to work right. Currently, it's giving me an illegal operation before it prints one line. It's probably a pointer problem, but I can't figure it out. Anyway, the program is supposed to take in a phrase, then translate it to pig latin using the strtok function. (I'm just trying to get it to work with the phrase written into the code right now.) Also, we are to assume that the phrase has no punctuation and that all the words are at least two letters. On with the code. #include <iostream> #include <cstring> using namespace std; char printlatinword(char* token); void main() { char phrase[]="Hello world"; char* translation=NULL; char* tokenptr= NULL; tokenptr = strtok( phrase," "); while (tokenptr != NULL) { printlatinword(tokenptr); cout<< tokenptr <<endl; tokenptr = strtok(NULL," "); } } char printlatinword(char* token) { char* firstletter = NULL; char* translation = NULL; firstletter = strncpy(firstletter, token, 1); translation = strcat(token, firstletter); translation = strcat(token, "ay\0"); return *translation; } The problem is definitely in the printlatinword function. When I replaced the function call with a cout<<tokenptr statement, it printed the tokens without a problem.
http://cboard.cprogramming.com/cplusplus-programming/11421-i'm-stupid-help-me-simple-program.html
CC-MAIN-2015-22
refinedweb
211
62.17
Hi, the return value of the packing() function on a Crystal is an instance of a Molecule, not a Crystal, and the 'intermolecular' attribute of the HBondCriterion does not apply: all the HBonds are considered to be intramolecular, even if they are in disconnected components of the molecule. Additionally, the HBonds will not be found since the path_length_range attribute if the HBondCriterion is left at its default setting of (4, 999), requiring the HBond to be within a single connected component of the molecule. You can discover the HBonds by setting the path_length_range to (0, 999), allowing HBonds to be between disconnected components of the molecule, and you can determine which HBonds are between disconnected components by testing the shortest_path() method of the atoms of the HBond, that is to say criterion.path_length_range = (0, 999) criterion.intermolecular = 'ANY' packed = cry.packing() hbonds = packed.hbonds(hbond_criterion=criterion) inter_component_hbonds = [hb for hb in hbonds if packed.shortest_path(hb.atoms[0], hb.atoms[-1]) == 0] I hope this is helpful, If anything is unclear please get back to us. Best wishes Richard Dear Joanna, the definition of what constitutes an hbond is contained in the class molecule.MoleculeHBondCriterion. Here there are options for the geometry, the presence or absence of the hydrogen, and crucially for you, a means to specify atom types which may form a hydrogen bond. These are documented in the API in: I hope this is helpful. Best wishes Richard Dear Jose, you can use the python API to do this. For example: from ccdc import io with io.EntryReader('/path/to/file.sdf') as reader, io.EntryWriter('/path/to/file.pdb') as writer: for entry in reader: writer.write(entry) I hope this is helpful. Please come back to me if anything needs clarification. Best wishes Richard Dear Jack, I don't have an existing script to do this, but here is a sketch of how you might go about it. import os import glob from ccdc import io, descriptors directory = '/path/to/directory/of/cifs' cif_files = glob.glob(os.path.join(directory, '*.cif')) for cif_file in cif_files: with io.MoleculeReader(cif_file) as rdr: cif = rdr[0] for a1 in cif.atoms: for a2 in cif.atoms: print a1.label, a2.label, descriptors.MolecularDescriptors.atom_distance(a1, a2) It is worth noting that if you use an EntryReader to read the CIF file, all of the CIF attributes are available, for example, cif_entry = io.EntryReader(cif_file) a1 = cif_entry.attributes['_geom_bond_atom_site_label_1'] a2 = cif_entry.attributes['_geom_bond_atom_site_label_2'] length = cif_entry.attributes['_geom_bond_distance'] for a1, a2, length in zip(a1, a2, length): print a1, a2, length Hope this is helpful. Please come back with any questions you have about this, or indeed any other API matter. Best wishes Richard Hi Tahereh, in the API a component is a connected set of atoms and the bonds connecting them. These can be copies of the fundamental molecular structure as is the case with PENCEN03 where there are two copies of pentane, or different structures as in the case of ABEBUF. These may be solvent molecules, coformer molecules, cocrystals or salts. When we pack the unit cell, we can get copies of all these components in a single molecule. So in PENCEN03 you will get 10 copies of the pentane molecule. When we pack ABEBUF, we get eight copies of each of the two structures of the crystal. I hope this is clear. If not, I'll try to expand on it, or ask a crystallographer here to make things clearer. I really don't mind whether you open another topic or keep it here, but since it naturally follows on from your earlier question, perhaps here is best. Best wishes Richard Hi Tahereh, as long as the mol2 file contains the crystallographic information, i.e. a CRYSIN line, then we can do this very easily: from ccdc import io reader = io.CrystalReader('/path/to/crystals.mol2') for c in reader: unit_cell_molecule = c.packing() coordinates = [a.coordinates for a in unit_cell_molecule.atoms] The packing method of the crystal will return a molecule, which may be several disconnected structures, which are found in the specified box, which by default is the unit cell. There is an optional inclusion paramter to this method which controls whether or not to include atoms. By default this is to include the whole molecule if the centroid is found in the unit cell. Other options are, 'AllAtomsIncluded', 'AnyAtomIncluded' and 'OnlyAtomsIncluded'. Hope this is helpful. Best wishes RIchard Hi Frank, It looks as if you've spelled csd_licence.dat as csd_licencw.dat, so that may be the source of the problem. Incidentally, you're a brave man to be running these things as root! Best wishes Richard Hi Vladimir, the warning is issued by the underlying C++ code, and is not under the control of the python API. The only thing I can think of is to record the identifiers of the molecules involved before performing the search, possibly using ccdc.utilities.Logger, then inspecting the output. I'm sorry I can't be any more helpful at the moment. Best wishes Richard HI Frank, can you run mercury successfully? If so, the Help->About mercury should say where it found the licence. If the licence is in a non-standard place, i.e. not in CSD_2018/CSD_539/csd_licence.dat or /home/.../csd_licence.dat then you may need to set the environment variable CCDC_CSD_LICENCE_FILE to point to its location. Let me know if this works. Best wishes Richard Hi Frank, I think you need to set the environment variable, CSDHOME so the API can find where the CSD is located: export CSDHOME=/path/to/CCDC/CSD_2018 Try this, and see if that works, please. Best wishes Richard
https://www.ccdc.cam.ac.uk/public/5dd7c9a3-9189-e311-8b17-005056868fc8/forum-posts?page=1
CC-MAIN-2019-04
refinedweb
952
66.44
sqrt - square root function #include <math.h> double sqrt(double x); The sqrt() function computes the square root of x, An application wishing to check for error situations should set errno to 0 before calling sqrt(). If errno is non-zero on return, or the return value is NaN, an error has occurred. Upon successful completion, sqrt() returns the square root of x. If x is NaN, NaN is returned and errno may be set to [EDOM]. If x is negative, 0.0 or NaN is returned and errno is set to [EDOM]. The sqrt() function will fail if: - [EDOM] - The value of x is negative. The sqrt() function may fail if: - [EDOM] - The value of x is NaN. No other errors will occur. None. None. None. isnan(), <math.h>, <stdio.h>. Derived from Issue 1 of the SVID.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/sqrt.html
CC-MAIN-2016-18
refinedweb
139
76.11
This action might not be possible to undo. Are you sure you want to continue? A Study of Classic Maya Rulership A Dissertation submitted in partial satisfaction of the requirements for the degree of Doctor of Philosophy in Anthropology by Mark Alan Wright August 2011 Dissertation Committee: Dr. Karl A. Taube, Chairperson Dr. Wendy Ashmore Dr. Stephen D. Houston The Dissertation of Mark Alan Wright is approved: ___________________________________ ___________________________________ ___________________________________ Committee Chairperson University of California, Riverside Acknowledgements Countless people have helped bring this work to light through direct feedback, informal conversations, and general moral support. I am greatly indebted to my dissertation committee, Karl Taube, Wendy Ashmore, and Stephen Houston for their patience, wisdom, and guidance throughout this process. Their comments have greatly improved this dissertation; all that is good within the present study is due to them, and any shortcomings in this work are entirely my responsibility. I would also like to thank Thomas Patterson for sitting in on my dissertation defense committee on impossibly short notice. My first introduction to Maya glyphs came by way of a weekend workshop at UCLA led by Bruce Love back when I was still trying to decide what I wanted to be when I grew up. His enthusiasm and knowledge for the Maya forever altered the trajectory of my undergraduate and graduate studies, and I am grateful for the conversations we‘ve had over the ensuing years at conferences and workshops. I have continued to study the glyphs at the Texas Meetings at Austin, where I have met many wonderful people that have helped me along the way. The following (incomplete) list is comprised of people that I‘ve interacted with through email or at various conferences, symposia or ot her fora that have given me new insights or ideas concerning my research (and occasionally set me straight on some of my misguided theories). Some of the conversations were brief, others were more detailed, but all made an impact on me. In no particular order, thanks to Marc Zender, Alexandre Tokovinine, Stanley Guenter, Dorie Reents-Budet, Lucia Henderson, Erik Boot, David Stuart, Danny Law, Gerardo Aldana, Mark Van Stone, iv Peter Mathews, Bill Saturno, Kerry Hull, Julia Guernsey, John Clark, Allen Christenson, Michael Coe, Mathew Looper, Genevieve Le Fort, Andrew Weeks, and many others. This dissertation relies heavily on the foundation laid by two great scholars in particular, Pierre ―Robbie‖ Colas and Virginia ―Ginny‖ Fields, both of whom passed away unexpectedly during my time as a graduate student. Robbie‘s work on theonyms and divine titulary is the basis for a large portion of my Chapter 2, and Ginny‘s dissertation examined the origins of divine kingship among the Maya, which is a thread that runs throughout this entire work. I had the honor of knowing Robbie and Ginny, and they both provided me with resources and insights that proved critical to my research. Despite their genius, they exemplified kindness and humility. Thank you to my fellow graduate students in the Anthropology Department at UC Riverside for making the grad school experience much more enjoyable. Thanks especially to Laurie Taylor, Lauren Schwartz, Lucia Gudiel, Melissa Yeager-Farfan, Taisuke Inoue, Shuji Araki, Laurette McGuire, Mike Mathiowetz, Matt Yacubic, Shankari Patel, Patrick Linder,Christina Halperin, Reiko Ishihara-Brito, and Ryan Mongelluzzo, for great conversations over the years. I would also like to thank Brant Gardner and Diane Wirth for helping to create order out of the organizational chaos that I unleashed in the writing process. I would still be in bullet-point limbo were it not for their suggestions. I am greatly indebted for the financial support I received throughout this study to conduct research. The Foreign Language and Area Studies Fellowship Program (FLAS) funded my language studies in Yucatan in 2007 and 2009. The Ancient America v Foundation funded my language research in 2004 in Jocotán, Guatemala. BYU Religious Education Graduate Studies Grants funded summer research and attendance at the European Maya conference in 2008. I am grateful to the Maxwell Institute at BYU for awarding me the Nibley Fellowship yearly from 2003-2007. On a personal level, I would like to thank my mother, Janet Wright, for raising me in a house full of books about archaeology and a curio cabinet full of artifacts (legally obtained, of course!), for earning a certificate in archaeology from UCLA, for going off to Israel to dig at Tel Dan when I was a teenager, and for dragging me to my first Maya Weekend at UCLA. My love of archaeology (and a good portion of my library) came directly from her. None of this would have been possible without the unconditional love and support of my brilliant and beautiful wife Traci. We met when we were both in graduate school, and she has only ever known me as a stressed-out grad student. She has shown amazing resilience as I have left her for weeks and months on end to do fieldwork or attend conferences, and far too often even when we‘re together my mind ends up wandering around the ancient Maya area instead of truly being with her in the present. Yet she always makes me laugh and she‘s the only one capable of lifting my spirits when I‘m discouraged and she kept me going when I felt like giving up. Now that this chapter (or these five chapters, rather) of our life are behind us, my beloved ―dissertation widow‖ can finally have her husband back. Thank you for believing in me even when I didn‘t believe in myself, Traci. I couldn‘t have done it without you. vi Dedication For Traci vii and the composition and adaptation of local pantheons. ethnohistoric and ethnographic data to demonstrate there was significant local and regional variation in the way kingship was expressed through artistic programs. Contrary to that assumption.ABSTRACT OF THE DISSERTATION A Study of Classic Maya Rulership by Mark Alan Wright Doctor of Philosophy. accoutrements of power. Riverside. Chairperson Classic period Maya rulers are often reduced to ―ideal types‖ and are discussed in terms that would suggest they were a homogenous group of individuals cut from the same cloth. and complementary opposition. ritual activity. iconographic. The identity of each polity was inseparably connected with that of its ruler. calendrics. Graduate Program in Anthropology University of California. this study employs epigraphic. Taube. August 2011 Dr. duality. Karl A. sacred warfare. The underlying theoretical approach relies on concepts of mimesis and alterity. archaeological. and variations on the rulership theme served to reinforce their unique identity in the larger landscape vis-à-vis other polities. all of which are creative viii . the taking of theophoric throne names and titulary. ix . This study also examines concepts of divine kingship and deification. and argues that rulers were ―functionally divine‖ while living and were elevated to ―ontologically divine‖ status upon becoming apotheosized ancestors after death. both human and divine. they took their place in the pliable local pantheon which further reinforced the unique identity of each site. As apotheosized ancestors.acts which serve to establish a sense of Self in contrast to the Other. ..................... Sacred: The Contested Nature of Kingship among the Classic Maya ............................................................................................................................................................................................................................................................................................................................................................................. 23 Cross-Cultural Comparison and Ethnographic Analogy .......................................................................................................Table of Contents Chapter 1 Theoretical....... 19 Methodology and Methodological Concerns .............................................................................. 3 The Functional Divinity of Classic Maya Rulers .................................................................................................................... 1 The Theoretical Foundation .......................................................................................................... 43 Hierarchical Concerns..................................................................................................................................... 29 Mimesis of the Divine Realm .......... 14 Concepts of Self and Other........... and Methodological Foundations of the Study of Divine Kingship in Mesoamerica ........................... 1 Divine vs.............................. 15 Mimesis ............................................................................................................................................................................................... 23 The (somewhat) Direct Historical Approach ....................................................................... 41 The “Ideal Type” of Classic Maya Rulers ................. 26 Chapter 2 Royal Responsibilities ............................................................................................................................................................................................................................................................................................................... 35 Sacred Architecture ............................................................................................................. 9 The Divided Aspect of Divine Rule ...................................... 24 Epigraphy and Iconography ...................... 26 Outline of Text.......... 10 The Material Aspect of Divine Kingship .................... Historical............... 29 The “Ideal Type” of Classic Maya Polity ...................................................................................... 37 E-groups ............................................................................................. 12 The Uniqueness of Each Polity and the Creation of Identity........... 10 The Historical Foundation of Divine Kingship in Mesoamerica .................................................................................................................................... 7 The Social Aspect of Divine Kingship ........... 49 x ........ 45 The Divinity of Classic Maya Rulers ....................................................................................................................................... 29 The Polity ....................................... 32 The Royal Court .......................... 6 The Ideological Aspect of Divine Kingship .......................................................... ..................................................................... 175 Jester God.............. Bloodletting............................................................................................ 65 Rituals of Rulership............................................................................................................................................................................. and Conjuring ..............................................................Theophoric Throne Names and Divine Titulary ................................................... 172 Thrones ...................................................... 82 The Royal Ballgame ........... 149 Accession Phrases..................................................................... 77 Calendric Rituals and the Re-enactment of Creation ............................................................................ 136 Stages of Accession ....................... 141 Pre-Accession Rituals....................... 74 King as Time ............................................................................................................................................................................... 92 Chapter 3 The Passing of Rulership Among the Classic Maya ....................................................... Headdresses and Helmets .............................................................................................................................................................................................................. 143 Interregna............................................................................................................................... 55 Royal Artistic Programs .......................................................................................................................................................... 137 The Royal Succession........................................................................ 172 Headbands...................... 67 Raising of the World Tree ....................................................................................................................... 71 Impersonation Rituals .......................... 87 Summary ... 53 Regional Variation of Names ..................................... 179 Ko’haw Helmet ........................ 80 Ritual Warfare ............................................................................................ 179 xi ................................................................................................................................ 176 Turbans .................................................................................................................................... 79 The Sacred Landscape ........................................................................................................................................................................................................................................................................................... 73 The Significance of Sacred Time ............................................................................... 171 Dance ..................................................................................................................................................... 70 Dancing................................................................................................................................................................................................................ 66 Scattering............................................................................................................................ 61 Monumental Texts .......................... 150 Rituals and Accoutrements of Accession ............................................................... ..... 296 Commoners ................................................................................K’awiil Scepter ............................................................................................................................................................. 183 Chapter 4 Maya Gods and Ancestors .................................................................................................................................................................................................................................................................................................. 243 The Materialization of Gods and Ancestors.................................. 297 Recommendations for Further Research .............................................................................................................................................................. 261 Chapter 5 Summary and Conclusions .......................... 233 The Actions of Gods and Ancestors ............................................................................................................................................................... 244 Effigy Censers and Censer Stands ................................................. 242 The Morphology of Maya Gods .............................................................................. 223 The Ideology of Gods and Ancestors .......................................................................................................................................................................................................................................................................................... 294 Noble Women ..................................................... 250 Becoming a Deified Ancestor .. 293 Discussion........................................................................ 229 Euhemerized Ancestors ....................... 245 Royal Treatment of Godly Images .............................................................................................................................................................................................................................................. 252 The Cycles of Death and Rebirth................ 255 Known Depictions of Apotheosized Ancestors in Monumental Art ..................................... 247 Capture and Sacrifice of Gods .............................................................................................................................................. 236 Overseeing of Rituals ................................ 293 Overview ......... 298 xii .................................................................... 228 Local Patron Gods......................................................................... 224 The Eminence of Maya Gods ............................................. 227 Local Variation in the Maya Pantheon..................................................................................................... 181 The Burial and Deification of the King’s Predecessor ................................................................... 238 Gods as “Owners” ....................... List of Figures Chapter 2 Figure 2......4 Figure 2...........................................104 Dental modification mimicking the Sun God ..................20 Figure 2.113 La Pasadita Lintel 2....13 Figure 2........................... Ruler stripped of his titulary and clothing ......111 Uaxactun Stela 20......... ......................108 Tikal Stela 16...... Template for later stelae at Tikal ................. Summoning of ancestors through sacrifice ........................110 Quirigua Monument 26............................................102 Jadeite portrait denoting ruler’s childhood name ... Iconographic precursor to Uaxactun Stela 20 ......109 Tikal Stela 22........107 La Venta Stela 2..............99 Copan Temple 11 Bench...... Rulers and patron gods sit upon name glyphs ..................15 Figure 2..................... Modeled after Tikal Stela 16 .......115 San Bartolo West Wall Mural detail.. K’uhul.....22 Figure 2..........................................................................97 Piedras Negras Panel 3.......21 Figure 2. Ruler preparing to raise the World Tree .......... Supernatural portrait .... Type-site for E-Group Complexes.........................................112 Tikal Stela 4.................120 xiii ..........................116 Personified bloodletting implement .............................105 Royal titulary: K’inich......25 Figure 2.....98 Copan Altar Q.......94 Ek’ Balam Capstone 15. Preclassic sacrificial bloodletting .. Mimics Uaxactun Stela 20.26 Figure 2........... Ruler surrounded by supernatural beings ............1 Figure 2..................2 Figure 2.............100 Palenque Temple XXI Platform Face.............103 Tonina Monument 122.118 Detail of Pakal’s Sarcophagus............95 Group E at Uaxactun. Commemoration of Ruler 4’s k’atun anniversary ....................................27 Tonina Monument 183.....101 Naranjo Stela 22... Deceased ancestor interacts with ruler ...17 Figure 2.............. Scattering ritual performed by ruler of Yaxchilan .................... Model for Quirigua Monument 26 .............. The Ajk’uhuun Title ... Sahal..... “Shiny Jewel Tree” .............7 Figure 2.....6 Figure 2...................8 Figure 2.... T516 .....................3 Figure 2............ Dynastic sequence of Copan ........114 Yaxchilán Lintel 15....................9 Figure 2....... .................................24 Figure 2......16 Figure 2..96 Directional Kaloomte titles..5 Figure 2........ Ajaw...... Ukit Kan Le’k Tok’ deified as Maize God .......23 Figure 2......................10 Figure 2.... Example of iconographic rebus writing.. The uh te.......119 Variants of the “dance” glyph...................18 Figure 2.117 San Martin Pajapan Monument 1.............12 Figure 2....... .....11 Figure 2.19 Figure 2........106 La Venta Monument 25/26....................14 Figure 2... .........124 Copan Stela 16 and Quirigua Stela U.............. Ruler receiving headband .....................123 K2795......3 Figure 3. Nobles engaged in an impersonation ritual .188 Palenque Pier C........11 Figure 3...128 Copan Stair Block II of Structure 10L-16. T644..........37 Figure 2.133 San Lorenzo Monument 34.......... Ruler deified as Sun God ....2 Figure 3.38 Figure 2....30 Figure 2........... K’an Bahlam as the god Unen K’awiil (GII) ....40 Figure 2....127 Tikal Stela 31 detail........... PNG....13 Palenque Temple XVIII Stucco Sculpture............................. ..................32 Figure 2.....122 K2695..... A ruler receives a mask prior to an impersonation ritual ...........................1 Figure 3...........197 Piedras Negras Stela 25. Period of lamentation ...............121 Quirigua Altar L..........34 Figure 2...131 Palenque Temple of the Sun................... Ruler presented with war regalia by parents ................. Youthful lords kneeling in submission before ruler ........................130 Palenque Palace Tablet............. Bird Jaguar IV engaging in pre-accession rituals .4 Figure 3........ Supernatural accessions ...129 Palenque Temple XVII Tablet........................41 Figure 2.8 Figure 3.....36 Figure 2......7 Figure 3................................. Placing in order of hiers........187 Palenque Pier B........................191 Accession phrases: T684......5 Figure 3....................199 xiv .....31 Figure 2..198 San Bartolo Murals..28 Figure 2................... Olmec ruler in ballplayer garb..35 Figure 2..... T670 .....6 Figure 3.............192 Palenque Temple of the Inscriptions East Tablet.........126 Palenque Temple XIX Platform............ Anomalous calendric reckoning ......... Central Mexican-style war regalia .... Scaffold accession scene.... Ruler offers emblems of war to GIII .. A captive ruler is costumed prior to sacrifice ..........190 Yaxchilán Stela 11............. Ruler presented with regalia ........................................ Niche stela accession scene .............194 Palenque Tablet of the Cross.. Palenque.....10 Figure 3....................195 Palenque Temple of the Cross West Sanctuary Jamb.. Rare militaristic scene from Palenque ..............135 Chapter 3 Figure 3..... T713/757........ Earliest glyphic reference to dance ...... Innovative accession template ..33 Figure 2............39 Figure 2......42 San Bartolo West Wall Mural Detail. Ancestral headdress ......... Resurrecting Maize God............... K’an Bahlam cradled by deceased ancestor ..Figure 2................9 Figure 3...29 Figure 2........12 Figure 3.....132 Tonina Monument 155.125 The “First Three Stone Place” from Quirigua....193 Palenque Oval Palace Tablet..196 Palenque Palace Tablet.........134 Ballplaying scenes from Yaxchilán ..189 Piedras Negras Lintel 2. and Dos Pilas .... .....................29 Figure 3..............209 Tonina Monument 111.....213 Palenque Tablet of the Slaves............... Bird Jaguar IV’s “seating” six days after his accession ..31 Figure 3......14 Figure 3......208 Tonina Monument 144.33 Figure 3...........15 Figure 3...218 Dos Pilas Stela 1. The ko’haw helmet ...217 Copan Altar Q Detail.212 The Leiden Plaque.....202 Quirigua Stela E......22 Figure 3................. Only known dance performed on accession day .216 Formative period example of trefoil headband ................................................35 Figure 3.. Bloodletting ritual recorded on day of accession ................................... Earliest contemporaneously recorded accession ......36 Incised Bone.... Quirigua ruler accedes under the auspices of Copan’s ruler . Ko’haw helmets ... Caracol........ Possible niche accession scene .................. Down-gazing ancestor .....................................20 Figure 3.........................................200 Copan Stela 9............210 Yaxchilán Lintel 21..270 Kaminaljuyu Stela 11....269 Caracol Stela 6..................26 Figure 3...219 Palenque Temple of the Inscriptions Central Panel........18 Figure 3........4 Figure 4... Ruler 4 .......... Turban as marker of Copanec identity ......214 Variety of Jester God headbands .....203 Quirigua Stela J...................222 Chapter 4 Figure 4.....................................3 Figure 4....... Last known accession statement at Copan .......................... K’ahk’ Tiliw’s accession ......... K’uk’ Bahlam I .... Teotihuacan influence on Maya iconography ..23 Figure 3.... Scaffold accession scene ............207 Tikal Stela 29..................16 Figure 3.................................205 Quirigua Stela I (east face)............21 Figure 3.................19 Figure 3. Ruler being presented with regalia ........27 Figure 3............30 Figure 3.....267 Ixlu Stela 2.......271 xv . Dallas Museum of Art.......................2 Figure 4............32 Figure 3...... Ritual overseen by deified ancestor .............201 Copan Altar L...28 Figure 3..............34 Figure 3.....5 Triadic grouping of gods: Palenque.206 Tikal Stela 31. Another account of K’ahk’ Tiliw’s accession ...................................220 Parentage statement linking mother to child . Tikal.................................25 Figure 3...... Naranjo ................. Paddler gods oversee a scattering event ...................................................................215 Olmec pectoral.....204 Quirigua Stela I...17 Figure 3......................268 Censer stand portraying Palenque’s founder. Wahy spirits .......Figure 3........ Earliest depiction of a ruler from Tikal ......... Retrospective record of accession ......................................211 Yaxchilán Lintel 1....................................................... Earliest known example of “seating” glyph .................1 Figure 4..........221 K791..24 Figure 3......... ........................... Maize God resurrection scene ....281 K731............ detail of Sarcophagus lid.........274 Hauberg Stela.......................9 Figure 4...... Sun God imagery. Pakal resurrecting as Maize God .............................290 Tikal Stela 22.............16 Figure 4.............14 Figure 4.......19 Figure 4..............288 Palenque......291 Caracol Stela 5....272 Yaxchilán Stela 1.........10 Figure 4............ solar ancestor .. Non-ancestral supernatural beings overseeing rituals ................279 Quirigua Stela I........... Yax Pasaj resurrection scene .... Deified solar ancestor floats above ruler’s head... Only known depiction of a deified ancestor at Caracol ............ Ruler 4 making an offering to entombed ancestor ............23 Figure 4.................... Down-gazing ancestor ... Ancestors sprouting as trees ....275 Censer stand from Palenque depicting Jaguar God of the Underworld ....289 Examples of deified ancestors in solar and lunar cartouches .7 Figure 4..............................................17 Figure 4.....25 Figure 4................276 Portrait-style incensario from Palenque ..12 Figure 4...............282 Censers from Copan depicting deified ancestors as cacao trees ........... ................277 Piedras Negras Stela 40.........Figure 4............15 Figure 4....................................285 Yaxchilán Hieroglyphic Stair 3 Step III...13 Figure 4... Ancestors in solar and lunar cartouches ..........................................21 Figure 4..............287 Copan Stela 11..6 Figure 4......11 Figure 4.......273 Jimbal Stela 1.280 Tikal Temple IV Lintel 2............ The god Yaxhal Chaak depicted as owner of stela ...... Supernatural “travelers”.22 Figure 4.....26 Naranjo Stela 45...... Sarcophagus lid..........283 Copan Stela A Detail...286 Palenque.. Tikal boasts of capturing Naranjo’s patron god ................ Uk’it K’an Le’k as deified..........284 Ek’ Balam Stela 1..20 Figure 4........278 El Zapote Stela 1.............. The capture and burning of Copan’s patron gods ....24 Figure 4... Sun God within cosmic caiman’s belly ...292 xvi ................... .8 Figure 4.18 Figure 4...... methodology.Chapter 1 Theoretical. As data have become more abundant. therefore. Maya scholars typically referred to kings by the general designation ―rulers‖ (Morley 1911. The second question asks what it means for a ruler to be divine. The trend has been a move away from generalized metatheories that attempt a cross-cultural explanation for the institution of divine kingship and a move towards concentrated micro-theories that find little application outside of a specific time and place. Michael Coe 1 For an in-depth analysis of the many problems in Frazer‘s The Golden Bough. it has become clear that the Maya area was a heterogenous palimpsest of cultures and polities with a great deal of variation across space and time. asks which Maya are being discussed. see Feeley-Harnik (1985) 1 . In 1961. How was divinity conceptualized? What was the ruler‘s relationship vis -à-vis the divine realm? Up until about 1960. Proskouriakoff 1960). but the years have not been kind to his data. Historical.1 The ensuing decades have seen a great many more works on the subject in general and on regionally specific institutions of sacral rulership (Feeley-Harnik 1985). The first question. or conclusions. and Methodological Foundations of the Study of Divine Kingship in Mesoamerica The Theoretical Foundation The academic study of divine kingship was first popularized by Sir James Frazer‘s magnum opus The Golden Bough in 1890 (Frazer 1890). Among the Maya. the study of divine kingship is something of an exercise in infinite regression. based on recurring intervals of dates on the monuments of Piedras Negras that she presciently determined were birth. and arrogated their divine power. Proskouriakoff (1960) was the first to demonstrate that the individuals depicted on monuments were historical rulers. J. inauguration.(1961:74) intimated the lack of understanding of Classic rulership when noting that certain multi-room structures likely belonged to ―a king. a priest or ruler. priest. or whoever ruled the Classic Maya. Eric Thompson (1973) was one of the first to systematically demonstrate that Classic period Maya rulers were considered divine. Coe (1972:9) was referring to Maya rulers as ―divine kings. ultimately. were selected by them to act as their mouthpieces.‖ Based on the then -recent discovery of the sarcophagus in the Temple of the Inscriptions at Palenque and other similar finds across the Maya area. A more intensive study of divine kingship was launched by Schele and Miller‘s 1986 catalogue The Blood of Kings: Dynasty and Ritual in Maya Art. followed by Schele and Freidel‘s A Forest of Kings (1990) and. he argued that ―one can infer the existence of more powerful political authority at the head of the Maya social order than has yet been assumed by writers on this questions – perhaps even absolute kings‖ (ibid. Within a decade. 1976).). noble. prince.‖ Mayanists were similarly unsure whether the individuals depicted on monuments represented ―a deity. Drawing upon ethnographic analogies from Late Postclassic Yucatan and Central Mexican polities. The terms ―divine kingship‖ and ―divine rulership‖ began entering the common parlance of Maya studies by the mid-1970s (see Furst 1976. he argued that rulers claimed descent from the gods. or an abstract conception symbolically portrayed‖ (Proskouriakoff 1950:4). and death dates. forged into a trilogy by Schele and Mathews‘ The Code of Kings 2 . Robertson et al. Kaplan 2001. The broad strokes used in the following section will provide the backdrop for the detailed analysis in the chapters to follow. The most concise work on divine kingship among the Maya has been Houston and Stuart‘s (1996) article “Of Gods. This chapter provides an overview of the theoretical underpinnings. This umbrella term encompasses a great many institutions that manifest themselves in disparate ways. Rice 1999.‖ which has been cited in virtually every ensuing work on the subject for its authority rather than by way of critique (Beekman 2004. Webster 2000). Glyphs and Kings: Divinity and Rulership Among the Classic Maya. a medium through which the divine 3 . Sacred: The Contested Nature of Kingship among the Classic Maya In the nearly six katuns that have passed since Frazer‘s Golden Bough. Trigger 2003. historical foundations. Vail 2000. a ―sacred ruler‖ may be thought of as a conduit of supernatural power. much has been published on the topic of divine kingship. Zender 2004.‖ and the other two books in the trilogy are likewise showing their age. In general terms. Colas 2003a. Freidel (2008:192) himself recently acknowledged that A Forest of Kings is ―now thoroughly obsolete as a result of advan ces in textual decipherment and archaeology. Among some cultures the ruler is explicitly divine—a god on earth—whereas in other cultures he or she may be mere representatives of the divine or supernatural realm. Lucero 2003.(1998). and methodological approaches and concerns that will inform the remainder of the dissertation. Although the works by Schele and her collaborators were ground-breaking and still have much to recommend them. Looper 2003. Martin and Grube 2008. Divine vs. deals with internal beliefs and is a cognitive function that is difficult to quantify or subject to empirical testing (Sachse 2004:3). with no apparent clues from the iconographic or ethnohistoric record. The challenge to modern students of ancient Maya religion is the inescapable fact that religion. it examines the variety of ways the institution of kingship was expressed at the local and regional levels and seeks to understand the significance of variation across space and time. Schele. material manifestations of how their religion was practiced. but nothing else is known about this mythological event (Miller and Martin 2004:105). Among researchers of the ancient Maya. In addition. Freidel.2 Entwined with the debate concerning the divinity of Maya rulers is the ongoing debate as to whether the rulers were ―shamans‖ or ―priests‖ (Houston 1999:60). 4 . We are left with the external.passes. 2008. Freidel and Guenter 2006) continues to be a vocal proponent. and Parker (1993) laid out the most detailed arguments for the ―shaman -king‖ concept. it tests the assertion that the rulers were divine kings in the fullest sense: living gods on earth. 2 For example. This dissertation examines the nature of kingship among the Classic Maya. in large measure. with precious few textual clues as to their underlying beliefs. there is still little agreement concerning how ―divine‖ these rulers were considered to be by the ancient Maya themselves and what their role was vis-à-vis the divine realm (Houston and Stuart 1996). In particular. we find obscure and singular textual references to mythological events we know nothing else about. and Freidel (2002. on the Creation Tablet at Palenque there is a passing reference to the beheading of a ―day fisherman‖ and a ―night fisherman‖ by an important local god. At times. whereas a ―divine ruler‖ is a receptacle o f supernatural power and possesses that power in and of himself. . and Zender (2004) — because shamans are traditionally dissociated from state-level societies and stand at the fringes of those societies of which they are a part (for contrary views.While there is no question that the Classic rulers used religious symbols and ideology as a means of legitimizing their right to rule. Rather than shaman-kings. Marcus (2002). (2002). but likewise by Kehoe (2000). Thomas and Humphrey 1994:1-12. McAnany (2001:143) similarly notes that although many of the duties performed by rulers are similar to those performed by shamans. so did the ecclesiastical bureaucracies. the conjuring of ancestors is an expression of their authority. Marc Zender (2004) argues for the existence of a bureaucratic priestly class among the Classic Maya. At issue is the anthropological definition of what it means to be a shaman. Pasztory (1982). as there is little epigraphic or iconographic evidence to support it. and suggests that the rulers were ex officio high priests. The very use of the term shaman and its application to ancient Mesoamerican rulers has been severely critiqued in recent years — most harshly by Klein et al. David Stuart (2002:411) believes that the shaman king concept is faulty when applied to the Classic Maya case. rather. yet some ―shamanistic survivals‖ can be found in their beliefs and practices that are holdovers from an earlier era (ibid. Vitebsky 2001:116-119). see Humphrey 1994.‖ 5 . ―their authority stems not from their ability to conjure ancestors (as among contemporary Tzotzil shamans). He acknowledges that there are some shamanic aspects of rulership in the Early and Middle Preclassic periods and suggests that as Maya societies grew more complex. 2004:79). The Functional Divinity of Classic Maya Rulers The question remains as to how divine the ancient Maya rulers actually were. The word is based on the root ch’uh/k’uh. I argue that Classic Maya rulers were ―functionally divine‖ (Selz 2008:16) rather than ―ontologically divine‖. and not just during certain rituals. that is to say.‖ Among Zinacantecos. so his power was functionally equivalent to that of the gods. He could propitiate. Ancestor worship was clearly a central element of their religious practice as well. they ―responded with the names of former and contemporary rulers. and expressions addressed to supernatural forces‖ (Tate 1999:181). for all intents and purposes. the names of royal ancestors. as well as in objects that provoke 6 . they acquired god -like powers from the divine realm and they functioned as gods to their subjects on a full-time basis. The ruler had pragmatic control over the elements and it was his responsibility to keep the cosmos in their proper order through proper ritual action. The ethnographic concept of ch’ulel aids our understanding Classic Period kingship. Central Mexican ethnohistoric accounts demonstrate the prominent place that the worship of living and dead kings held. This is not to say that the king was the exclusive entity worthy of devotion by commoners. but they were not self-possessed of divinity. among both elites and commoners (to be discussed in Chapter 4). ―god. ch’ulel is the animating ‗inner soul‘ that dwells in humans and gods. The relationship between kings and their gods was paralleled by the relationship between the people and their king. interact with. and even control the supernatural realm on their behalf. when the Zapotecs were asked about their gods by the Spanish. ancestry. or holy crosses. Evon Vogt (1976:141) notes. Rulers even took upon themselves the title k’uhul ajaw. such as musical instruments. and continues on to the diurnal paradise of the sun after death (Guiteras-Holmes 1961:150. beauty. flowers. and so on—and a person‘s status and position within a hierarchy may shift throughout his or her life as attributes are developed or lost. instead. 270). a stance that Gramsci labels ―hegemony‖ (Lawner 1973). The factors affecting a person‘s status can vary—physical might. wealth. salt. Ch’ulel resides in the heart and circulates through the bloodstream. The Ideological Aspect of Divine Kingship Social hierarchies must be legitimized to maintain order in a society. Hegemony refers to the widespread acceptance by commoners of elite 7 .‖ Each person possesses ch’ulel. This soul is considered immortal and indestructible (Vogt 1965:33). divine sanction. it wasn‘t just their blood they were offering. As a matter of self-preservation. but that of Classic Maya kings was closer to that of the gods than to the commoners. 176. it is. charisma. as we would perceive them. so when rulers performed autosacrificial rites. ―godlike/holy lord‖ upon accession to distinguish themselves from mere humans (to be discussed later).physical and emotional sensations. those at the highest levels of society—the ruling class—seek to establish the legitimacy of their positions and do all they can to ensure that their ideology is embraced by their subjects. nor between persons and objects. it was their very soul (Schele and Mathews 1998: 413). intelligence. ―the most important interaction in the universe is not between persons. between the ch’ulel souls possessed by these persons and objects. skills. Regardless of whether the event was a ritual. Concomitant with ritual is myth.‖ although admittedly the categories do at times overlap (ibid. there was a distinction between public and private rituals. a spectacle. However. and Classic Maya rulers similarly relied upon mythology to legitimize their right to rule (Schele and Freidel 1990.).). religious ritual refers to ―an agreed-on and formalized pattern of ceremonial movements and verbal expressions carried out in a sacred context‖ (Livingston 2005:81). and Parker 1993. Freidel and MacLeod 2000). A common way for elites to legitimize their status is through ritual. Coe (1989) has shown the great influence that the mythical charter set forth in the Quiche Popul Vuh had in the legitimization of authority. Among its many definitions. but as Kerr (2000:1) 8 . but nevertheless continued to reflect their Formative roots‖ (ibid. The initial process of legitimization works within an established system of belief. he or she is then in a position to modify the beliefs and practices of their subjects through hegemonic means (Ringle 1999:186). after the ruler‘s legitimacy has been established. Freidel. ―ideology provided a set of metaphors whose application to society grew and changed over time. or a performance. Reese 1996.ideology vis-à-vis the social and political order. Schele. which essentially serves to ―naturalize‖ the system in the eyes of the people. Kappelman 1997. We may be tempted to view all public ritual as a spectacle or performance. Rituals serve to unite a community (Durkheim 1995) and are a vital part of group identity. Among the ancient Maya. ―ritual ≠ spectacle ≠ performance. but as Houston (2006:135) succinctly states. Among the Classic Maya. all public events enhanced the sense of cohesion in Classic Maya society and the effectiveness of divine rulers (Rivera Dorado 2006:829). As they witnessed the interaction of their ruler with their local gods. but the present discussion is concerned with the sense of identity of the polity as a whole. as he performed rituals on their behalf in their city center. the king was further exalted and the people were drawn together with a unified sense of identity. The Social Aspect of Divine Kingship Along with their roles as religious and political leaders. Schele and Freidel 1990). with the king himself standing as the living axis mundi to his subjects (Schele and Miller 1986:77). with the center of power found in the main plaza or acropolis (Valdés 2001:138). 3 There were certainly subgroups within each polity that identified themselves through kin or other local groups (Inomata 2006:833). there were surely distinct versions of the tale that varied from region to region according to local traditions. Through their participation in these events they reaffirmed their sense of belonging to that particular society and reinforced their identity as a cohesive group (Durkheim 1995 [1912]). created a space where large groups of citizens could enter sacred space and participate in sacred events (Freidel et al.points out. the city itself marked the fifth cardinal direction. McAnany 1995. The rulers created these sacred spaces. 9 . Classic Maya rulers were also ―social leaders who served as embodiments of community identities‖ (Inomata 2006:832) that created social integration within the community. and in so doing. 1993. The king‘s person had a unifying effect on his polity and played a vital role in the creation and maintenance of group identity for those living within it.3 In the quadripartite cosmos. Braswell (2001:313) argues that rulership was divided among multiple individuals as a way to distinguish between ―power‖ and ―divine authority. written documents. symbolic objects.‖ charging that the phrase implies a singular command of the polity (Becker 2006:821). there was clearly a bureaucratic organization that governed Classic period polities. He further argues that sacred rulers effectually lost power because they were conceptually distanced from their subjects to the point that they were unable to directly exercise force upon the general populace. 1996:16). it would be a mistake to suggest that he ruled with unilateral power and authority. DeMarrais et al. and ceremonial 10 .‖ which was necessary to resolve the contradictory pressures of the preservation of power and the maintenance of sacred authority.The Divided Aspect of Divine Rule Although the ruler stood as the ideological and social center of his polity. and…the opposed centripetal and centrifugal tendencies of sacred rulership were an important source of instability in Maya political systems‖ (Braswell 2001:313). meanings are ―envehicled‖ in symbols (Geertz 1980:135). to take religious beliefs and concepts and fashion them into objects that range from the portable to the monumental for the purpose of communicating that ideology to others (DeMarrais et al. Although not completely understood. Some scholars have opposed the term ―divine rule. The Material Aspect of Divine Kingship There is a human tendency to materialize ideology. He declared that ―‗[d]ivine kingship‘ is an oxymoron. In so doing. (1996) suggest four ―means of materialization‖ in which the profane is transformed into the sacred: public monuments. There was regional and site specific variation in the use of sacred objects. Vogt 1981). In all of these ―envehicled‖ symbols. the supernatural takes a natural form. Schoenfelder (2004:402). and places are all necessary in providing a phenomenological experience for both participants and observers. events. caves. in discussing the Balinese. In other words. and the performative. adds a fifth means that is equally salient among the Maya: profane flesh is made sacred in the bodies of cultural experts. Ritual objects. we may add a sixth: sacred geography. and possession and ritual use of sacred objects enhanced their claims. it is through an individual‘s embodied experience (either as participant or observer) that their beliefs are authenticated (Dornan 2004:29). rivers. For the Maya. reinforce. and intangible beliefs are made into tangible objects of devotion. experiential aspects of beliefs and symbols are critical in imbuing beliefs with meaning (Eliade 1963). Ritual has the power to create. and authenticate belief through the subjective experiences of participants. To these. and other geographic features were all places that were imbued with an extra portion of sacredness and such features may have influenced their site planning principles (Brady 1997.events. referring to natural features that are not of human creation but that are made sacred through human ideology. cenotes. The power held by Maya rulers was legitimate in that it was believed to be legitimate (Weber 1978) both by the rulers themselves and by their subjects who consented to that authority (Dornan 2004:30). and these will be discussed in their contexts in later chapters. mountains. 11 . but rather prefer to see the Olmec as a cultura hermana. and symbolic systems created by the Olmec were diffused to their less complex contemporaries and later successors (Pool 2007:16). Clark and Pye 2000. Not all scholars agree with the cultura madre claim for the Olmec. Hammond 1988). The Olmec are both poorly understood and poorly defined (Pool 2007:12). Many scholars continue to carry the cultura madre torch (Clark 1997. Cyphers 1996:61. The essential argument is that the complex sociopolitical institutions.C.‖ Clark and Pye (2000:218) more loosely define the Olmec as ―a politicoreligious entity (or several) of societies and peoples with deeply shared cultural practices‖ that reflects a ―cultural and/or political commitment to certain beliefs. Diehl and Coe 1995. Flannery and Marcus 2000. Tolstoy 1989). Taube 1995. 1996. Grove 1997.The Historical Foundation of Divine Kingship in Mesoamerica The first great civilization in Mesoamerica was the Olmec. cultural practices. or Sister Culture to other Formative societies that all shared a common ideological and symbolic ancestry and who mutually interacted and influenced one another (Demarest 1989. Christopher Pool (ibid. such as the use of lime 12 . which has been conceptualized as the cultura madre or ―mother culture‖ of later Mesoamerican civilizations since the days of Matthew Stirling (1940:333). practices and material representations‖ rather than a specific ethnic group.) restrictively defines them as ―the archaeological culture of the southern Gulf Coast that existed from about 1500 to 400 B. 2000. They point to traits that are attested to among contemporaries of the Olmec but that are not found among the Olmec themselves. Alfonso Caso (1942:46) and Miguel Covarrubias (1944). Taube (2004c:42) similarly posits that ―it is clear that the Zapotec. see also Lesure 2004:79) argues that social stratification and a pronounced political hierarchy appeared first in Olman. contributed significantly to the development of later Mesoamerican civilizations. Maya. including the Olmecs. The debate between the Mother Culture and Sister Culture adherents is still far from over. Flannery and Marcus (2000:6) have admitted that ―the Olmec look impressive relative to their contemporaries‖ and they concede tha t the Olmec were more advanced than some of their contemporaries and contributed much to them and later cultures. 13 . but they ultimately feel the Mother Culture adherents ― credit the Olmec with many things their neighbors did earlier or better‖ (ibid.:2). and stone masonry by Central Mexican cultures. and many Early and Middle Formative societies.plaster. Olmec societies influenced some of their neighbors and interacted with others to different degrees and in diverse ways. although there has been some inching towards a middle ground. Pool (2007:17. has at least acknowledged that the Olmec did not hold unilateral influence over their contemporaries (1997:230) and that many aspects of Maya culture date to pre-Olmec times that are indigenous to the Maya area.‖ It seems clear. and other Formative peoples outside the Olmec heartland were not simply diluted Olmec. all of which became widespread during Classic period civilizations (Flannery and Marcus 2000:8). John Clark. but people who possessed their own distinct cultural patterns and trajectory. clearly indicating that certain aspects are not Olmec in origin (Clark et al. In the Sister Culture corner. the reigning heavyweight champion of the Mother Culture cause. The truth probably lies somewhere in the middle. adobe brick. 2000). ‖ yet the Maya adapted these Olmec institutions and made them uniquely their own. Referring to distinct Classic Maya polities.‖ Clark and Hansen (2001:34) claim. to the point that they explicitly linked themselves to the Olmec by both treasuring and modifying Olmec heirloom jades (Schele and Freidel 1990. and the prized status of jade and quetzal plumes and their use in royal ritual (Taube 2004c:46). Of these. that some specific ideological concepts and artistic styles found among cultures such as the Zapotec.however. the early Maya showed the most similarity (Fields 1989. Schele 1995) and creating their own imitations of them (Freidel et al. ―the Maya appear to have borrowed from institutions of Olmec kingship and sacred space. the most significant ideological inheritances and material influences that the Classic Maya received from the Olmec are those associated with rulership: stelae celebrating a particular ruler and/or his gods. a concept that will be explored in more depth below. The Uniqueness of Each Polity and the Creation of Identity From an outsider‘s perspective. the cult of rulership. Teotihuacan. stone thrones. Rosemary Joyce (2005:308) argues that there is ―no support for the idea that adherents of different factions or alliances recognized each other as part of a 14 . and the early Maya have their origins in the Olmec. Freidel and Suhler 1995. They clearly conceptualized themselves as being different from their neighbors. 2002:46). bloodletting. However. For our present discussion. the differences between c losely related groups appear to be overshadowed by their similarities. Taube 2004c:46). ―On all counts. ancient Maya polities seemed to have been preoccupied with distinguishing themselves from their neighbors. conventionalized body poses and portraiture. and what significance can we attribute to them? To answer these questions. there is no sense 15 . Beyond the factions within particular polities. covert dissent. they of necessity shared much in common. How did the similarities and the differences come about. no two Maya cities are identical nor are any specific aspects of any two Maya cities identical. In the written records. But Inomata cautions that ―multivocality does not necessarily mean outright rejection of religious beliefs but may entail varying degrees of commitment to such beliefs. Concepts of Self and Other Each Maya polity was composed of a self-contained group of individuals whose identity was unique to its specific place and time. indeed. Yet despite this multivocality and the existence of disparate factions. there is a great deal of variation from one site to the next. a fundamental discussion of identity creation and the concepts of Self and Other in is order. ―groups that individuate themselves within a community of this sort are connected to each other by shared principles of individuation‖ (Harrison 2003:352). and individualized ways of internalizing religious notions‖ (ibid. Indeed.single overarching entity. indifferent conformity.‖ Inomata (2006:832) similarly argues that we must ―recognize the problem of uncritically assuming the homogeneity of culture and note the prevalence of multivocality‖ when dealing with the ancient Maya. Yet despite the many similarities. there is clearly a great deal of similarity between ancient Maya polities—enough that we can confidently place them under the umbrella category of ―Maya‖ and make distinctions between them and non -Maya cultures that coexisted with them in Mesoamerica.). of a cohesive ―Maya history. Sharer and Golden 2004. primarily from the Olmec (Coe and Diehl 1980.‖ but rather their histories focused on the specifics of their own individual polity (Stuart 1995).4 It appears that each city-state had its own historical traditions and origin myths and each ―conceived of itself as an independent player in the passage of the tun and katun‖ (Stuart 1995:171). The common symbols allowed them both to identify with and to distinguish themselves 4 For a discussion of cross-culture models concerning the organization of Classic period polities (Segmentary State model [based on African models] vs. Theater State model) see Chase and Chase 1996. 5 Importantly. as discussed above. Marcus 2003. Geertz 1980. Beyond creating identity by sharing practices amongst themselves. Demarest 1992. for contrary views. not just with any others at random. but with specific others with whom they represent themselves as having certain features of their identities in common. For it is only when people identify with one another that a felt need can arise for them to differentiate themselves. Clark 1997. ethnic. despite their differences. they are united by the shared visual language that was used to express those differences (Harrison 2003). Yet their cultural. which can be either explicit or unacknowledged. Inomata 2001. and historical identity—their Self—was also created through ambivalent relations to the neighboring Others who were not a part of their specific group (Wobst 1977:329). Galactic Polity model [based on Southeast Asian models]) vs. 5 Wiener (1990) coined the term ―Versailles effect‖ to describe this phenomenon in the Old World. the commonalities in the features that identify each group derive in large measure from a shared ideological ancestry. Among the Maya. see Grove 1997. as well as from contemporaneous mutual emulation. Flannery and Marcus 2000). Harrison (2003:345) argued: Groups define themselves through contrasts. Constructivist approaches to the creation of ethnic identity suggest that peoples actively create and define their ethnic affiliation through their shared cultural practices (Jones 1997). Webster 2000. 16 . 17 . the notable variability in Maya elite culture may have existed both for historical reasons and as a means of reinforcing such differentiation between dynasties. yet they emphasized their differences from each other by the pan-Maya gods that held preeminence at their particular polity. ―conventionalized representations expressed conventionalized ideas among the Classic Maya. the ancestral deities would differ from site to site. Stuart and Taube (2006:2) argue. Schortman (1989:58) suggested that. Yet despite the many superficial similarities. Each community seems to have identified itself by and consecrated itself to a specific deity cult (Houston 2000:166).). there also appear to be distinctions in the roles these deities played at each site. Sabloff 1986). all Maya polities are similar in that they propitiated both major gods and local ancestors. As Houston. For example. Freidel (1979:50) has shown that the similarities among Maya polities span a wide range of regions. and obviously. However. and regalia (Morley and Brainerd 1983. At Copan. writing systems. kings had deities that were so personalized that both ruler and god were enthroned on the same day. and calendrics. which stands in stark contrast with Palenque‘s gods that transcended individual kings (ibid. Houston (ibid. rituals.‖ Some of the conventions included general site -planning principles (Ashmore 1986). even across great distances and culture areas.) argues that the gods of a certain city aided in the creation of the unique ethnic identity of that individual polity: [C]ontrasts in belief and ritual practice would have been as effective a mechanism as any in distinguishing such communities from their neighbors.from each other. there is considerable local variation on most if not all of these points. as well as sociopolitical sytems. 1957:199. there is a double movement. where the Other is simultaneously emulated and repudiated. the Other represents a kind of screen upon which both the despised and the desired aspects of the Self can be projected. This concept is not new. 1964:91) long ago commented on the ―narcissism of minor differences. as part of a strategy by its members to promote and control the flow of goods among their dispersed localities. . so that the dialectics of sameness and difference is resolved into a kind of difference in sameness. That is to say. It is rather to be understood as a denial of resemblance to the Other and a disavowal of them in regular and systematic ways. and difference-as-equality. ―constructs of difference and of shared identity always exist together. and were used to symbolize membership in.the shared material patterns noted reflect the existence of. Freud (Freud 1930:114. 1945:101. may be seen as superior in relation to the Self. and the source of this ambivalence is the recognition of Self in Other. As Sax (1998:294) argues. yet this systematic denial of similarity can only work within their closed system of shared symbols. Perceived differences are not always negative. it may b e useful to employ Harrison‘s (2003) three categories of differences and denied similarity between Self and Other: difference-as-inferiority.‖ Polities that are geographically the closest often make the greatest efforts to emphasize their differences. a spatially extensive salient status system that linked the rulers of a number of different independent polities. This creation of group identity goes beyond simply emphasizing the differences between a group and their neighbors. but they may also be perceived as equals and. difference-as-superiority. In discussing the Classic Maya. As Harrison (2003:345) states.‖ where closely related groups of 18 .C. The postulated identity system apparently developed as early as the last centuries B. The Other may be seen as inferior. admired and despised. in some instances. what Taussig (1993) terms alterity. . . Sax 1998). and the highest admiration was for those who were most distant. In keeping with Freud and later theorists who shared his view (Harrison 2003. Valdés 2001:138).‖ and this appears to be true of political relationships in ancient Mesoamerica. The fiercest rivalries were often between those polities who were geographically the closest.people tend to exaggerate the differences between their own group and their neighbors. and suggested that those with the most in common are those who make the most effort to differentiate themselves. architecture. and 19 . I argue that the Maya went to great trouble to differentiate themselves from their neighbors for purposes of identity creation and reinforcement. both spatially and temporally. only occasionally interspersed by alliance and cooperation‖ (Miller and Martin 2004: 20). Classic Maya cities were constantly trying to outdo each other in art. and pageantry (Miller and Martin 2004: 21. Mimesis The lover‘s maxim claims ―distance makes the heart grow fonder. they typically ―made bad neighbors to one another. many ideological and artistic conventions were emulated by Late Formative. and Classic Mesoamerican groups. This animosity was driven by a sense of Self and Other. Protoclassic. predisposed to mutual animosity and sporadic violence. As mentioned previously in our discussion of the Olmec. each Maya city was in fact unique in its site plan and there is no ―typical template‖ (Miller and Martin 2004:21). As a broad and preliminary example. despite modern generalizations and idealized types of Maya siteplanning principles. Beyond the conceptual attempts at asserting superiority. Rather than producing an antagonistic relationship. In Harrison‘s (2003) terminology. weaponry. the Maya area was one of wealth and prosperity. As Miller and Martin (2004:282. among them intermarriage. it represents an ancient mutual admiration society. such as the one that took a new ruler to Copan in 427 AD (Martin and Grube 2000:29-34. For example. such as Tikal and Copan. even after its political collapse. Xochicalco. but receives scant attention in the inscriptions. López Luján 1989. Teotihuacan appears to have manipulated dynastic succession at Tikal in 378 —perhaps by force—and provided some of the impetus or inspiriation for colonizing missions. Taube 2004c:47). this view of Teotihuacan would be categorized as ―difference-as-superiority. called waxaklajuun ub’aah kaan (―18 heads/images of the snake‖) by the Maya (Freidel et al. Maya rulers would don the headdress and armor of the Mexican War Serpent. which required other sorts of contact. religious cults. in warfare. and trade agreements. Military intervention may have been of less importance than more subtle forces. seemed to maintain a relationship (whether real or fictitious) with Teotihuacan that involved an intense identification with them as the Other. when only its aura remained. and even their style of armor (Miller and Martin 2004:20). Certain Maya polities. Stuart 2000a:465-513). 192-193.‖ Teotihuacan represented the pinnacle of military prowess. To the Teotihuacanos. 1993:281). Footnote 5) noted: The historical relationship between the Maya and Teotihuacan was complex. Matos Moctezuma and López Luján 1993.we find a similar hearkening and appropriation of the past among the Late Postclassic Aztec. so the Maya appropriated their war gods. and Tula (Umberger 1987. This relationship between the Maya and Teotihuacan went both ways. who seem to have used conventions from the desolate but revered sites of Teotihuacan. brimming with 20 . Teotihuacan was an exalted Other that was viewed as a well-spring of appropriable power. and precious jade (Taube 2006:165. as its power and very existence began to fade in the seventh century.resplendent feathers. an attempt to reenact the identity-myths of others so deeply as to make them completely. traveled to what we suppose was Teotihuacan. Miller and Martin 2004:21). K‘inich Yax Pasaj gives a r etrospective history of the dynasty‘s founding and subsequent line of rulers. but whose memory was called upon for purposes of legitimization (Miller and Martin 2004: 20). K‘inich Yax K‘uk‘ Mo‘ appears to have been an influential figure at Teotihuacan itself. K‘uk‘ Mo‘. he was known as K‘inich Yax K‘uk‘ Mo‘. one‘s own. Borrowing of this sort is neither pure imitation. However. Harrison‘s discussion of the appropriation of identity-myths is particularly appropriate when considering Teotihuacan in relation to the Maya. but something in between. However. cacao. but rather they wanted to imitate them to a degree that they merged with them conceptually in an effort to blur the lines between Self and Other. the Maya did not want to become carbon-copies of Teotihuacan.6 Interestingly. and genuinely. As Harrison (2003:350-351) states. the Maya continued to view it as a mysterious and sacred place. Upon his return. It is a kind of mimetic appropriation. they did not go out of their way to differentiate themselves from Teotihuacan. Unlike the relationship certain Maya polities maintained with their closest neighbors. jaguar pelts. For example. a concept that Taussig refers to as mimesis. on Altar Q at Copan. nor pure differentiation of Self from Other. It is imitation intimately involved in the production of difference. The founder. known more through myth and legend than experience. at least after his 6 The significance of the K‘inich prefix and the taking of throne names will be discussed in detail in a later chapter. They wanted to harness the prestige of Teotihuacan while simultaneously setting themselves apart from it. 21 . which somehow legitimized his right to rule. unlike the case at Copan during the reign of Yax K‘uk Mo‘. and strontium isotope ratios conducted on relevant Tikal burials do not support the hypothesis that Yax Nuun Ayiin was a Teotihuacano by birth. James Borowicz (2004) argues that in emulating Teotihuacan. He is depicted as a Teotihuacano warrior during his lifetime. during Yax Nuun Ayiin‘s reign there was a major shift in the iconographic program. Spearthrower Owl.‘ 22 . A variety of explanations have been offered as to why he chose to adopt Teotihuacan‘s symbols of power. is named as a Teotihucano. at Tikal we find explicit references to Teotihuacan in the context of legitimization of a Maya ruler. K‘inich Yax K‘uk‘ Mo‘ may have embodied both Teotihuacan as well as Maya concepts of the sun. The father of Yax Nuun Ayiin. but this may be another instance of mythology replacing history. but rather was born and raised in or near the Tikal region (Wright 2005a). Similarly. appears to have been mutual to some degree. 7 However. However. The mimetic influence between Teotihuacan and Copan.death when he had been apotheosized as the Sun God. his ancestry is still subject to debate. Yax Nuun Ayiin was valorizing his foreign ancestry over his local heritage. Others suggest that the Teotihuacanos came at Tikal‘s invitation with the hope and expectation that they would intervene in the dynastic 7 According to David Stuart‘s (2000) interpretation of Teotihuacan as the ‗Place of Reeds. Just as the Postclassic Tonatiuh was based on the concept of a Maya king. K‘inich Yax K‘uk‘ may have been apotheosized as the sun not only at Copan but at Teotihuacan as well. Taube (2006:165) noted that figures from the Conjunto del Sol and Pinturas Realistas from Teotihuacan may be depictions of an apotheosized K‘inich Yax K‘uk‘ Mo‘ and argues that As a ruler of the easternmost major Maya site. therefore. Teotihuacan‘s difference-as-superiority was embraced by Tikal. the danger of using cross-cultural comparison and 23 . Methodology and Methodological Concerns Houston. Teotihuacan was seen as the preeminent war power. namely (1) using evidence from historic or ethnographic Maya. and through mimetic processes. and their gods of war were likewise paramount. As it must. past and present. (5) using data from one Maya site to explain another. this dissertation relies upon all of the above datasets. Whether real or fictitious. (4) using comparative anthropology. but recognizing them for the mine of information that they are. Cross-Cultural Comparison and Ethnographic Analogy Although the institution of divine kingship is widely attested in many parts of the ancient and modern world. (2) using what Classic elites say according to their own texts. and (6) using glyphs and imagery at all. and it is significant that it was specifically the iconography of war that was appropriated by Yax Nuun Ayiin. from other parts of Mexico and northern Central America. mindful of the pitfalls each may potentially present. A brief discussion of the value and dangers of these sources of data follows. Stuart and Taube (2006:1-2) raise and address a number of methodological concerns that arise for researchers of the Classic period Maya. the ideological linkage to Teotihuacan served a legitimizing purpose. Yax Nuun Ayiin was re-enacting the identity-myths of Teotihuacan while simultaneously making them completely and genuinely his own (Harrison 2003). (3) using information.succession (Culbert 2005). there are several challenges when using ethnohistoric data from the Colonial period as a 24 .‖ Houston (1993:9ff) called for a move away from all-encompassing pan-Maya theorizing and a move toward a regional emphasis that places local. However. without micro-focusing to the point that the individual polities lose their broader context. Although some cross-cultural information regarding divine kingship may be drawn upon. it would only serve to minimize the temporal and spatial diversity of individual polities (Sharer and Golden 2004:24. ―no single interpretive model can be applied to all of ancient Maya society. this dissertation at tempts to examine the temporally and spatially specific ways in which the institution of divine kingship was implemented at a number of Classic Maya sites. Lewis (1995:135) cautioned. it will be for comparative and illustrative purposes rather than a Frazerian attempt to create a universal ―ideal type‖ of divine king.ethnographic analogy is that all too often it reifies models. site specific variation within its regional context. The (somewhat) Direct Historical Approach Similar to the problems with the cross-cultural approach and ethnographic analogy. Manipulating the data from the Classic Maya into models from other cultures separated by space or time is akin to forcing a square peg into a round hole. Heeding Houston‘s call. Marcus 1995). If these models were applied to the Maya case. due to the heterogeneous nature of Maya polities and the considerable local variation that is known to exist at each site. Sharer and Golden (2004:24) call for a model that synthesizes parallel features from a variety of non-Maya-based models to create a Maya-specific model. and place them within their regional context. much useful information can be gleaned from later Mesoamerican cultures. Beyond these challenges is the evidence that the institution of divine kingship had all but collapsed by the tenth century in the Maya area. Complicating the matter further is the fact that Colonial Mayan texts such as the Quiche Popol Vuh and the Yucatec books of Chilam Balam were often written as reactions to colonialism and. Despite these challenges. Even when not doing so intentionally. therefore. Sahagún is often described as the ―father of American ethnography‖ due the depth and breadth of his knowledge of native language and culture and his meticulous recording of virtually every aspect of the lives of both commoner and elite (Keber 1988:53. the concepts and metaphors are still foreign and a great deal of effort is required of modern readers to make any sense of them.tool for understanding the Classic Maya. and among whom the institution of divine kingship was still flourishing. 25 . and the interactions between the two. especially the Aztecs. and ethnohistoric accounts of political organization reflect a Late Postclassic system rather than the organization that was in place during the Classic period.). for whom we have a wealth of data thanks to meticulous chroniclers such as Fray Berdardino de Sahagún and Diego Durán. It is often difficult to determine which beliefs and practices were Prehispanic and which represent Christian influence (Sachse 2004:4). the Florentine Codex will prove especially useful due to its detailing of both the supernatural realm and divine rulers. Taube 1992:8). For our purposes here. used metaphors and concepts that were intentionally obscure to Western readers (ibid. the light they shed on each other is both temporally and spatially salient. Stuart and Taube 2006:1). Although not fully deciphered or perfectly understood due to insufficient linguistic data (e. for purposes of this dissertation. beyond what they actually tell us. Fortunately. we can interpret the meta-messages of elite world-views based on what they chose to record with chisels and paint and what they chose to ignore. and only represent a glimpse into elite ideology and lifestyle (Houston.Epigraphy and Iconography A concern when using epigraphic and iconographic data is that virtually all texts and images were produced by elites. arguably for propagandistic purposes. In the epigraphic data we find the names and titles of humans and gods. Outline of Text This dissertation draws heavily on the concepts of mimesis and alterity.g. The iconographic data gives us a glimpse into how they visualized the natural and supernatural realms. and we are given dates and locations for significant events.. we are informed about relationships and genealogies. that is precisely the view we are interested in. the glyphic system still provides a massive corpus of readable. logograms with no known phonetic compliments) or obscure idioms that defy Western understanding. and invite us to witness how porous the boundary between the two realms truly was. understandable data that complement the iconographic program. Although clearly slanted and one-sided. The data sets are symbiotic. whereby concepts of Self and Other were created among the Classic Maya vis-à-vis their 26 . and unlike ethnohistoric or cross-cultural data. This dissertation attempts to analyze the site and regionally specific ways in which rulership was practiced and seeks to understand the motivation behind the variation. all of which had a distinctively divine flavor. and efforts made by successors to deify the deceased. from political legitimization to ritual performance. rituals of accession. It discusses ―ideal types‖ of divine rulers and their polities. ritual. both near and far. Chapter 2 is a discussion of the function of divine rulership among the Classic Maya. the actions and material culture they produced affected concepts of identity within their communities. past and contemporary. material culture. but these concepts cannot be understood without examining rulership from multiple angles: ideology. etc. It explores a wide range of aspects relating to rulership. mortuary rituals. Previous research on Maya divine kingship has focused in large measure on pan-Maya generalities while ignoring how rulership was practiced at specific sites or regions and the significance of local and regional variation. with a focus on the gods of regeneration—specifically the Sun God and Maize God—and the king‘s apotheosis in 27 .relationships with foreign entities. Chapter 4 is a discussion of the divine realm and the ruler‘s place within it after death. Chapter 3 discusses the sacred process of royal succession: pre-accession rituals. As Classic Maya rulers were the center of focus in their polities. identity. The thread of mimesis weaves together seemingly disparate elements of this work. The principle goal of this dissertation is to understand divine kingship among the Classic Maya and to gain a deeper understanding of the relationship the kings had with their gods. and then explores the local variation that veers from the ideal type and the significance that the variation may have. human and supernatural. from the microcosmic to the macrocosmic. 28 . The discussion in Chapter 5 weaves together the pieces of the tapestry presented in earlier chapters.relation to them. and offers suggestions for avenues of further research concerning divine kingship among the Classic Maya. and points of connection between spatially and temporally disparate peoples and places. 29 . and we cannot reduce the system to a single ―Maya political organization‖ (Stuart 1995:186). However. Such is often the case in the study of the Classic Maya. In this chapter we will examine royal responsibilities that pertain to the ordering of both polity and cosmos. and used their sacred buildings and designated natural features as stages for their ritual activities. Rulers determined the architectural and monumental programs for their cities.Chapter 2 Royal Responsibilities The Polity The identity of a polity was deeply rooted in the activities of its king. of necessity. they were not homogeneous. thoughts and things. be a reduction to what Max Weber refers to as an ―ideal type. they also have a tendency to homogenize or essentialize them. contrasts. The “Ideal Type” of Classic Maya Polity Any generalized discussion of Classic Maya polities must.‖ According to Weber (1969:90).‖ While ideal types allow for comparisons. despite the many similarities in Maya polities we find across space and time. A discussion of ideal types of Maya polities is not merely an etic exercise: we can presume that the ancient Maya similarly had some emic conceptions of what qualities an ideal polity would have (Reents-Budet 2001:222). an ideal type ―is not a description of reality but it aims to give unambiguous means of expression to such a description. yet they appear to have based their collective identity on propriety mediations with certain gods or local materialization of deities. The initial construction of monumental architecture was likely concomitant with the birth of dynasties. Proskouriakoff 1950. Willey et al. Houston and Stuart (2001:60) applied the term ―ethnic kingdoms‖ to polities that ―may speak the same language and share similar customs. Spinden 1913. materials. At any given polity.‖ Settlement data may suggest that many Classic period polities were inhabited long before they were inaugurated as dynastic kingdoms. organization.g. and methods that define localized styles.. and ―palaces‖ are structures that appear to have been the seat of political authority.Sharer and Golden (2004:35) note ―the particularities of administration. but these realms do not appear to have been clearly distinguished among the Classic period Maya so the precise 30 . and implementation of the Classic polity differed from place to place and changed dramatically over the centuries even within the same polity.‖ making it somewhat challenging to generalize. although others before him certainly showed an awareness of local variation in material culture (e. Stuart (1995:118) coined the phrase ―site -specific genres‖ to refer to the distinct meanings. and newly constructed sites would have served to create group identity (Clark and Colman 2008:96). ―Temples‖ are buildings whose primary function we assume to be religious. 1967). ―temples‖ and ―palaces‖ typically anchor the site core. Ball 1993. The transitions to kingdoms and the birth of dynasties were momentous occasions—or at least they were commemorated as such by later generations—that marked a change from chaos to order and were ―tantamount to the rebirth of the world‖ (Florescano 2005). at the site of K‘o in Belize.C. A richly furnished burial (designated Tomb 1) was discovered at San Bartolo. Formative period temples are generally not focused on individual rulers. they tend to highlight specific supernaturals – the Principal Bird Deity being a favorite – and reflect grand cosmologies rather than individual histories (Schele 1998). apparently those of rulers from the Miraflores phase (400100 B. In very general terms. The epigraphic and iconographic records contain virtually no clues concerning the function of temples. indicating it was a royal tomb (Estrada-Belli 2009). however.function of these structures is not clearly understood. Similarly. contained two richly furnished burials. rather. each of which may have served different religious or political purposes (Lucero 2007:407). it is unsurprising that most of them do not contain royal tombs (Hansen 1998). While the burials at San Bartolo and K‘o indicate the growing reverence given to deceased rulers . often within a single site core. it is not until the Early Classic (after about AD 300) that the principal pyramids at the site cores were used primarily for the purpose of deifying their ancestors rather than focusing predominantly on the gods (McAnany 2001:136). a triadic grouping of structures located to the northwest of the site core (Pellecer 2006). a burial was d iscovered in a residential compound that contained a greenstone diadem and other high-quality grave goods.) (Shook and Kidder 1952). there appears to have been a shift concerning the ―ideal type‖ of temple from the Preclassic to the Classic periods. Mound E-III-3 at Kaminaljuyu. As Fransisco Etrada-Belli (2011:63) 31 . There are exceptions. for example. As the focus of Preclassic temples was typically not on specific human agents. Larger sites typically have multiple temples. but it was discovered in the Grupo Jabalí residential compound. 1991. there is evidence that suggests the designs of Maya royal courts and the rituals performed within them intentionally mimicked divine models (Reents-Budet 32 . Smith (2003. Mimesis of the Divine Realm Mircea Eliade (1959:5-12) argued that city designs reflect a desire for heavenly mimesis. 2000). invented by scholars to satisfy their desire to reconstruct ancient cosmology from fragmentary evidence‖ (Smith 2005:220). He suggests that ―Maya architectural cosmograms are modern phenomena. 1992).‖ However. but rather uses ―cautious and judicious‖ language in formulating her arguments (Smith 2005:217). Michael E. He commends the scholarship of Wendy Ashmore (1989. His primary critique is that too many of our scholars use language befitting established empirical fact to draw their conclusions when more cautious language is called for. 2005) has sharply criticized Mesoamericanists for their over-reliance on the cosmogram as an explanation for site-planning principles (see also Carl et al. it is certainly possible that the lack of known burials from the Preclassic period may simply be due to the fact that less excavation has been done on structures dating to that period (Stephen Houston.notes. India. personal communication 2011). and Cambodia. there are no Maya texts that explicitly state that rulers were deliberately following cosmological models when laying out their capital cities (Smith 2003:222). With that caveat. which does not treat speculations as though they were established fact. ―these sporadic finds of high -status burials in unassuming residential locations indicate that rulers and elites were not buried in temple-pyramids prior to AD 100. Unlike other ancient cultures such as China. O master. 9 8 The palace template based specifically on the court of Itzamnaaj (God D) appears to be a relatively late innovation (Stephen Houston. ―Concede. we must caution that Fray Bernardino de Sahagún was not a dispassionate. O our lord. for example. but the lives of the gods were considered models for behavior for the human realm. and established a mythical charter for how rulers interact with the gods they are entrusted to care for and protect. As Stuart and Stuart (ibid:211) note. Muwaan Mat‘s ―overseeing of the creation and establishment of the Triad deities served as a model for kingship at Palenque. 2011). with the ruler sitting in as their regent. but rather a Franciscan Friar whose intent was to proselytize the native inhabitants. the mythological accession of Muwaan Mat as k’uhul ajaw of Matawiil in 2325 BC was said to be unaah tal. ―the first‖ (Martin and Grube 2000:61). Book 6 of the Florentine Codex (Sahagún 19501982 Book 6:24) informs us that the principal priest would pray to Tezcatlipoca when preparing to install a new ruler. that [the ruler] live. objective anthropological observer. which I suggest demonstrates diachronic variation and ideological flexibility. 33 . personal communication.1994:236). At Palenque. The opening phrase on the inscription of the Tablet of the Cross related to Muwaan Mat‘s birth as an aspect of the Maize God. The Florentine Codex was primarily intended to be used as a resource for missionaries in their efforts at evangelization (Bremer 2003). By the Late Classic the court of the supreme creator deity Itzamnaaj appears to have been considered the most powerful and worthy of emulation (Miller and Martin 2004:29).8 It would seem they did not merely emulate heavenly architecture and spatial layout for their cities and courts.‖ The throne of a particular city may have belonged conceptually to its patron gods. designated GI. who was also the creator of the Triad gods. 9 Despite his reputation as the Mesoamerican proto-ethnographer. ―a mirror held to the aspirations and behavioral norms of a culture‖ (ibid:95). GII and GIII (Stuart and Stuart 2008:198). I seek. thy word. thy ears. where thou usest one as a flute. where there is speaking for thee. Book 6:42-44). proclaiming that they were not just regents of the gods. thy place of honor. there are certainly hints that these ideologies were held among the Maya which must be gleaned from short. where thou art replaced by another. thou countest me with acquaintances. It is where thou art given a proxy. I expect. that he may guard this. whose texts are as laconic as the Florentine Codex is verbose. the mother of the gods. thou wilt hide thyself in them. Ueueteotl. thy acquaintances. who ordered things for thee on thy reed mat. with which thou hast inspired thy friends. where thou makest one thy mouth. where thou speakest from within one. Though not explicitly spelled out. Such garrulous sentiments from Central Mexican ethnohistory offer intriguing insights into the nature of the ruler‘s essence and may represent enduring ideologies from earlier Mesoamerican cultures. I do what I can for thee. thy friends. thy reed seat. where there is pronouncing for thee. who is the in the center of the hearth…I await thee at thy humble home. Give him as a loan for a little while thy reed mat. I request.‖ The rulers themselves would offer humble prayers upon their accessions. they will pronounce for thee…and [it is they] who will pronounce for thy progenitor. where thou makest one thy eyes. thy realm. where thou art substituted. at thy humble waiting place. I ask of thee thy spirit. thy jaw‖ (Sahagún 1950 -1982. from within them thou wilt speak. on thy reed seat. designate him. 34 . and thy rule. thou bringest me among. formulaic texts and iconography steeped in culturally specific artistic conventions. I place my trust in thee.Concede to him. but actually vessels of their essence: Who am I? Who do I think I am that thou movest me along. thy chosen ones…Thou wilt have them substitute for thee. the father of the gods. but we must be cautious not to presume identical beliefs among the Classic period Maya. The royal household included the ruler. Fash et al. The ethnohistoric data suggest that. 1992. The ―royal court‖ and the ―royal household‖ are not synonymous. Fash et al. But the ruler was not merely primus inter pares—he was qualitatively different due to his supreme office and sacred status. the existence of noble titles indicates that other elites populated the royal court at Copan and elsewhere. and other relatives. specialist retainers. his wives. Fash and Fash 1990. children. In contrast. William and Barbara Fash argued that a similar council style of governance traces back to Late Classic Copán based on their interpretation of the so-called Popol Nah. a supreme ruler sat in council with principal men known as ah kuch kabob (McAnany 1995). 1992. The toponyms that adorn the structure refer to mythical locations (Stuart and Houston 1994:72). Fash et al. in Late Postclassic Yucatan. a shrine that housed ancestral effigies.The Royal Court The k’uhul ajaw were not autocrats who single-handedly administrated all of the affairs of their polities. 10L -22a was a popol na. but the precise size and role of organized bureaucracies during the Classic period is still a contested issue (Inomata and Houston 2001). Regardless of whether or not Copan had some type of formal noble council. the royal court was composed of politically powerful men and women with specialized duties who 35 . 1996:441-56). she notes that the throne room within a palace served as a location where a ruler would receive visits from other nobles (Wagner 2000:44). or Council House designated Structure 10L-22a (Fash 2002:14-15. but Wagner (2000) demonstrated it was actually a waybil. Despite Wagner‘s rejection that Str. and slaves (Traxler 2001:47). as well as a variety of attendants. the portraits and toponyms may actually be gods and mythological locations (Stuart and Houston 1994:72). the prosperous court of Waxaklajuun Ub‘aah K‘awiil was responsible for innovative artistic styles and an aggressive building campaign (Stuart 2008). The court of his successor. Their public portraits and their accompanying toponyms in the façade of the Popol Nah would have been unthinkable during the more authoritative reign of Waxaklajuun Ub‘aah K‘awiil.1. Barbara Fash (2005:138. This was likely due to the extremely young age at which many of its rulers acceded to the throne and their reliance on regents and guardians to govern the affairs of the kingdom until they were capable of governing themselves (Miller and Martin 2004:188). Footnote 16) suggested that some type of council existed prior to K‘ahk‘ Joplaj Chan K‘awiil‘s reign and that they gained much greater political power in the wake of Waxaklajuun Ub‘aah K‘awiil‘s beheading. The inscription on Monument 183 recounts the seating of an individual into the office of Aj k’uhuun in the year 612 (Fig. with no known stela and only one architectural contribution. This was a time of turmoil for Tonina and no supreme ruler is known. 2. a piece of regalia normally reserved for rulers. At Copán. K‘ahk‘ Joplaj Chan K‘awiil. Members of Tonina‘s royal court shared the public stage with the king to an unusual degree. He is depicted wearing a Jester God headdress. was understandably less productive. However. An eight year old K'inich 36 . for example. The size and function of royal courts display diachronic and geographic variation reflecting the specific histories of each site. Zender 2004:156-157). as noted above. the so-called Popol Nah or Council House. and could change quite quickly for better or for worse.often bore named ranks or titles (ibid). Maya rulers typically commissioned royal palaces for themselves that served as a central place for them to sit in rulership. administrative.Hiix Chapaht would not accede until three years later (Miller and Martin 2004:188). along with the rituals that were performed there. Royal buildings were often decorated with powerful symbols of rulership and used images of gods and ancestors to validate their authority (Traxler 2001:49). rulers would offer prayers and incense and perform bloodletting rituals (Schele and Freidel 1990). such as receiving tribute to elaborate costumed impersonation rituals. and activities range from mundane administrative transactions. and ritual activities. Within the private chambers. served to reinforce the social differences that existed between king and commoner (McAnany 2008:221). 1993:234). Each new building was a creation of ordered 37 . yet the king‘s role and status were paramount. and dedicatory rituals would imbue them with a soul (Freidel et al. Palace scenes are common on polychrome vases. Many of the rituals (such as deity impersonation and bloodletting) and even some of the paraphernalia (such as headbands) associated with the k’uhul ajaw were at times used by subsidiary rulers or even nobles within a particular ruler‘s court. The sacred texts and cosmologically charged iconography that adorned these buildings. Structures were considered living entities. so it is plausible this Aj k’uhuun acted as his regent. The public architecture they commissioned was an expression of their individual identity (Reilly 1995). Sacred Architecture The royal complexes were centers for domestic. Mathews and Garber 2004). As they succinctly stated. which contrasted with the chaos of the forest. His physical presence was not necessary for his spiritual essence to be manifest. Schele and Mathews (1998:34) suggested that regional and local architectural styles may have been a combination of limitations of local building materials and the legacies of individual. These satellite palaces were not ―places where the king was but rather places where the king might be‖ (Webster 2001:161). Monumental architecture served as markers of both sacred space and seats of power (McAnany 2001:135). and areas of restricted access). monumental structures with corbelled vaults. ―style could be political‖ (ibid). Buildings were considered living beings and were frequently anthropomorphized.space that reflected the quadripartite division of the cosmos (Ashmore 1991. The doors of the temples were literally referred to as ―mouths. there is a 38 . the authors suggest that there was a conscious stylistic emulation of other sites as a way to affiliate themselves with contemporary sites or to evoke the style of the site of their supposed origin. 2006:238). multiple interior courtyards.‖ and from them would issue forth oracular pronouncements and commandments (Houston et al. While there are some general similarities in the architectural designs and site planning principles across the Maya area (such as raised platforms. long-lived rulers who created unique local templates within their polities. and the sajals or other lesser nobles who ruled in his absence did so under his auspices. Furthermore. It is likely that powerful kingdoms that controlled large geographic regions established multiple palace complexes in each of their subordinate centers (Ball and Taschek 1991). The first multi-room structures with vaulted ceilings date to the Late Preclassic. This new architectural style was intended to accomodate and elevate a new class of ruler. a feat virtually unknown at other lowland sites. has soaring corbels that are cut at right angles to produce a cathedral-like interior space.‖ Simon Martin (2001a:176) contrasted the dispersed court plans of Tikal to the concentrated layout of Calakmul. whose history is instead recorded in stucco panels set within the walls of its temples. House A at Palenque. sizes and proportional emphases. Martin suggested the disparities may be due to the unique political histories of each site. as well as the radial causeways within the complex at Caracol and the distinctive layout of Naranjo‘s ceremonial center. The earliest known examples are found at El Mirador. He noted significant differences in their respective arrangements. are notably absent from Palenque. so common at sites like Copán and Tikal. Like Schele and Mathews.great deal of local variation in regards to the royal court complexes of the Classic period. As Miller and Martin (2004:204) note. and the variations of this architectural theme served to distinguish one site from another. Stelae. Tonina and Copan are distinguished by carving sculptures in the round. It is also unique architecturally in that the city is essentially one massive building that covers the side of a 39 . ―No other Maya engineers ever approached these architectural feats. for example. Polities distinguished themselves architecturally and artistically by what they emphasized and shunned. but also suggests that functional differences may explain why the court complexes were so different (ibid:175). and Uaxactun (Valdés 2001:139). Cerros. Nakbe. Tikal. Palenque‘s neighbor Yaxchilán is noted for eschewing wood in favor of stone for its intricately carved lintels. Significantly. The format was generally similar: there was typically an image of a propitiatory deity.mountain. but rather ―the king idealized and transformed himself into the Maize God‖ (Grube et al. 2003:47). the latter incorporating mortar with oyster shells. Comacalco is the only Maya city known to have used fired-clay bricks. For example. The western Maya region in general is characterized by its use of finely worked stucco (Miller and Martin 2004:161). 2. The vaults were also linked to creation events. The artists at Tonina and Comalcalco also showed great mastery of stucco working. Architectural features often served mythological as well as functional purposes. cover‘ in passive voice. burial chambers in the Puuc and Chenes architectural styles had corbelled vaults that may have been symbolically equated with the maw of the Underworld. seen as representations of the turtle carapace earth from whence the Maize God regenerates (ibid:133-134). but on Capstone 15 from Ukit Kan L‘ek Tok‘s burial chamber we find a unique depiction of the Maize God seated atop 5 Flower Mountain (Fig. in northern Yucatan. at Ek‘ Balam we find many capstone images of K‘awiil and Itzamnaaj. this is not an impersonation. a short text that framed the image that gave the date. 40 . More precisely. 2003:11 -14). a reference to the building and the name of the building‘s owner (Grube et al. we see Ukit Kan Le‘k Tok‘ transformed into the Maize God. These capstones often portrayed images of celestial deities.2). the verb mak ‗to close. Hull and Carrasco (2004) argued that the central capstones may have served as portals through which supernatural beings could manifest themselves. Tikal is noted for its striking Twin-Pyramid complexes. Additionally. For example. there does appear to have been an emic concept of an ―ideal type‖ of royal court. were resurrected during) the Late Classic period. The earliest examples. Harrison 2003:354). despite the vast differences in the layouts and structural materials of royal complexes that have been uncovered archaeologically across and within regions. They are the namesakes of Group E at Uaxactun. 700-400 BC). Nakbe. Tikal. such as those from Balakbal. human and artifactual contents. often on a shared.Surprisingly. are sometimes called ―Commemorative Astronomical Complexes‖ (Hansen 1998) and are more correctly described as ―horizon calendar complexes‖ (Aveni 2010:210) because 41 . either on the other side of the plaza or in the middle of it (Fig. Reents Budet (2001:222) compared a stylistically diverse range of pictorial pottery that was produced in distinct geographical regions and noted that they all depicted ―similar architectural forms.3). E-groups Distinctive architectural complexes known as E-Groups began appearing in the southern lowlands as early as the late Middle Preclassic (ca. 2. formal layouts.‖ While there were undeniably expressions of local stylistic preferences and even idiosyncratic functional differences. which face toward a fourth building to the west. and Yaxha. and continued through (or more precisely. Uaxactun. They are typified by three linear buildings located on the east side of a plaza with a north-south orientation. there were baseline similarities that created a sense of social cohesion with other Maya polities (ibid. first mapped by Ricketson (1928) and identified as a recurring assemblage in the southern lowlands by Ruppert (1940). substructural platform. and ritual activities in the royal court. Wakna. Cohodas 1980. Radial pyramids may be microcosmic representations of the quadripartite earth. ballcourts formed a core of Maya identity 42 .they served as rudimentary observatories for the solstices and equinoxes. Pseudo-E-groups are identified by having the general form of Late Middle Preclassic E-groups but lack the precise orientation to serve as functional horizon calendar complexes (Cohodas 1980:215). Guderjan 2006. Chase and Chase 1995. 2003. Aveni et al. The western structures were typically square radial platforms with stairs on all four sides and no superstructure. the sheer number of E -groups or pseudo-E-groups suggests that these architectural forms were ―embedded into the Maya conception of necessary elements in public architecture‖ (ibid:101). Over one hundred E-Groups or pseudo-E-Groups have been identified in the southern Maya lowlands (Aveni et al. which may have been due to the influence of Teotihuacan (Aveni and Hartung 1989. a ruler performing rituals on the platform would become the axis mundi at the center of the cosmos (Cohodas 1980:219). It is likely that rulers performed public rituals to mark celestial and agricultural cycles and to reenact creation events (Aveni and Hartung 1989. Guderjan (2006:97) noted that there are significant temporal and regional differences found among E-groups. Like E-groups. Ricketson 1928). and as such. which suggests their use as a place of ritual performance (Cohodas 1980). and argued that these differences were an expression of identity for each polity and further served to legitimatize the ruler‘s authority. The orientation of E-Groups shifted during the Early Classic period. Fialko 1988. Aveni et al. Laporte and Fialko 1995). Despite the variations. 2003). The haitus of E-group construction has been correlated to the rise of Teotihuacan‘s influence in the central Peten. 2003. For example. This discussion of ideal types is not merely an etic exercise. we must consult the Maya‘s own depictions and descriptions of rulers as found in their iconographic and epigraphic records. as Teotihuacan‘s influence faded.‖ Even small ceremonial centers constructed E-groups. 43 .‖ Their role shifted from serving predominantly astronomical functions in the Late Middle Preclassic to fulfilling primarily social functions in the early part of the Late Classic (Guderjan 2006:98). However. caution must be exercised to avoid homogenizing the ancient Maya. To reconstruct an emic ideal type of the Classic Maya ruler. Guderjan (ibid:99) argued that these non-functional pseudo-E-groups mimicked earlier functional E-groups ―Not on desire for the function of an E -group but on the integration of the idea of an E-group into the sacred space of a polity and the need for its rulers to incorporate such a complex because it was a necessary part of their identity. and both types of constructions ceased during the peak of Teotihuacan‘s architectural influence in the central Peten. for we can presume that the ancient Maya similarly had emic conceptions of what qualities an ideal ruler would have.(Guderjan 2006:101). sometimes serving as their only civic construction (Cohodas 1980:214). The “Ideal Type” of Classic Maya Rulers As is the case with Classic Maya polity. E-groups and ballcourts are often found in close proximity to each other (Aimers 1993). any discussion of Classic Maya rulership as a general institution must also be a reduction to an ideal type. many polities in the Peten began hearkening back to their own architectural histories by creating ―pseudo-E-groups. But eventually. Significantly. but the point is simply that not all Classic period iconography can necessarily be illuminated by it. As Stuart and Stuart (2008:256 Note 10) caution. for example. Similarly. When used appropriately. 1973 and Tedlock. While they are clearly useful in some instances. they are few. we should exercise caution in our use of Colonial period documents in our interpretation of Classic period iconography. Many of the mythological episodes from the Popol Vuh are clearly attested to from the Preclassic through the Postclassic. but they admittedly offer fascinating and detailed insights into the later Mesoamerican e mic ―ideal types‖ of ruler. but there is not a one-to-one correlation. …it is fair to say that interpretations of Classic Maya religious iconography based on the Popol Vuh have been overemphasized in the last few decades (Coe. Book 6 of the Florentine Codex. displayed irreverence in sacred locations. but there is also much that is different (Saturno et al.Houston and Stuart (1996:302) have cautioned against interpreting all Maya beliefs and practices through the lens of Palenque‘s mythology. That is certainly not to say that the Popol Vuh is completely disconnected from the beliefs and practices of earlier periods and has no light to shed. we may have developed an over-reliance on the Colonial era K‘iche‘ Popol Vuh as a rubric for understanding virtually all earlier Mesoamerican art. Unsatisfactory rulers were those who grew prideful. 1985). and abused their 44 . 2005:51). The murals of San Bartolo. the Popol Vuh can shed valuable light on earlier Maya cultures. While strands of individual stories that we read in the Popol Vuh have deep and obvious reflections in the ancient art. for example.‖ were prone to drunkenness. show many clear correspondences to the Popol Vuh. outlines the qualities of both good and bad rulers. Similarly. engaged in ―perverseness. we must exercise caution when using ethnohistoric sources from Central Mexico to interpret Classic period kingship. certain polities gained dominion over others both near and far. Hierarchical Concerns Unlike ancient empires such as Egypt or China. they would pray for him to die as soon as possible. the lowlands were home to many city-states of varying sizes. Ch. Sometimes at peace. a warlord who is believed to have been sent by 10 Scenes of tribute are common on polychrome vessels. Rather. Conquered cities would typically retain their local leadership. Siyaj K‘ahk‘.―position of merchanthood‖ for personal gain (Sahagún 1950 -1982. For such unworthy rulers the principal priest would earnestly petition Tezcatlipoca to show mercy upon the ruler (but in reality. religious. Uaxactun.10 Subordinate kingdoms would make reference to their overlords on monumental inscriptions. economic. or political ties. Teotihuacan‘s influence on the Maya area is most directly evidenced by an abrubt shift in architectural and ceramic styles in the lowlands during the late 4 th century (Stuart and Stuart 2008:120). But through competition and conflict. but often at war. in other words. but allegiance and tribute were requisite. Book 6:25-26). El Perú. Cities could be linked to each other by familial. Epigraphically. but extremely rare on monumental inscriptions (Miller and Martin 2004:282 Footnote 8. the ―Entrada‖ of 378 is noted at La Su fricaya. the ruled) by allowing the contemptible regent to come quickly to the land of the dead to join the ancestors. 4) 45 . These overlords would oversee the accessions and other significant ritual activities of their subordinates. the Classic Maya were never unified under a single supreme ruler. these polities sought to control the resources within their territories. and Tikal. Subsequently. the presumed toponym for Ek‘ Balam). Tok Casper‘s accession was on the same day as that of Yax K‘uk Mo‘ (6 September 426). The relationship 11 The only other example of the Xaman Kaloomté title was identified by Stanley Guenter from the Terminal Classic period Ixlu Altar 1 from Central Peten (Grube et al. demonstrating his shifting alliances. oversaw a ―second crowning‖ event one year later. appears to have come from the west. Curiously. Copán‘s illustrious founder. Significantly. An illustrative example comes from Stela 4 at the site of Moral-Reforma. in 690. acceded to his throne in 661. U-Kit Kan Le‘k. One of the site‘s rulers. the great king of Calakmul. nicknamed Tok Casper. Significantly. Hawk Skull (possibly read Muwaan Jol). Yax Nuun Ahiin was placed in power as ruler of Tikal in AD 379 by Siyaj K‘ahk‘ (Stuart 2000a. Yuknoom Ch‘een II. a foreign ruler who carries the title k’uhul ajaw and an Emblem Glyph of a polity that has yet to be identified (Lacadena 2004a).11 He appears to have arrived with the purpose of overseeing the enthronement of Ek‘ Balam‘s first ruler. although the exact relationship between the two is unclear. It mattered who oversaw a ruler‘s enthronement. as evidenced by the inscription on Stela 15 from El Perú that mentions him 8 days before his arrival at Tikal. The Mural of the 96 Glyphs at Ek‘ Balam records the ―arrival‖ of Chak Jutuuw Chan Ek’ at Ek‘ Balam (more specifically at Talol. Yax K‘uk‘ Mo‘s accession appears to have had ties to both Teotihuacan and Tikal (Looper 2003:37). 2003:II-11) 46 . Quirigua‘s founder. acceded under the auspices of or ―by the doing of‖ K‘inich Yax K‘uk Mo‘. Wright 2005b:89). he is also called a B’akab’ (―Head/Prince of the Land‖) and Xaman (―North‖) Kaloomté. Hawk Skull underwent a ―third crowning‖ under the authority of K‘inich Kan Bahlam II of Palenque (Martin 2003). however.the emperor of Teotihuacan. 2. and most commonly we find Ochk‘in (―West‖) Kaloomté. but those who carried it were the most powerful rulers within their regional hierarchies (though it is not indicative of a unified empire or state). For example. The precise meaning of the title remains elusive. at Ek‘ Balam we find the title Xaman (―North‖) Kaloomté. who is named as an Ochk‘in Kaloomté on Stela 31 at Tikal (Grube et al. Although the text is syntactically challenging and therefore difficult to decipher. Chak Jutuuw Chan Ek‘ (ibid:18). Beneath the k’uhul awajtaak were the sajals. Martin 2003b:63-64). They were typically beholden to the ruler of the regional polity. The title may have been brought in from the west with the entrada at Tikal under the auspices of Spearthrower Owl. but later the title was typically preceded by a directional glyph (Fig. at Lamanai in Belize we have record of an Elk‘in (―East‖) Kaloomté. ―and then was made the king of Talol‖ under the auspices of and upon the ―First Throne‖ of the foreign kaloomté. which often seems to be a reference to Teotihuacan. presumably Chak Jutuuw Chan Ek‘ (Grube et al. 2003:12).4.glyph reads u-b’a-tz’a-ma or u-b’a[ah]tz’am. a sajal known only as 47 . The most supreme title a ruler could wield was kaloomté (Stuart et al. Wagner 1995). which is not completely understood but seems to refer to the ―head throne‖ or ―chief throne‖ of somebody. it appears to relate that Ukit Kan Le‘k was i-patlaj Talol Ajaw. 1989. at Copán and Quirigua (in reference to Copánec rulers) we find Nohol (―South‖) Kaloomté. The earliest forms of the kaloomté title from the beginning of the Classic period were not linked with any of the cardinal directions. For example. 2003:12). Sajal was a title used for subsidiary lords of secondary centers or for military captains (Stuart and Stuart 2008:223). 2. It is found only during the Late Classic period and is highly favored in the western Maya lowland region (Houston and Stuart 2001:61). Much like the status of ajaw. its ―sajal-ship‖ (sajal-il). Overlords also appear to have paid visits to their subordinate sites. At Yaxchilán.He of White Lizard (Aj Sak Teleech) ruled over the city of Lacanha but was under the overlordship of Knot-Eye Jaguar of Bonampak (Miller and Martin 2004:80). and two days later he did the same thing at Tamarindito. several of whom bore the sajal title (including Yopaat Bahlam II of Yaxchilán) (Escobedo 2004:77). and he is surrounded by 14 nobles and visitors. Sajals were expected to be present at ceremonies sponsored by their overlords. ―a sajal may be born into his status but acquires its essence. apparently as part of some kind of ritual circuit 12 He also carried the titles bah ajaw (―Head Lord‖) and yajaw k’ahk. 48 . Ruler 4 of Dos Pilas. (―Fire Lord‖) (Schele 1991). The use of the sajal title is fairly limited in both space and time. Sites typically ruled by a k’uhul ajaw could be governed by a sajal during interregna due to turmoil or as regents for child-kings. Chak Sutz‘ (―Red Bat‖) of Palenque carried the sajal title and appears to have been a war captain. visited Seibal and performed a scattering rite. Sajals could sit in positions of subordinate authority at sites ruled by a k’uhul ajaw. similar to the Oval Palace Tablet in House E and the Palace Tablet in House A-D (Stuart and Stuart 2008:223). for example. only through rituals of enthronement‖ (ibid).5) commemorated Ruler 4‘s k‘atun anniversary on the throne. a sajal named Yopaat Bahlam II ruled during the ten year interregnum between the reigns of Shield Jaguar and Bird Jaguar IV (Escobedo 2004:77). Panel 3 from Structure O-13 at Piedras Negras (Fig.12 The Tablet of the Slaves comes from his modest throne room. we do not look to thee as human. they would effectually hold certain nobles hostage in royal complexes at these capital cities. as well as military leaders (ibid). 49 . noble. A priest. no more art thou human. or great dignitary would address the newly enthroned ruler and proclaim. now thou art deified. The halach uinic appears to have been functionally similar to a Classic period k’uhul ajaw in that he was the supreme leader in matters of both state and religion (Zender 2004:80). appears to have been held hostage at Calakmul for three years (Houston and Stuart 2001:67). Such hostages may have been supported by tribute sent from their hometowns.(McAnany 1995:87-90). as was the case in 14 th and 15th century Mayapan (Tozzer 1941. Ethnohistoric data from the Late PostclassicYucatan shows that vestiges of this hierarchy remained. as are we. One young lord. thou replacest one. although thou art our friend. In effort to assert their hegemony over their subordinate kingdoms. Although thy common folk have gladdened thee. presumably from La Corona. Below him were the batabs. and although thy younger brother. cited in Miller and Martin 2004:281 Footnote 1:10). Martin and Grube (2008) argue that the two greatest ―superstates‖ of the Classic Maya were Calakmul and Tikal. Already thou representest. our younger brother. The Divinity of Classic Maya Rulers The most explicit statement regarding the divinity of Mesoamerican rulers comes from Book 6 of the Florentine Codex (Sahagún 1950-1982 Book 6:52). our older brother. although thou art our son. in that they were somewhat autonomous regional governors and heads of their municipal civil and religious functions. thy older brother put their trust in thee. Although thou art human. as are we. who appear to be fairly comparable to the Classic period sajals. ‖ the wooden effigies of Copán‘s ancestral deities Chante Ajaw and K‘uy Nik Ajaw. These fictive genealogies were politically motivated tropes ―which conveyed the sacred identity of a person through his or her divine bloodlines‖ (Looper 2003:203).6. as will be discussed in more detail in Chapter 4. 2. Similar to Altar Q. Yax K‘uk Mo‘. it seems to indicate that ―the gods of Waxaklajun Ub‘ah K‘awil. each seated upon throne -like renditions of their respective name glyphs (Fig. Yax Pasaj (Taube 2004b:267). among them Chante Ajaw and K‘uy Nik Ajaw. Altar Q from Copán depicts the polity‘s first 16 kings. to the sixteenth ruler.7). Claiming descent from a deified ancestor reinforces the divinity of the living king. in depicting the 50 . Martin and Grube 2000:192). a number of Copán's rulers sit upon identifying glyphs (Fig.The Classic period Maya made no such explicit statements concerning the divinity of their rulers. Although the decipherment of the text is not entirely certain. the Temple 11 bench. Stela I from Quirigua sheds additional light on these two patron gods. Also from Copán comes the bench of Temple 11. but there are some clues that they may have held similar beliefs. Thus. he was clearly apotheosized as the Sun God after his death. While Yax K‘uk Mo‘ may or may not have been considered divine in his own lifetime. 2. were captured and burned during a battle between Quirigua and Copán (Looper 2003:78). Epigraphic evidence that some Classic Maya kings considered themselves divine can be found in king lists that trace a living ruler‘s genealogy back to a supernatural ancestor. But unlike Altar Q. some of the Copán‘s patron gods also sit on top of their name glyphs. Its central theme shows a literal ‗passing of the torch‘ from the founding king of Copán. An enthroned but long-deceased K‘inich Janaab‘ Pakal hands a feathered bloodletter to his grandson K‘inich Ahkal Mo‘ Nahb (Fig. deified ancestors. Kan Bahlam II made every effort to explicitly link Palenque‘s human dynasty to the Triad and their 51 . The origins of their dynasty begin in mythological time with accounts of the ―Triad Progenitor‖ – a local aspect of the Maize God named Muwaan Mat – and his three divine offspring (Stuart 2005:80). Foliated Cross.living king. There is a rare glyphic phrase that may characterize rulers as literal successors to specific gods that were the mythological founders of their dynasties (Houston and Stuart 1999:37). likely a gesture that conveyed the legitimization of Ahkal Mo‘ Nahb‘s rule as well as the fundamental importance of royal bloodletting rituals (Stuart and Stuart 2008:230). and their doings were essentially cast as narratives of heroism and their actions ―served as a metaphor for the trials and triumphs of the kingdom as a whole‖ (Stuart and Stuart 2008:191). These deities were Palenque‘s principal patrons and tutelary gods. the inscriptions at the Temple of the Cross. suggests the equivalency between them all.8). and Sun were commissioned by K‘inich Kah Bahlam II with the intention of linking his patriline with the supernatural narrative regarding the kingdom‘s foundation (Martin and Grube 2008:169). and other nobles (Miller and Martin 2004). and patron deities all seated in similar fashion. patron gods. deified ancestors. Similarly. Taken as a whole. The Temple XXI carving at Palenque is conceptually comparable to Copán‘s Altar Q. 2. the monuments commissioned by Ahkal Mo‘ Nahb represent a persistent campaign of legitimization that called upon the support of parents. ‖ a specific location that remains unknown to us. Coe 1989). This title was also taken by some of his immediate successors.‖ which has supernatural or stellar connotations. Lineage histories also served as charters for the social order that existed in each polity (Carmack 1973:13). K‘uk‘ Bahlam‘s successors made almost no reference to him. This contrasts sharply with sites such as Copán and 52 . the historical dynastic founder appears to have been K‘uk‘ Bahlam. Curiously. is as much a political statement as a religious one (Schele and Freidel 1990). McAnany 1995:128). either iconographically or epigraphically. At Palenque. then.Progenitor (Le Fort 1994:33. Such narratives legitimize the power of a ruler by linking him to the exemplary actions of his forebears (McAnany 2001:138). His name is that of the ―Zip Monster‖ or the ―Square-Nosed Beastie. He is referred to as ―the Holy Lord of Toktahn. We see a similar practice in the names of other dynastic founders (such as at Tamarindito). in addition to the ―Holy Lord of Baakal‖ honorific that was used by virtually all later rulers of Palenque. as long as the general population bought into it (Fowler 1987). The Founder figure at Naranjo does not seem to be a historical figure. regardless of whether the individuals were real or the connections to them are genuine. so he would have lived well in the distant past. The authenticity of a ruler‘s genealogy was largely irrelevant. The Cross Group. but not frequently enough to see a pattern (Houston 2000:167). Later rulers refer to themselves as being his 36th or 38th Successor. and the doings of the gods would have provided a model of behavior for rulers (Stuart and Stuart 2008:214. for example. they were believed to embody some type of vital force known as ip that was so powerful that it was dangerous for others to touch or even draw too near unto them (Houston 2000:167). whereas nobility claimed descent from supernatural forces or beings (Marcus 1992:222). Among the Colonial period Yucatec Maya.‖ or at best from other lowly commoners. and the jesting name (coco kaba) (Roys 1940). Onomastics (the study of names) of the Classic period gives us insight into the relationship between kings and their gods and the divinity of rulers. childhood name (paal kaba). Nobility may have been genetically closer to the gods than they were to commoners. Theophoric Throne Names and Divine Titulary Names are powerful things. They can draw people together or. commoners were thought to be descended from ―mud men‖ or ―stone men.Tikal. construct and reify social divisions (Charmaz 2006:396). Although Classic period rulers did not make such explicit claims. Among the Classic 53 . At least four types of names have been identified in the Colonial period: the paternal name. maternal name (naal). individuals could possess a number of different names depending on their age and social status. whose rulers made great efforts to celebrate the founders of their own individual polities (Stuart and Stuart 2008:113). An individual‘s identity vis -à-vis the community transforms as they acquire different names as they pass through various life stages (Lévi-Strauss 1982:167). at least according to later Mesoamerican belief systems. conversely. Among the Late Postclassic Zapotec. Although relatively few examples of the childhood names of Classic rulers survive. theophoric (ibid:116). their birth names were typically never mentioned again (García Barrios et al.Maya. a few observations can be made. rulers would receive new names and titles upon accession which established their relationships to both the human and divine realms (Colas 2003b. and they are rarely. They are highly variable and do not seem to rely on names of dynastic predecessor. Houston and Stuart 1998:85 Footnote 11). pictographic. at times seamlessly melding syllabic. a ruler‘s ―proper‖ or childhood name is never incorporated into the iconography (Eberl and Graña-Behrens 2004:116). if ever. The taking of a theophoric throne name upon accession was a clear indication of the individual‘s transformation to an elevated.9. sacred or even divine status (Eberl and Graña-Behrens 2004:102). a turning away from their childhood names and identities. No less than ten variant spellings of K‘inich Janaab Pakal‘s name are known from Palenque (Stuart and Stuart 2008:30). Martin and Grube 2008:77). A ruler‘s identity was so closely associated with his throne name that it was carried to the grave and beyond as he was venerated as an ancestor (ibid). 2004:3). 54 . Once they received their throne name. Rulers‘ throne names were celebrated through playful epigraphic and iconographic variations in spelling. 2. Titles and names provide additional epigraphic evidence that Maya rulers considered themselves divine. Headdresses typically served to identify the ruler (Kelley 1982). and rebus signs to indicate the name of the ruler (Fig. It is only the throne name that appears in the headdresses. Deity names were appropriated by rulers upon their accession in order to associate themselves with specific gods and thus emphasize their divine authority (Taube 2001b:267). for example. However. possibly kooj.‖ The portrait may be a visual pun for his name. Different sites favored different gods as their dynastic patrons. would highlight the ruler‘s association with agricultural fertility.Rulers typically never made reference to their childhood names after accession. The rulers of the Yucatecan sites of Dzibilchaltun and Uxmal. or using K‘inich in his nominal phrase would link him to the cycles of death and rebirth associated with the sun. ―puma. but with other prestigious polities. and the ruler was likely making claims of sharing said attributes with the god in question (Grube et al. Incorporating the name of the rain god Chaak into ones throne name. 2. as the sign for kooj is a feline with a winik sign in its mouth. For example. Certain theophoric names could associate rulers not only with the gods. the designation ‗divine headband -tying name‘ only occurs in the western region. a jadeite portrait was recovered from the cenote at Chichen Itzá that depicts K‘inich Yo‘nal Ahk II of Piedras Negras from a period early in his reign where he is still using his childhood name. and the portrait depicts a man wearing a feline headdress (Fig. both used Cholan appellatives in their nominal phrases rather than following a Yucatecan 55 . They often highlighted certain attributes of the god. there is a great deal of variation in regards to throne names. and even the manner in which the appropriation of a throne name was indicated had regional associations. specifically at Palenque and Piedras Negras (Eberl and GrañaBehrens 2004:115).10) Regional Variation of Names As we would expect. 2003:80-81). for example. ‖ as part of their name (Houston 2004:273). and K‘an are all repeated. The dynasty at Yaxchilán is perhaps one of the longest lasting and the most well documented. Some sites are characterized by specific dynastic lines. at least six of it rulers incorporated his name into their regnal name. and the names Bird Jaguar. At Palenque. the names Janaab Pakal.syntax. After AD 460. and K‘an Joy Chitam is taken by two rulers. Chak Tok Ich‘aak. At Tikal. which was incorporated into the names of at least four of its rulers. the names Sihyaj Chan K‘awiil. suggesting a major conceptual shift concerning their dynasty (Tokovinine 2007:19). Kan Bahlam. 56 . likely a form of mimesis of southern lowland naming practices and even an appropriation of the cult of the god Chaak (Lacadena 2004b:95). where the same name was used by multiple individuals. Interestingly. Tonina dynasts favored the name Chapaat. and at least two of Quirigua‘s rulers worked Yopaat into their throne names. not to mention those that recycled the names of Yopaat Bahlam and Knot-eye Jaguar (two apiece). At Caracol the names K‘ahk‘ Ujol K‘inich. ―Turtle. and Ahkal Mo‘ Nahb are each used three times. The god Chaak was clearly favored at Naranjo. and Yax Nuun Ahiin are all reused by later rulers. we see a shift in naming practices at Naranjo after the arrival and rule of Lady Six Sky from Dos Pilas at Naranjo. and the specific name Yo‘nal Ahk is taken by at least three of its kings. Yajaw Te‘ Kinich. At Calakmul the name Yuknoom is incorporated in the names of at least six of its known rulers. Four Late Classic rulers of Copán incorporated the name of the god K‘awiil into their throne names. all Piedras Negras kings use ahk. and K‘inich Tatbu Skull were each taken by no less than four rulers apiece. Itzamnaaj Bahlam. serves as a rigid designator. and Colas further argues that kings would explicitly liken themselves to the Sun God by prefixing their names with his.K’inich Pierre Colas (2003a) argued that the K’inich lexeme prefixed to throne-names taken by many Classic period rulers upon accession served a similar function to the k’uhul aspect of Emblem Glyphs (Fig. K’inich is the name of the Classic Maya Sun God. The prefixed K’inich acted more as a title than as a name. thus proclaiming their own divinity. the name K‘ahk‘ Ujol K‘inich from Carocol can be interpreted as ‗Fiery head of the Sun God‘ (ibid:273). antipassive. 57 . As a prefix. For example. K’inich is grammatically unconnected to the rest of the ruler‘s name and.13). Throne names were typically epithets that were descriptive of certain aspects of a specific deity or deities (Houston and Stuart 1996:295) that formed stative.11). 2. 13 K‘inich in the pre-position is never found in preaccession names and is clearly a part of that ceremony. 2. For example. These names are non -rigid 13 Emblem Glyphs were first identified by Heinrich Berlin (1958). therefore. K’inich has a different function when it is in the post-position of a ruler‘s name and is grammatically connected with the rest of his name. it seems to have been recognized only within the boundaries of a ruler‘s own polity. an epithet connected with rulership (Colas 2003:275). is depicted as a prisoner on Tonina Monument 122. He has been stripped of both his k’uhul and K’inich titles (ibid:275). K‘inich K‘an Joy Chitam. and his name is given only as K‘an Joy Chitam (Fig. and like the k’uhul prefix. the Holy Lord of Palenque. These personal names were verbal statements that associated the ruler with a particular aspect of a god. and passive sentences (Colas 2003:272). or post position. K‘inich Janaab Pakal was the first to take the title upon his accession at Palenque in 615 AD. and he provided the rains that nourished the maize and enabled it to grow (Taube 1985. Most of these sky-diety names are forms of the rain/lightning god. K’inich is not the only deity name taken upon accession. some elites even engaged in dental modification to create Tshaped incisors. 2. K’inich became an integral title in some polities. ibid:224). such as B’ajlaj Chan K’awiil. but most of the throne names appear to be associated with the sky. K’ahk’ Yipyaj Chan K’awiil. Whether K’inich was used in the pre. and all of his successors followed suit (Stuart and Stuart 2008:148). the name of B’ajlaj Chan K’awiil of Dos Pilas can be translated as ‗K‘awiil Hammers (in) the Sky‘ (Guenter 2003). 58 . and K’ak’ Tiliw Chan Yo’paat can be translated as ‗Fire Burning Celestial Lightning God‘ (Looper 2003).12. The lightning god was a powerfully symbolic name for a king to use because lightning was believed to crack the carapace of the cosmic turtle that led to the rebirth of maize.designators and refer to the personal self of the ruler as opposed to the pre-fixed K’inich title that acted as a rigid designator of his public persona. the rulers were clearly anxious to associate themselves with the Sun God. These names are verbal statements essentially conveying that ―God X‖ does something to or in the sky. and K’ahk’ Tiliw Chan Yo’paat. and the deities whose names are chosen are virtually all celestial in nature. McAnany (2008:224) noted that roughly a third of all rulers whose names have yielded to translation included K’inich in some way. likely in effort to mimic this characteristic trait of the Sun God (Fig. During the Late Classic. for example. Houston 1989:55). This was done to elevate the ruler‘s status above that of the growing class of nobles. sacred. the ruler inserts himself into larger mythological narratives. divine‘ and is based on the root k’u. Grube and Martin 2001:149. By taking such a name. it would literally mean ―he of the shout‖ or ―shouter‖ (Houston and Stuart 1996:295.agentive prefix.13. ‗shout‘ (Kaufman and Norman 1984:116). Footnote 3). ‗sacred entity‘ (Houston and Stuart 1996:291). references to k’uhul ajawob found at other polities often do not include the k’uhul prefix (Mathews and Justeson 1984:217). It was not until the fifth century AD that k’uhul was appended to the titles of the mightiest kings (Fig. 2. k’uhul.‖ thus highlighting his associations with agricultural fertility. much like the hueitlahtoani (‗great speaker/ruler‘) of the Aztec empire distinguished himself from the lesser tlahtoani (‗lord‘ or ‗speaker‘) (Grube. Combined with the aj. the Emblem Glyph of the ruler of Tikal would read K’uhul Mutal Ajaw. translated as ‗Holy Tikal Lord‘ (Martin 2001b). K’uhul as an adjective means ‗holy. which suggests that a ruler‘s 59 . it may be based on the proto-Cholan root *aw. 2. Significantly. et al. Houston and Stuart 1996:295). Mathews and Justeson (1984) suggested ajaw stems from an ancient root with connotations of planting seeds.Looper 2003).:295). ajaw. and the name of the area where the ruler claimed authority (ibid.13). Phonetic decipherment has revealed that these are exalted titles composed of three terms. Although etymologically uncertain. The K’uhul Ajaw Title The title ajaw was taken by Maya kings at least as early as the Late Preclassic as a designator of rulership (Fig. 2003:84. For example. implying the ruler was a ―sower. and many others (Zender 2004:168). The ajk’uhuunob’ were sometimes captioned as ―belonging‖ to the ruling kings. such as ‗Dignitary. For example. David Stuart (2005:32) suggests the root of the word may be k’uh-Vn and offers a meaning of ‗to guard something‘ or ‗to venerate‘ and expands these semantically as ‗one who guards‘ or ‗one who obeys. The Ajk’uhuun Title Additional textual evidence for the divinity of the living kings may come from the courtly title ajk’uhuun (Fig.1).divinity was not recognized outside of his own polity (Colas 2003:281). Architect‘. the inscribed hieroglyphic bench from Structure 9N-82 of Copán refers to a local lord as the ―ajk’uhuun of‖ the ruling king of Copán. as Zender suggested. Freidel (2008:193) argues that these courtiers were worshippers of the king himself rather than cultic priests. This selfdesignation of ―divine lord‖ is perhaps the strongest and most straightforward epigraphic evidence that Classic Period Maya rulers considered themselves divine. 2. ‗Intermediary. ‗Servant of God‘. ‗Mason. If Zender‘s decipherment of this title is correct and Freidel‘s interpretation of its meaning is valid. because these ajk’uhuunob’ are typically depicted in association with living kings. Various interpretations have been offered over the years for this title. and the caption of the Temple XIX panel expresses the same relationship with the living king of Palenque (Stuart 2005:32). ‗He of the Blood‘. Lord‘.‘ Marc Zender argued that the ajk’uhuun title could best be translated as ‗worshipper‘ (2004:180 -195) and suggested that they were cultic priests who worshipped the gods or euhemerized ancestors. ‗Courtier‘. ‗He of the Temple‘. it would support 60 . Mediator‘. However. When one site mimics the artistic style of another. has virtually no epigraphic references to war —there are no ―star war‖ events mentioned in the epigraphy. and the differences in themes are striking. indirect evidence for the divinity of Maya rulers. 61 . while others seem to have largely avoided the subject. for example. the meaning of the title is unclear. Aj k’uhuun could simply be a title for someone who worships the gods on behalf of the king rather than indicating it was the king that they were worshiping. Royal Artistic Programs Monumental art was critical in establishing a polity‘s identity vis-à-vis their neighbors. and rulers typically cradle a ceremonial bar in their arms rather than wielding a weapon and shield (Stuart 1992).the view that the Classic Maya kings were indeed considered divine and were actually worshipped as gods during their lifetimes. The monumental art of some cities emphasized militaristic themes and portrayed their rulers as mighty warriors. Copán. Rather. Ultimately. it may suggest that Copanec rulers chose to play up their role as cosmic center and downplay their role as military leader. However. This is not to say Copanec rulers did not actually engage in war. Regular iconographic quotations from a site‘s own artistic history helped to establish a distinctive local identity (Tate 1992:xi). lithic evidence suggests that the Copan valley was active militarily from the Early to Late Classic periods (Aoyama 2005). no bound captives appear in their iconography. and is at best only weak. providing details of their conquests and captives. it typically denotes some type of political relationship (Looper 2003:33). typically depicted themselves as protagonists. Stelae were common at Preclassic sites such as Kaminaljuyu. 711) created a new stylistic 14 The Classic Maya term for stela was lakamtun.The stelae tradition can be traced back to the Formative period Olmec. 2.D. and Taube (1996) has suggested that the stelae are essentially jade celts writ large. La Venta Stela 2 conveys the message that the veil between the natural and supernatural realms is extremely porous. 62 . Classic period rulers. and El Baúl (Looper 2003:8).15). Thematically. and if supernatural beings were present. They portrayed themselves as idealized figures. Takalik Abaj. in contrast. La Venta Monument 25/26.C. ReeseTaylor and Walker 2002:92) and the earliest inscriptions tended to privilege theology over history (Houston 2004:308). As for subject matter. Rulers could initiate bold new artistic programs at their sites that would endure for generations. they were relegated to the periphery of the scene. Izapa. as a living ruler stands holding a staff of power. Jasaw Chan K‘awiil‘s Stela 16 (A. which emphasized their vigor. At Tikal. Preclassic iconography focused more on gods than it did on historical individuals (Freidel and Schele 1988a: 550-552. which means ―banner stone‖ or ―large stone‖ (Stuart 1996b:154). for example. 2.) we find the earliest upright stone monuments carved in both high and low relief.14). which are themselves identified with maize. 14 At La Venta (1000-600 B. we find both natural and supernatural representations carved into these stones. but left them all but devoid of individuality and personality (Miller and Martin 2004). is a purely supernatural portrait of a deity who wears a headdress topped by a trefoil maize icon (Fig. surrounded by six supernatural beings that hold similar staffs (Fig. This template was followed by Yik‘in Chan K‘awiil‘s Stelae 21 and 5 and Yax Nuun Ahiin II‘s Stelae 22 and 19 (Fig. The creation of three dimensional stelae there. there can also be a great deal of variation within a single site throughout the site‘s hi story. as well as at Copán. In the mid-sixth century. 2.template where the ruler was depicted with a front-facing body but his with his head in profile. stelae commissioned by later Tikal rulers were planted in Twin Pyramid Complexes (which represented the path of the sun) which symbolically associated the ruler with celestial authority (Ashmore 1991:201). The subject and length of Quirigua‘s texts shifted as well. like those of Stelae C and N from Copán. the focus of the texts found on their stelae was primarily 63 .17. altars. A concise example comes from Quirigua. K‘ahk‘ Tiliw Chan Yopaat‘s monuments clearly emulate those of Copán in both style (Riese 1986) and content (Stuart 1995). According to the pattern established by Jasaw Chan K‘awiil. We ultimately see a shift away from stelae at both Quirigua and Copán by the end of the Late Classic. accompanied by a short text naming the protagonist and just one or two events (Fig. While variation between sites is to be expected. which has a comparatively short lived monumental history. 2. is certainly a testament to the mastery of their artisans. Sky Xul at Quirigua and his contemporary at Copán Yax Pasaj shifted their efforts to architectural texts.16). The content. hearkens back to calendrically significant events in deep history (Stuart 1995). Tonina inventively began creating fully rounded sculpture (Miller and Martin 2004:48). Miller 1999:129-130). but it is also a function of the supple texture of their locally available stone (Stuart 1996b:149). After Waxaklajuun U‘bah K‘awiil‘s unfortunate encounter with the ruler of Quirigua. and zoomorphs (Stuart 1995). as is typical of Copán‘s sculpture. so did their artistic style. the zoomorphs being inscribed with lengthy and complex narratives. their large bas relief tablets. The lone stela from Palenque was a three dimensional portrait commissioned in 692 by Kan Bahlam to commemorate the end of the 13th K‘atun (Martin and Grube 2008:169). When their political alliances shifted. rather than treating each side as a self-contained unit. Palenque was not a member of the ―stelae cult‖ that was so pervasive across the lowland area. Uaxactun and Copán. 2. At Piedras Negras. 2. Period Endings were extremely important and monuments were erected every hotun (five years) to commemorate them. Monument 26 ultimately appears to owe its iconographic heritage to Tikal Stela 4 (Fig. and 28.19). Rather. In general.dedicatory in nature. Quirigua‘s monumental tradition appears to be variously cribbed from Tikal. Copán had been erecting stelae for centuries and to suddenly turn away from them as a form of public media is a striking change of program (ibid). 2. often with extraordinarily lengthy texts. were set into walls and seem to have been functionally equivalent to stelae as they likewise served to ―immortalize rulers and to record rituals and the key dates of myth and history‖ (Stuart and Stuart 2008:28). The iconographic elements found on Monument 26 (Fig. Clearly Quirigua and Copán were influencing each others‘ stylistic programs. although the execution is decidedly different.20). 2. but the rest of the Usumacinta 64 . in that the frontal iconography continues onto the sides of the monument.18) appear to be directly copied from Uaxactun Stela 20 (Fig. Some sites in the Puuc region also appear to have rejected the stela cult (Stuart 1996b:149). early stelae at Quirigua follow the pattern set by Tikal Stelae 1. texts were extremely concise. Unlike the stelae programs at Quirigua and Copán. such as bloodletting and dance (Grube 1992). and Dos Pilas. and ceramic vessels (McAnany 2001:141). In stark contrast to the generally brief. Ek‘ Balam. 2000).region appears to have paid them little attention. Yaxchilan. which also served to give literate persons access to esoteric knowledge. the syntax is extremely complex and has proven a 65 . Substitutions patterns in Maya epigraphy suggest that language use was linked to regional identity (Wichmannn 2006:290). which all had strong militaristic and ritual themes to their texts. they were also a central theme on Quirigua‘s monuments far to the east (Stuart 1995). formulaic dedicatory texts of Copán and Quirigua are more western sites such as Yaxchilan. Along with descriptions of warfare. In general. such as stelae. for example. distinct from that used by commoners (Houston et al. seems to have the largest number of inscriptions concerning warfare of any Maya site. demonstrates unique traits in its glyphic system. Although Piedras Negras‘ immediate neighbors did little to celebrate Period Endings. with most of the references occurring in the Late Classic (Stuart 1995). Classic Maya writing may have represented a prestige language. Prior to the Late Classic. Monumental Texts Literacy was limited to nobles and elites. in fact. lengthier texts began to be used on a variety of media. Yaxchilan instead concentrated its inscriptions on doorway lintels (Tate 1992). In the Late Classic. Yaxchilan‘s lintels give us insight into many of the royal ritu als that were performed. Aguateca. lintels. On the same text. For example. 2003:18). Houston (2006:145) noted the emotional impact that a ruler‘s strategic appearance and disappearance would have had on an expectant crowd.‖ 66 . such as K’ahk Okxam (―Fire ?‖) and Ocho’m. The carved human femur found in the left hand of Ukit Kan Le’k in Tomb 1 contains many unknown appellatives to deities (ibid:45). Rituals of Rulership Classic Maya rulers fit into the Pan-Mesoamerican model of being the head of both civic and ceremonial life of their polities. ―The rhetoric of texts and images constantly refers to the prototypical actions of supernatural beings who conduct sacrifices and dedicate stone monuments just as historical rulers do. As Looper (2006:826) states. that are poorly understood. Mural A (also called the Mural of the 96 Glyphs) from Substructure 29 of Structure 16 breaks from the standard paired column reading order. The mural is also unusual (though not entirely unique) for its length. the scribe wrote out forty-nine consecutive days with their coefficients (Grube et al. Ritual activity seamlessly connected the past and the present. we find titles that are unique to the site. but rather the text is presented horizontally in long rows (Grube et al. and the passing of centuries were presented as if but a moment. Their public rituals would therefore have served both political and religious purposes. similar to the Late Postclasssic emperors among the Aztec and Mixtec that acted as both supreme political rulers and high priests (Zender 2004). in place of a Distance Number. Another unique feature of this text is that at one point. 2003:10-11).difficult challenge for epigraphers. and will be so in perpetuity (Morehart and Butler 2010:592).). which translates as ―scatter. even sacred substance. Scattering. with varying elements issuing from his hand. Humans are indebted to the gods. was symbolic of death yet a source of life (ibid. such as incense ( ch’aaj) or blood (Fig. what is recorded gives us important glimpses into their fundamental religious beliefs (Sachse 2004:14). sacrifice and offerings were referred to as nextlahuanlizti. Although Classic period inscriptions detailing rituals tend to be vague or cloaked in metaphor. for example. Mesoamerican ritual in general is primarily geared towards satisfying Mauss‘s (1990:16) notion of the ―fourth obligation.Yaxchilán Lintel 21. connects the ritual actions of Bird Jaguar at the ―4 Zotz House‖ to an identical ceremony performed by Yo‘pat Balam (now a revered ancestor ) over three centuries earlier.‖ ―sow‖ or ―cast. ―debt payment‖ (Morehart and Butler 2010:592). and 67 . Blood sacrifice. Sacrificial blood could be dripped on bark paper and burned within a bowl. the ruler is typically shown with his arm extended downward with his palm facing up or inward. We know the names of some specific ritual actions. but there is no general term for the concept of ‗ritual‘ among the ancient or modern Maya (ibid). Among the Nahuatl of the sixteenth century. and Conjuring One of the most common rituals performed by rulers was known as chok. and offering it to the gods may have been a way to symbolically reenact the sacrifices the gods made while creating the world (Bradley 2001:33).21). then.‖ gi ving to the gods. Human blood was considered a precious. Bloodletting.‖ Iconographically. 2. Drucker et al. Clear iconographic representations of bloodletting from the penis can be found from the Late Preclassic to the Late Postclassic. so royal scattering rituals ―reproduced popular practices. establishing connections with common people but at the same time veiling rulers in an aura of awesome spiritual power‖ (Looper 2003:15). such as a shark‘s tooth. Joyce et al. ibid:120-121). 2010:10-13). and a jade ―ice -pick‖ perforator (Coe 1977:188. Maya rulers sought to portray themselves as humble agriculturalists (Miller 2001:203). The casting of drops of incense or blood mimicked the way farmers would cast seeds into the ground and pour liquid offerings onto the field to propitiate the gods (Looper 2003:13-15). Among the Maya. each with a distinct offering being made to the Principal Bird Deity (Fig. 2.the smoke rising up would be both a way for the gods to manifest themselves unto humans as well as an offering to the gods (Fig.23. 2. Although the archaeological evidence for bloodletting in Mesoamerica dates to the Formative period. 1959:272. stingray spines (as well as a jade effigy of a stingray spine). They reinforced the ruler‘s role as caretaker of his city. Freidel at al 1993:204). 1991:3). the ritual is never actually depicted in Olmec art (Taube 2004c:122).22. A tomb discovered in Mound A-2 at La Venta contained several implements associated with bloodletting. Drucker 1953:23-26. the earliest iconographic representation of autosacrifice comes from the Preclassic site of San Bartolo (Taube et al. The west wall mural graphically depicts Young Lord (an analogue of Hun Ahaw of the Classic period or Hunahpu of the Popol Vuh) piercing his genitals before four different trees. The mythological scenes of sacrifice by the Young Lord would have provided a divine 68 . etc. which were emblematic of bloodletting (Fig. bloodletters depict Chak Xib Chaak. as would be expected. the bloodletting implement itself was deified (Coe 1977:188). For example. The smoke arising from the sacrificial bowl provided a medium through which gods and ancestors could manifest themselves. tzak.15 The specific associated deities varied from site to site. shark teeth. obsidian lancets. 1991:1). 2. the strongest bloodletting associations are predictably with the Triad (Berlin 1963).prototype for humans.. Young princes also engaged in autosacrifice and their first bloodletting or yax ch’ab seems to have been a rite of passage at the time of puberty (Houston 2006:144).24). At Palenque. That they are also sometimes associated with bloodletting demonstrates the polyvalent nature of Maya gods as well as the the conceptual link between bloodletting and agricultural fertility. which ultimately depends on the rains. in the form of stingray spines. particularly for rulers. were often a part of royal regalia (Joyce et al. Glyphic texts that accompany conjuring scenes occasionally 15 The Paddler Gods are more closely affiliated with water generally and the summoning of clouds and rain specifically (Stephen Houston. personal communication 2011). at Piedras Negras. When ―personified‖ (Joralemon 1974). while those at their rival site of Yaxchilán depict K‘awiil (Fitzsimmons 2002:203). and typically donned a headdress of three-knotted bands. The Paddler Gods are sometimes associated with Period Ending bloodletting rituals (Schele and Miller 1986:52). The three-knotted bands were sometimes tied around the wrists and ankles of ritual participants and the staffs that they held (Joyce et al. The conjuring of deities. 1991:1-2). was often the goal of bloodletting rituals. 69 . but other gods have strong bloodletting associations with it as well. Bloodletting paraphernalia. ―a place where communication with sacred power is made possible‖ (Livingston 2005:46). 70 . as a living axis mundi. Reilly 1994:186-187). or manifestations of the divine.‖ The ritual has great time depth. its roots extended into the Underworld and its branches pierced the heavens.25. For example. 2. was an embodiment of sacred space – wherever they stood was a ‗holy place‘. At Palenque the ‗world tree‘ was named the uh te. dating back to at least the Middle Formative. then.refer to the event as the ―birth‖ of the deity (Looper 2003:22) and they were subsequently nurtured by the offering (Freidel and Schele 1988). Eliade used the term axis mundi to refer to specific places that are made sacred through hierophanies. ―Shiny Jeweled Tree. Raising of the World Tree One of the primary royal rituals in Mesoamerica was the raising of the cruciform ―world tree. A ruler‘s control over this cosmological axis would have been a powerful reminder of the distinction between ruler and ruled (McAnany 2001:141). A Classic Maya ruler.‖ and rather than a general concept of cosmic centering. and its cruciform shape established the quadripartite horizontal plane (Mathews and Garber 2004). at Palenque it appears to have carried a more 16 Interestingly.16 The world tree served as an axis mundi that centered and ordered the cosmos both vertically and horizontally. It bridged the three vertical levels of the cosmos. Monument 1 from San Martin Pajapan in Veracruz depicts the raising of the world tree by a ruler wearing an Olmec style Maize God headdress (Fig. Monument 1 was found on the summit of a volcano (Reilly 1994:186). ‖ which is used in the context of offerings made to the gods (Looper 2009:17). heir designation and other 17 GI appears to embody the sun in its transitional pre-dawn status (Stuart and Stuart 2008:198) 18 In modern Yucatec we similarly find όok’ot ―dance. and dance continues to be an acceptable attitude of prayer among traditional Mesoamerican communities (Houston 2006:144). intercede and defend someone. representative of the womb of the cosmic alligator from which the sun is reborn (Fig. ―to pray. 17 The tree is shown rising out of a k’in or solar bowl.‖ and ok’ot b’a. ibid). 2.18 In essence. and these agents are always male rulers. and thus prayer and intercession‖ (Acuña 1978:19) 71 .27). and as such was associated with the eastern sky and GI. the verb ahk’ot is exlusively used in reference to human agents.‖ ahk’ (Macri and Looper 2003:206). Nikolai Grube (1992) was the first to translate the T516 glyph as ‗to dance‘ (Fig. see Chapter 3). ―he/she gives (it). Dancing Dancing was one of the most common rituals performed by Classic Maya rulers throughout their reigns (though curiously uncommon as an accession ritual. the actions of the gods were apparently not considered ―offerings. as a way to penetrate into the supernatural realm. 2. While images of dancing gods are prevalent.specific connotations of prosperity (Stuart and Stuart 2008:176). sacrifice. dances may be seen as offerings or tributes to the gods (ibid:18). This glyph is read phonetically as ahk’ot and may be semantically related to the term for ―give. Significantly. be they a supreme k’uhul ajaw or a subordinate sajal (ibid:19). It was bejeweled and resplendent as the rising sun.‖ Dances were associated with a wide variety of events: deity impersonation rituals. Ahk’ also serves as the root for yahk’a(w).26. warfare. Looper 2009:6. the glyphic recording of dance was relatively short lived and late (all references come from the Late Classic period). Sahagún (1950-1982. the brave warriors. Looper 1991:91). Piedras Negras. the rain god Chaak to the viewer‘s left and the god of terrestrial standing water to the right. associated with locally significant deities. the noblemen. secured by a tumpline across his forehead (Fig. 2. Curiously. He is flanked by water deities seated upon thrones. and claims it was done ―in order to hearten and console all the peers. but despite the limited data set some chronological and geographical patterns are discernable.28). it was used to reinforce alliances with other powerful rulers and their subordinate lords. 2. along with their specific accoutrements would have been employed by each ethnic kingdom to distinguish themselves from neighboring polities (Boas 1955:346-347). Naranjo. 2010:125). Just as dance was used to strengthen the bond between rulers and their gods. Tambiah 1985). where the Maize God dances and taps his turtle shell drum within a quatrefoil earth. The Maize God bears the burden of corn on his back. The earliest known reference to dance dates to AD 653.29. La 72 . and all the common folk and vassals.dynastic events. Other early references (AD 668-733) come from Dos Pilas. and visits by overlords (Looper 2009:5). Book 8:150) lists dancing as one of the ruler‘s primary responsibilities. the lords. Such dances would have heightened the sense of community identity and reinforced the local sociopolitical status quo (Leach 1954:13-14. One of the earliest portrayals of dancing is on the San Bartolo west wall mural.‖ The distinctive dances performed by rulers. found on Altar L at Quiriguá (Fig. depicted as a turtle (Taube et al. 2. and related sites. reference to dance is found scattered throughout the Maya area (Looper 2009:18). Tokovinine (2003) translates the glyphic phrase cha’nil as ―public ceremony. Although approximately fifty instances of this ritual have been identified across the lowlands.30). Dances and public spectacles (Houston 2006) need not be seen as purely religious events. Schele and Miller 1986). After about 780. could perform them with the king. but rather he is ―concurrent‖ with the deity being impersonated. Houston and Stuart (1996:297-300) note that the ruler‘s identity is not displaced. but they also served socio-political functions in legitimizing the ruler‘s power (Looper 2009:5. K2695 may depict Yax Nuun Ahiin II preparing to impersonate an earlier ruler from Tikal‘s dynasty (Fig. Impersonation Rituals Rituals involving dance are often done while the ruler is in the guise of a god or deified ancestor. The purpose of deity impersonation rituals was likely to reenact mythological or historical events of local import. The ruler was not the only person permitted to do such rituals.Corona. For example. occasionally even women. typically referred at as a ―deity impersonation‖ ritual. which suggests that some dances were intended to be performed in front of an audience (Looper 2009:18). such as on the unprovenienced door jamb (likely from Xcalumkin).‖ which sometimes occurs in conjunction with dance expressions. other nobles. From AD 752-780 the majority of dance references come from the Yaxchilan region. Schele and Freidel 1990. Sachse 2004:15. no discernable 73 . Ancestral figures may also have been impersonated regularly. hunting gods. such as: wind gods (ik’ k’uh). an 819 day count (likely 7 x 9 x 13 days). 2. 18 named months that cycle with the numbers 1 to 20 to form a haab of 360 days (plus a 5 day wayeb to approximate the solar year). the sun god. gods of ball playing. and the major god known as Itzamnaaj. 20). stony gods.pattern emerges with regard to which gods were impersonated or why. gods of incense burning. To them. moon goddesses. k’atuns of 74 .31. 13 numbers that cycle with 20 named days to create a 260 day sacred round we call tzolk’in. repeated dates would bring associated events (Looper 2003:10). Coe 1978: pl. a haab times a tzolk’in that gives a 52 year cycle. hotuns of 5 years. which is found primarily in the vicinity northwest of Lake Peten Itza (Houston 2006:146). fire drilling jaguar deities. nine day cycles (Thompson 1929). They employed a wide variety of ways to mark the passage of time. an enigmatic god known as 9 yokte’ k’uh. time and history were far more cyclical than they were linear. The Significance of Sacred Time The Classic Maya are celebrated for their advanced knowledge of time reckoning. a watery serpent (once ―concurrent‖ with a royal lady). Houston (2006:148) notes the wide range of gods they impersonated. The only discernable regional trait associated with impersonation rituals is the ―X -ray‖ iconographic convention of depicting a cut-away of the mask being donned in order to reveal the identity of the performer (Fig. They reckoned time with a boggling variety of perpetual cycles: seven day cycles (Yasugi and Saito 1991).‖ supernaturals connected to the Mexican state of Teotihuacan (18 u’b’aah k’awiil). underworld gods who exercise dominion over (pre-Hawking) ―black holes. 75 . Rituals were timed in accordance with important dates. The popular media have suggested that ―the Mayan calendar‖ will end in December of 2012 when the 13th cycle is completed. however on Tikal Stela 10 we find a date with a piktun coefficient of 19 and at Palenque on the West Panel of the Temple of the Inscriptions K‘inich Janaab‘ Pakal connects his accession to a future date that essentially requires a bak’tun count of 20. Yaxchilán is typical in that its piktuns appear to cap out at 13 cycles. At Palenque. Despite seeming uniformity. typically Period Endings.0 appears to have been the PanMaya ―zero date‖ for the reckoning of time. 13. For example. for example. Rulers were responsible for re-enacting creation through ritual action on calendrically significant dates in order to recreate the world on a microcosmic scale (Martin and Grube 2008:221). he was connecting himself to replicating the actions of the creator gods and asserting his powers of cosmogenesis (Looper 2003:11). as is the concept that there was a single ―Mayan calendar‖ that was synchronized among the various ancient polities throughout their history.20 years.0. b’ak’tuns of 400 years. When a ruler erected a stela in commemoration of a station of the calendar. they clearly did not expect 2012 to be the end of days. different polities could reckon time according to local inclinations. This misconception is unfortunately quite common. They calculate a piktun‐ending with a piktun of 20 bak’tuns. bringing with it all manner of calamities. and various cycles of lunations. which would clearly be impossible if the bak’tun count reset after it reached 13. Regardless of the differences in the details. piktuns of nearly 8000 years.0.0. In the Lunar Series from Dos Pilas. 480) truncate the Long Count after the tun and reverse the calendar round. 2.0. unlike the Late Postclassic period. 472) and Quirigua Stela U (9. Yaxchilan. placing the haab before the tzolk‘in (Fig. La Corona.0. 9.4.5. and while its oldest and most frequent usage comes from Palenque. and Quirigua.1. Diachronic variation is also evident. A. Naranjo.D.32). the lunar cycle was reckoned according to local empirical observations.17. A. reminiscent of the archaic calendric structure found on the Hauberg Stela (Looper 2003:39). Furthermore. as is documented among the Aztec (Sahagún 1950-1982.2.0. And each city 76 . it appears to have spread outward from there to nearby sites such as Yaxchilán and Bonampak and to distant polities such as Quirigua and Copan (Berlin 1965:341). The greatest amount of local variation in the calendar is found in the shorter cycles of time. Early monuments from Copán (Stela 16.Janaab‘ Pakal appears to have been the first to initiate the 819 day count in the Maya lowlands. a relationship can be seen between the Glyph C coefficient and the Ajaw who was ruling when the monument was erected (Fuls 2007:279). Book 4:87-88) and is prognosticated in the Dresden Codex. Fuls‘ (2007) analysis of month counts and Lunar Series data suggests that rulers could initiate new calculation methods when they acceded to the throne. Interestingly. Le Fort‘s (1994:35) analysis of accession dates revealed no clearly discernable regional or site specific patterns during the Classic period. there does not seem to be any association between ―auspicious‖ days and the dates associated with a ruler‘s enthronement.D. and at times a particular 29-day lunar ―month‖ noted at one site might be reckoned as 30 days at a different site. Piedras Negras. winal. There are several Classic period monuments where the day sign Ajaw was fused with the portrait of the king. we find variation in the specifics. so as a personified world tree and living axis mundi.960 days). whereas Palenque‘s aggregate lunar cycle was only 81 moons (2392 days). conflates an image of the ruler K‘awiil Yopaat with the day name Ajaw (Fig. rulers themselves could become embodiments of time (Houston et al. Martin and Grube 2008:217). but again. there does not appear to have been an 80 year ―Period of Uniformity‖ where lunar cycles were synchronized across the lowlands (Fuls 2007:279). Lunar cycles could be aggregated into larger units. 2006:87). Copán. The dancing rituals performed on calendrically significant dates would have metaphorically 77 . Their most basic count of days was originally based on the number of fingers and toes on the human body. Estrada Belli 2006:64). The calendar was inseparably connected with the four cardinal directions.determined for themselves whether the moon was the first. was thus conceptually and semantically related to the human body. The name of this count of days. for example. Quirigua Altar L. the Dresden Eclipse Pages account for 405 moons (11. In the Postclassic. 2. for example. had a cycle of 149 moons (totaling 4400 days). King as Time Just as time could be materialized when inscribed on stone monuments. or the sixth moon of a lunar half year.29. the third. Copán‘s Lunar Series is so inconsistent with the rest of the lowlands that it may represent a different system entirely (ibid:281). Contrary to Teeple‘s (1930:54) assertion. the body of a k’uhul ajaw was the embodiment of the calendar (Stuart 1996b:165-167. as ‗seating‘ and ‗binding‘ are used to indicate both the dedication of monuments at important stations of the k’atun as well as the enthronement of rulers (Houston et al. Quirigua Altar L explicitly conflates their ruler with time itself by featuring his portrait inside of the cartouche rather than the day sign (Looper 2003:51). and they are found in figuratively subterranean spaces. and Quirigua (Looper 2003:52-53) and Tikal (Schele and Freidel 1990:205) each have one. 78 . They are typically defined by the presence of a large Ahaw day sign in reference the day of the monument‘s dedication. The presence of these distinctive monuments at Quirigua serve to reject the artistic tradition of Copán (where no Giant Ajaw Altars exist) while simultaneously ideologically aligning themselves with Caracol (Looper 2003:52-53). their bearing of the title K’inich would have linked them to the passage of time with each sunrise (Houston et al. Some of the language of accession rituals likewise reinforces this association. 2006:83). 2006).represented the movement of time (ibid). Houston (2011. A special class of monument dubbed ―Giant Ajaw altars‖ are most commonly found at Caracol and are a hallmark for their local artistic style (Chase and Chase 1992:45). personal communication) notes that the the Giant Ajaw altars at Caracol portray time as if it were a war captive reduced to wearing perforated cloth. Furthermore. but they are found to a lesser extent at Tonina (Miller 1998:211). First Three Stone Place.C. so it cannot accurately be described as a day of creation. We typically gloss the date 4 Ajaw 8 Kumk‘u as the date of creation. The specifics about what actually happened on that day and at that place vary from site to site. the Paddler Gods dedicated the Jaguar Throne Stone at Naahho‘chan (―First Five Heavens‖). there are events recorded that predate 13.0.Calendric Rituals and the Re-enactment of Creation The most important rituals performed by Classic Maya rulers involved the reenactment of local ―creation‖ events (Freidel et al. 1993:67. the Tablet of the Cross at Palenque. It appears to be the date that the cosmos were reorganized. as do the preceding and subsequent events in a site‘s primordial history. and a number of inscriptions state that the location of these events was the ―First Three Stone‖ place (for example. 79 .0. Footnote 22). Quirigua Stela C contains the most detailed account of 4 Ajaw 8 Kumk‘u events.0. renewed.0. followed by the dedication of the Water Throne Stone by Itzamnaah at the ―??-Sky. Yaxchilán‘s creation mythology includes the beheading (ch’ak baah) of the Maize God and two other deities (whose names remain undeciphered).). Dos Pilas Panel 18. According to their local mythology. 2.33). or set in order and it ushered in the age of humanity (Stuart and Stuart 2008:256. Looper 2003:11). and Piedras Negras Altar 1. Quirigua Stela C.0.0. Fig. on 13.0 by millions of years.‖ All of these events were overseen by a god named Six Sky Ajaw (Freidel et al. To be clear.0 4 Ajaw 8 Kumk‘u (13 August 3114 B. then a god whose name resists decipherment dedicated the Snake Throne Stone at Lakam Kah (Large Town). 1993). for example. ―Earth. 2. embodies Yax Naah Itzamnaah and acts as overseer of the accession in direct emulation of mythological events. As Stuart (2004b:264) notes. the existence of pilgrimage sites denotes there was a basic. and underworld are sacred animate realms. Janaab Ajaw. which symbiotically imbued both person and place with even greater spiritual potency. sky. and in the middle he is depicted sitting upon his throne in the guise of GI (Fig. Rulers explicitly linked and likened their own accessions to those of the Triad. Rulers would visit such places for their ritual activities. ―The historical accession of Ahkal Mo‘ Nahb is not simply a harkening back to mythical symbolism. some features of the landscape were so magnificent that supplicants would 80 . specifically to GI. but truly becomes a re-creation of that earlier event.‖ The Sacred Landscape The Maya landscape was alive with spiritual beings and energy. where one god installed another in office. and all Mesoamerican landscapes are thus inherently sacred landscapes. Although Maya religion was in many ways a local expression (to be discussed in Chapter 4). Though each Maya city had its locally significant sacred spots. K‘inich Ahkal Mo‘ Nahb. glyphically recounts GI‘s accession and rebirth on the day 9 Ik‘ on the left side of the Temple XIX tablet. He then recounts his own accession on 9 Ik‘ on the right side of the tablet.The main focus of Palenque‘s primordial mythology is the creation of the Triad and their subsequent actions. His cousin.‖ But some locations were deemed more spiritually potent than others. As Ashmore (2009:185) states. underlying Pan-Maya belief system.34). Caves. as entrances to the Underworld. has no archaeological settlements associated with it. The sacrifices and offerings associated with cave ritual are extremely varied across space and time. The natural and man-made were not in conflict with each other. Naj Tunich. Jiménez-Sánchez 2004:190). 81 . ceramic evidence for long-distance pilgrimage associated with cave rituals spans from the Middle Preclassic all the way through the Late Classic (Spenard 2006:3). Lakamha‘. such as the cenote at Chichen Itza. yet its richly adorned walls indicate it would have been an important destination for pilgrims (Ashmore and Blackmore 2008). who make long trips to perform rituals at important but distant ceremonial centers (both man-made and natural features) (Vogt 1969. At a cave near Cancuen. But it was not just the natural landscape that was considered sacred. for example. harmonizes natural and man-made sacred space. Pilgrimages continue today among modern Maya priests. built into a hillside. due to local and regional social and geographical conditions (Morehart and Butler 2010:594). as does Temple XIX‘s location adjacent to the spring from whence the Rio Otulum originates. were extremely sacred features of the landscape and as such were important pilgrimage sites (Brady 1989).travel great distances to perform rituals there. Man-made structures were likewise imbued with spiritual potency. but rather could merge seamlessly together. the ritual center of Palenque. The Temple of the Foliated Cross. is an elegant blend of natural and man-made sacred space where rulers and other elites conducted their rituals (Stuart 2005:184). Some caves appear to have been more important pilgrimage sites than others. The ruler was to be the supreme commander. Although these weapons are sometimes associated with Teotihucan.‖ and lists their roles and responsibilities in regards to warfare first and foremost among their kingly duties. and it put to the test a god‘s ability to act as protector to his people. and he would reward brave warriors by presenting them with insignia. often emblazoned with images of their gods. Bound captives appear on Preclassic 82 . in essence. Warfare is also attested to iconographically. The importance of warfare in the Maya area is plainly manifest in the Preclassic period. similar to the one held in the hand of the ruler on Kaminaljuyu Stela 11. The overarching question in this research study is concerned with the relationship between the Maya rulers and their gods. the pitting of one ruler‘s god against another. The Classic Maya likely held similar beliefs about their own rulers. and El Mirador (McAnany 2001:138). The bas-relief at the entrance of Loltun caves depicts a ruler wielding a weapon resembling a macuahuitl in his right hand and a ―fending stick‖ in his left (Grube and Schele 1994:2-3). strategist. The emblems of war were ritual objects. and supplier for his armies. the early date of the carving demonstrates that such weapons were in use prior to the expansion of Teotihucan‘s influence in the Maya area (ibid.Ritual Warfare The Florentine Codex (Sahagún 1950-1982. Edzna. Our purpose here is not to recount the specific battles that were waged between sites throughout the Classic period. Book 8:51) details ―the exercises of the rulers and how they might perform well their office of government.). There is abundant archaeological evidence that attests to large-scale war efforts (Webster 2000:69) as evidenced by defensive ditches and walls at the Late Formative sites of Becan. Ritual warfare was. and metaphorically represented the ruler as ‗king of the forest‘ who ―prowled the landscape as f ierce beasts guarding and extending their domain. A ruler (dressed in avian regalia) holds an obsidian knife in his left hand. Kaminaljuyu. El Jobo Stela 1 depicts a bound captive at the feet of the triumphant protagonist (likely a ruler). culminating in the Late Classic which is characterized by the abundance of warfare iconography. At end of the fourth century that we begin to see iconographic representations of rulers depicted with Central Mexican-style warfare regalia such as Tlaloc shields and shell mosaic helmets (McAnany 19 Taube (2003a:480) notes that jaguar palanquins were common in Classic Maya art.‖ 83 .19 The victim‘s left hand appears to cradle the foot of the attendant at the rear. the emphasis on warfare once again returned to prominence. The victim is likely a ruler. where rulers would typically hold religious objects such as the ceremonial bar rather than weapons of war. During the Early Classic. and the decapitated body lies at his feet with blood flowing out of its neck. perhaps indicating it was he who had been carried to the battlefield in it. and Izapa Stelae 21 and 55. as he is adorned with a jade necklace and earspools. Chalcatzingo Monument 2. In the background is a jaguar palanquin being carried by two attendants. One of the more graphic representations of royal warfare from the Preclassic period is found on Izapa Stela 21. Monument 65. and in his right hand he grips the hair of a severed head that gushes blood.monuments such as La Venta Altar 4. But as the Classic period progressed. there appears to have been a subtle shift away from the iconography of warfare. who carries a trophy head in his left hand and in his right hand wields a weaponized femur that has been fitted with a flint blade at one end and an anthropomorphic head at the other (Miles 1965:259). Webster 2000:93). The shifting emphasis on the warrior-king motif calls in to question the notion that military prowess was always considered a prerequisite for rulership. those who were sources of chaos and disorder to his polity. Curiously. Although the preferred royal regalia sometimes shifted between weapons of war and purely ritual objects such as the ceremonial bar. This may speak to beliefs concerning the afterlife. namely. that the ruler would not be required to engage in combat to secure his place in the heavens (McAnany 2001:138). the underlying function of these objects was essentially the same. 2.35. Even during the Late Classic period. when a ruler‘s role as warrior was iconographically ubiquitous. Invading enemies could throw a city into chaos by destroying its temples and capturing or even burning the wooden images of their patron gods. Likewise.2001:137). the weapons of war were a way for the ruler to subdue his enemies. Maya rulers again moved away from fearsome ―warrior king‖ depictions of themselves and instead portrayed themselves as ―refined. Yet iconographic depictions of deified ancestors may portray them in full warrior regalia. The wielding of sacred objects was a way for the ruler to establish himself as the world center. Stair Block II of 84 . Tikal Stela 31 explicitly unites the ideologies of rulership with that of warfare (Fig. courtly monarchs‖ (Miller and Martin 2004). For example. the microcosm over which he had dominion (Webster 2000:94). there is a curious absence of weapons in burial contexts. see also Fash 1991. Baudez 1994). for a comparatively brief period during the 7th8th centuries. a bringer of order to the cosmos. This role became so important that even rulers with no recorded war events would be portrayed in full military regalia (ibid. A Late Classic style panel excavated from Temple XVII (Fig.Structure 10L-16 at Copán portrays K‘inich Yax K‘uk‘ Mo as ―a solar war god performing a dance of victory as he rises skyward out of the dark realm of the dead‖ (Fig. the astronomical import of warfare has been overstated by Maya scholars in the past (Miller and Martin 2004). While the cosmological underpinnings of warfare are clear. however. Schele and Freidel 1990. Nahm 1994). 1994. 2. Of their local patron gods. and Stuart and Stuart (2008:115) suggest it may represent the establishment of Lakamha as the ritual and political center of the dynasty. Taube 2004b:290). 2. The iconography of Palenque is not dominated by warfare as it is at other polities.‖ but it appears to be a retrospective history of events that happened some two centuries earlier than the date of the panel itself. his father presents him with the ―drum-major‖ headdress and his mother presents him with a personified eccentric flint and a rather gruesome shield made of a flayed human face (Fig.38). although it is certainly present. Aveni and Hotaling 1994. demonstrates that Maya rulers were not ―automatons programmed to wage war according to a celestial clock‖ (Aldana 2005:318).37) depicts ―a militaristic scene of conquest – a rare theme in Palenque‘s art – with a ruler standing above a kneeling captive. A more careful analysis of the dates connected with these star war events. Lounsbury 1982. The ―star war‖ glyph used to indicate war was overzealously argued to correlate to stations of the planet Venus. claiming major wars were timed to correspond to different points of the Venus cycle (Kelley 1977.36. On the Palace Tablet. 2. the Jaguar God of the Underworld appears to be 85 . Emblems of war were used as sacred regalia for K‘inich K‘an Joy Chitam II‘s accession. 1981. Closs 1978. which depicts K‘inich Kan Bahlam in the act of offering an animated flint ( took’) and shield (pakal) to the Jaguar God of the Underworld. akin to a deity impersonation ritual (Miller and Martin 2004:165). would bring high status captives back to their city where they were paraded around town and publicly humiliated. For example. Maya warriors would also don Tlaloc masks or headdresses into battle to invoke the power of Teotihuacan (ibid. Its warfare associations are most clearly illustrated on the inner tablet of the Temple of the Sun. Martin and Grube 2008:182). but the phrase took’ pakal may also have been a difrasismo denoting the general concept of war (Martin 2001d: 178-179). and subsequently sacrificed. Rulers would be depicted monumentally as literally trampling their victims under their feet. which signified the king‘s victory.40. The ritual aspects of war continued after the battles had ceased.). 2. Took’ and pakal represent specific implements used in warfare (Houston 1983). Monument 155 from Tonina depicts a captive from the city of Anaay Te‘ named Yax Ahk Ajaw (a vassal of K‘inich K‘an Bahlam of Palenque) who was dressed as the Jaguar God of the Underworld in preparation for his sacrifice (Fig. Captives would also be depicted on the tread of stairs (Miller and Martin 2004:168). Warriors would embellish their shields with the visage of the Jaguar God of the Underworld (or that of other gods) so that when it was raised to protect their face they would effectually become that god. such as Tonina. It is possible that the way a captive was killed depended upon which god he was compelled to impersonate. The central icon of the Tablet of the Sun is a ceremonial shield with two crossed spears (Fig. then dressed as gods.39). dressed 86 . Some sites.primarily a solar god but is also strongly associated with fire and with warfare. 2. For example. Yax Ahk Ajaw may have endured immolation as a re-enactment of the mythological episode found on K1299 and K4598 where the Hero Twins set the JGU on fire. Miller and Houston 1987. This is not to say the game 87 . controlled fertility. Freidel et al. suggesting a wide-spread shared belief that divine rulers had access to the gods. Evidence for the ballgame extends back to the Olmec. The Royal Ballgame Numerous depictions of rulers as ballplayers suggest that participation in the ballgame was one of their primary ritual responsibilities (Taladoire 2001:97).41). The ball playing abilities of Late Postclassic Aztec emperors was symbolic of their overall power. 2. San Lorenzo Monument 34 depicts a kneeling ruler wearing a Sun God mirror pendant dressed in ballplayer garb (Fig. warfare and ritual sacrifices ―follow a program ordained by the gods‖ (Miller and Martin 2004:177). but there is no epigraphic evidence and little iconographic support that directly links Classic period ballplayers to the heroes of the Popol Vuh (Tokovinine 2002). and needed to be ballplayers in order to do so (Bradley 2001:36). Through the ballgame rulers were able to bridge the gap between the mythological past and human history. Nearly identical garb is found on figurines from Tlapacoya and Tlatilco. Clearly. ruler of Texcoco. 1993). Schele and Miller 1986:241-264. It has long been held that one of the functions of the ballgame was to reenact the adventures of the Hero Twins in the Popol Vuh (Baudez 1984. and Moctezuma and Nezahualpilli.as the Jaguar God of the Underworld. famously determined the fate of the empire by playing against each other (Taladoire 2001:97). the ballgame was an extremely important function. Tokovinine suggests the ballgame served as a conceptual framework for any story that involved competition. Warfare imagery is also quite common. Ballcourts would have been filled with the sounds of trumpets. and heavy rubber balls bouncing off of masonry walls. Regardless of the specific myths particular rulers were re-enacting.did not have cosmological significance. The great noise may have been likened unto thundering clouds 88 . Tokovinine (2002:6) notes that among the Aztec there are several very distinctive legends that involve the ballgame. a story of Topiltzin and a tlachtli model as written by Ixtlilxochitl (1975: 279). Interestingly. but rather it re-enacted more locally significant mytho-history. Stern 1966:67). the noise is represented by ubiquitous speech scrolls coming off of the walls themselves (ibid. and hunting metaphors are extremely common in ballgame scenes. and that the ballgame in the Popol Vuh is merely the result of the way the K‘iche‘ framed their local myths. as evidenced by the wide range of media on which such events were recorded. all of which would have created quite a racket (Zender 2004b:1-2). such as: a version of Huitzilopochtli myth recorded by Tezozomoc (1878: 227-229). The game may also have had associations with storms. similar to the Popol Vuh. as players wear animals and birds in their headdresses (Miller and Martin 2004:91). the ballgame of Quetzalcoatl versus Tezcatlipoca (when the latter turned into a ―tiger‖) recorded by Mendieta (1870: 82. the ballgame between Huemac and the tlalocs as told in the codex Chimalpopoca (Bierhorst 1992:156). rasps. A common (but not necessarily universal) underlying theme in the ballgame. Iconographically. is the struggle for life over death. the most common deity who is impersonated during the game is actually the hunting god (Tokovinine 2002:6).). 2011) and one of the purposes of the game may have been to summon rainclouds. which depict his deceased forebears Itzamnaaj Bahlam III and Bird Jaguar III (Fig. Panel 7 at Yaxchilán depicts the living king Bird-Jaguar IV playing ball. or warfare. the common underlying theme was that the ballgame was a metaphor of life.‖ Whether or not the ballga me is truly a reenactment of the Popol Vuh. the ballcourt was clearly depicted as a meeting place for the living and the dead. The modern game of ulama that continues to be played in Sinaloa bears many similarities to the ethnohistoric accounts of the Aztec game. and to the left and right of it we see Panels 6 and 8. the largest ballcourt at Chichen Itza (measuring 96. For example. The rules must have differed at various sites due to distinctive court designs. 2. which clearly demonstrates that the ballgame has Otherworld associations (Freidel et al.42). death. (1993:350) state. 1993:358-360) and that any division between the two realms is porous. respectively. As Freidel et al. ―The essence of the metaphor was that life was a game. personal communication. But research into the modern survival of the game and 16th century accounts suggest that the way points were scored varied according to where and when the game was played (Miller and Martin 2004:64). and the gear worn by these modern players as well as the positions they assume while in play strongly resemble ancient monumental and ceramic depictions (Taladoire 2001:100). and regeneration (Miller and Taube 1993:43). Itzamnaaj Bahlam III is depicted sitting in the middle of an Otherworld portal. and that the ultimate stakes were the rebirth of the ancestral dead in the afterlife.(Stephen Houston.5 x 30 m) is six times 89 . Whether or not the ballgame at each site had specific links with the Maize God cycle. hunting. with variations of each type.:103-107) has identified 13 general types.larger than Tikal‘s small ballcourt (16 x 5 m) (Taladiore 2001:100). Uxmal. and many of the smaller Classic period sites lack them (Stephen Houston. Most of the larger archaeological sites throughout Mesoamerica had at least one ballcourt.:97). for example. Interestingly. 300-600) no new ballcourts are constructed in the Maya lowlands (or almost anywhere else throughout the Mesoamerica core area. El Tajin has 18 known ballcourts and Cantona has 24 (Taladoire 2001:98). even those with little signs of sociopolitical complexity (Anderson 2010). Curiously. Taladoire (ibid. Xochicalco and Tenochtitlan appear to be a Postclassic innovation that would have required new methods of scoring than were used in the Classic period (ibid. In the state of Veracruz. such as Teotihuacan in Central Mexico and Bonampak and Tortuguero in the Maya area (ibid. during the Early Classic period (A. only to vigorously 90 . in the Middle Preclassic Yucatán. Although there is a great deal of chronological and geographical variation in the architectural design of the ballcourts. Well over 1500 ballcourts have been discovered by archaeologists in every region of Mesoamerica (ibid. Due to its time-depth and wide geographical dispersion.:98). although there are certainly exceptions. the rings that appear at sites such as Chichen Itza. Beyond just the size of the court. It is significant that all of the areas that were influenced by Teotihuacan turned away from the ballgame during the Early Classic. for that matter) and those that had been constructed earlier began to fall into disuse (Taladoire 2001:109). variation in the ballgame with its associated architecture and regalia is to be expected (Taladoire 2001:99-100). Larger sites sometimes had multiple ballcourts.D. the smallest of sites had ballcourts. personal communication).). The ―ideal type‖ of ballcourt proposed by many archaeologists was oriented along a north-south axis. ―of the five well-mapped sites along the Usumacinta drainage. they ―may belong to the same or different types. After Teotihuacan‘s decline. it is during this construction boom in the Late Classic that we also find marked diversification in ballcourt types (ibid). The vast majority of ballcourts from the lowland Maya area were constructed in the Late Classic period. Tikal reverted back to building typical Maya-style ballcourts. even within sites that have at least two ballcourts. However. a ballgame using sticks called Pelota Tarasca is depicted in the murals of the Tepantitla Palace. the underlying reason was due to a desire to consciously 91 . Scarborough (1991:138) similarly noted. This game has been documented at Tikal as well (Taladoire 2001:112-113). The Entrada of 378 made explicit Teotihuacan‘s influence over Tikal. be similarly oriented.‖ but I propose the opposite.‖ He suggests their ―buffer zone location‖ led to a reduced influence of ―core zone building conventions. three [including Piedras Negras and Yaxchilán] represent the most unconventional court orientations recorded in the southern lowlands. Taladoire‘s (1979) detailed analysis has shown that in practice there is no consistent orientation.). They may be located in the same part of the site or quite apart from one another‖ (Taladoire 2001:114).resurrect the tradition after Teotihuacan declined in AD 600 (ibid. Although Teotihuacan does not have a ballcourt. or oriented at angles to one another. In fact. and there was similarly an explosion in ballcourt construction in the Central Mexican highlands and in the Gulf Coast region (Taladoire 2001:110). there are no identifiable patterns. Importantly. Summary This chapter examined the ruler‘s responsibilities with regards to his people. the ruler performed rituals on behalf of his polity as a whole to propitiate the gods through autosacrifice and conjuring. His sacred or divine status was reinforced in the eyes of the people by his taking the titulary and names of his gods. The ruler oversaw construction projects at his polity. Harrison 2003). Similarly – and as we might expect – Quirigua‘s ballcourt also manifests an ―unconventional orientation. He was viewed as a living axis mundi and an embodiment of time itself.distinguish themselves from their more orthodox neighbors. as demonstrated with the waxing and waning of E-groups. his body effectually comprised the center of both space and time. while maintaining a sense of social cohesion by the very act of constructing a ballcourt (cf. which varied from site to site according to local mythologies. etc). and taludtablero architecture. and the ideal city was laid out according to cosmological principles and was an earthly model of a divine prototype. At times the ―ideal types‖ of architecture shifted depending on who a particular polity was striving to emulate at any given period (Teotihuacan. dancing and impersonation. ballcourts. The ruler was also ritually responsible for his polity as a whole.‖ and I would likewise argue it was done to contrast themselves from their more orthodox rivals at Copán. These polities sought to distinguish themselves from their neighbors through variations in their ballcourts. He brought order to the cosmos through ritual 92 . and even by playing ball. Although the commoners undoubtedly engaged in household rituals. earlier dynastic periods from one‘s own site. and prevented chaos by subduing his enemies in warfare. In the next chapter we will turn to the process of becoming king. and the variations that are found therein. The variation that is found in all of these themes throughout space and time served to create or reinforce a polity‘s identity vis -à-vis neighboring.activity. rival sites. and the rituals and regalia specifically associated with accession. 93 . Drawing by Marc Zender in Zender 2004:505) 94 .Figure 2. (Photo from Miller and Martin 2004:188. Tonina Monument 183.1. Seating of an individual into the office of Ajk’uhuun. Figure 2. The text reads Ho’…lnal ajaw Ukit Kan Le’k Tok’ ―(At) Ho…nal [Five…Flower] there is the king Ukit Kan Le‘k Tok‘‖.2. (Drawing by Alfonso Lacadena. Ek Balam‘s ruler Ukit Kan Le‘k Tok‘ deified as the Maize God while seated upon glyphs denoting Five Flower Mountain. Ek Balam Capstone 15. 95 . in Lacadena et al. 2003:II-26). Figure 2. the type-site for E-group Commemorative Astronomical Complexes.3. (From Chase and Chase 1995:90 Figure 56) 96 . Group E at Uaxactun. in Grube.Figure 2. Lacedena and Martin 2003:13 Figure 12) 97 . (Drawings by Simon Martin.4. Directional Kaloomte’ titles. 5.F Figure 2. Piedras Negras Ruler 4 commemorating his k’atun anniversary accompanied by sajals and other high-ranking nobles. (Drawing by John Montgomery 1989. (Drawing by John Montgomery 1989.5. Piedras Negras Ruler 4 commemorating his k’atun anniversary accompanied by sajals and other high-ranking nobles. Courtesy of FAMSI) 98 . Courtesy of FAMSI) Figure 2. 1) 99 . in Schele 1990:10 Fig. Altar Q from Copan.6.Figure 2. (Drawing by Instituto Hondoreño de Antropología e Historia. Temple 11 Bench from Copan. gods. (Drawing by Linda Schele. displaying rulers.7.Figure 2. ancestors and foreign dignitaries sitting upon identifying glyphs. courtesy of FAMSI) 100 . Figure 2. A long-dead K‘inich Janaab Pakal passes a personified bloodletter to his grandson K‘inich Ahkal Mo‘ Nahb.8. Temple XXI platform face. in Stuart and Stuart 2008:228-229) 101 . (Drawing by David Stuart. The elements of K‘ahk‘ Tiliw Chan Chaak‘s headdress are used to spell his name.Figure 2.9. Naranjo Stela 22 (drawing from Martin and Grube 2008:77) 102 . kooj. drawings by Proskouriakoff in Grube et al. ―Puma‖ (photo in Martin and Grube 2008:145. Jadeite portrait found in the cenote of Chichen Itza that iconographically references the pre-regnal name of K‘inich Yo‘nal Ahk II. 2003:6) 103 .Figure 2.10. 11. 104 . (Drawing in Graham and Mathews 1999 Fig. A captive K‘an Joy Chitam of Palenque is stripped of his exalted K’inich and K’uhul Ajaw titles. Tonina Monument 122. 6:153).Figure 2. a. 105 . with T -shaped incisors (from Joyce 1914: Figure 72). Figure 2. K‘inich Ajaw.12. b. (b) Examples of dental modification mimicking the K‘inich Ajaw‘s T -shaped incisors (Figures from Williams and White 2006:140-141 Figures 1 and 2. modified from Romero Molina 1986:11). (a) The Maya Sun God. (b) Variants on the ajaw title. (c). Figure 2. Royal titulary. Variants on the sajal title.13. (Drawings from Coe and Van Stone 2001:69-77) 106 .a. c. (d) An idealized k’uhul prefix to an Emblem Glyph. d. (a) Variants on the K’inich title. b. Figure 2. Figure 1b. Supernatural portrait.14. after James Porter 1996:Figure 8) 107 . (Drawing by Karl Taube 2005:24. La Venta Monument 25/26. Figure 2. (Drawing by James Porter. Formative Period ruler surrounded by supernaturals. in Taube 2004c:14 Fig. La Venta Stela 2.15. 5) 108 . # Tikal 69-5-55. Coe. Jasaw Chan K‘awiil‘s Stela 16 initiated a new iconographic program at Tikal (drawing by William R. in Harrison 1999:138 Figure 79) 109 .Figure 2. University of Pennsylvania Museum. Neg.16. Figure 2. (Drawing by William R. in Harrison 1999:168 Fig. 101) 110 . Coe.17. # Tikal 69-5-59. University of Pennsylvania Museum Neg. Yax Nuun Ahiin II‘s Stela 22 mimicked the template set by Jasaw Chan K‘awiil. Figure 2.18. (Drawing by Matthew Looper 2003:41 Figure 1. 111 . Quirigua Monument 26 mimicking Uaxactun Stela 20.6). Uaxactun Stela 20 may have influenced the iconographic conventions of Quirigua Monument 26. (Drawing by Ian Graham 1986:181 Fig. 5:181) 112 .Figure 2.19. a. Figure 2. (b) Back: First contemporaneously recorded accession at Tikal (Yax Nuun Ahiin I on 8. (Drawings by John Montgomery. courtesy of FAMSI) 113 .2. (a) Front: Iconographic precursor to Uaxactun Stela 20 and Monument 26 from Quirigua (among others).16. Tikal Stela 4.17.20. b.17). 21.Figure 2. (Drawing by John Montgomery. La Pasadita Lintel 2. Scattering ritual performed by Bird Jaguar IV of Yaxchilán (left) accompanied by Tiloom. courtesy of FAMSI). 114 . ruler of the subsidiary site of Pasadita. 3:39. wahy of K‘awiil) is summoned forth by the burning of bark paper soaked with the sacrificial blood of Lady Wak Tuun (wife or consort of Bird Jaguar IV). courtesy of CMHI) 115 .22.Figure 2. A supernatural (the Waterlily Sepent. (Drawing by Ian Graham 1977 Fig. Yaxchilán Lintel 15. 23. Preclassic sacrificial bloodletting from the penis. in Taube et al 2010:10 Figure 7) 116 . San Bartolo West Wall.Figure 2. (Drawing by Heather Hurst. 24. Fig. Personified bloodletter.1. courtesy of FAMSI) 117 . IV. (Drawing by Linda Schele in Schele and Miller 1986:176.Figure 2. 25. San Martin Pajapan Monument 1.Figure 2. (Drawing by Elizabeth Wahle. Middle Formative ruler from the Veracruz region preparing to raise the World Tree. in Karl Taube 2004c:108 Figure 49) 118 . Figure 2. courtesy of FAMSI) 119 .26. Detail of the uh te. (Drawing by Linda Schele. ―Shiny (or Jade) Jewel Tree‖ from Pakal‘s Sarcophagus in Temple of the Inscriptions. (Drawings by John Montgomery. T516.Figure 2. Variants of the ―dance‖ glyph.27. courtesy of FAMSI) 120 . (Drawing by Heather Hurst. San Bartolo West Wall.Figure 2. The Maize God dancing out of the turtle earth.28. in Taube et al 2010:11 Figure 7) 121 . Figure 2.29. 122 . dating to AD 653. courtesy of FAMSI). Quirigua Altar L (after drawing by Linda Schele. The earliest epigraphic reference to dance. 30. A ruler being presented with a mask in preparation for an impersonation ritual. 123 . (Photo by Justin Kerr.Figure 2. K2695). depicted using the ―X-ray‖ iconographic convention to indicate the identities of the participants.31. K2795) 124 . (Photo by Justin Kerr. Nobles engaged in an impersonation ritual.Figure 2. 32. Examples of truncated Long Count and reversed Calendar Round.5) 125 . (drawing by Linda Schele in 1990:26 Figure 17a) (b) Quirigua Stela U (drawing by Matthew Looper 2003:40 Figure 1.a b Figure 2. (a) Copan Stela 16. a b c.4). (c) Piedras Negras Altar 1 (drawing by Looper 2003:14 Figure 1. 126 . Figure 2. C7 (drawing by Looper 2003:14 Figure 1. (a) Quirigua Stela C (drawing by Looper 2003:12 Figure 1. d. The First Three Stone Place. (d) Dos Pilas Panel 18 (drawing by Stephen Houston.11) (b) Palenque.14). Temple of the Cross.14). in Carrasco 2005:310 Figure 5. main panel.33. (Drawing by David Stuart 2005) 127 .34. The Temple XIX platform at Palenque.Figure 2. Figure 2. Detail from Tikal Stela 31. Central Mexican-style war regalia. (Drawing by John Montgomery. courtesy of FAMSI).35. 128 . K‘inich Yax K‘uk‘ Mo‘ as the Sun God.36.13) 129 . (Drawing by Karl Taube. in 2004:287 Figure 13. Stair Block II of Structure 10L -16 at Copan.Figure 2. courtesy of FAMSI). Rare militaristic scene from Palenque depicting a victorious K‘inich Kan Bahlam. Temple XVII tablet.Figure 2. (Drawing by Linda Schele.37. 130 . 38. courtesy of FAMSI). 131 . Palenque. Palace Tablet. (Drawing by Linda Schele.Figure 2. K‘inich K‘an Joy Chitam II‘s being presented with emblems of war as part of his accession regalia. courtesy of FAMSI). (Drawing by Linda Schele.39. 132 .Figure 2. K‘inich Kan Bahlam offers emblems of war to GIII. Palenque. Temple of the Sun. Ruler of Anaayte. courtesy of CMHI) 133 .40. Yax Ahk (―Green Turtle‖). (Drawing by Lucia Henderson 2006 Figure 9:89.Figure 2. taken captive and dressed as JGU in preparation for sacrifice. San Lorenzo Monument 34. 134 . Olmec ruler in ballplayer garb.Figure 2. (Drawing by Coe and Diehl 1980:342 Figure 466).41. Bird Jaguar IV (b) plays ball flanked by his deceased predecessors (a) Itzamnaaj Bahlam III and (c) Bird Jaguar III.42. 135 .Figure 2. (Drawing by Linda Schele in Freidel et al 1993:360 Figure 8:16). although evidence from Palenque suggests certain childhood rituals may have imbued young princes with a measure of divinity years prior to 136 . But no matter the number of rituals performed or accomplishments amassed. Accession was the focal point of a ruler‘s life (Eberl and Graña -Behrens 2004:104) and would be celebrated on calendrically significant anniversaries with dance (Looper 2009) and other rituals. or ot her accoutrements of power. including the erection of commemorative stela every five years (Le Fort 1994:37).). beginning with heir designation in childhood and culminating in coronation at an average age of thirty one and a half years old (Le Fort 1994:35).Chapter 3 The Passing of Rulership Among the Classic Maya As with previous chapters. Miller and Martin 2004:26). only accession to the throne fully elevated a noble to the status of divine ruler (Eberl and Graña-Behrens 2004:104). who had performed the necessary pre-inaugural rituals (ibid. The heir should have been designated from his childhood as a baah ch’ok. ‗head youth‘ (Martin and Grube 2008:14. Kingship. The ideal transfer of power was from father to first-born son. had been placed into office soon after his father‘s death (Fitzsimmons 2002:387). we must begin with a discussion of ―ideal types‖ when it comes to the passing of rulership among the Classic Maya. the K‘awiil scepter. was anticipated and prepared for from youth. had proved himself worthy as a leader and protector through successful warfare and captive taking. an heir born of the king‘s principal wife—one from a prominent lineage (Fox and Justeson 1986:28-29). ideally. It was a gradual progression. and had received the headband of rulership. and post-accession burial of his predecessor which essentially completes the process. Tikal. such as Palenque. were ideal. and the question arises as to whether such variations represent temporal and spatial variation or whether these divergent data form something of a sequence that can be reconstructed into a pan-Maya ―ideal type‖ that was a part of a shared ideological and ritual program 137 . Designation and preparation. and Naranjo. his pre -accession rituals.enthronement. the pre-accession and accession rituals. We will synthesize the baseline similarities across the Maya area while examining the function of variations that occur within and between specific geographic regions. We will also discuss the burial and deification of an incoming ruler‘s predecessor as an aspect of the accession process. and the ritual regalia associated with the accession process. Enthronement rituals could even take one who was unknown. Piedras Negras. unprepared and without designation and elevate him to the status of k’uhul ajaw. then. we follow the process of legitimization that begins from the time of a ruler‘s heir designation in youth. Stages of Accession There is a variety of rituals and royal regalia that are associated with accession. but not mandatory. In essence. accession rituals. this ideal was frequently departed from. As we shall see. In this chapter we will survey what is known about succession from some of the regional capitals. Copan. We will begin with a general overview of the pattern of succession. Eberl and Graña-Behrens 2004:102. Announcement of one‘s having been appointed to some office (Bardsley 1996:4) 4.employed by the Classic Maya themselves (Le Fort 2001:20-21). Accompanied or overseen by parents (either seated next to ruler or in the skyband). Synthesizing the various models yields the following sequence: 1. the transformation of humans into kings had been formalized into a precise ritual consisting of several stages that seems to have been used at most sites. but none of them quite agree on all of the elements (Bardsley 1996:4. Heir designation as a youth 2. Enthronement. Different sites and their rulers chose to emphasize different points in this ritual sequence. Several scholars have attempted to outline the accession sequence among the Classic Maya. or gods (Schele and Grube 1994:109) 138 . other nobles (Schele and Miller 1986:111-112). Schele and Miller 1986:112). Martin and Grube 2008:14. Schele and Miller (1986:109) argued that By the early Classic period. the seating of the heir on a jaguar skin cushion (Martin and Grube 2008:14) 5. Performance of pre-accession or youth rituals 3. Le Fort (2000:17) argues that the specific sequence of accession rituals used by the Classic Maya were essential rites of passage (see also van Gennep 1960) in which symbolic death and rebirth were manifested through the ritualized retreat and reinstatement of the king. Captive sacrifice (Schele and Miller 1986:110) 9. Martin and Grube 2008:14) 8. Commissioning of some marker of the ceremony (Bardsley 1996:4) 11. Adornment with some regionally accepted symbol of authority (Bardsley 1996:4) a. Although there is undeniably a great deal of overlap in many of the accession rituals at various Classic period polities. The question arises as to whether this is due to an incomplete data set or whether there was in fact a fixed. they represent an idealized sequence. Tying on of the Sak Hu’n/Jester God Headband (Schele and Miller 1986:111) b. Autosacrifice (Schele and Miller 1986:110) 10. and rarely do we find evidence that any particular ruler fulfilled all of the above requirements. I argue that the overlapping 139 . Receiving a new name. Receiving a mosaic helmet of jade and shell with quetzal plumes (Schele and Miller 1986:112) c. Taking of the K‘awiil scepter (Martin and Grube 2008:14) d. Dedication and setting up of that marker (Bardsley 1996:4) While all of the elements above are certainly common. pan-Maya ritual sequence that was rigidly followed across the lowlands.6. I reject the hypothesis that a formalized ―precise ritual‖ (Schele and Miller 1986:109) existed across the Maya area. typically theophoric and that of a predecessor and/or grandparent (Colas 2003b. Holding the Double-headed Serpent Bar (Schele and Miller 1986:110) 7. Although these macro-rites revolved around a single individual. accessions ―are specific events with specific actions having its own rules and which took place at special times and in specific locations. and his formal public ceremonies reinforced the unique local identity of that society. receiving the headband of rule. we must question whether or not the ritual was even performed and the implications that that might have in the creation of local identity. and so forth. As Eberl and Graña-Behrens (2004:105) state. (Harrison 2003:354) We must. they must resemble each other in some way. one has to ensure the existence of the background similarities against which the differences can appear. As Harrison explains. In this respect. that individual was representative of the society as a whole. . . therefore. as are statements of seating. David Stuart (1995:206) acknowledged the similarities in accession formulae but also emphasized that the subtle differences can be significant: Despite the overall heterogeneity of themes and genres characteristic of Maya inscriptions. taking office. Yet despite the almost monotonous repetitions of events and 140 . employing the same titles and iconographic conventions. and can exist only against a background of resemblance. and rather than questioning whether or not a certain ritual was ―emphasized‖ at a particular site. To create diversity. Bergesen (1998:63) argued that accession to the throne is a macro-rite oriented to the society as a whole. differences always presuppose similarities. it is true that rulership is expressed in much the same way from site to site.‖ all of which were unique to each polity. sharing some dimension on which they can be contrasted and compared. in order for ethnic groups or any other entities to differ. Ahaw glyphs are identical. .elements merely provided a common base from which the unique variations could create group identity within each site while simultaneously contrasting themselves with their neighboring polities. examine the specific epigraphic and iconographic evidence relating to accession rituals from specific sites. The question then becomes one of addressing the specific differences concerning accession rituals that are found at different Classic Maya sites. Rather than invent an exact accession sequence for each major polity—an impossible task with the surviving data—I will instead examine the anomalies. or even create entirely new and innovative accession templates that would shape future generations. However. the outliers that seem to break away from the pan-Maya ―ideal type‖ that scholars have cobbled together. or they could appropriate portions of anot her site‘s template while modifying it for their own purposes. which in turn served to reinforce the unique group identity. Rulers could modify the templates at their own sites (especially useful when following on the heels of an unsuccessful predecessor). each site had its own variation on the inaugural theme and that these variations served to form a unique ―accession template‖ for that site. which literally translates as ‗youthship‘ but in specific contexts it designates ‗princeship.titles associated with rule. it seems clear each polity intentionally emphasized or ignored certain rituals or regalia to the point that it set them apart from their peers. The Royal Succession A royal successor was typically designated in very early childhood and seated in ch’oklel. these templates were not static.‘ At Palenque. Instead of adhering to a formal sequence. there exist some differences which may reflect important distinctions in political organizations or hierarchies. Rather than a precise ritual sequence. K‘an Joy Chitam I was just six years old when he received his ch’ok title and became the designated heir to the throne of Ahkal Mo‘ Nahb I (Martin 141 . These sons did in fact all accede to the throne. and Tiwol Chan Mat. four years before Pakal‘s death. apparently because K‘inich Kan Bahlam II had no sons. We are given the pre-accession names of K‘inich Janaab Pakal‘s three sons. the ch’ok title is helpful in tracking the evolving status of rulers from childhood through adulthood. 21 Although it was not an ideal order of succession. A clear example of the distinction between these titles comes from Palenque.and Grube 2008:158). on a stucco sculpture from Temple XVIII (Fig. it was not uncommon for the throne to pass from brother to brother rather than from father to son. 20 The Tablet of the Cross informs us that a preaccession rite for K‘an Joy Chitam I took place at Tok Tahn on 9.3. Ideally.0. 142 . K‘inich K‘an Joy Chitam II finally transitioned from baah ch’ok to k’uhul ajaw as a 57-year-old man. This public declaration of succession order was likely necessary since Pakal himself had acceded under questionable circumstances. ―You are satisfied (that) you put them in succession‖ (Stuart and Stuart 2008:162). 20 The ch’ok title itself does not necessarily imply either youth or heir apparency.12.1. but rather indicates heir potentiality. 3. whereas the b’aah ch’ok title seems to have been reserved for the principal heir (Houston and Stuart 1998:79).0 5 Ajaw 4 K‘ayab (26 January 679).12. ―(they) are arranged in order‖ and tihmaj awohl atz’akbuij.6. 12 Ahau 8 Ceh (Guenter 2007:9). K‘inich K‘an Joy Chitam. In such instances.1) dated 9. and the inscription states tz’akbuaj.15. The best evidence for this comes from Palenque. the order of succession would have been laid out by a ruler prior to his death to lessen the potential for a contested throne after his passing.21 Eighteen years later. when the 40-yearold K‘inich K‘an Joy Chitam II was elevated from a mere ch’ok to baah ch’ok on the same day his brother K‘inich Kan Bahlam II acceded to the throne. K‘inich Kan Bahlam. The mythological texts of Palenque inform us that Muwaan Mat —the ―Triad Progenitor‖—engaged in a ―deer hoof‖ ceremony when he was an eight year old child (Stuart 2005:172). typically years before their accession (Lounsbury 1980.Pre-Accession Rituals An important part of the gradual progression towards rulership was ritual performance. K‘inich Ahkal Mo‘ Naab engaged in this ritual when he was a ch’ok of 14 years old (Eberl and Graña-Behrens 2004:110). The evidence for childhood rituals is somewhat scant. and bloodletting seems to have been one of the rites. then known by his childhood name of Ux Ch‘ak Kab‘an Mat Ch‘ok (Carrasco 2005:452). Rather than falling into the trap of over-generalization. accession. followed later by ritual bloodletting. they typically assumed adult costume and pose (Joyce 2000:128). Palenque One of the best attested—yet still poorly understood—pre-accession rituals at Palenque is the k’al may ―deer hoof binding‖ event. This youth ritual was performed by ch’oktaak (youths). I will discuss specific pre-accession rituals known from particular sites. and ultimately 143 . He also appears to have performed his first bloodletting ritual at about this same time (Guenter 2003:8). Stuart 2000c:5) and may have constituted some sort of training for designated heirs (Eberl and Graña-Behrens 2004:110). and the only generalizations that can be accurately made is that they were performed by boys who were between six and fourteen years of age. K‘inich K‘an Joy Chitam performed a similar ritual when he was about seven years old (Stuart 2000c:5). Spencer 2007:94).the erection of a building. but the polydactyl foot is never otherwise associate d with him as it is with Kan Bahlam II 24 Schele and Mathews (1998:99) identified the ancestor as K‘uk‘ Bahlam I based on an inaccurate rendering of his headdress. his forehead penetrated by the emblematic K‘awiil axe and his left leg transformed into a serpent. Pier B (Fig. depicts a six-year-old Kan Bahlam II as the god Unen K‘awiil. which indicates a supernatural setting (Schele and Mathews 1998:99). 3. otherwise known as GII of the Palenque triad (Robertson 1983:37. 23 He is cradled in the arms of his illustrious forebear K‘an Joy Chi tam (who had been deceased for well over a century by that time) and they are framed by a skyband that emanates from a personified sacrificial bowl. Schele and Freidel 1990:236. and therefore Palenque‘s mythology appears to have created a ―cosmological precedent for the transformation from childhood to adult status‖ (Joyce 2000:124)—their earthly kingdom becoming a microcosmic reflection of their localized conception of the divine cosmos. The piers from the Temple of the Inscriptions provide intriguing evidence that the rulers of Palenque did not have to wait until the day of their accession to have some measure of divinity bestowed upon them.2). but David Stuart‘s examination of Maudslay‘s 1890 photographs revealed the headdress represents a peccary head with an infixed k’an cross in the eye (Stuart 2007). 144 . As Schele and Mathews (1998:99) state. ―he is both the child heir (the ba ch’ok.24 This was no mere impersonation event by the child. or 22 Loundsbury (1980) and Schele and Freidel (1990:246) interpret this event as the implied birth of GI. but similarly attributed the event to GI rather than to Muwaan Mat (Carrasco 2005:452). he is cradled like Unen K‘awiil.22 All of these actions were those expected of human rulers at Palenque. 23 Stanley Guenter (2007:5) makes a strong case that the baby is actually K‘inich Janaab Pakal reborn as Unen K‘awiil. Joyce (2000) recognized it as a childhood ritual. but rather it began to be infused into them at least as early as their heir-designation ceremonies. for example. his right leg displaying Kan Bahlam‘s characteristic six -toed foot. ―first sprout.The entire suite of heir designation ceremonies was clearly localized in the way it was carried out.3) and D by either his parents or grandparents (Stuart 2007). Stuart has suggested that the dates on which they fell were related to stations of the k‘atun and were calendrically significant. and the Hieroglyphic Jambs of Temple XVIII record one of his pre-accession events when he was fifteen years of age (Stuart 2000c:5). They are all kneeling in seeming submission to a ruler and his heir (exactly which ruler and which heir is still 145 . While all of these youth rituals are poorly understood. As a young man. Fig.‖ of the lineage) and the embodiment of the divinity personified in K‘awiil. K‘inich K‘an Joy Chitam was involved in a little understood ―cord taking‖ rite (Stuart 2000c:5). Piedras Negras Piedras Negras Panel 2 (AD 667.4) may depict a pre-accession ritual related to warfare.‖ Kan Bahlam II is also presented to the public on Pier E by Kan Bahlam I and on Piers C (Fig. all of whom were deceased. Deified ancestors from their own dynasty presented K‘an Balam II as if he were a god of their local triad. all of whom Schele and Miller (1986:149) estimate to be about twelve years old. 3. He further suggests the braided cloth and ribbons that youths wore were part of pre-accession ritual attire (Stuart 2000c:5. four from Lacanha and one each from Yaxchilán and Bonampak (Martin and Grube 2008:144). The Temple XIX stucco panel records the forty-year anniversary of a pre-accession ritual performed by K‘inich Ahkal Mo‘ Nahb. It depicts a number of youthful ajawtaak (―lords‖). 3. Stuart and Stuart 2008:197). the Early Classic ruler of Piedras Negras. were directly linked to Teotihuacan.141). The events recorded on Panel 2. 2002). Caracol. and Turtle Tooth‘s right to rule. The pre-accession rituals from Piedras Negras and Palenque were clearly different.25 What is clear is that the monument commemorates Ruler 2‘s taking of the Teotihuacan-style war helmet called ko’haw. in re enacting the event. Naranjo. 2009:147). the obscure Waxak Banak Hun Banak (8 Banak 1 Banak). Turtle Tooth‘s reception of the ko’haw – the Teotihuacanoid war helmet – was overseen by a foreigner named Tahoom Uk‘ab Tuun who bore the ochk’in kaloomté’ title (ibid. likewise ties himself to Teotihuacan. A wooden box discovered in Tabasco directly states Tajoom Uk‘ab‘ Tuun was a Teotihuacan lord and successor to Siyaj K‘ahk‘ (Anaya Hernandez et al. Tikal. Ruler 2. Yaxha‘ Chaak (the Maya god of lightning). which the text further explains was a re-enactment of the same ritual performed by Turtle Tooth in 510 (Martin and Grube 2008:144). The re-enacted event was overseen by three gods which had been conjured by Ruler 2 to witness the event. Ruler 25 Martin and Grube (2008:144) suggest it may be a retrospective depiction of Turtle Tooth. yet both re-enacted events significant to their local dynasties (whether mythological. historical. or some combination of the two) and in connection with their local gods.. 146 . and Palenque all had triadic groupings of gods that were unique to each of their polities (Stuart 2005:160).subject to debate). the famous warlord who brought down Tikal‘s dynasty and reestablished it according to Spearthrower Owl‘s designs. the combination of them along with Waxak Banak Hun Banak constituted a triad unique to Piedras Negras. and the Jaguar God of the Underworld (Fitzsimmons 1998:273. Although Chaak and the JGU were pan-Maya deities. Significantly. Lady Ik‘ Skull. Fitzsimmons 2002:383. There is no mention of either Bird Jaguar IV or his mother in any texts dating to the reign of Itzamnaaj Bahlam III (Bardsley 1994:1). they also legitimized the ruler‘s right to rule. He paints a vivid picture of the innovative methods used to legitimize the rule of one who was not designated as an heir in his youth and had little to recommend him as the rightful successor before his accession to the throne (Bardsley 1994. Beyond creation of identity. 147 . Yaxchilan We can look to Bird Jaguar IV of Yaxchilán as an example of one who definitively breaks from the ideal type of heir apparent.2 from Piedras Negras sought to legitimize his ritual performance by juxtaposing it iconographically and epigraphically with those performed by Turtle Tooth under the eye of the Teotihuacan empowered ochk’in kaloomté. Bird Jaguar IV was the son of an elderly Itzamnaaj Bahlam III and one of his obscure lesser queens. and there is a ten-year interregnum between the death of Itzamnaaj Bahlam III and Bird Jaguar IV‘s accession. whereas Palenque‘s youth were reenacting the rituals that were performed by Muwaan Mat in mythological time —a mythology unique to Palenque. an identity that would only become more ingrained as they progressed towards the throne. Martin and Grube 2008:129). they stood as evidence that the rulers h ad many years worth of experience under their belts when it came to interacting with and sacrificing to their gods (Stuart and Stuart 2008:195). In essence. These early rituals were influential in creating a local identity for these future rulers. Yuknoom Yich‘aak K‘ahk of Calakmul appears to have undergone some pre -accession 26 The retrospective history contained on Panel 3 from Piedras Negras provides limited but intriguing evidence that an individual named Yopaat Bahlam II ruled at Yaxchilan during part or all of the ―interregnum‖ between Itzamnaaj Bahlam III and Shield Jaguar IV (Martin and Grube 2008:127). which depicts Bird Jaguar engaging in a flapstaff dance with his father and dates the event to 741. but the event is not depicted iconographically (Bardsley 1994:4).:8). The most explicit of these comes from the river side of Stela 11 (Figure 3. B‘ajlaj Chan K‘awiil‘s pre-accession rituals are recorded on the central portion of Hieroglyphic Stairway 2 (Guenter 2003:3). therefore. B‘ajlaj Chan K‘awiil engaged in a ―flat-hand‖ event. Bird Jaguar‘s accession is mentioned three times in the hieroglyphic inscription on the stela. a year before his father‘s death. According to the accompanying inscription. The iconography itself is an innovative break from Yaxchilán‘s typical program. likely a first bloodletting ritual. the flapstaff ritual represents both a pre-accession heir designation ceremony during his father‘s life and a much later period -ending rite performed on behalf of his now-deceased father. and each of its two scenes pulls double-duty. 148 . commissioned retrospective monuments containing revisionist histories that depict him engaged in pre-inaugural rituals with his father—events that likely never happened.26 Bird Jaguar.suggesting a contested throne.5). Curiously. Other Known Childhood Rituals At Dos Pilas. when he was nine years old (ibid. The iconography on the temple side of the stela represents both a pre-inaugural military conquest attributed to Bird Jaguar IV as well as his own forthcoming inauguration (Bardsley 1994:4). intriguingly. 2003. and even within a single site there are vast differences at various periods in their history. ranging from under two months to over four years. Caracol stands unique in that the ruler K‘ahk‘ Ujol K‘inich II apparently acceded to the throne 29 days before his father K‘an II had died (Fitzsimmons 2002. see Guenter 2002. Martin and Grube 2008:94). Somewhat surprisingly. but there appears to be no standardized pan-Maya timeframe between the death of one ruler and the accession of the next (Fitzsimmons 2002).rituals at Yaxa’ (likely Yaxha’). Copan is unusual for its efficiency and regularity. the throne always passes between two to five weeks after the death of the ruler (Fitzsimmons 2002:388). 149 . Exceptionally long interregna are typically attributed to periods of political unrest. they rarely receive any mention in the inscriptions and they governed only until the 27 For the potential political implications of this event. The time between a ruler‘s death and his heir‘s succession appears to have been something of a liminal period in Classic Maya polities. Although there were regents who oversaw the affairs of the kingdom during these periods. was witnessed by Nuun U Jol Chaahk and B‘ahlaj Chan K‘awiil of Tikal (ibid. Palenque—which has at times been abused by Mayanists as an ―ideal type‖ for all things Classic Maya (Houston and Stuart 1996:302)—indicates wild variations in the duration of interregna. which. with no clear pattern ever emerging. they did not carry the title k’uhul ajaw. 27 Interregna The period between a ruler‘s death and the accession of an heir varies widely from site to site.:19). In addition. was used in analogous contexts to the T684. In the inscriptions at Yaxchilán and Copan Proskouriakoff (1960:470) recognized that the ―seating‖ verb. the headband-tying expression. as an inaugural statement. They also identified the T713/757 compound.6) are curiously infrequent as the main subject of either the epigraphic record or the accompanying iconography on monumental texts (Le Fort 1994:37). accession statements (Figure 3. although it is not exclusive to enthronement 28 ―Seating‖ as an expression of inauguration continued into the Late Post -classic among the Acalan Chontal (Smailus 1975:32) and among Yucatec speakers. Stuart).designated heir was elevated to the throne. namely T684. T670 (ch’am. which we now read as hoy/joy (Martin and Grube 2000:231. Accession Phrases Despite the paramount importance of inauguration to a ruler‘s legitimacy and frequent references to it throughout his lifetime. T644 (now read chum). As Fitzsimmons (2002:391) argues. ―the institution of k’uhul ajaw was temporarily frozen following the burial of the dead king‖ until the time that the new heir acceded. ―to receive‖) is sometimes used to denote accession. nicknamed the ―Toothache‖ glyph by Thompson because of the knot tied around the head. 150 . citing personal communication from D. however. argued that T644 chum was interchangeable with other accession expressions. as found in the Book of Chilam Balam of Chumayel (Roys 1933). Tatiana Proskouriakoff (1960) was the first to identify an inaugural statement in the glyphs of Piedras Negras. but suggested that a different observance was taking place on those dates rather than being synonymous expressions. 28 Mathews and Schele (1974). Poor preservation and unrecovered or unrecoverable texts prevent us from knowing with certainty if the variation in usage represents actual ancient rhetoric or is merely a product of modern sampling limitations (Stephen Houston. In discussing local variation in the selective employment of accession verbs in the ancient inscriptions. the challenge facing epigraphers is a compromised data set. It is still not entirely clear if the differing terms referred only to specific moments of the enthronement ritual or if they could all be used to denote accession in general. personal communication 2008). The statements explicitly referring to the accoutrements that the ruler received include ch’am/k’am k’awiil ―to take or receive the K‘awiil scepter‖ or k’al u sak hu’unal tu b’ah ―to wrap the white headband around oneself‖ (ibid. The statements that refer to the office itself include chumlaaj ti/ta ajawlel ―to sit down in rulership‖ and joy?-aj ti/ta ajawlel ―to be ‗encircled‘ in rulership‖ (‗encircling‘ may make reference to the headband being wrapped around the head). accession phrases fall into two categories. a sufficient number of accession statements have survived from major sites across the Maya area that some broad observations can profitably be made.ceremonies (Le Fort 1994:19). Excavations at some sites have unearthed an abundant glyphic and iconographic corpus whereas others have produced a dearth. In general. 151 . those that refer to the office itself and those that refer to the accoutrements of power received by the ruler during his accession (Eberl and Graña-Behrens 2004:102). Without claiming statistical precision.). but there is evidence that T684 and T713/757 denote specific moments of the ritual (Le Fort 1994:41). Genevieve Le Fort (1994:23-24) similarly suggests that the different verbs may reflect different portions of the ritual. such as Copan and Yaxchilán. Le Fort (1994:22) found that ―each site. and Eberl and Graña-Behrens (2004:103) note that the same accession may be described by several different phrases found on distinct monuments. For example. for instance. Hok' [joy – T684]. Stuart suggests the variation in verb use may be due to linguistic differences between sites or perhaps there may even be functional differences as to how they were used (Stuart 1995:204). but was virtually unknown at Piedras Negras. rather than each region. and neither of the terms was ever used in the relatively short-lived textual history of Quirigua. employ both verbs. Many other sites.The basic formulae for accession remain essentially the same throughout the Maya area. As Marc Zender (2004:154) notes. . chum may be used to refer generally to accession. in her analysis of the geographical distribution of accession statements. and in very general terms the individual phrases are not specific for one site or one time period (Eberl and Graña-Behrens 2004:103). although if this is the case. However. ―accession statements in Classic Mayan inscriptions have long been known to involve formulae such as chumlaj ti-X-il "he sits in TITLE-ship" or k 'ahlaj huun tub 'aah tiTITLE-il "the headband is bound onto his head in TITLE-ship. made its 152 ." Although there are only a limited number of phrases that were used to designate accession in the ancient texts. in turn. there are some general trends as to how they were used. the distinctions are not yet clear. . whereas the k’al hu’n event may refer to the specific moment of accession where the ruler puts on the headband. never was employed by the scribes of Palenque. As David Stuart (1995:204) notes: ―Seating‖ [T644] was a popular statement of accession in the central Petén sites such as Tikal. Tikal ultimately preferred T644 while Naranjo. but this is not always the case. T644 is the most common accession expression used throughout the Classic period. For example. as suggested by accompanying iconography. the fact that certain verbs are used to the exclusion of 153 . happens to be the exclusive statement used by its downstream rival at Piedras Negras and the predominant statement used at Yaxchilán. the only accession statement that is completely absent at Palenque. much more prominently at Copan. when the T713/757 compound is used.choice concerning the use of the verb. its close rival to the east. the event is typically depicted iconographically as well (Le Fort 1994:31). and it became the exclusive accession statement at Palenque (Le Fort 1994). sites that are near neighbors with frequent interaction – if not conflict – seem to favor different accession verbs. rarely at Copan.‖ However. as T644 began to be used more often at Tikal. Significantly. For example. At times the accession phrases used in the texts make direct reference to what is being portrayed iconographically (Eberl and Graña-Behrens 2004:102). Copan favors T644 and T684 whereas their rival Quirigua preferred to use T670. Although it is still unclear whether these accession verbs represented one phase within a larger ritual sequence or were singular events unto themselves at their respective sites. used T684 and none other. T684. and Le Fort found that ―it appears only in the early texts at Tikal.‖ Berlin (1970) noted that T684 was used predominantly at Piedras Negras and Yaxchilán. In contrast. At the eastern extreme. but it typically serves as background information rather than the main focus of a text. and never at Palenque. through time the preferences seem to have shifted. Although it is unclear what the qualitative difference is between the statuses of hu’n and ajawlel. Stuart and Stuart (2008:144) noted a curious pattern in the glyphic expressions employed to denote accession at Palenque. Despite the wealth of texts we enjoy from Palenque. making it ―difficult to say where myth ends and history begins‖ (Stuart and Stuart 2008:109). what is significant is the fact that a clear distinction is made in the narrative itself.others and seemingly in deliberate contrast to their neighbors strongly suggests that they were seeking to differentiate themselves in effort to create a unique identity vis-á-vis their rivals (Harrison 2003). Palenque was attacked again just a few years later by Chan Muwan of Bonampak in AD 603 (Grube 154 . when attempting to reconstruct their political history we are challenged by the fact that the rulers sought to situate themselves in the larger cosmological framework. It was under Ix Yohl Ik‘nal‘s reign that Palenque was brutally conquered and had their gods ―thrown down‖ by Calakmul in AD 599 (Grube 1996:3). the queen Ix Yohl Ik‘nal. as it comes after the disastrous reign of Ajen Yohl Mat‘s mother. Palenque Palenque gives us a taste of the fluid and localized flavor that accessions could take even within a single polity throughout its history. a word often used to refer to the paper scarf that was tied onto a ruler‘s head upon accession. The historical backdrop adds meaning to this shift. but rather they sat in hu’n (―headband‖). None of the rulers who preceded Ajen Yohl Mat—the ninth known ruler of Palenque—sat in ajawlel (―rulership‖). Fortunately. It was during Muwaan Mat‘s reign that heartbreaking laments were recorded in the Temple of the Incsriptions (Figure 3.1996:3).161). equal parts restoration and re-invention. which elaborately expanded upon earlier prototypes (Stuart and Stuart 2008:168). satay k’uhul ixik. the ritual care and presentation of god effigies was the responsibility of the ruler. was old enough to ascend to the throne (ibid.. Ajen Yohl Mat may have been attempting to create a new accession template to dissociate his reign from that of his mother.7). and Palenque was harshly attacked by Scroll Serpent of Calakmul in 611. But his reign did not fare much better than his mother‘s.‖ ma u nawaaj. and these duties were apparently forsaken by Muwaan Mat due to the troubled times they were in. who may have been a divine regent (Martin and Grube 2000:161) – a metaphorical ―second coming‖ of the Triad Progenitor – or perhaps it was merely a pseudonym for Lady Sak K‘uk‘ who served as regent until her nine-year old son. the future K‘inich Janaab Pakal. As ex officio high priest (Zender 2004). he placed heavy emphasis on his ritual activities. He is unique in that both of his parents appear to have been living witnesses 155 . during K‘inich Janab Pakal‘s long and glorious reign he took it upon himself to give Palenque‘s royal template a dramatic make -over. satay ajaw ―lost is the divine lady. however. His reign was followed by that of the poorly understood ruler Muwaan Mat. In an effort to compensate for the failures of his immediate predecessors and reclaim his kingdom‘s former glory.‖ and ma’ yak’aw ―(s)he did not give [offerings to the gods]‖ (Guenter 2007:21-22). ―he was [or they were] not presented publicly. lost is the lord. Stuart suggests the new use of ajawlel reflected Palenque‘s debut on the larger regional stage and was a move away from their previously insular tendencies. inheritance of a throne or major office occurred after the death of a parent. even the subject – the transmission of power from mother to son – is fresh and adventurous. also displayed a restorationist (or perhaps revisionist) bent. and at least three of his successors were inaugurated on that very throne (Le Fort 2000:20.‖ It is unique not only in the Maya world but also in Palenque itself. he uses the T713/757 k’al sak juun (―the white headband was tied‖) expression to declare the accessions of the purely mythical Muwaan Mat (the Triad Progenitor. Martin and Grube 2008). at F7-F8). a break away from the ―ideal type. a new localized accession template. He hearkens back to deep time in order to associate himself with the mythical founders of Palenque. as far as we know.‖29 In 654 he commissioned the sak nuk naah. the 29 As noted above. carved on an unusually shaped interior panel that itself replicated the jaguar cushion for the ruler‘s back. K‘inich Janaab Pakal I created a new tradition. ―Elsewhere in Maya history.9). The Oval Palace Tablet itself provides an interesting example of variation in both space and time. it was the first intimate. the ‗White Skin? House‘ (House E) which housed the new seat of power and the Oval Palace Tablet (Figure 3. in effect. K‘inich Kan Bahlam II. 156 .to his accession. K‘ahk‘ Ujol K‘inich II at Caracol also appears to be an exception to this rule (Martin and Grube 2008:94). By commissioning this monument. As Stuart and Stuart (2008:149) note. He created. it has the subjects off center. indoor scene of accession. Janab Pakal‘s son. The Oval Palace Tablet at Palenque was completely innovative.8) on which he depicted his own accession to the throne. As Mary Ellen Miller (2004) notes. On the Tablet of the Cross (Figure 3. Interestingly. The parents are depicted as living and active participants. dynastic founders were manufactured entities. 157 . the ruler is depicted iconographically in the act 30 Formerly known as Uk‘ix Kan (or Chan). worthy of emulation. accessions are depicted at Palenque in three separate scenes. K‘inich Janaab Pakal I (Skidmore 2003). and ultimately his own. and Luis Lopes (2005) have argued the stinger or fish spine glyph be read kokan rather than k’ix. Marc Zender (2004). Generally speaking. who are presenting him with the emblems of rulership: the jade plaque helmet and the flint-shield. the semi-mythical ruler who is said to have acceded in 967 BC. ―in large part. and Stuart and Stuart (2008:215) argue that the rulers of Palenque viewed him as ―a proto -typical king.quasi-mythical U Kokan Chan30 (at P1-P2). however. regardless of whether or not they were still alive. At the Temple of the Cross on the inner sanctuary jamb panel (Figure 3. then.10) he dons an antique costume and a headdress bearing the name of U Kokan Chan. the historical dynastic founder K‘uk‘ Bahlam (at Q7-P8). The first scene depicts the simply-dressed acceding ruler flanked by his parents.‖ Curiously.‖ An ―ideal type‖ of accession at Palenque was suggested by Schele and Miller (1986:112). with honors and attributes bestowed upon them long after their deaths…these ancestors supported future dynasts in their claims to supremacy. but Albert Davletshin (2003).11). on both the Oval Palace Tablet (Figure 3.8) and the Palace Tablet (Figure 3. the only rulers to liken themselves to this legendary ruler were K‘inich Kan Bahlam II and his reformationist father. Schele and Mathews (1993:33) suggested U Kokan Chan was an actual historical ruler whose memory had been preserved through legend. As Fitzsimmons (2009:117) states. dynastic ancestors could likewise be invented to legitimize one‘s rule (McAnany 1995). Just as rulers created gods in their own image (Coe 1982:159). There is an orderly patrilineal succession from illustrious royal father to first-born son. where the T684 expression is completely unknown. the deceased but ever potent predecessor serving as guide for the forthcoming ruler (Eberl and Graña-Behrens 2004:103). the father is absent despite the fact that both were alive at the time of his accession. who is clad in a funerary loincloth because his breath had been extinguished about four months prior. Piedras Negras‘ major rival in the lower Usumacinta region (Martin and Grube 2008:143).of receiving these regalia. bloodletter. This stands in marked contrast to Palenque. despite the fact that he was only 12 years old at the time of his accession (although he was 49 when House E was dedicated) and at this point his mother had been dead for 14 years (Stuart and Stuart 2008:157) In the Cross Group. These scenes fit well into an idealized type. Piedras Negras‘ dynastic founder. joy. Furthermore. and K‘awiil scepter from his father K‘inich Janaab‘ Pakal I. headband. but the accompanying glyphs do not mention these as part of the accession phrase. appears to have created this accession template 158 . Piedras Negras stands unique in its regular use of niche stelae to depict enthronement scenes. Also of interest is the fact that the Oval Palace Tablet only portray‘s the ruler‘s mother. K‘inich Janaab Pakal is depicted as an adult. Piedras Negras Accession at Piedras Negras likewise had a decidedly local flavor. K‘inich Yo‘nal Ahk I. K‘inich Kan B‘alam II is shown receiving the flint -shield. The only verb used to denote accession at Piedras Negras was T684. 14. each bordered on the sides and top by a bicephalic skyband upon which is perched the Principle Bird Deity (Bardawil 1976:12). In the Late Postclassic Yucatan. 32 Morley (1920:575-576) was the first to note the similarity between the supernatural accession scenes on Mayapan Stela 1 (then called Stela 9) and those in the Paris Codex.12). for example on Mayapan Stela 1 and on Page 6 of the Paris Codex (Taube 1987:8-9. but Piedras Negras appears to be the only Classic Period polity that fully embraced the tradition. five of his successors emulated his innovative Stela 25 (Figure 3. 2005). and their posture upon the throne mimics the posture of kingly gods who sit upon skybands (Eberl and Graña-Behrens 2004:102). 32 The scaffold accession scene from San Bartolo (Figure 3.13) demonstrates the practice had considerable time depth (Saturno et al. Footnote 4. Significantly. 25. and over the following century and a half. 11. Taube et al. and the ruler is surrounded a sky-band canopy upon which sits the Principal Bird Deity. we see gods themselves engaged in scaffold accession rites strikingly similar to those from San Bartolo and the Dallas incised bone. 2010 Figure 41). 31 On these monuments. 33 The incised bone from the Dallas Museum of Art also depicts a scaffold accession scene.for his polity. 33 The Piedras Negras thrones are typically depicted as the cosmic caiman or Starry-Deer-Alligator topped by a jaguar cushion. 159 . although it is found to a much lesser degree at Naranjo and Quirigua. essentially placing the ruler at the center of the 31 Stelae 6. the scaffold is marked with kab or ‗earth‘ signs. and 33 each depict a different ruler seated within a niche. but unfortunately lacks provenience. and the combination of ‗sky‘ and ‗earth‘ creates an iconographic couplet that forms a difrasismo that designates ‗everywhere‘ or ‗the whole world‘. the rulers are seated on an elevated scaffold that symbolically placed them in the celestial realm. 2010:58). personal communication. the Maize God accession scene on the southern-most scaffold on the West Wall has a strip hanging down from the platform that is marked with a footprint (Taube et al.14) explicitly shows a god seated upon a scaffold receiving the headdress of rulership (Tokovinine and Fialko 2007:6. Taube (1988c) has demonstrated that heart sacrifice in connection with accession upon a scaffold is associated with concepts of agricultural fertility. Fig. serving to create an identity unique to their polity. and the incised bone from the Dallas Museum of Art (Figure 3. Regardless of the specific message they were intended to convey. 160 .34 The iconography explicitly mimics the images of gods seated upon their thrones in the celestial realm (Taube 1988c). Rather than accession. Tedlock 1985:148. Not all scholars agree that the niche stelae were focused on enthroment rituals. for example among the Ch‘orti‘ who use the Spanish loan words mundo/syelo (Hull 2003:80). The scenes from Piedras Negras typically show a sacrificial victim lying at its base. The footprinted cloth iconographic convention and associated ideology can also be traced to San Bartolo. and the king‘s bloody footprints lead up the cloth-draped ladder that grants access to the throne (Martin and Grube 2008:142. and Piedras Negras‘ emphasis on the ―niche‖ convention set them apart from their neighbors. the meta-message is that a unique type of monument was created to commemorate some ideologically important event (be it accession or Period Endings).cosmos (Tokovinine 2008:141). however. 8). 2011). the focus of the niche stelae may instead have been on commemorating Period Endings (Stephen Houston. 34 This couplet continued to be used into the Colonial period among the Quiche caj/ulew (D. Taube 1988c). Christenson 2003) and is still maintained today. 0.5 6 Chikchan 18 K‘ayab (5 February 628).17.9. This accession expression was literally used until the very end of the Copanec dynasty.10.0 4 Ajaw 13 Mol (28 July 667).5. He acceded on 9. Although he acceded on 9. He used the T684 joy expression. as the T644 seating verb is the last known glyph ever inscribed at 161 .17 (2 July 763) and recorded his accession when he dedicated both the Temple 11 NE Panel (D2) and Bench (A2) on 9. who acceded on 9. 9.6.0.19. He seems to have established something of a new accession template at Copan.5.14. both to record their own accessions and to retrospectively commemorate the accessions of their predecessors.0.0.11. Yax Pasaj. The earliest surviving accession date provided by a living ruler to record his own accession comes from Moon Jaguar.0 (24 January 771). we have no record of his accession until nearly forty years later.15.15).12. The next contemporary record comes nearly a century later with K‘ahk‘ Uti‘ Witz‘ K‘awiil.16. They maintained a distinctive architectural and monumental style throughout their history. which would be used by all subsequent rulers.3. which is only used in a contemporary context by one later ruler.0 8 Ajaw 3 Mak (24 May 553) and recorded his accession several months later on Stela 9 (F3) (Figure 3.0.17. There are no known contemporary accession statements from the first centuries of Copan‘s dynastic rulers. He used the T644 ―seating‖ verb.Copan Copan lies at the eastern fringe of the Maya area. and its Late and Terminal Preclassic foundations reflect the local cultural traditions of the Southeastern Maya rather than those of the Peten. which seems to have had little influence there (Sharer et al. 2005:149). a monument commemorating the period ending 9. Although early contemporary accession statements are few at Copan.5 (10 February 822).13.16. Copan stands out for the devotion it pays to its dynastic founder.18. and he further identified Yax K‘uk‘ Mo‘ as the founder.0 6 Ajaw 13 Tzek.16). K‘inich Yax K‘uk Mo.19.4. dedicated about 350 years after the fact.‖ Quirigua The only clear references to the accession of a ruler from Quirigua during the first three centuries of its existence come from retrospective monuments at both Quirigua and Copan. and the four sides celebrate the unbroken chain of fifteen rulers that succeeded him. Quirigua‘s first ruler.17. 162 .‘ one gets the clear impression that K'inich Yax K'uk' Mo' served as a social and political role model for the position. found on the unfinished Altar L (Figure 3. thanks in large measure to the hieroglyphic stairway begun by Waxaklajuun Ubaah K'awiil around 710 (9. but Yax K‘uk‘ Mo‘ sits upon an ajaw glyph. ―When later kings are seated in office ‗as the ajaw.9 12 Muluk 7 Muwaan) and rejuvenated by K‘ahk‘ Joplaj Chan K‘awiil on 9. Stuart (2004c:228) observed.6) details the events of Yax K‘uk‘ Mo‘s accession. Tok Casper.1. The focal narrative on the top of Altar Q (Figure 2. acceded to the throne on 8 September 426 35 Berthold Riese (1988) was the first to show that Altar Q was a historical representation of Copan‘s dynasty. 35 Most of the rulers are depicted sitting upon their name glyphs.14. we nevertheless have a consistent record of accession dates beginning with that of Bahlam Nehn in AD 524 and lasting until the final accession of the dynasty in 822.11.Copan. The template for rulership that was attributed to him was held up as a standard until the end of the dynasty. dated 3 Chikchan 3 Uo 9. Whether the apparent Teotihuacan hegemony in Copan and Motagua region was real or was merely a reimagining of the past is subject to debate. Iconographically.0. Stuart 2004c:232). 37 In essence. Wite’ naah literally translates to ―root tree house‖ but is to be understood as an ―Origin House‖ that has strong associations with Teotihuacan (Stuart 2000a). He is arrayed in typical royal attire: a jade pectoral. waistband.0. erected on 15 September 795 (9.‖ 163 . earflares.0) both record Tok Casper‘s accession (Colas 2003:274.36 As recorded on Altar Q of Copan. Quirigua may have influenced by Copan‘s hegemony as Copan is influenced by the hegemony of Teotihuacan (Martin and Grube 2008:216). but the hearkening to Teotihuacan imagery was powerful nevertheless.11. he oversaw the accession of Tok Casper of Quirigua.18. then. but the earliest record we have of it comes nearly three and a half centuries later.(8. 37 Schele and Freidel (1990) describe to the wite’ naah compound as the ―founder‘s glyph. bracelets. Although we have no glyphic record of accessions at Quirigua between 426 and 724. and headdress.11 9 Chuwen 14 Tzek (2 June 653) (Satterthwaite 1979). and his left hand extends and 36 There may be another reference to Tok Casper‘s accession in 426 on the Hieroglyphic Stairway at Copan (Martin and Grube 2008:217).0).10. anklets.5. immediately after K‘uk Mo‘ Ajaw of Copan ascended to the throne at the wite’ naah and became K‘inich Yax K‘uk‘ Mo.0.5. dedicated 29 December 775 (9.29) provides us with an image of an enthroned ruler dating to 9.11. K‘awiil Yopaat is depicted sitting cross-legged on the glyphs that contain the account of his dance.17.11. Altar L (Figure 2.0) and Altar Q from Copan. as if they were his throne. Quirigua Zoomorph P.19. 39 Stylistically.14. Stela 38 This is the earliest example of the Quirigua royal title (Martin and Grube 2008:217). but was the favored expression used by K‘ahk‘ Tiliw to mark his accession.0 in 652 and records that the ruler K‘awiil Yopaat ak’otaj ti nep (―danced with a nep‖) 231 days later (Schele and Looper 1996:120). Stuart 1992:175). 164 .11. The reference to the Copanec ruler strongly suggests that Quirigua is still under Copan‘s hegemony.4. Altar L mentions K‘ahk‘ Uti‘ Witz‘ K‘awiil. his accession was marked by his receiving of the K‘awiil scepter.40 Glyphically.0. which seems to be a title held by provincial lords operating under Copan‘s hegemony (Schele 1989). which is not in and of itself an accession statement as it is often taken in other contexts as well. It is unclear what a nep is. He is named on several monuments as an Ek’ Xukpi Ajaw. jus t as Quirigua‘s dynastic founder Tok Casper had done under K‘inich Yax K‘uk‘ Mo. Altar L falls into the ―Giant Ajaw‖ category of altars common at Caracol (Chase et al 1991:2) and Tonina. ―Black Copan Lord‖ (Looper 1999:268). he was the first to do so at Quirigua (Le Fort 1994:19). the 12th ruler of Copan (although the context of why he was mentioned is not entirely clear) (Martin and Grube 2008:217). 38 The text of the monument celebrates the period ending 9.touches the Quirigua royal title. Interestingly.17) informs us that K‘ahk Tiliw Chan Yopaat acceded ukabjiiy (under the supervision of) Waxaklajuun Ubaah K‘awiil of Copan on 9. Stela E (Figure 3. 39 40 This title is also found on Stela 2 from Nim Li Punit in southern Belize in seeming reference to a lord from Quirigua. there is evidence that the tributary provinces within Copan‘s hegemony were formally numbered (Wanyerka 2004:48). However.0. and the ruler himself substitutes for the day sign Ajaw. and the iconography gives no clues (Schele and Looper 1996:120).17 12 Kaban 5 K‘ayab (29 December 724) (Martin and Grube 2008:219. cham k’awiil.13. Our first contemporary reference to accession at Quirigua does not appear until 724. who in turn had a long-standing alliance with Tikal. less than two years before K‘ahk Tiliw‘s betrayal. the ―13 th in the line‖ of rulers from Copan. ―the Nine-ConjuredFire-Shark headband was tied upon his head. Copan. and ceremonial plaza were all rebuilt in a way that 41 The other possibility is that K‘ahk Tiliw Chan Yopaat was the 14 th successor in the Quirigua line. K‘ahk‘ Tiliw remodeled Quirigua on a grand scale. funded by their newly-gained control over the Motagua trade route (Martin and Grube 2008:219). ballcourt.‖ which. Calakmul‘s primary enemy (Martin and Grube 2008:219).19) on 9. If Quirigua were indeed supported by Calakmul. Rather. it would have given them the courage to throw off the centuries of dominion by Copan. Waxaklajuun Ub‘aah K‘awiil. A ruler from Chik Nab – a toponym associated with Calakmul – played some role in the dedication of Quirigua Stela I (Figure 3. but rather appropriation.J (Figure 3.5. K‘ahk Tiliw Chan Yopaat is perhaps most well known for his rebellion agains t the very man who placed him into power. they emulate their former oppressors. is the name of a headdress used in accession rituals at Yaxchilán on HS 3 (Schele and Looper 1996:124). he captured and decapited his overlord. the dearth of texts from Quirigua‘s early history make it difficult to know for sure 165 . but uses the T713 k’al headband binding compound. The acropolis.0. Not just emulation. Quirigua does not appropriate the iconographic stylistic heritage of Calakmul. Despite this likely alliance.0. 41 There is circumstantial evidence that Calakmul played a background role in K‘ahk Tiliw Chan Yopaat‘s rebellion (Looper 1999:270-271). and named himself the ―14th in the line‖ (Riese 1986) which may suggest he fancied himself usurper of the entire Copanec dynasty (Martin and Grube 2008:219). In 738. rendering k’alaj b’olon tzakaj k’ahk’ xook juun tu b’aaj.18) also records his accession. curiously.15. wearing a headdress. It is imitation intimately involved in the production of difference.20). Applying Taussig‘s concept of mimesis. but something in between.both reflected and overshadowed Copan (ibid. but rather may be a cosmological prototype idealizing rulership (or perhaps. Recalling Harrison (2003:350-351): Borrowing of this sort is neither pure imitation. the individual seated within the niche on Stela I has god-markings on his arms. an attempt to reenact the identity-myths of others so deeply as to make them completely. However. one‘s own.‖ Jade Sky‘s accession is not recorded glyphically. and may not represent Jade Sky himself (Le Fort 1994:64).:220). On a similar note. as it remodeled itself into a capital worthy of commanding its own hegemony and assuming the ceremonial role once performed by Copan. nor pure differentiation of Self from Other. which bears iconographic similarities to the niche scenes used to denote accession at Naranjo and Piedras Negras (Sharer 1990:48) where a ruler is sitting cross-legged. but may be alluded to on the east face of Stela I (Figure 3. and surrounded by sky symbols. It is a kind of mimetic appropriation. which is always used in association with nicheaccession scenes at Piedras Negras and Naranjo (Le Fort 1994:104). and genuinely. The lack of the T684 verb also calls into that this is an accession monument to Jade Sky. Jade Sky is making a bold claim to divinity for himself). Martin and Grube (2008:221) argue that ―Quirigua‘s physical transformation was essentially functional. 166 . more speculatively. Quirigua seems to have appropriated Copan‘s stylistic tradition in effort to both harness Copan‘s prestige and assert their superiority over them. 16. or ―lord of‖ Sihyaj K‘ahk‘. recorded on Stela 4.22) which is the earliest known depiction of a Tikal lord.2. Stone 1989). His regalia are not typical Maya. perhaps Foliated Jaguar.Tikal The earliest contemporaneously recorded accession at Tikal is that of Yax Nuun Ahiin I. meaning Yax Nuun Ahiin was somehow subordinate to Sihyaj K‘ahk‘ (Stuart 2000a:479). In the inscriptions on the back. whose royal regalia would serve as a template for Tikal‘s rulers for the next six centuries (Martin and Grube 2008:26). Sihyaj Chan K‘awiil II likewise incorporated Teotihuacan imagery into his accession monument. but rather reflects central-Mexican attire (Borowicz 2004:223). 42 It is unclear whether this foreign iconography is intended to portray Yax Nuun Ahiin I as a transplanted ruler from Teotihuacan or if it is intended to add prestige and legitimacy to a local ruler who merely hearkens to their military prowess (Brasswell 2004. He is depicted frontally rather than the typical profile view.17. By mixing the iconography of the Maya and Teotihuacan.17 (12 September 379). As Martin and Grube 42 The atlatl or spear thrower may be a precursor to the K‘awiil scepter commonly taken at accession and wielded by rulers (Sharer and Traxler 2006:739) 167 . all of which have a distinctive Teotihuacan flavor (Coe 2005:96). we find his accession expressed through the taking of the Jester God (Taube 1998:457). wears a shell necklace. and holds an atlatl in his left arm. Stela 31 mimetically hearkened to Teotihuacan‘s power but made it uniquely their own. Stela 31 (Figure 3. a feline-headdress. The inscriptions tell us that Yax Nuun Ahiin I was the y-ajaw.21) while heavily borrowing the pure Maya-style iconography of Stela 29 (Figure 3. Yax Nuun Ahiin‘s son and successor to the throne. dated to 8. Clearly the specifics of the ritual being performed are not identical at Tikal and Palenque. However. typically the ―drum-major‖ headdress. The differences stand out in high relief and help the rulers of Tikal create a unique identity vis-à-vis those at Palenque and vice-versa.(2008:34) state. he did it for himself (Le Fort 1994:50. or ―kalomte‘-ship. the only known exception coming from the wooden lintel at Dzibanche. Schele and Villela 1992:4). The Early Classic rulers at Tikal. who is dressed as a Teotihuacan warrior. ―Stela 31 proclaims the rebirth of orthodox kingship. rather. Tikal stands virtually alone in its use as a title taken at accession. and Copan. Yaxchilán.‖ Although the kaloomte’ title is attested to at other major polities such as Palenque. such as 168 . the epigraphy and iconography agree that Sihyaj Chan K‘awiil does not receive the headband of rulership from his parents (as did K‘inich K‘an Joy Chitam) or even from a high priest (as did K‘inich Janab Pakal). Stela 31 depicts Sihyaj Chan K‘awiil holding aloft a headdress and flanked by images of his father Yax Nuun Ahiin. Although the accession verb is the same on Stela 31 as it is in the accession scenes from Palenque (T713). although the background similarities are there. which means the action was not done for him.‖ Schele and Villela (1992:3-4) likened the iconography of Stela 31 to accession scenes at Palenque where parents (living or dead) flank their acceding son and present him with the accoutrements of power. but reinvigorated.16). it is not followed by the benefactive particle (T757). he boldly takes it upon himself. neither sullied nor diluted by its foreign blood. One of the most striking aspects of accession at Tikal is the fact that its rulers could be seated in kalomte’el. which may have been a seat of the Snake Kingdom at the time with Sky Witness as ruler (Martin 2005b:7 fn. 169 . As discussed previously. While these titles are typically used to differentiate between the offices of paramount kings and lesser rulers.Yax Nuun Ayiin and Sihyaj Chan K‘awiil did not take the kaloomte’ title but rather were vassals to a foreign kaloomte’. which corresponds to the decline of Teotihuacan. it must be done against ―background similarities. such as kaloomté’-ship. it only appears once at Dos Pilas. In contrast to Tikal‘s frequent use of the kaloomte’ title. and sajal-ship. The earliest known rulers at Tikal to take the title were the Lady of Tikal and Kaloomte Bahlam in the early 6th century. namely Spearthrower Owl of Teotihuacan. 43 Stuart (1995:208) hypothesizes that the appearance of this title taken at accession corresponds to the time that Tikal was attempting to reassert its supremacy after a recent series of defeats by Bajlaj Chan K‘awiil of Dos Pilas under the sponsorship of Calakmul. Tikal began declaring its independence through its use of the exalted title. 43 Mathews and Justeson (1984:227-228) have argued that the abstractive suffix (-il.12.17. on Hieroglyphic Stairway 3 (ibid.16 (AD 682) (Jones 1977:32). It is not until the beginning of the Late Classic that rulers begin to accede as kaloomte’ (as opposed to taking the title at some point after accession). -(i)l-el) are markers of office or role rather than social rank or class. if differences are to be made apparent.9. It would appear that as Teotihuacan‘s hegemonic influence over Tikal began to wane. the difference is expressed through unique titulary.‖ One of the background similarities concerning accession is the ―seating‖ into office. Jasaw Kaan K‘awiil appears to be the first to take the kaloomte’ title at his accession on 9. Tikal‘s nearly exclusive use of the kaloomté’ title in accession suggests an attempt to elevate the office of its paramount rulers above those of the paramount rulers of other powerful polities. ajaw-ship.). and after his death he immediately faded into obscurity. The only hint of his ancestry comes from Monument 144 (Figure 3. K‘inich Baaknal Chaak.23). an otherwise unknown woman who is distinguished with the local Emblem Glyph. Obviously such a young king would have never have had the opportunity to partake in pre-accession rituals or prove himself on the fields of battle. Although the years of his reign were full of triumph. His successor. who acceded a few months after his fifth birthday (Martin and Grube 2008:74). Clearly such a young king would not be able to rule effectively. nor does he attempt to create a genealogy to connect himself to an illustrious predecessor. He is further anomalous in that he does not appear to be the offspring of his predecessor. so until he came of age the affairs of the kingdom were administered by K‘elen Hix and Aj Ch‘anaah. each step being recorded on distinct monuments spread across the main plaza. the credit belonged to his handlers. Monuments 29 and 134 state that K‘inich B‘aaknal Chaak ―sat down in rulership‖ 44 The next youngest ruler known to have taken office was K‘ahk Tiliw Chan Chaak of Naranjo. did not pay homage to him but rather performed a fire-entering ritual in the tomb of Ruler 4‘s immediate predecessor. an altar dated to 722 (ostensibly during Ruler 4‘s reign) that commemorates the death of Lady K‘awiil Chan. 44 Ruler 4 (K‘inich-? K‘ahk‘) was only two years old when he was enthroned. two nobles bearing the title aj k’uhuun (Martin and Grube 2008:183). the illustrious K‘inich Baaknal Chaak (Fitzsimmons 2002:134). K‘inich Ich‘aak Chapaat.Tonina Tonina stands out for having the youngest ruler ever known to accede to the throne. 170 . Eberl and Graña-Behrens (2004:103-104) have argued that the monuments of Tonina provide strong evidence that it was a multi-step process. As for the accession ritual itself. Yaxchilán There is evidence that accession rituals at Yaxchilán may have spanned several days.25) states that six days later he was ―seated.12 (14 June 688) and Monument 111 (Figure 3.‖ Lintel 21 (Figure 3.16.0. when he was joyaj ti ajawlel. According 171 . called k’uhul ajaw.(chumlaaj ta ajawlel. or ―divine lord‖ (Houston and Stuart 1996:295-297). Rituals and Accoutrements of Accession Accessions among the Classic Maya were essentially rites of passage that transitioned a human prince into a sacred ruler (Eberl and Graña-Behrens 2004:105.‖ However.16.). Not a few monuments inform us that Bird Jaguar IV was formally inaugurated on 9. ―tied/encircled in lordship.1. The huey tlatoani would fast and perform penance in seclusion for four days and likely received instruction on the duties of rulership during that period (Townsend 1987:393). the inscription lacks the prepositional phrase ―in lordship.‖ so it is possible that this event referred to his ritual seating within a specific structure (the ―Four Bat Place‖) rather than his placement in office (Stuart 1995:201).12. Taube 1988a:1011).3. The authors argue that a walk through the plaza would serve as a re-creation of the ceremonial procession that occurred on the ruler‘s accession day (ibid. Aztec sources similarly suggest that the rites of passage associated with rulership could last several days. the predominant accession statement at Tonina) on 9.0.24) informs us that he scattered blood that same day (but curiously does not mention the fact that it was his accession day). Thrones The use of thrones to denote rulership in Mesoamerica dates back at least to Early Formative San Lorenzo (Taube 2004c:8). In this instance. this period could last for four days (Townsend 1987). Taube 1994:672). dance does not seem to have been a major part of the accession ceremony proper.to Van Gennep (1960). of any dance being performed in conjunction with enthronement (Mathew Looper. this is the only known instance where it is danced with on the day of accession. Eberl and Graña-Behrens 2004. Yaxchilán Lintel 1 (Figure 3.26) contains the only known record of a dance being performed on the day of a ruler‘s accession. rites of passage have three essential stages: (1) separation from the previous social status. continued through the Middle Formative at 45 There is debate as to the duration of the liminal period experienced by acceding rulers. essentially without status. and (3) reincorporation into society with a new status. personal communication. but evidence for such a lengthy period is lacking for the Maya (cf. Dance Somewhat surprisingly. although dances were used as both precursors to accession and later in a ruler‘s reign to commemorate accession anniversaries (as discusse d in Chapter 2). Bird Jaguar IV danced with the K‘awiil scepter. LeFort 2000:19. and among the various Classic Maya polities. Among the Aztec. While receiving the God K scepter can be part o f accession at some sites (to be discussed below). or indeed.45 These transitions are accomplished according to culturally specific beliefs and practices. they would have been followed according to locally significant cosmologies. (2) the period of liminality. 2009). 172 . Chum is often spelled with the phonetic complement –mu suffix. As discussed earlier.30). however it was not found near Tikal. and it contains no known names from Tikal. 173 . accession monuments often depict the ruler seated upon a throne while taking or receiving royal insignia. ‗to be seated‘. spread to the Protoclassic Guatemalan highlands by 300 BC and diffused to the lowland region by the Preclassic (Clark and Hansen 2001:32). The crown worn by the Maya ruler on the back of the pectoral is virtually identical to the crown that is being presented to the ruler in the West Wall mural. which retrospectively records the accession of Chanal Chak Chapaat (―Celestial Red Centipede‖) at the Moon -Zero-Bird location at the ―chi-altar‖ place in 320 AD. The earliest example may be found on the Dumbarton Oaks flanged quartzite pectoral (Figure 3.12.14. or September 17 AD 320). as on the Leiden Plaque (Figure 3. chumvanihix ta auule (Lounsbury 1989:228) 47 The Leiden Plaque has long been erroneously associated with Tikal.3. The incision depicts the profile of a ruler sitting cross-legged. which was an Olmec pectoral that was repurposed by the Late Preclassic Maya. Stanley Guenter speculates that the chi-altar place may have been at El Mirador (personal communication). The ‗seating‘ glyph used in association with accession dates back to the Late Preclassic.27. Iconographically. Proskouriakoff (1950:105) notes that while the date inscribed on the Leiden Plaque is early (8.46 The logogram chum represents an abstracted human torso and thigh. it has no Tikal emblem glyphs. and the chum glyph is found in the accompanying text at A5 (Schele and Miller 1986:120-121). which may indicate they correspond geographically and temporally (Boot 2008:35). as if viewing someone from the side who was seated cross-legged. Bricker 2007:29-30).1.47 46 Lounsbury was the first to recognize an equivalent expression in Colonial Chontal in reference to accession.Oxtotitlan. the most common accession expression found in the glyphic corpus (though noticeably absent from Piedras Negras and Naranjo) is chum (T644). Harrison has shown that thrones whose seats are rimmed by a sky-band are most commonly found at Copan (such as the one found in Structure 66C). royal or non-royal. the authority of whomever is seated upon them. unadorned benches. typically with little or no iconographic or epigraphic details.:79). Sitting atop a sky-banded throne would have the iconographic conventions of the carving itself suggest a later date for its creation. Bardsley (1996:4) summarized some of the known variations in throne types: Whether the benches are plain uncarved stone slabs. Some of the variation is merely functional. Indeed. they are all seats of authority. or representations of inscribed stones in ceramic or in mural painting. cantilevered assemblages in stone or painted of same.There is an astonishing amount of temporal and spatial variation in throne types. which are unknown at Tikal but are found at Palenque (ibid. designed to represent zoomorphs (jaguars or reptilians). Karl Taube believes the carving may date to the mid 5 th century A. the only common feature that unites ‗thrones‘ as a category is that they were something upon which rulers sat in order to literally and metaphorically elevate themselves above their subordinates (Bardsley 1996:4. Tikal stands out for having had the plainest thrones in the region. 174 . from richly carved and decorated celestial thrones to simple. It is unsurprising that its near neighbor and eventual rival Dos Pilas sought to differentiate itself by creating thrones that were elaborately carved. Harrison 2001:78). Peter Harrison (2001:79) demonstrated that these distinct types of thrones were found across the lowlands according to local patterns. carved from stone with glyphic messages. (personal communication).). different thrones would have been used for different occasions.D. They are validations of one‘s having been seated or appointed at some level of authority. such as one that featured pseudo-Atlantean figures supporting a seat with Sun God armrests (ibid. 2006:274). Headdresses and Helmets A distinction needs to be drawn between headbands. Karl Taube (2005:28) has demonstrated the conceptual overlap between thrones. The ruler‘s body was sacred and at times likened unto a temple (and vice versa). thus placing rulers in a cosmological setting when they were seated upon them. In general. essentially carrying a portable throne with them wherever they went (Houston et al. The costume elements included jade beads with woven mat designs incised into them. hu’n can refer to either a headband or a headdress. and helmets. Headbands. Rulers would often wear costume elements around their waists that represented thrones (as on Tikal Stela 22. The head was the marker of individuality. see Figure 2.had cosmological implications as it placed the ruler in a position normally reserved for gods and deified ancestors.). and cosmic centrality.17). feline pelts. Glyphically.‖ David Stuart (2003:17) suggested that thrones conceptually represented the surface of the sky. Maya kings may have been considered living embodiments of royal thrones in ritual performances. sometimes referred to as the ―drum major‖ headdress. masks and/or headdresses were the principal emblems that served as seats of spiritual power for those that donned them (Looper 2003:28). headdresses. jade. and headdresses typical emphasized or directly identified its wearer. and a headdress was essentially a ―roof comb‖ to a his body 175 . Headbands are typically indicative of rulership. As Taube (2005:30) states ―Wearing jaguar-pelt kilts and elaborate jade-belt assemblages. and ko’haw refers a shellmosiac helmet. and mirrors (ibid. (Houston et al. In general. 2006:273). literally a ―living embodiment of the temple and its divine occupants‖ (Taube 1998:466). As discussed earlier. We find the presentation headdresses depicted both iconographically and in the accompanying text on the Palace Tablet and the Tablet of the Slaves (Figure 3.‖ which typically has a ―Jester God‖ diadem attached to it (Figure 3. or ―white headband. accession scenes at Palenque depict the new ruler atop his throne receiving the ―drum -major‖ headdress of sacred warfare from his parents (whether living or dead) (Stuart and Stuart 2008:157). but was likely used for the installation of subordinate officers to their positions (since House E of the Palace seems to have been the place where rulers acceded to the throne) (ibid. the T713/757 compound makes reference to the tying of a headband 176 . K‘inich Ahkal Mo‘ Nahb receives both the headband and the drum-major headdress. A ruler donning a headdress would thus become part of the architectural landscape.29). but lack textual reference to the event (Le Fort 1994:41). On the Temple XIX platform (Figure 2.34). The presentation of the headband or headdress was the key inaugural motif at Palenque.19).28). The Oval Palace Tablet and a fragment found in the bodega also depict the presentation iconographically. both adorned with the Jester God (Stuart 2005). The cloth headband was the principal symbol of the status of ajaw (Stuart 2004b:263). Jester God Perhaps the most common headdress across the Maya area is the sak hu’n. House A-D was dedicated as the ―headband binding house‖ in 720 AD under K‘inich K‘an Joy Chitam (Stuart and Stuart 2008:218).. where the ruler wears the trefoil Jester God on his brow and the foliated Jester God atop 177 .upon the ruler‘s head as part of the accession ceremony. or even showing shark-like characteristics (Taube et al. Some of these traits could be combined. The taking of a headdress at accession has considerable time depth.31) (Fields 1991) and continuing into Preclassic Nakbe (Hansen 1994:30). but as multiple types of Jester Gods can be found at a single site. 2010:66). trefoil. although they almost all share some form of the Jester God as a component (Le Fort 1994:50). and this phrase is most commonly found in the Western Maya region. Although the glyphic phrase is the same and the iconography is similar. similar to the one on the West Wall at San Bartolo (Skidmore 2011:6). with presentation scenes appearing among the Late Preclassic Maya at San Bartolo and the wearing of trefoil headbands by rulers extending back to the Middle Formative period among the Gulf Coast Olmec (Figure 3. reptilian. Le Fort (1994:50) suggested the variations in headdresses may have been intended to reinforce local identities. Guatemala (in the Holmul region) that may date to the transition between the Late Middle Preclassic and the Late Preclassic (350-300 BC). Miller and Martin 2004:68). and even within a single representation (as on the Dumbarton Oaks plaque. A modeled ceramic censer was recovered that prominently features a face donning a trefoil Jester God motif. avian. The earliest example of the Jester God in the Maya area comes from a burial found at the site of K‘o. 2010. such as being foliated. it should be noted that the headdress itself differs at each site. such as the ―foliated avian Jester God‖ worn by the ruler on the Dumbarton Oaks plaque (Taube et al. Several variants of the Jester God exist and it was represented with a wide range of traits. the ruler ideologically established himself as the source of maize fertility. rather than being presented with the headdress. Early rulers in several Maya polities are depicted receiving and wearing a trefoil crown.his head). which positioned 178 . Sihyaj Chan K‘awiil is a striking exception to this rule. the central maize motif on the headband was typically flanked by four jewels recalling the world tree. The trefoil icon was derived from Olmec representations of foliating maize (Taube 2005:28). This is true of both human and divine agents. The crown itself was actually a cloth headband with a central trefoil icon flanked by bifurcated ornaments. wearing a simple garment and turns to the left to receive the headband from whoever is presenting it to him. the yellow maize silk serving as hair and the sprouting leaves forming a trefoil (Fields and Reents-Budet 2005:26). The foliated jade ―Jester God‖ of the Classic Maya is clearly embl ematic of the trefoil maize symbolism associated with the Olmec Maize God (Fields 1991) and represents the animate spirit of maize (Stuart and Stuart 2008:197). By wearing such a crown. as discussed earlier. but the full suite of ideas associated with the variant forms of the Jester God are still not completely understood (Miller and Martin 2004:68). as the incised bone from the Dallas Museum of Art demonstrates (Le Fort 1994:49). the precursor to the Late Classic Jester God diadem (Fields 1991). both the glyphs and the iconography testify that he boldly took the headband upon himself (Figure 3. he is typically seated. when a ruler is depicted in the act of receiving the headband. Iconographically. it is likely that the differences were intended to be cosmological (Taube 2004c:35). Furthermore. They were sometimes portrayed with a maize cob for a crown.24). 179 . Ko’haw Helmet The ko’haw or ―drum major headdress‖ (Schele and Miller 1986:69) was an appropriated version of the Teotihuacanoid war helmet (Martin and Grube 2008:143). Waxaklajun Ubah K‘awiil appears to have re -enacted Yax K‘uk‘ Mo‘s receiving of the headband (ibid. Jester Gods are typically adorned with three circles or spheres. its function was identical to the headbands and headdresses of other polities.‖ it likely did not refer to the sak hu’n or Jester God (which is comparatively rare at Copan) but rather to the distinctive woven cloth turbans that were a marker of Copanec identity (Schele and Newsome 1991:5). as evidenced by the name glyphs found in the turban of Yax K‘uk Mo..32). which is likely an allusion to the three stone hearths associated with conceptual center of the Maya home (Taube 1998:454-462). Turbans Unlike Palenque and other sites. 6). when rulers of Copan ―received the headband. It could act as both as an indicator of Copancec identity as well as to identify individuals. effectively creating a unique template for his successors.48 Interestingly. depicted iconographically and epigraphically as a shell mosaic headdress (Macri and 48 Marc Zender (2004:70-72) has questioned the notion that jade jewels mark the ruler as the world tree.the ruler as an axis mundi as he wore it. Copan‘s founder Yax K‘uk‘ Mo‘ was the first to don the royal turban (Figure 3. If later iconography is to be believed. Although the specific style of the turban may be unique to Copan. Tikal was intentionally hearkening to Teotihuacan in order to bolster its own prestige.16. and the main text uses the presentation of the headdress as the accession 49 Ko’haw is likely a loan-word from the Nahuatl root cua:(i)-tl (Macri and Looper 2003:290). Its first appearance at Piedras Negras is in AD 667 on Panel 2. It is always presented to the acceding ruler at the center of the scene by his parents seated to his left. The youths all wear ko’haw helmets as well. we see Itzamnaaj K‘awiil of Dos Pilas donning the ko’haw at on his Stela 1 (Figure 3. The scene itself depicts six youths from Yaxchilán. The presentation of the ko’haw became one of the key rituals of accession at Palenque.5) under the supervision of an ochk’in kaloomte’ named Tahom Uk‘ab Tun. which commemorates Ruler 2‘s re-enactment of Turtle Tooth‘s taking of the ko’haw in AD 510 (9. Bonampak and Lacanha (all vassal to Piedras Negras at the time) kneeling in submission to Turtle Tooth and his supposed heir Joy Chitam Ahk (who is never heard from again.33). which commemorates the defeat of a Tikal lord during his reign in 705. Fitzsimmons 2002:84). which refers to the crown of the head (Lόpez Austin 1988:2:143) 180 .49 It makes its first iconographic appearance in the Early Classic at Tikal on Sihyaj Chan K‘awiil‘s accession monument. who may have had some connection to Calakmul (Martin 1997:860).0. Stela 31. Interestingly.Looper 2003:290). and it is limited to those two sites. Its epigraphic usage appears first at Piedras Negras and later at Palenque (Macri and Looper 2003:290).3. but the T678 grapheme that specifically names the helmet does not appear until centuries later. The Early Classic iconographic hearkening to the ko’haw at Tikal makes sense in light of the heavy Teotihuacan influence on the site beginning with the entrada of 378 (Stuart 2000a). It typically has a Jester God affixed to the front (ibid. Schele and Freidel 1990:475). the Quadripartite Badge ko’haw to GI-Chaak (GI). This same glyph is used to denote the relationship between rulers and their gods. more specifically by its mother. But rulers were not the only ones to receive ko’haw helmets at Palenque. K’awiil Scepter K‘awiil is the Classic period name of God K (Stuart 1987:15). 2006:67-68). and though he is essentially a pan-Maya deity he is also ―among the most puzzling of Maya gods‖ (Houston and Inomata 2009:207). immanent quality of ‗godhood‘‖ (Houston et al. Unlike other characters from Maya 181 . Linda Schele (1978) first suggested the glyphic phrase that comprised a parentage statement linking mother to child (Figure 3. The first mention of the ko’haw at Palenque comes from the Temple of the Inscriptions in 683. although Houston and Stuart (1996:294) reject the suggestion that rulers would thus be considered ‗mothers‘ of the gods (Schele 1978:8. false god‘ in Poqom and Kaqchikel) or a generic physical expression of godhood. now read huntan and translated as ―cherished one‖ (Stuart 1997:8) or ―precious thing‖ (Houston and Stuart 1996:294).34) (Macri and Looper 2003:290). This supports the view that the gods were cared for by the rulers as a child is cared for by its parents.29-30). he offered the Chaahk ko’haw to Unen K‘awiil (GII).35). Here we read that K‘inich Janab Pakal offered individualized ko’haw helmets to various gods (Guenter 2007:34). For example. K‘awiil may simply be an expression for ―effigy‖ (the word kauil means ‗idol. much as God C seems to express the ―invisible. and the Sak? Hu’n ko’haw to K‘inich Ajaw (ibid..phrase (Le Fort 1994:44-45). where it occurs six times on the central panel (Figure 3.:46). but it is not limited to those occasions. K‘awiil is never shown actively participating in mythological scenes. For example. 50 Likewise at Yaxchilán. the K‘awiil scepter was held on various occasions and at diverse times of the year (Le Fort 2002:3).0. however not all of them make direct reference to his taking of K‘awiil. after K‘ahk‘ Tiliw Chan Yopaat of Quirigua removed the head of his overlord Waxaklajuun Ub‘aah K‘awiil (Copan‘s 13 th successor) he took the K‘awiil and dubbed himself the ―14th successor‖ (Riese 1986).0. which could only be wielded by rulers. Bahlam Nehn‘s Stela 15. Proskouriakoff (1973:168) presciently understood that the taking o f K‘awiil could be used as an accession statement. Waxaklajuun Ub‘aah K‘awiil‘s Stela J and Yax Pasaj Chan Yopaat‘s Altar Q (Fash 1991:83). K‘awiil was heavily emphasized at some polities while virtu ally ignored at others. but much more passively emerges from serpents or is held statically by rulers. the K‘awiil scepter is a frequent accoutrement held on various occas ions at diverse times of 50 K‘uk‘ Mo‘s accession is commemorated on K‘inich Popol Hol‘s Stela 63. It could also be taken by rulers on occasions before or after their accessions.mythology. three decades prior to his accession. Unlike the ceremonial bar.0 was celebrated for generations on the most prominent public monuments at Copan (Fash 1991:83). The first K‘awiil taking was prefixed with yax. an already established ruler could take K‘awiil to indicate some fundamental shift in the nature of their own rulership.‖ At Yaxchilán. literally ―unripe‖ or ―young. Furthermore. the K‘awiil scepter was taken at times by non-royalty. K‘uk‘ Mo‘s grasping of K‘awiil on 9. Kan Bahlam II takes the K‘awiil when he is approximately 18 years old. At Palenque. The taking of the scepter mimicked the actions of the gods and blurred the lines between myth and history (Martin 1997:863). 182 .0. The ruler‘s soul did not immediately ascend or descend to the Otherworld. they all but ignore the god. accession was a liminal period for the ruler. Bunzel 1952:150). Eschewing one of Yaxchilán‘s favorite gods and rejecting the specific accession ritual associated with that particular god enabled Piedras Negras to reinforce their unique identity vis-à-vis their neighboring rivals. the rulers not only fail to take K‘awiil at accession. the soul is believed to linger for at least two or three days after death (Vogt 1969:222). This liminal period is dangerous for the living because the dead seek to return (Fitzsimmons 2009:44). at the site of their neighbor and rival Piedras Negras. It was a transition from his status as a dead ruler to his rebirth as an ancestor. and since the souls of rulers were 183 . but death was likewise a liminal period for the recently deceased king. or even elevated to the status of a god. but rather it would linger on earth for several days. and the god K‘awiil himself was summoned regularly. Among modern Maya groups. preferring instead to highlight Chahk in their ritual actions (Houston and Inomata 2009:207). As discussed above. The Burial and Deification of the King’s Predecessor Chapter 4 will discuss the ultimate fate of deceased kings and the anniversary rituals performed on their behalf. It was essentially his first order of business. Significantly.the year wielded by both rulers and non-elites (Le Fort 2002:3). necessarily performed before he could be seated upon his throne. and as long as seven (LaFarge 1965:44) or even nine days (Guiteras-Holmes 1961:139-140. our purpose here is to examine the immediate demands of burial and deification of a predecessor as an integral aspect of an incoming ruler‘s own accession. The incoming ruler. and the burying of a ruler‘s body was likened unto planting a seed that would lead to rebirth as an ancestor (Taube 2001b:270-271).. was acting as sower as he carved into the surface of the earth to create a tomb and buried his predecessor (ibid. could interact with or even kill the wahy of other rulers. The Maya equated humans with maize. ―the Classic Maya had no such overarching models.). ibid. the wahy. Grave goods were provided to aid the deceased in their journey through the Otherworld. it appears that burials and their associated symbolism shared a fundamental concern with concepts of descent into the underworld. As is expected. It would have been imperative for the acceding king to perform the proper death rites for his predecessor to minimize the danger inherent in this liminal period. We may speculate that the lingering wahy of a deceased ruler could have been perceived as a legitimate threat to the well-being of an acceding ruler. By and large. to the point that we cannot profitably construct an ―ideal type‖ of burial among the Classic Maya. then. 46).considered to be the most potent it would therefore have been a very precarious interlude. Likewise. 11). Classic Maya royal 184 .. even from one king to the next.. and entry into the flowery paradise (ibid. as on K791 (Figure 3. however. 64) noted.36. As James Fitzsimmons (ibid. there is a great deal of variation across the Lowlands regarding the amount of time between a ruler‘s death and the rites performed on his behalf (Fitzsimmons 2009:7). rebirth as a god. there is great variety in the rites performed. mode of burial.‖ In only the most general of ways. One of the souls possessed by Classic Maya rulers. and they produced burials whose characteristics varied over space and time. and the symbolism used. grave goods. ceramic vessels (bowls. Tikal stands out for typically placing a single bowl beneath the head of the deceased ruler. etc). and Altun Ha (Ruz Lhullier 1968 and Welsh 1988). These two sites. Palenque and Piedras Negras are notable for their paucity of grave ceramics. rarely have bowl-over-skull burials. along with Copan and Tonina. and the remains of codices and textiles (A. obsidian. The new types of ceramics and jade.burials contain some.). 185 . and the heads are predominantly oriented to the north as they are at Piedras Negras. Copan. Seibal. masks. precious maritime goods (shells. pendants. tinklers. pearls). of the following items: worked jadeite accessories (jewelry. shell. where the rulers were placed on an entire bed of dishes (ibid. Calakmul may have been appropriating this practice and making it uniquely their own in the burials of Structures III and VII. tripod vessels. Tonina and Palenque tend to reuse graves for successive interments. etc). Altar de Sacrificios. Fitzsimmons 2009:83-84). Tikal. and bone artifacts all reflected heavy influence by Teotihuacan (Fitzsimmons 2009:87). ear-flares. ―we find both items shared with other sites and local innovations‖ (Fitzsimmons 2009:83). But as would be expected in groups seeking to define themselves in contrast to their neighbors. red pigments (cinnabar or hematite). plates. Chase 1992:37. and Uaxactun. bloodletting implements (jade. stingray spine). This contrasts with the predominantly eastern head orientation found in elite burials at Dzibilchaltun. if not many. There was a marked shift in the types of burial goods found in the Central Peten and at Copan around the time of the entrada in AD 378. In perhaps a case of one-up-manship. 186 . In the ancient West Mexican polities ―this rivalry and tendency toward one-upmanship also resulted in the heterogeneous set of tomb forms and practices that we are just beginning to plot out today… but the dominant theme at this point appears to be the individual expression of power at the local level‖ (Beekman 2000:393).The notable variation in burial practices was not limited to the Maya but rather seems to have been a pan-Mesoamerican phenomenon. Stuart from Stuart and Stuart 2008:163 Figure 51).1.Figure 3. The ―placing in order‖ of Pakal‘s heirs as recorded on the stucco sculpture on the rear wall of Temple XVIII (Drawing by D. 187 . detail of Pier B (drawing by Linda Schele. based on Maudslay‘s original photographs. 188 .2.a. courtesy of FAMSI). (b) Stuart‘s drawing (2007). (a) K‘an Bahlam II as the god Unen K‘awiil (GII of the Palenque Triad). Figure 3. b. shows it is K‘an Joy Chitam that bears K‘an Bahlam II in his arms. not K‘uk Bahlam as suggested by Schele and Mathews (1998:99). Palenque Pier C (Drawing by Linda Schele. courtesy of FAMSI). 189 .Figure 3.3. Piedras Negras Lintel 2 (Drawing by D. courtesy of CMHI). Stuart.Figure 3. 190 .4. b. 191 . courtesy of FAMSI). Figure 3. Schele. (a) Temple side (drawing by J. courtesy of FAMSI). (b) River side (drawing by L.a.5. Montgomery. Yaxchilán Stela 11. Figure 3. c.6. courtesy of FAMSI) 192 . Montgomery. b. Accession Phrases.a. (a)T684 joy/hoy ―encircle‖ (b)T644 chum ―seating‖ (c)T713/757 k’al sak hu’n ―tie the white headband‖ (d)T670 ch’am k’awiil ―grasp K‘awiil‖ (drawings by J. d. 7.Figure 3. (from Guenter 2007:20-21) 193 . East Tablet of the Temple of the Inscriptions. 8. courtesy of FAMSI) 194 .Figure 3. The Oval Palace Tablet (drawing by Linda Schele. (a) Muwaan Mat (F7-F8) (b) U ―Kix‖ Chan (P1-P2). (Drawing by Linda Schele. 195 . courtesy of FAMSI).a. Figure 3.9. Detail from The Tablet of the Cross. b. ―Headband -tying‖ accession phrase used for supernaturals/mythological founders. courtesy of FAMSI). West sanctuary jamb from the Temple of the Cross (Drawing by Linda Schele. K‘inich Kan Bahlam II wearing the headdress of U Kokan Chan (U ―K‘ix‖ Chan).10. 196 .Figure 3. Figure 3. (Drawing by Linda Schele. The Palace Tablet (without main text). courtesy of FAMSI).11. 197 . courtesy of FAMSI) 198 .12.Figure 3. Piedras Negras Stela 25 (drawing by John Montgomery. (Drawing by Heather Hurst. San Bartolo scaffold accession scene.13.Figure 3. in Taube et al 2010:11 Figure 7) 199 . Scaffold accession scene. 200 . incised bone.14.Figure 3. Dallas Museum of Art. (Drawing by Linda Schele. courtesy of FAMSI). 15.Figure 3. (Drawing in Schele and Looper 1996:155) 201 . Copan Stela 9. courtesy of FAMSI). 202 .16. Copan Altar L.Figure 3. (Drawing by Linda Schele. Figure 3.17. Quirigua Stela E. (Drawing by Matthew Looper 2003:153) 203 Figure 3.18. Quirigua Stela J records the headband was bound upon K‘ahk‘ Tiliw‘s head. (Drawing by Matthew Looper 2003:103) 204 Figure 3.19. Quirigua Stela I records that a ruler from Chik Nab played some role in the accession of K‘ahk Tiliw. (Drawing from Schele and Looper 1996:127) 205 Figure 3.20. Quirigua Stela I east face. Possible niche accession scene. (Drawing by Matthew Looper 2003:194) 206 Figure 3.21. Tikal Stela 31. Iconographic mixture of Teotihuacan and Maya symbolism. (Drawing by John Montgomery, courtesy of FAMSI). 207 Figure 3.22. Tikal Stela 29. The earliest depiction of a ruler from Tikal, AD 292. (Drawing by Linda Schele, courtesy of FAMSI). 208 Figure 3.23. Tonina Monument 144. (Drawing by Lucia Henderson, courtesy of CMHI) 209 Figure 3.24. (Drawing by Ian Graham. courtesy of CMHI). 6:3. 210 . 1999. Tonina Monument 111. K‘inich B‘aaknal Chaak scatters blood on the day of his accession (at S). Bird Jaguar IV‘s ―seating‖ six days after his acces sion date. (Drawing by von Euw. 3:49. courtesy of CMHI) 211 . Yaxchilán Lintel 21.Figure 3.25. Yaxchilán Lintel 1. The only recorded instance of a ruler performing a dance on his day of accession.Figure 3. courtesy of CMHI) 212 . (Drawing by Ian Graham.26. 3:31. Chanal Chak Chapaat is seated at the chi-altar place. courtesy of FAMSI). The Leiden Plaque. (Drawing by John Montgomery.27.Figure 3. 213 . 214 . (Drawing by Linda Schele. The Tablet of the Slaves. courtesy of FAMSI). Presentation of the ―drum -major‖ headdress with Jester God diadem.Figure 3.28. Drawing by Linda Schele (in Schele and Freidel 1990:115) 215 . Variety of Jester God headbands.29.Figure 3. Figure 5) 216 . Text contains earliest known example of chum (―seating‖) glyph (at A5). Olmec pectoral reused by Late Preclassic Maya.Figure 3.30. Drawing by Harri Kettunen (in Kettunen and Helmke 2009:10. Figure 3. (Drawing by Linda Schele. Formative period example of trefoil headband. courtesy of FAMSI) 217 .31. holding a burning dart.Figure 3. Detail of Copan Altar Q. (Drawing by Linda Schele. a marker of Copanec identity. courtesy of FAMSI) 218 .32. which alludes to his glorious resurrection as the Sun God. K‘inich Yax K‘uk Mo‘ wearing a turban. 33. Dos Pilas Stela 1. courtesy of FAMSI) 219 . (Drawing by Linda Schele. Itzamnaaaj K‘awiil dons the ko’haw after Dos Pilas‘ defeat of Tikal in 705.Figure 3. 34. Temple of the Inscriptions central panel. (Drawing by Linda Schele. and M4). courtesy of FAMSI) 220 .Figure 3. I9.K8. D9. F2. mentions the ko’haw helmet six times (C6. Figure 3. Lit. but sometimes denoted relationship between rulers and their gods. courtesy of FAMSI). ―cherished one‖. juntan/huntan. 221 . (Drawing by John Montgomery. Parentage statement typically linking mother to child.35. Figure 3. 222 .36. (Photo courtesy of Justin Kerr). K791. The ixiptlas were imbued with sacred power or divine energy known as teotl. Rather.Chapter 4 Maya Gods and Ancestors There does not appear to have been a general concept of ‗religion‘ in ancient Mesoamerica (Pharo 2007:62). k’uhul ajaw. visions. which is usually translated as ―representation‖ or ―substitute‖ (Stuart 1996b:162). or whisps of smoke from sacred offerings (ibid. but the Classic Maya had but a single qualifier that encompassed all of these concepts: k’uh. or seen in dreams. As discussed previously. living rulers could blur the distinction between humans and gods through impersonation rituals. In English we label rulers as ―sacred‖ or ―holy‖ and use nuanced understanding to distinguish them from the pure ―divinity‖ of gods. Yet gods were not merely abstract concepts. but rather tangible (or at least perceptible) beings that could be touched when in the form of masks or effigies. but there is still some debate as to whether living Maya rulers were considered perpetually god-like or merely ‗holy‘ during their lifetimes. which views natural and supernatural forces as a ―unified whole‖ (Sachse 2004:11). Although we lack a Classic Mayan term that refers generally to physical representations of their gods. which may call into 223 . Stuart 1996b:162. Houston and Stuart 1996:297. nor was there a sharp division between the natural and the supernatural realms. This word is used to label gods.). and it is used as a root in the title for supreme lords. Hvidtfelt 1958). it has been characterized as a monistic system. they likely had a concept analogous to the Nahuatl term ixiptla. which enabled humans to physically interact with the supernatural realm (Boone 1989:4. Schellhas created a classification system for identifying the deities that were represented in the Late Postclassic codices from Yucatan.question whether there was a qualitative difference between living rulers and gods from an emic perspective (Sacshe 2004:11). but there are subtle differences in the terms. but in order to fully understand the afterlife they expected as gods. Karl Taube‘s important volume The Major Gods of Ancient Yucatan (1992) updated Schellhas‘ study and discussed the defining characteristics of each major god and the symbolism embodied in each. What is clear. Deification generally refers to the concept of becoming god-like. The Ideology of Gods and Ancestors Paul Schellhas attempted the first in-depth study of Late Postclassic Maya deities over a century ago in his classic work Representations of Deities of the Maya Manuscripts (1904). which continues to be used today. and euhemerismis a more specific concept wherein deified heroes were incorporated into the official cultic pantheon after their deaths (Proskouriakoff 1978:116-117. 224 . we must first seek to understand the nature of Maya deities. Selz 2008:21). apotheosis means to be elevated to the status of a god. In the literature the process is variously referred to as deification. however. is that after death some rulers were elevated to the status of a god. who claimed gods were deified historical figures. or euhemerism. 51 Maya rulers expected to be euhemerized. 51 Named in honor of the ancient Greek philosopher Euhemerus. apotheosis. is that some of these ―manifestations‖ merely represent different episodes stemming from a particular god‘s mythology. our understanding of Classic period gods is still ―gravely opaque‖ (Grube 2004:59).‖ and I will adhere to that definition throughout. and discrete beings is not applicable to the Mesoamerican pantheon. Although a great deal of change occurred between the Classic and Late Postclassic periods concerning the identities of specific gods and their attributes. perhaps. Vail‘s (2000) assessment of the nature of Postclassic gods can perhaps usefully be applied to the earlier Classic Period. each having various aspects. Miller and Martin (2004:145) note that Maya gods resist neatly defined categorization because they often merge with other gods. attributes and even the gender of Maya divinities are 225 . to the point where even defining what a god is can be daunting.The study of Maya gods is an admittedly tricky task. Houston and Stuart (1996) lamented the scholarly ethnocentrism that has hindered understanding of Classic Maya deities. similar to many Egyptian deities. ages. appearances. Looper (2003: 29) notes that the names. Taube (1992:8) broadly defines Maya gods as ―supernatural sentient beings that appear in sacred narrative. Another possibility. Despite remarkable advancements in the field of epigraphy. She states. immortal. since a western conception of gods as perfect. Grube (2004:74) suggests that different manifestations of a single god may be functionally equivalent to the Avatars of Vishnu which do not contain the full essence of the god but rather contain only certain aspects or attributes of the god necessary for specific purposes. ―The picture that emerges is one of a series of deity complexes or clusters. or manifestations‖ (Vail 2000:123). composed of a small number of underlying divinities. since only a scant few of the hundreds of theonyms that are recorded can be clearly identified anciently. As Morning Star. One is Child San Pascual. it may seem contradictory to the Western mind that he is both Venus as Morning Star (an enemy of the sun) and a manifestation of the sun during a particular hour of the day. cited in Carrasco 2005:260). They say that when it is just getting light its name is Child Redeemer of the world. One name is Child Guardian. and is therefore analogous to the Aztec god Tlahuizcalpantecuhtli. one of these is its name. ethnohistoric and ethnographic sources may obfuscate rather than clarify. This is not to suggest that all aspects of Maya religion changed over time. But in many instances. then. (Fought 1972:485) Each of the above manifestations has distinctive individual attributes for the Ch‘orti‘. Beirhorst 1992).fluid. The one by which he is best known by people continues to be Jesus Christ. San Pascaul is also the patron saint of death and is skeletal (Christenson 2001:208). but such is the fluid nature of Maya conceptions of divinity. They say that at each hour. the skeletal Lord of the Dawn and Venus as Morning Star (Taube 1993:15. But even in the course of a single day the solar deity shifts identities: They say that the Sun has not just one name. but diachronic variation has led to discontinuity 226 . San Gregorio emits beams of light. San Antonio is the fire god. And those few whose names can be identified seem to have functioned in far different capacities anciently. One is Child Succor. One is Child Creator. One is Child Refuge. and San Pascual is Venus as morning star (ibid. as are their domains of influence. Tlahuizcalpantecuhtli ―battled the rising sun at the first dawning at Teotihuacan‖ (Taube 1993:15). One name is San Antonio of Judgment. For example. One name is San Gregorio the Illuminator. The modern Ch‘orti‘ conceptualize one of their principal deities as a maize spirit in the rainy season but as a solar being during the dry season. In the case of the Ch‘orti‘ mythology surrounding San Pascual. Interestingly. The rulers were thus intercessors between humans and the gods.‖ and ―invoke‖ and ―remember us‖ (ibid). After failing to create beings that could make acceptable offerings. provider. it appears that modern humans were allowed to survive because they properly repaid their debt to the gods (Spenard 2006). for good or bad (Sabourin 1973:11-12). Humans worshiped and petitioned the gods through offerings but they could not force the gods into action (Zender 2004:46). They wanted beings that could ―keep our days. Unlike the previous unsuccessful attempts. Thompson 1970:170). they were considered superior beings that could control the forces of nature and played an active role in human destiny. The gods were expected to respond to properly offered sacrifices in a type of quid pro quo contractual relationship (Houston and Stuart 1996:292.‖ ―glorify us. Our purpose here is not to categorically define every Classic period god – an impossible task – but rather to discuss the gods that were most highly favored by certain 227 . the creator gods said ―Let‘s try to make a giver of praise. but were not believed to directly control the supernatural.between some aspects of Classic period religion and the beliefs and practices attested to in the 16th-17th centuries. Although the specific motives are not spelled out in the ancient inscriptions. the importance of proper worship is highlighted in the creation narrative of the Popol Vuh. giver of respect. although there was a sense of ‗negotiation‘ with the gods (Monaghan 1995:215-216). The Eminence of Maya Gods Maya gods were not just of a different order than humans. nurturer‖ (Tedlock 1996:68). there are localized cults. especially Palenque. it is futile to attempt to encompass Maya religion within a single conceptual framework (ibid. for example. Because of these particularities. we will discuss which gods were called upon to sanction the ritual actions of rulers during their lifetimes. euhemerized ancestors and tutelary gods are typically specific to particular polities or even dynasties within a polity (Sachse 2004:8). but we cannot presume an identity of ritual roles. Local Variation in the Maya Pantheon While there are certainly pan-Maya deities that are known across the Lowland region. or history of development. as a paradigmatic model for beliefs elsewhere in the Yucatan peninsula. Gillespie and Joyce 1998). attributes.rulers from some of the major polities. Yet even within a single site we are faced with the possibility that different belief systems were held both diachronically and synchronically. Early in Copan‘s history. More specifically. and naming patterns to better understand local variation (Grube 2004:75. Houston and Stuart (1996:302) similarly inform us: There is no one set of gods codified and venerated by all Classic Maya. meanings. indicates the participation of local gods at an event usually interpreted in pan-Maya terms (cf. Maya theology was conceptualized ―in local ways that expressed local needs‖ (see also Monaghan 2008:28. A 'creation' event at Dos Pilas.:20). A god revered at one site may partly share the name of a god at another. Grube advocates creating a ―microhistory‖ of Maya supernaturals by carefully examining local traditions. Future studies of Classic religion must take this variety into account and avoid using one site. and examine which gods were most relevant in the context of a ruler‘s resurrection and apotheosis. Freidel et al. Miller and Martin 2004:20). As Houston (1999:51) noted. 1993: 64-75 and Houston 1993). Guatemala. Rather. rulers appear to have emphasized 228 . 229 . since we appear to be dealing with ―various synchronic states of Maya mythology‖ between and even within individual polities (Sachse 2004:13). Evidence for synchronic variation within a site can perhaps be inferred from ethnographic examples. an adjustment to the local pantheon would be necessary (Monaghan 1995: 307–55). each with increasing access to esoteric knowledge (Carlsen and Prechtel 1991:26).‖ Local Patron Gods Local patron gods were held in equal if not greater esteem than pan-Maya gods. apparently from one ruler to the next. We are thus faced with the discouraging thought that it is unlikely we will ever be able to reconstruct a precise mythology for even a single site. Each time a new ruler was enthroned.pan-Maya gods. Although many of their names have resisted decipherment. A king‘s personal gods accompanied the ruler throughout his life. personal communication. Among modern Atitecos. but as time progressed they began placing more emphasis on local gods and ancestors (Alexandre Tokovinine. they are frequently listed in the inscriptions. It may seem curious to us that the mythology of a site can change so rapidly. for example. Hamann (2002:354) noted that ―the social lives of objects and locat ions. where it is not uncommon for religious specialists of a single community to provide divergent explanations for the same phenomenon . but as Carlsen (1997:181 Footnote 6) has observed among modern Maya groups. there are multiple levels of initiation within the cofradía system. In some instances the ruler and his gods were both ―seated‖ in rulership on the same day (Houston and Inomata 2009:200). 2008). ―myth can take root very quickly. Local narratives would have served as mythic templates that guided royal ritual and performance (Houston and Stuart 1996:292). Chimalteco group identity stems from local mountain deities and the images of saints housed on the local church that hold particular significance to the local people (Watanabe 1992:79). Tikal (Stela 26). 4. It is 230 . These triadic groupings are typically prefixed with an epithet that Mark Van Stone suggests is read ox‐lu‐ti‐k’uh. the ―Three-Born-Together-Gods‖ (Fig. Monaghan (1995:9) went so far as to suggest that Mesoamerican communities might be better understood as ―congregations‖ because of the power that local deities had in the maintenance of group identity. 2011) notes that all of the known examples of the epithet lack isoloble syllables and therefore cannot be confidently deciphered. and the social identity of communities are all closely linked. and B‘olo‘n ‗Okte‘ (Lopes and Davletshin 2004:3).‖ For example. ‗Ahk‘u‘l Xukab‘. but they lack the qualifying epithet. Naranjo (HS1 Step II C2b-D2) and throughout Palenque (Staurt 2005:160).1).‖ meaning the traditions of a people are inseparable from the place where they dwell. The individual gods within each triad may have been worshiped outside of a particular polity‘s borders. but Stephen Houston (personal communication. Group identity in Mesoamerica is often ―spatially exclusive. We find triads at Caracol (Stela 16). but collectively each triad created a diacritical marker of local identity and provided a unique mythological template for each city. ‗Ahku‘l Muuch. A number of Classic Maya cities appear to have emphasized triadic groupings of gods that were of elevated prominence within the local pantheon (Stuart 2005:160). La Mar Stela 1 may itemize three gods.the supernatural forces they house. 231 .also possible that this is actually only naming two deities. The Paddlers appear on Ixlu Stela 2 where they oversee a scattering event (Fig. such as eight turtle Bakabs(?) and four raccoons who appear to have had some role in Tortuguero‘s local creation mythology. A fascinating passage from Yaxchilán Lintel 35 (C5-D8) claims a war captive became the ―eating‖ ( u-we’-iiy?) of these two principal patron gods (Houston et al. Yaxchilán emphasizes a local variant of the rain god.2006:123). The inscription on the Sotheby‘s Panel describes the dedication of a waybil for Ahkul Muuch Ahkul Xukab (ibid). The Paddler Gods can be found across the Lowlands. Not all sites emphasized triads. they ―awaken the hearts‖ of other supernaturals.2. 4. or at least they would pair up particular sets of gods from their larger local pantheons on specific occasions. but Tonina appears to have given them more attention than any of the other sites (Mathews 1977). 52 On Monument 6. Tortuguero‘s two principal patron gods appear to be Ihk‘ K‘ahk‘-Ti‘ Hix and Yax Suutz‘ (Gronemeyer and MacLeod 2010:59). 53 Dos Pilas and Aguateca similarly appear to have had two principal gods. as there may be a single deity named Ahkul Muuch Ahkul Xukab. which may indicate the name represents a single deity. Interestingly. however. La Mar and Sak Tz‘i appear to have shared the patronage of Akul Muuch Akul Xukuub' (Biro 2004:19). see also Stuart 2003:3-4). 52 Yax Suutz‘ may also be mentioned on the East Tablet from the Temple of the Inscriptions in conjunction with a ―giving‖ ritual (Guenter 2007:13). Stuart et al 1999:169). 53 The raccoons may be conceptual cognates with the four opossums found in the New Year Pages of the Dresden Codex (Gronemeyer and MacLeod 2010:56 Footnote 63. as well as the Jaguar God of the Underworld. Many sites appear to have had two primary patron deities. Ah K‘ahk‘ O‘ Chaak. At Piedras Negras. Bolon Yokte‘ K‘uh. Modern Highland groups consider deified ancestors to be protectors of their community.‖ but unsurprisingly. Palenque and Naranjo both commemorated the accession of the ―Zip Monster. for example. although the narrative begins four years earlier. although it is possible that the Zip Monster‘s history is somewhat akin to that of GI at Palenque. which means ―guardians‖ or ―those who watch.‖ which suggest they served as protectors of the ruler and his dominion (ibid:204). and La Mar. attend. and interestingly. but are not necessarily pan-Maya. At Copan. 232 . Ruler C (Martin and Grube 2008:141). perhaps with the accession of a new king. images or effigies of deified ancestors are referred to as chajal. This likely reflects variation in the local mythologies between the two sites. Palenque. as evidenced by single story masonry rooms that housed the personal gods of the rulers of Chichen Itza (Houston and Inomata 2009:200). which literally means ―guard‖ or ―guardian‖ (Orellana 1984:96). the local patron gods are sometimes referred to as koknoom. for example. who appears to have had accession events both before and after he was ―born‖ (Guenter 2007:43). a practice that continued at least into the Terminal Classic. they differ on the details such as the accession date. Texts from Copan and Quirigua confirm that rulers had exclusive claim on certain gods. is a god (or perhaps a set of gods) known from Classic period Tortuguero (Monument 6). we have the names of several of their patron gods listed in conjunction with temple dedication festivities that occurred in 518. Among the Cakchiquel. from the Chilam Balam of Chumayel. Some gods are attested from multiple sites. fire and sustenance.54 There is abundant evidence for ancestor worship in the Classic period as well. and the living continue to accept the authority of the deceased (Weeks 2001:21). and is also associated with the Sun God (Sachse and Christenson 2005:15).) speculate may have held ancestral effigies (though no effigies were actually found within the niches). and the upper façade was adorned with a series of rectangular panels. Ancient ancestor shrines known as waybil – places of sleeping or dreaming for the ancestors – were fairly common as well (Grube and Schele 1990. than major gods. Structure 10L-29 at Copan may be an example of a waybil. if not more so. Offerings were burned in order to feed and conjure the gods and ancestors. heroes and ancestors are transformed into deities (Marcus 1992:301). Colonial and contemporary offerings to ancestors mirror the sacrifices the K‘iche made to Tojil (Sachse 2004:8). Burn marks are evident on the floor at the entryways 54 Tojil is a major creator god that brings rain. they are not second class citizens of the divine realm. Houston and Stuart 1989). as attested to in the iconography. It is an L-shaped vaulted building. There are eight or nine large wall niches inside its two rooms. Among contemporary Maya. which Harrison and Andrews (ibid. there does not appear to be a significant distinction between major gods and local deified ancestors. each depicting serpent heads emerging from the corners. similar to ancestor cartouches found on panels at Palenque and Yaxchilán (Harrison and Andrews 2004:132). 233 . Powerful individuals maintain their authority after death. Ancestors are equally prominent.Euhemerized Ancestors The term ―euhemerism‖ refers to the process by which dead kings. calendar priests (7ahq’ih). Ancestor worship likely began as a familial practice that linked lineages to specific landholdings. and Maya rulers were certainly not the only ones with prominent ancestors that were venerated. however. native town priests (b’o7q’ol b’aal watz tiix). which may indicate that burnt offerings were regularly made to the ancestors (ibid). Bunzel (1952:270) 234 . Worship was not limited to an individual‘s own ancestors. ―Commoners‖ buried their ancestors—but not all their predecessors—within their houses and residential compounds to lay claim to their resource rights and as a marker of inheritance (ibid). Colby (1976:75) has shown that the modern Ixil Maya pray to the departed souls of town leaders ( b’o7q’ol tenam).and in the corners of the room. McAnany (1995:161-162) argues that these interments created a ―text -free genealogy‖ that would have been known and recognized as valid by the ancient Maya but have proven difficult for modern archaeologists to interpret. Over time. which could then be used to legitimize systems of taxation and tribute (ibid:125). Not all dead relatives from whom one claims descent are ancestors. but Classic period elites modified the ideology of ancestor worship in order to validate royal claims of divinity. and curers (b’aal wat tiix) in addition to their own lineal forebears. An ancestor is a culturally constructed product of a selective process (McAnany 1995:60). domestic structures that housed the remains of ancestors were often recontextualized into a ritual shrine or temple throughout the lowland area (ibid). Ancestors represent ―a select subgroup of a population who are venerated by name because particular resource rights and obligations were inherited through them by their descendants‖ (ibid: 161). K‘inich Yax K‘uk‘ Mo‘ was not only the founder of 235 . In contrast. the first mention we ever get of him is from late 7th century retrospective texts recounting the founding of Palenque (Martin and Grube 2008:156). However. while at other sites. The inscriptions at Palenque attri bute K‘uk‘ Bahlam I with being their dynastic founder in AD 431. The dearth of evidence indicating K‘uk‘ Bahlam was worshiped prior t o the late 7th century may suggest they took a revisionist approach to their own past in regards to their founder. or even the quasi-mythological dates associated with Ukokan Chan in 967 BC. lineage heads and people of position were venerated after their deaths and their remains were given preferential treatment beyond those of the general public. dynastic founders served as culture heroes and were celebrated and worshiped for generations.0. during the Colonial period. These stone censers were typically used for ancestor veneration (Miller and Martin 2004:230). which were back in deep time. At certain Classic period sites.3). Unlike the mythological births of the Triad. Although K‘uk‘ Bahlam eventually came to some prominence.similarly demonstrated that deceased public office-holders were invoked along with an individual‘s own ancestors in the church at Chichicastenango because they are believed to now hold positions of authority in the world of the spirits.13. Landa (Tozzer 1941) confirms that. who is identified by elements in his headdress that convey his name (Fig.18. A stone censer from Palenque portrays K‘uk‘ Bahlam. his importance to the dynasty is dwarfed by the significance that Late Classic rulers placed on their purely mythological founders. the texts give K‘uk‘ Bahlam‘s birth date as a believable 8.6 5 Kimi 14 K‘ayab (30 March 397). 4. the founders are virtually forgotten by their successors. the presence of the ―Principal Bird Deity‖ (PBD) appears to have provided supernatural sanction for important ritual events. While their presence was an integral aspect of rituals. The Actions of Gods and Ancestors Having discussed what gods and ancestors are. but a revered culture hero as well.‖ as on Caracol Stela 6 when a deified ancestor ―sees‖ the censing ritual performed by Yajaw Te‘ K‘inich II (Fig.the Copanec dynasty. a cult of veneration began and was consistently maintained for nearly four hundred years (Martin and Grube 2008:194). deified kings were still involved in ―consultations. The gods and ancestors role was to ―see.4. From the moment of his death. In some instances. Houston 2006:142). their yilaj or ―seeing‖ role was not on par with the ukabjiiy or authorizing role associated a superordinate ruler‘s presence. oversight committees (albeit supernatural ones). we now turn to what it is they actually do. or mortuary bundle. effigy censer. they were understood to be present and co-participants in the rituals (Looper 2006:827). Rice (1999:41) argued that modeled image centers were believed to be living representations of deceased ancestors that functioned as ―m aterial implements of power‖ for rulers who claimed to interact with or receive divine inspiration from the dead. and other forms of episodic contact. such as accessions (Bardawil 236 . whether through ethereal smoke or in a more tangible form such as a statue.‖ Although typically depicted as peering down from the heavens. One of their primary responsibilities was to be present at royal rituals. As Fitzsimmons (2009:15) notes. 4. The West Wall murals from San Bartolo depict it atop the four directional world trees (Taube et al. 55 David Stuart first proposed the reading Mut Itzamnah in a personal letter to Linda Schele in 1994. 2010).:4). 2010:31-41). 20 and 113. In the Classic period. the PBD seems to have been the avian aspect or avatar of Itzamnaaj. where it appears on the accession monuments of several rulers (see Chapter 3). 2010:37). Its presence can be found in the Classic period at Piedras Negras. but it was also associated with maize. the PBD appears to have had strong solar associations and may have been a particular aspect of the sun. where it is referred to as the Ave de Pico Ancho (ibid. 237 . agricultural fertility and wealth (Taube et al. Plate 75) and Xcalumkin (Guernesy 2006:169 Note 32).1976:15-16) and sacrificial offerings (Taube et al. however. Yet it continued to be depicted in the Late Postclassic and it appears in the Paris Codex (Taube 1987). The PBD may have originated with the Olmec (Taube et al. and is even directly called Muut Itzamnaaj (―The Itzamnaaj Bird‖) in Classic period texts from Tonina (Miller and Martin 2004:145. the arrogant bird with solar associations (Bardawil 1976. In the Preclassic period. 55 But it is also identified with Vucub Caquix of the Popol Vuh. Altar 10. Taube et al. but depictions of it are found most commonly in the Preclassic and Early Classic (Cortez 1986). the Principal Bird Deity even transcended cultural boundaries and extended into the Zapotec area. Beyond its temporal longevity. but it is not as dominant as it was in the Preclassic or Early Classic. Stela 2) and ubiquitous on Izapan monuments (Guernsey 2006). It is common on monuments from Kaminaljuyu (ex. 2010:35). Altars 13. Stela 11). Takalik Abaj (ex. 2010). Marcus (1976:43) suggests these may have been symbolic or abstract ancestors rather than lineal forebears. 2. More recently. La Venta Stela 2 (Fig. 4. and the very presence of these supernatural beings suggest that the ruler is qualitatively different. ancestors were commonly depicted as down-gazing deified heads that appear directly over the head of the living ruler. For example. Both gods and ancestors frequently bear sacred objects that we may conclude are being offered to the king. Unlike the Middle Formative Olmec depictions of supernaturals who seem to pass ritual objects to the ruler.Overseeing of Rituals A common trope denoting a god or ancestor was a ―floating‖ figure in relation to a living individual. however. who all wield ritual objects identical to the one he holds in his hands (Newsome 2001:17-18). but the purpose they served was to legitimize the king‘s right to rule.5) and Takalik Abaj Stelae 2 and 3 (Marcus 1976. which established his divinely sanctioned right to rule. the Late Preclassic and Early 238 . Stuart (1988:221) suggested the six floating supernaturals on La Venta Stela 2 were royal ancestors that were invoked to pass sacred regalia to the ruler. Taube (2004:15) suggested they are forms of the Olmec rain god who don ballplayer regalia (as does the ruler) and the objects they wield are shinny sticks for playing stickball. such as Kaminaljuyu Stela 11 (Fig.15) shows a ruler surrounded by floating supernaturals. he is the one with visionary and cosmological powers that only he can control (Newsome 2001:17). Tokovinine and Fialko 2007:4). Houston 2006:142). In the Preclassic and Early Classic periods. often appearing in S-shaped scrolls to mark their divine status (Stuart 1984:11. The Classic period ―floater‖ convention has its origins in the Formative period (McAnany 1995:161). Tate 1992:59-62. the front of Naranjo Stela 45 (Fig. demonstrating a growing conceptual linkage between ancestors and the sun in the Classic period (Martin 2006:158. Aj Wosaj Chan K‘inich (Martin 2005a:8). depicted as one of several ancestors on Naranjo Stela 43 (late sixth century) about two hundred years after his death. suggesting 239 . Interestingly. Taube 2004b:286-287). Fig. who may have been an ancestor to Aj Wosaj Chan K‘inich (Houston 2009:162). Houston et al. where he floats above the protagonist. At Yaxchilán. Interestingly. Floaters could appear alone or in groups. Naatz Chan Ahk himself appears to have become a deified ancestor. For example.7).6) depicts a little known deceased ruler named Tzik‘in Bahlam as one of these disembodied ancestral heads floating directly above the protagonist. 2006:156). which appears to denote solar heat or ―hot breath‖ and is sometimes used as a diagnostic feature of the Sun God (Stuart 2005:23. By the Classic period there is a shift away from disembodied floating heads to fullbodied ancestors who sit above the ruler in solar cartouches or in clearly demarcated upper registers of scenes (Tokovinine and Fialko 2007:4). deceased male rulers are typically in solar cartouches and their deified consorts are within lunar cartouches (Tate 1992.Classic period ―floaters‖ appear to have had a more passive role as witnesses of the events whose mere presence served to sanction them. Naranjo Stela 43 depicts several gods and ancestors floating above Aj Wosaaj Chan K‘inich (Martin 2005:8). for example. The solar cartouches that the ancestors sit in are elaborated glyphs for yaxk’in (‗first sun‘). Ancestors at times display the ―Zip monster‖ squared snout. 4. the ruler Naatz Chan Ahk (Tokovinine and Fialko 2007:4). 4. one of the other ancestors is identified by the glyphs in his headdress as Chak Tok Ich‘aak II. 1.10. Fig. The Hauberg Stela may depict both a floating ancestor and these types of ―travelers‖ (Fig. such as trees.8) appear to depict floating ancestors (cf. (2010) suggests they are supernatural ―travelers‖ that bridge the natural and supernatural realms in transitional or liminal periods. as on 240 . and the mortuary bundle may be that of his mother or perhaps another prominent female ancestor (Hammond 1981).0. and smoke.0) and Jimbal Stela 1 (10.equivalency between ancestors and the Sun God and carrying connotations of the postmortal paradise of Flower Mountain (Taube 2004a). At first glance. Curiously. which may be an intentional contrast to the deified women of Yaxchilán (a rival of Piedras Negras). 4. who typically have lunar rather than solar associations. Marcus 1976:42). the mortuary bundle on Stela 40 from Piedras Negras emanates this hot breath from a burial vault (indicated by a partial quatrefoil) that rises up above the skyband and then descends upon the supplicant who offers incense. They are sometimes embodied in jade jewelry and worn as pectorals or hanging from belts (Houston 2006:142). the Late Classic Ucanal Stela 4 (10. They are typically depicted riding or clinging to objects that traverse the three levels of the universe. The supplicant is Ruler 4.0.9).2.0. Interestingly. Her exaggerated size denotes her ―supranormal status‖ (Stone 1989:168) and her Teotihuacan -style headdress was likely used to imply dynastic ties. but the figures lack any kind of ancestral referent and are likely some other class of being (McAnany 1998:284). These ancestral portraits could visually depict a ruler‘s name in their headdress or on their forehead.0. WilsonMosley et al. she emanates hot. There is another class of ―floater‖ that may not represent ancestors. twisted ropes. clouds. umbilical cords. solar breath. 4. Ancestors are not limited to the ―floater‖ form. Pakal is shown impersonating a quasi-historical ruler that supposedly ruled Palenque in 252 B. and even deified ancestors could be merged into one.C. It highlights the importance of dynastic founders. Naranjo Stela 45 presents a nice case study that brings together several concepts introduced up to this point (Fig. We again see him.8). Schele and Miller 1986: 114). 2.the belt ornament from Caracol Stela 6 that depicts K‘ahk Ujol K‘inich (Houston and Stuart 1998:86 Figure 11). The presence of ancestors during rituals is common at Palenque. Death did little to prevent Pakal from participating in the ritual activities of his descendants. essentially giving voice to the dead ancestors (Taube 2005:32). for example. both mythical and historical. local gods. 241 . Naatz Chan Ahk. In one scene. The monument depicts Naranjo‘s living ruler. a fully grown Ahkal Mo‘ Nahb sits in the company of Pakal. the suspended slats of jade would emit loud. apparently holding a ceremonial bar while Naranjo ‘s founder. and it demonstrates the way major gods. The whole composition is intended to link Ahkal Mo‘ Nahb back to the beginning of Palenque‘s dynasty. 4. The Palace Tablet. 2.8). on the Temple XXI Platform commissioned by Ahkal Mo‘ Nahb. which is clearly contrived since Ahkal Mo‘ Nahb was just a child when Pakal passed away (Miller and Martin 2004:232). deceased ancestors are depicted interacting with their descendants as if they had never died. shows an adult K‘an Joy Chitam II engaged in a ritual while his long-dead father and mother (Pakal the Great and Lady Tz‘akbu Ajaw) flank him as if they were alive and well (Fig. Instead. distinctive clinking sounds. In an adjacent scene. seemingly alive as ever. thus legitimizing his right to rule (Fig. though they typically do not use the ―floater‖ trope.38. As a ruler walked or danced. owned by] god‖ (Grube and Schele 1990:3). ―the sleeping place of [ie. At Chichen Itza. and as such. Small house models from Copan were anciently designated as u-waybil k’uh. perhaps suggesting it is intended to identify a specific entity rather than merely denoting the metaphorical concept. for example. such as the pib naah56 or inner sanctuary atop the Temple of the Foliated Cross. Tzik‘in Bahlam is merged with the mythological founder of Naranjo‘s dynasty.Tzik‘in Bahlam. Gods as “Owners” Classic Maya deities were often considered active participants within a community.attributes ownership of these objects to the gods. Palenque‘s gods were presented with u-pik (―its skirt. as indicated by the mirrored eyes (Tokovinine and Fialko 2007:10). whi ch was ―owned‖ by GII according to the alfarda tablet (Stuart 2005:19). Lintels 2 and 6 both name 56 Pib naah or ―pit-oven structure‖ may have originally been a term for sweat bath (Stuart 2005:102. dressings‖) (Stuart 2005:166). a deity of local prominence known as the ―Square-Nosed Beastie. Divine ownership of larger structures was extremely common during the Postclassic. looks down as a floating ancestor. in this instance the entire compound denoting the name of Naranjo‘s mythological founder is present. Houston 1996) 242 . They could also own specific buildings at Palenque. Although the ―fret -nosed serpent‖ motif associated with this god is often used metaphorically to denote the heat of the sun or the warmth of living breath (Taube 2005:37). Ownership of an object was marked by the possessive u-.‖ This hybrid of Tzik‘in Bahlam and the Square -Nosed Beastie is further merged with the Sun God. The 3rd person possessive ergative u. they could own property or objects. as well as local gods that were 243 . 2. The epithet k’uh is always used in reference to personalities that could be called gods (Houston and Inomata 2009:198). deceased rulers. or dancing the sacred bundle (Carlsen and Prechtel 1991:27-28). and foreign dignitaries are all virtually identical (Fig.7). ideally so. The Sun God can at times appear fully human. and no divine epithets.‖ or symbolically through prayer. Among modern Atitecos. Humans and gods were essentially of the same species. which included major gods such as the Sun God and the Maize God. There are no god markings. The Temple 11 bench is a prime example. Whatever the form. Others gods took the form of animals. on the Casa Colorada Hieroglyphic Band text the god Yax Uk‘uku‘m K‘awiil is also said to be the ―owner‖ of the first fire -drilling. 2003:65). the burning of copal incense. The Classic Maya appear to have had an emic distinction between gods and other classes of supernatural beings. where patron gods. to the point where they are virtually indistinguishable from humans. the Flowering Mountain Earth can literally be fed through a hole in their land that is called r’muxux ―umbilicus. The Maize God is similarly quite human. other than his large eyes. The Morphology of Maya Gods Maya gods are commonly depicted in fully human form. they were all considered living entities in need of sustenance. suggesting ritual actions were also possessed. Interestingly. while others were animated versions of features of the natural landscape. like mountains or caves.the gods Yax ?-che Kan and Yax Uk‘uk‘um K‘awiil as the owners of the house (Grube et al. no large eyes. Akan is not divided into manifestations and appears to have been elevated to the status of a god (Grube 2004:74). De Landa (Tozzer 1941:161) informs us that ritual specialists were charged with carving effigies out of cedar wood. illnesses or spells (Houston and Inomata 2009:208. They are never assigned the divine epithet k’uh nor do they ever directly interact with beings that are labeled k’uh (Grube 2004:74). but in some instances the wahy appear to have been linked to a particular dynasty rather than with an individual ruler. The Classic period wahy Akan. which is still referred to as k’uche’ or ―god tree‖ by the Yucatec Maya 57 In the Postclassic. some wahyoob’ also appear to have had multiple manifestations. Similar to gods. and Stone-throwing Akan. ceramic effigy censers (Price 1999). wooden statuary (Tozzer 1941). among others. Although not completely understood.confined to specific sites. Newsome 1998). Ch‘ak Ubaah Akan (―self decapitating Akan‖). Gods and deified ancestors could be embodied in a variety of media. and stucco friezes (Robertson 1985). such as stone stelae (Stuart 1996. some Classic period wahy may have been personifications of disease. Perhaps the most common type of supernatural entities not classified as gods from the Classic period are a fantastical and often terrifying class of beings called wahy (Calvin 1997). Both humans and gods could have wahy spirit companions.57 The Materialization of Gods and Ancestors Ancestral representations (or even their remains) were particularly prized by communities and were used as validation for genealogical claims (McAnany 1995:27). has distinctive manifestations where he is specifically given different names. for example. 244 . Zender 2004:72-77). such as Ux Pik Akan. Houston (1996) noted that sweatbaths were connected to pregnancy and childbirth. imbue them with life force. as evidenced by the gods that carve masks in the Madrid Codex 96d and 99d. but this appears to have been purely symbolic as there is no evidence that any type of heating apparatus was present (Moyes 2005). Following such a mythical template. Effigy Censers and Censer Stands Censers (and at times even their stands) were integral to the worship of gods and ancestors in the Maya area for generations. These ―activated‖ images were then delivered to those who commissioned them. Gods could be conceptually ―born‖ in ritual structures known as pibnaah (literally ―sweatbath‖). The work of carving was also attributed to the gods themselves in the Late Postclassic Yucatan. Each of the Cross Group temples are named as a pibnaah for each corresponding member of the Triad. portals between the human and divine planes.(Tozzer 1941:159-160). the teotl was put into the ixiptla. and sustain and care for them with tenderness. they are broadly lumped as either effigy (image) censers or non-effigy (non-image) 245 . Although they were produced in a wide array of shapes and sizes. incense was fed to the statue and prayers were offered to animate the effigies. and were used to restore the ―heat‖ or energy that women lost during childbirth. The priests were expected to fast and be sexually abstinent while engaged in the work of carving lest some unspecified danger befall them (ibid. Taube (1999:427) notes that censers served as the symbolic hearth of a temple and they functioned as axis mundis. in Nahuatl terminology. rulers would likewise create their gods. After the carving was done.:161). and as is expected. there is a great deal of local and regional variation in their production and distribution (Rice 1999:32). a group of ceramic specialists were commissioned to produce a new set of ‗appropriate‘ ritual paraphernalia. Unlike the Classic period effigy censers from Palenque that depicted 246 . 1979:4). For example. It makes a rather sudden appearance after the inauguration of Kan Bahlam II. 1993:454). spiked censers are extremely common in the Peten. The use of this new style was so drastic that Rands et al. (1979:22) suggested ―it is as if. The most well known type of censer stand from Palenque is of the large. chronological variation in censer types within a single site was also common. and in Belize. Effigy censers or censer stands also take a variety of shapes and sizes. this specific form did not appear there until the Late Classic. however. Non-effigy incensarios are typically either bowl shaped or take the form of a pedestal (often biconical) and usually have some type of decorative elements such as fillets or spikes. Beyond geographical variation. but are unified as a type by being anthropomorphic or zoomorphic representations of supernatural beings and ancestors. effigy censers were referred to as ox p’uluut k’uh. but are virtually unknown at Palenque (ibid). which were representative of the thorny trunk of the ceiba tree (Freidel et al. which seems to have been a ―time of intensive ceremonial innovation and redirection‖ (Rands et al. distinct groupings of interred censers and stands demonstrate temporal variation in their local iconographic and stylistic conventions (Cuevas Garcia 2004:255). At Palenque.‖ Glyphically. the southeastern periphery. with a new royal administration. The Lacandon continued to use ―god pots‖ until about 1970. flanged effigy variety. literally ―god censers‖ (Cuevas Garcia 2004:254). for example.censers. identifiable individuals (be they gods or ancestors).‖ Schele (1978) was the first to 247 .10). so the effigy censers interred there would have been conceptualized as seeds and were planted in anticipation of their eventual regeneration. Linda Schele (1978:4647) noted that in the Popol Vuh. such as GI or the Jaguar God of the Underworld (Fig.‖ and after the span of a typical human lifespan they would be interred (Cuevas Garcia 2004:234). The cycle of death. burial.11). the word used to indicate offerings or sacrifices to the gods is tzuqul. 4. and rebirth associated with these censers and the gods they represented would have been exemplars for the living rulers who commissioned them. which almost certainly represented deified ancestors (Stuart and Stuart 2008:196). They were effectually ―born. these effigy censers literally had lives of their own. Royal Treatment of Godly Images The manner in which gods were cared for by the rulers has been compared to the way a child is cared for by its parents. At Palenque. The Lacandon similarly buried their censers (ibid: 255). Censer stands buried in the Cross Group complex depict the faces of important gods. That these human figures would be intermixed with those of GI and the JGU suggests an equivalency between the deified ancestors and the ―major‖ gods. a word that also means ―to nurse a child. more specifically by its mother. the Lacandon god pots served as abstracted mediums through which their offerings were transmitted to the gods for consumption. 4. The Cross Group was a conceptual entrance to the Underworld. but they also take the form of realistic human portraits (Fig. such as on the panel of the Foliated Cross which notes that several gods. The incense feeds the ancestor through a knotted breath cord that passes through the nose of the ancestor (Martin and Grube 2008:148). ―appeased the hearts of his gods‖ (Carrasco 2005:78). likely his mother. 2002:75). 4. 248 . are the huntan of K‘an B‘alam II (Freidel et al. who is dressed in Teotihuacano garb (Martin and Grube 2008:148). Houston and Stuart (1996:294) reject the suggestion that rulers would thus be considered ‗mothers‘ of the gods (cf. We frequently find this expression at Palenque. The most vivid depiction of the symbiotic relationship between rulers and their sacred ancestors comes from Piedras Negras Stela 40 (Fig. including the Sun God. now read huntan and translated as ―cherished one‖ (Stuart 1997:8) or ―precious thing‖ (Houston and Stuart 1996:294). The West Panel (A7-A8) suggests the offerings of K‘inich Janaab‘ Pakal utimiw yo’l uk’uhil. Although the huntan glyph is used to denote the tender relationship between rulers and their gods. The inscriptions at Palenque generally give us the most explicit textual references to the way gods were propitiated. which depicts the living Ruler 4 offering incense through a psychoduct into the quatrefoil shaped burial chamber of a female ancestor.‖ and it gives us a rare personal glimpse into ancient ancestor worship.recognize the glyphic phrase that comprised a parentage statement linking mother to child.12). Schele and Freidel 1990:475). Schele 1978:8. and in return the ancestor emits ―hot energies‖ (Houston and Inomata 2009:213). Houston (2004:275) describes the ritual as ―loving or pious. The Cross Group is full of references to the Palenque Triad being the ―cherished ones‖ of the rulers (Staurt and Stuart 2008:191). It notes that in 1550. [that of] Taçacto. that of Tachabt.‖ as one of his most significant responsibilities is to carry Maximόn on his shoulder during Semana Santa (Carlsen 1997:152). Properly caring for and propitiating the gods was vital for the well-being of their society (McAnany 2001:142). The richest body of data from the Classic Period concerning this ritual comes from the Central Tablet of the Temple of the Inscriptions (Stuart and Stuart 2008:191). the devil of Tadzunun. that of Atapan. the god Maximόn is carried by his personal shaman (aj’kun). In contemporary Santiago Atitlán. The aj’kun also bears the title telinel. The inscriptions inform us that K‘an Joy Chitam and K‘inich Janaab‘ Pakal gave vestments to the Palenque Triad to commemorate the turning 249 . each with a designated priest from one of the prominent founding lineages who would collect tribute for their patron god (Carmack 1981:264-281. The gods would be brought out from their shrines and ritually paraded through town on calendrically significant dates. in effort to eradicate idolatry. ―shoulder.The personal gods of the rulers appear to have had preeminence at their respective sites. and the other devils. Frey Diego de Béjar invited the rulers of several cities to Tamactun Acalan in southern Campeche (where he was residing) and encouraged them to bring forth their ―devils‖ (cizin).). All these they carried before Fray Diego de Béjar and he burned them‖ (ibid. The K‘iche likewise built temples for their gods. Tedlock 1985:208-209). One of the ritual responsibilities of rulers was the ―dressing‖ of their patron gods. he ―began to remove their devils: Cukulchan. A Chontal chronicle suggests the principal temple of a town was typically a house for the ruler‘s god (Scholes and Roys 1968:56). derived from the root telek. Once they had gathered. the devil of the ruler. helmets. earflares. the glyphs also indicate that monument itself is Yaxhal Chahk and provide the date when he was ―erected‖ (Fig. There are a number of ancient references to the capture and/or destruction of gods during episodes of warfare. 4. However. Among modern Mesoamerican communities. were more than mere depictions. be they wooden effigies. They were the gods (Monaghan 2000:26-27). Guatemala bears the portrait of the rain god Yaxhal Chahk and the inscription indicates that Yaxhal Chahk was the ―owner‖ of the monument. necklaces. rather than their native gods. Landa (Tozzer 1941:148) describes the manner in which idols were dressed and adorned with headdresses and jades. the ―Quadripartite Badge‖ and the Jester God (Macri 1988:117 -120. 2006). To capture or destroy one of these images was conceptually equivalent to killing that god. or ceramic censers. stone monuments. Stuart 2005:166-167). 1997:91-92. which denotes their sacrality.13). Some of these objects were given the qualifier k’uhul. Capture and Sacrifice of Gods Images of gods.of each K‘atun (ibid). Quirigua Stela I recounts the capture and fire-drilling (which has connotations of sacrifice 250 . which included headbands. or at least receptacles of godly essence (Houston et al. This practice of dressing the gods continued through the Colonial period and is still attested among contemporary Maya groups. they dress images of Catholic saints in ceremonial huipiles and adorn them with necklaces of gold coins (Stuart and Stuart 2008:191). David Stuart (1996b:158-159) noted that Stela 3 from the Early Classic site of El Zapote. At the Postclassic Yucatecan site of Mayapan. the patron gods of Waxaklajuun Ub‘ah K‘awil of Copan (Fig.15. According to the House C Hieroglyphic Stairway. Looper 2003:78). Tikal Temple IV Lintel 2 depicts the capture of Naranjo‘s patron god. ―stranger-image. This caused great mourning at Copan. however. Nuun Ujol Chak captured the war god of the prince and heir of Yaxchilán. which may suggest the literalness of the expression yalej.14.per Miller and Taube 1993:87) of Chante Ajaw and K‘uy Nik Ajaw. At Comalcalco. 4.‖ was seized and subsequently cared for by a noble (Houston and Inomata 2009:174). Among the Aztec. 4. no pyramids. no places‖ (Stuart 1996a). who takes the form of a battle palanquin (Fig. Martin 1996:7). 251 . and a portion of the text on the Hieroglyphic Staircase that records the aftermath of that event laments that there were ―no altars. Book 2:168). In 58 It is possible that ―plain‖ stelae were originally painted (Inomata 2006:834). the effigies of an enemy‘s gods would be captured and then housed within a temple at Tenochtitlan (Sahagún 1950-1982. the Palenque Triad was yalej. On 7 August 659 AD. ―thrown down‖ (Grube 1996) during the reign of Lady Yohl Ik‘nal on 21 April 599 by a ―chi-throne‖ vassal of Sky Witness of Calakmul (Martin and Grube 2000:159 -160). Itzam Balam. we find evidence that three carved and seven plain stelae – which were vessels of supernatural energy – were literally thrown down from temple Q126 during the Mayapán revolt around 1440 AD (Shook 1955:269-271). The burning of idols was similarly described in the Colonial era (Scholes and Roys 1968:56). one of the inscribed stingray spines found within a burial urn seems to indicate that a tz’ulba.58 Foreign gods were not always destroyed. The Maize God was a pan-Maya deity. Although many aspects of modern Maya beliefs and ritual practice have demonstrable continuity from earlier periods (B. Ethnohistoric and ethnographic data must be treated cautiously. others may be intrusions from Catholicism. It appears to have both great time depth and remarkable continuity from the Formative to the Late Postclassic. when warriors conquered their enemy in pre-Hispanic times.addition. According to modern tradition. they sometimes adopted the god of the vanquished people (Schele and Grube 1995:31). Hill and Monaghan 1987). Becoming a Deified Ancestor Unlike the Egyptian Book of the Dead. so we are left to reconstruct it from obscure clues in the epigraphy and iconography. it is sometimes difficult to disentangle Christian influence on beliefs or Colonial period interpretations of native beliefs that have been filtered through the lens of Christianity. Christ rises to the heavens after his crucifixion and transforms into the sun and travels along ―his road‖ in the sky accompanied by the souls 252 . there are no overtly eschatological texts that have survived from the Classic Maya. The mythology of a dying and resurrecting Maize God is fairly well fleshed out (as it were) in ancient iconography. who stands as one of the common denominators that served as a baseline similarity against which contrasts with others could be made (Harrison 2003:345). Tedlock 1982. Although a rich body of ethnohistoric and ethnographic literature exists that discusses native conceptions of the afterlife. and many elements of it appear to have survived until the present day. Virtually all modern Maya societies conflate Jesus Christ with the Maize God. they say that a great star was made that is called Hesper [Venus]‖ (Aldana 2003:36-37). The belief in deification of deceased rulers continued in Mesoamerica through the Late Postclassic period. The assurance that new life would follow death came not only from observing the sun in its daily journey. and material concerns (Westheim 1957:59). From the smoke that came from his body. in the custom of burning dead bodies. They turned into spirits or gods" (translation in Westheim 1957:59). Quetzalcoatl‘s soul dwelt in Mictlan for eight days. there is no known glyph for Xibalba or the Underworld (Fitzsimmons 2009:15). . but also from maize in its seasons of planting and harvesting. but they once again began to live. The Histoire du Mechique records that Quetzalcoatl ―shot an arrow into a tree and entered it. According to Sahagún (1950-1982). 253 . and on this account they regarded him as a god‖ (Tozzer 1941:157). and died there. known by names such as Metnal or Xibalba (which means Place of Fright). and afterwards it appeared as a star in the heavens (Carrasco 1982:148). ―there were among the Indians some who said that he had gone to heaven with the gods. . and his servants lit the tree on fire. Landa records that after Kukulcan had departed the Yucatan. The soul is a vital essence that is indestructible and transcended temporal. 59 Recent scholarship (Taube 2004a. ―The old men used to say that when men died they didn‘t perish. 2006) has shown 59 Although there is no shortage of Underworld imagery on Classic period ceramics and monuments. spatial. There is a common misconception that the only afterlife expected by ancient Mesoamericans was the dark Underworld. The Quiché Maya likewise believe their ancestors become stars after death (Graulich 1997:111).of ancestors (Sosa 1985:429-430). where he would be deified as the Sun God. Flower Mountain is depicted in Maya art not only as the desired destination after a ruler‘s death. but also as the paradisiacal place of creation and origin.that there was clearly a belief in a solar paradise as well. Caracol. the solar component is wholly Mesoamerican. and of those.C. it is indeed curious how rarely kings were represented as having been apotheosized (Fitzsimmons 2009:53). ―although the notion of a floral paradise recalls Christian ideals of the original Garden of Eden and the afterlife. reserved for those who could overcome the gods of the Underworld. Thirteen of these depictions come from Palenque.) and is also attested to among the Late Preclassic and Classic Maya as well. Between the six polities. Jane Hill (1992) demonstrated the tradition concerning this ―Flower World‖ has been maintained through the centuries and continues be found among modern Native American groups in American southwest.‖ Evidence for the belief in Flower Mountain dates to the Middle Formative Olmec (900-400 B. Out of the hundreds of known depictions of rulers found on a wide variety of media. Evidence from the Classic period Maya suggests that only those who were kings or other high nobles could look forward to resurrection and a return to this diurnal paradise and dwelling place of the gods and euhemerized ancestors.D. Only about a dozen such monuments have survived from a mere six polities: Palenque. from about 300 B. with a total of about 25 identifiable individuals (Fitzsimmons 2009:55). Taube (2004:70) notes that. Yaxchilán. 900. 254 . Tikal. Copan. only eleven rulers commissioned monuments that clearly depict apotheosized ancestors. called ‗Flower World‘ or ‗Flower Mountain‘ (Taube 2004a).C. and Ek‘ Balam. – A. and spanning nearly five centuries. which can be roughly understood as ―transformation and renewal‖ (Carlsen and Prechtel 1991:30). The Cycles of Death and Rebirth The rebirth of maize was a metaphor for human rebirth. These elements are all common in the iconography related to the rebirth of the Maize God. It also carries connotations that from one comes many. ―Agriculture and eschatology are intimately associated. who must fight their way out to be (re)born (Girard 1995:191). we will take a closer look at each of the monuments from these five sites. which requires heat. K‘inich Kan B‘alam II and his successor K‘inich K‘an Joy Chitam II were the only rulers to create such depictions at their site. Among the modern Tzutujil Maya. After a discussion about the process of resurrection and deification.‖ as it were. The seed planted in the earth is likened unto a child in the womb or an entombed body.ten appear on a single monument. and darkness (Carrasco 2010:620). Jal refers to the observable transformations that occur throughout the life cycle of something. the maize cycle is explicitly likened unto human change throughout an individual‘s life and regeneration after one‘s life is over. As Rafael Girard (1995:191) noted among the Ch‘orti‘ Maya. yet carries with it implications of continuity and renewal from one generation to the next.‖ The iconography associated with the rebirth of the Maize God appears to emulate the stages of growth of a maize seed (Taube 1985). water. K’ex is more concerned with generational change. just as a single seed can produce countless 255 . the ―husk. Notably. The concept is expressed with the phrase jaloj-k’exoj . it is a vehicle for immortalizing them (Mondloch 1980. Relying on iconographic data found on a variety of media from across the Lowlands. They break it down into four principal ―episodes‖: rebirth of the unadorned Maize God in the watery Underworld. 256 . Quenon and Le Fort (1997) have created a meta-narrative of the Maize God resurrection cycle. 61 Funerary pyramids were conceptual recreations of Sustenance Mountain (Martin 2006:160). 60 A fifth episode. k’ex is invoked when giving a child the name of its grandparent. His triumph from beyond the grave is that his offspring partake of his fruit and seeds and go on to perform heroic deeds. but ancient scenes depicting this event are not as frequently depicted (Quenon and Le Fort 1997:885). Although some attempts to link the narrative contained in the Popul Vuh to the Classic period may be strained. they distinguish between the terms ―rebirth‖ and ―resurrection‖ in this cycle. followed by burial in a cave or in Sustenance Mountain. his transit out of the watery Underworld (typically in a canoe). Taube 1985.61 A portion of his soul or spirit then leaves his body and rises to the heavens. the death and sacrifice of the Maize God. is also briefly discussed. ―rebirth‖ refers to the animation that occurs while the Maize God is still in the Underworld. Martin (2006:178) similarly outlined a panMesoamerican Maize God narrative that begins with death. the basic Maize God narrative is abundantly attested to (Martin 2006. Among the K‘iche‘. 1986). his dressing and adorning by beautiful young maidens. cf Warren 1989:57). which produce edible fruits and seeds. whereas ―resurrection‖ refers to the moment when he emerges from the Underworld by bursting through the surface of the earth from a crack or other opening (Quenon and Le Fort 1997:898). 60 Although often used synonymously. Trees spring from his buried corpse.offspring (ibid). and culminating with his glorious resurrection bedecked in his finery. trees were powerful symbols of resurrection and seem to have constituted a bridge between death and rebirth (Martin 2006:178). on K731 the lightning is named Yo‘at/Yo‘pat (Looper 2003:5) 257 . The Lightning God played an instrumental role in the Maize God‘s resurrection (Taube 1993:67). Unsurprisingly. There is a conceptual overlap with maize plants and trees. his beaded or net skirt and the belt assembly made with a xok-fish spondylus shell that he receives in the ―dressing‖ scenes are remarkably consistent throughout the Maya area (Quenon and Le Fort 1997:884).16). In some instances of Classic period mythology. To wear the xok-fish head was to assert one‘s impending rebirth (Quenon and Le Fort 1997:890). it specifically hearkens to the ―dressing‖ scenes wherein the Maize God receives his adornments in preparation for resurrection. At 62 Curiously. cacao was believed to be the first food grown from the body of the Maize God (Martin 2006). Many Classic polychrome vessels depict this moment. such as K731 (Fig. not just that of maize (Martin 2006). since the process had already been completed (ibid). He is sometimes depicted bearing large ―burdens‖ (kuch) of grains and riches (Stuart and Staurt 2008:179).Although some aspects of the Maize God narrative are subject to regional variation. When rulers don a xok-fish head during Maize God impersonation rituals. post-resurrection depictions of the Maize God typically show him without the skirt. 62 To be clear. which was conceptualized as a giant turtle carapace. Like the maize plant. The net skirt is emblematic of the turtle carapace from which the Maize God emerges. 4. With his lightning ax he would crack open the earth. the Maize God cycle metaphorically represented all agricultural fertility. 4. Ek‘ Balam Stela 1 depicts the site‘s fourth ruler. an apotheosized figure surrounded by a solar cartouche is seated on a throne comprised of the celestial sky band (Fig. Above him. this is the same individual discussed earlier that is depicted as the Maize God on Capstone 15 (ibid:47). an action emulated by human rulers (as discussed in Chapter 2). K’uh…Nal. the Sun God was also a symbol of rebirth and resurrection. both in life and in death (Cohodas 1976:162ff). The text directly informs us ub’aah K’uhul Kalo’mte Ukit Kan Le’k. donning the paraphernalia of rulership. he not only brings new life to humanity but he essentially centers the cosmos and brings order to the chaos (Martin 2006:179). 4. 4. These vessels may have been used as mediums through which the living could communicate with the dead. appear to refer to the death and apotheosis of Butz‘ Chan. Iconographically. Ukit Kan Le‘k‖ (Grube et al. 2003:67-68). The inscriptions on Stela H from Copan.18). for example.17). tree-like ceramic vessels (found under the floor of Structure 10L41a) depict human faces floating on their surfaces (Fig. which is linked to Stela H by a distance number.Late Classic Copan. ―it is the image of the Holy Kaloomté. including the cloth headband. suggesting the ancestors were literally reborn as (or through the aid of) trees (McNeil 2010:309). 258 . Like the Maize God. suggests Butz‘ Chan was also apotheosized as the Sun God (Newsome 2001:132).19). The solar imagery associated with Stela A (Fig. Similarly. Conversely. he is depicted in the guise of the Maize God (Stuart 2005:183). Maya rulers explicitly linked themselves with the Sun God. Stuart (1996b:166) notes that ―the Maya sun god himself often wears the accouterments of rulership. When the Maize God resurrects as the World Tree. Notably. Death was metaphorically expressed as och ha’ ―enters the water.‖ implying a descent into the Underworld. and his death was conceptualized as the sun‘s descent into the Underworld (Bardsley 1994:4).20). such as on Heiroglyphic Stair 3 Step III (Fig. the inauguration of a new ruler was the dawning of a new sun on a polity. and his profile closely resembles the panMaya Sun God and is even portrayed with a small k’in sign on his cheek on an Early 259 . Solar and lunar cartouches were sometimes used to indicate the deification of ancestors. Contemporary Ch‘orti Maya associate the cardinal direction west not only with the dying sun. 4. The cartouche was emblematic of the Sun God at Palenque and Yaxchilán. GI of the Palenque Triad had strong solar associations. But after death.‖ likely a reference to the celestial road of the sun associated with resurrection and rebirth (Taube 2005:42). ―Sun Lord‖ (Stuart 2005:175). but as the entrance to the Underworld and the abode of the dead (Girard 1949:641. Dynastic succession was likened to the cycle of the sun.suggesting that he was considered the ruler of the heavens. GIII of the Palenque Triad has solar associations (Schele and Miller 1986:50). His name glyph is typically prefixed by the k’inich honorific. followed by a cartouche containing a face in profile. ―enter the road. deified kings would continue to rule in the heavens. where it is found within the belly of the Starry Deer Crocodile (Stuart 2005:167).‖ Merged with the Sun God. a resurrected ruler was expected to och b’ih. Wisdom 1961:482). The cartouche is oftentimes occupied by the Sun God himself. Stuart (2005:176) suggests GIII may have been Palenque‘s localized version of the Sun God. and his standard identifying glyph is sometimes substituted with the compound K‘inich Ajaw. GI ―served to animate the larger theme of ancestral resurrection through the sun‘s eastern ascent‖ (Stuart and Stuart 2008:198). ―heated torch sorcerer. a name similar to K‘inich Tajal Wayib‘ has been found inscribed on cache vessels from the Tikal region dating to the Early Classic (Stuart 2004:225). rise‖ and is most commonly found in the inscriptions when it designates the direction east as el k’in. A very similar name. Stuart 2004:225). 4. 63 The most well-known scene of apotheosis from the ancient Maya world comes from Pakal‘s sarcophagus lid at Palenque (Fig. likened unto the dawning sun or sprouting maize. appears on Yaxchilán Lintel 10 but may be toponymic. 260 . According to Stuart and Stuart (ibid:173). At the Temple of the Cross. skeletal maw of the Underworld. he rises from a solar bowl. but are not necessarily indicative of a two-way portal 63 Although the context is poorly understood. Previous interpretations of the iconography described Pakal‘s descent into the Underworld. featured a depiction of K‘inich Tajal Wayib‘. but more recent scholarship suggests he is not falling into but rather rising out of the earth. built atop the vaulted crypt dubbed Hunal that served as K‘inich Yax K‘uk Mo‘s tomb. the body and lid of Pakal‘s sarcophagus ―convey a visual and textual metaphor of the king as the rising sun. Pakal is framed by the gaping. ―exiting sun‖ (Stuart and Stuart 2008:175). Taj Wayil.21). the Sun God played a prominent role in conceptions of the afterlife from its earliest days.Classic cache vessel (Staurt 2005:167). Indeed.‖ an aspect of the Sun God also associated with GIII of the Palenque Triad who also appears on Quirigua Stela C (Carrasco 2010:613. but such maws are typically used to represent cosmic emergence.‖ At Copan. Furthe rmore. The Yehnal funerary pyramid. which epigraphically denotes ―exit. Along with the Maize God and Sun God imagery. but rather it seems to testify of the deeply held religious conviction of the rulers. K‘awiil had the power to penetrate different worlds. This was not propaganda.(Taube 1994:674). Known Depictions of Apotheosized Ancestors in Monumental Art Despite the considerable ink that has been spilt concerning deification and the afterlife. Pakal also fuses with K‘awiil. unen. Its rich iconography was not intended to legitimize the dynasty in the eyes of the larger population. We often politicize the art of the Classic Maya (Marcus 1992). Stela 11 from Copan similarly depicts Yax Pasaj emerging from the Underworld as both the Maize God and K‘awiil (Fig. Pakal‘s sarcophagus was not on display for the public to see (Stuart and Stuart 2008:177). often using Palenque as an ideal type. 4.22). He strikes the pose of a newborn infant. but here we should note that unlike the stelae or other monuments that publicly celebrated the ruler in life and death. as indicated by the smoking tube emerging from his forehead. Taube 1994). suggesting this was literally a rebirth (Martin 2002. it was worship. suggestive of his innate ability to resurrect (Miller and Martin 2004:57). it may come as a surprise that only two of Palenque‘s rulers ever commissioned monuments that depicted unequivocally deified 261 . so Pakal‘s fusion with both the Maize God and with K‘awiil might be intended to convey his self -contained power to both crack the earth and spring forth from it with new life (Martin 2006:179). Pakal here invokes the two most powerful symbols of death and resurrection known to the ancient Maya: maize and the sun (Stuart and Stuart 2008:177). citing personal communication from Stephen Houston). about half are attributable to these two rulers. Most famously. Fig. 10. Palenque also depicts ancestors within solar cartouches (though not always). Chak Tok Ich‘aak (Stela 29. Like Yaxchilán. The deceased K‘inich Kan B‘alam II and K‘inich Kan Joy Chitam II appear in scenes where they are being adorned. 4. as on Stelae 1 (Fig. respectively. implying a celestial abode. The most explicit depictions of deceased rulers resurrecting as the Maize God are found at Palenque. Also unique to Palenque is the portrayal of ancestors sprouting as fruit trees (Fig. 4. some of Palenque‘s ancestors engage in ―impersonation‖ events as the Jaguar God of the Underworld and Chak Xib Chaak (Fitzsimmons 2009:53). and likely 6 (Fig. male and female ancestors are often depicted within solar and lunar cartouches. Fig. which features a deified Itzamnaah Balaam II and his wife Lady Ik‘ Skull (Fig.5a). however.24). K‘inich Janaab Pakal is dressed as the Maize God as he resurrects from the maw of the Underworld. Uniquely. At Yaxchilán. And of the two dozen or so monuments that depict deified ancestors from across the Lowlands. 3. 4. rather than a fixed merging with a solar deity. 445.9). 292. 4.23). At other times. as on the temple side of Stela 11. Yax Ehb‘ Xook (Stela 31.22). they emanate light (Fitzsimmons 2009:53. As celestial bodies.ancestors: K‘inich Kan B‘alam II and his successor K‘inich K‘an Joy Chitam II. Tikal holds the distinction of having both the earliest and the latest depictions of deified ancestors to have survived in all of the Maya lowlands.21) 262 . 3. There are only three total. 3. likely a hearkening to the Maize God resurrection cycle discussed above. ancestors are merely depicted seated in the upper register. Yax K‘uk‘ Mo‘s son and successor K‘inich Popol Hol erected the Yehnal temple directly on top of Hunal as a memorial to his father (c. rather. On Stela 31. it is as if the Sun God is impersonating Yax Nuun Ayiin. A. The only ancestor who is clearly apotheosized as the Sun God at Copan is K‘inich Yax K‘uk‘ Mo‘. 1999:7. most likely to house his remains (Sharer et al. All of these construction phases were encompassed by Temple 16 (also known as Structure 10L-16) which depicts the founder within a feathered solar portal. which was later transformed into a tomb.25. but this appears to be more than a deified ruler engaged in a celestial impersonation event. 437-45). Margarita was covered by Chilan. the face of the Sun God is wearing the regalia of Yax Nuun Ahiin. 445-460). personal communication 2011). 4.and an unknown ancestor depicted by Yax Nuun Ayiin II on Stela 22 (Fig. A. Yax Nuun Ahiin is not depicted wearing the regalia of the Sun God. A similar scene appears on the Early Classic Stela 2 from Takalik Abaj (Karl Taube. clearly denoting his apotheosis 263 . Fash 2002:17). James Fitzsimmons. whose façade shows K‘inich Yax K‘uk‘ Mo‘ merged with the Sun God. which was then subsumed by Rosalila (A. 571).D.D. which similarly depicts Yax K‘uk‘ Mo‘ merged with the Sun God. personal communication 2011). The stucco relief panels of Yehnal depict the sun god. Yax Nuun Ahiin is depicted as the Sun God K‘inich Ajaw. The Central Mexican -style talud-tablero platform nicknamed Hunal was his original royal compound. In a curious case of role-reversal.D. Yehnal was topped by Marg arita (c. which may be an allusion to Yax K‘uk‘ Mo‘s apotheosis or perhaps simply the K‘inich title he bore (Sharer 2004:152). The ―floater‖ style of dei fied ancestor on Stelae 22 and 31 intentionally hearkens to the iconographic style of Stela 29. K‘inich Ajaw. 7). 264 . Altar Q. the bench depicts Yax Pahsaj Chan Yopaat‘s accession as Copan‘s 16th ruler (9.(Fig. Chante Ajaw. Taube 2004b:266-268). which sits at the base of Str.5. Butz‘ Chan. is also sitting upon his name glyph. 10L-16. and Bolon K‘awiil64. 3. Although not an explicit depiction of deification. shows K‘inich Yax K‘uk‘ Mo‘ holding a burning dart. the four koknoom (―guardians‖) of Hux Wintik. so it may simply be a reflection of the porous nature of the veil that divided the human and divine realms with both natural and supernatural individuals standing as 64 At first glance it may appear that the name is ―14 K‘awiil. Bahlam Nehn. a name that appears to reference the entire site of Copan and possibly the lands around it (Tokovinine 2008:206). and K‘ahk‘ Uti‘ Witz‘ K‘awiil (Martin and Grube 2008:209).16. Included in the line-up are K‘uy Nik? Ajaw. 28 June 763). Similar in style to Altar Q. Some of the other witnesses appear to be contemporaneous rulers of other polities. another of Copan‘s principal patron gods. 2. which was witnessed by nineteen individuals who are seated upon stylized thrones comprised of their name glyphs or toponyms. the bench from Temple 11 suggests equivalency between deceased rulers and deities (Fig. Only four of the individuals are easily identifiable as previous rulers of Copan: Yax K‘uk‘ Mo. while some others appear to be from neighboring polities (Wanyerka 2009:347). Mo‘ Wits Ajaw. 2.12. Taube 2006:166).32.‖ but the ―bar‖ adjacent to the K‘awiil‘s glyph is actually the seated individual‘s loinc loth that is draping down. which alludes to his fiery immolation and resurrection as the Sun God (Fig. but it also celebrates the continuity of the dynasty from the founder to the sixteenth dynast as he passes the torch toYax Pahsaj. Tukun Ajaw.36.17 6 Kaban 10 Mol. D. which may suggest that there is a conceptual equivalency between them. so it was either a conscious attempt to hearken back to bygone iconographic conventions or they were simply being very conservative (Martin and Grube 2008:90). The iconography of the ‗Death Vase‘ demonstrates that by the Early Classic. 67 265 . unlike the other witnesses who don distinctive pectorals. most of which are tragically completely illegible due to erosion (Beetz and Satterthwaite 1981:28). 613. and it originally bore well over 200 glyphs. 66 Caracol Stela 5.witnesses to Yax Pahsaj‘s accession. perhaps his father Yajaw Te‘ Kinich II. both the Maize God and the Sun God had already 65 Wanyerka (2009:347) has argued that the toponym upon which the seventh figure to Yax Pasaj‘s right is seated is Tz‘am Witz (―Throne Mountain‖). a location at or near Pusilha‘s main stela plaza group. the time depth and geographical distribution of such representations suggest the ideology was deeply ingrained and not merely a site-specific or regionally limited belief. 4.65 However. 66 Viel‘s interpretation of the bench fails to recognize that some of the figures are gods. Also known as Ruler IV. Above him floats a solar deified ancestor. It is an iconographically dense monument. It features archaic iconographic conventions. Ahau Serpent and Flaming Ahau. It depicts Knot Ajaw67 in anachronistic regalia and wielding a rigid double-headed serpent bar in his arms. Although Classic period depictions of deified ancestors in the form of the Maize God and Sun god are comparatively (and curiously) few. is the only monument at that site to clearly depict an apotheosized ancestor (Fig. At his feet is a pair of miniature figures or dwarves who hold K‘awiil scepters.26). the pectorals worn by the patron gods are similar to those worn by the deceased Copanec rulers (Viel 1999). dating to A. 266 .been established as the primary figures associated with resurrection and apotheosis (Taube 2004a:79). c. Triadic groupings of gods from (a) Palenque Temple XIX (drawing by David Stuart 2005 Figure 123) (b) Caracol Stela 16 (drawing by Linda Schele) (c) Tikal (from Jones and Satterthwaite 1982:Figure 44a) (d) Naranjo.a. d.1. C2b-D2 (drawing by Ian Graham from Graham 1978:108). (After Stuart 2005 Figures 123-124). b. Hieroglyphic Stairway 1. 267 . Step II. Figure 4. Figure 4. Ixlu Stela 2 (drawing by Linda Schele. courtesy of FAMSI). The Paddler Gods oversee a scattering event.2. 268 . Censer stand portraying Palenque‘s founder.3. K‘uk‘ Bahlam I (photo by Javier Hinojosa.Figure 4. in Miller and Martin 2004:230 Plate 127). 269 . Caracol Stela 6 (detail of drawing by Beetz and Satterthwaite 1981 Figure 7b).4. 270 . A deified ancestor yilaj ―oversaw‖ (at B20) a censing ritual performed by Yajaw Te‘ Kinich II.A 19 20 21 B C Figure 4. 5. Courtesy of the New World Archaeological Foundation). 271 . Down-gazing deified head. Kaminaljuyu Stela 11 (drawing by Ayax Moreno.Figure 4. Figure 4.6. Reconstructed Naranjo Stela 45 depicts Tziki‘in Bahlam as a deified. down gazing ancestral head (drawing by Tokovinine and Fialko 2007 Figure 4). 272 . 7. Solar and lunar cartouches commonly used to denote deified ancestors at Yaxchilán.Figure 4. Upper register of Yaxchilán Stela 1 (detail of drawing by Tate 1992 Figure 124) 273 . 274 .Figure 4.8. Non-ancestral supernatural beings overseeing ritual activities. Jimbal Stela 1 (drawing by Linda Schele. courtesy of FAMSI). Figure 4.9. Supernatural ―travelers‖ and a possible deified ancestor accompany a ruler. Hauberg Stela (drawing by John Montgomery, courtesy of FAMSI). 275 Figure 4.10. Censer stand from Palenque depicting the Jaguar God of the Underworld (photo by Linda Schele, courtesy of FAMSI) 276 Figure 4.11. Realistic human portrait on an incensario at Palenque. (Photo by Linda Schele, courtesy of FAMSI). 277 Figure 4.12. Ruler 4 making an offering to an ancestor. Piedras Negras Stela 40. (Drawing by John Montgomery, courtesy of FAMSI). 278 Figure 4.13. The god Yaxhal Chaak is depicted on the front on El Zapote Stela 1, and the text on the back name him as the ―owner‖ of the monument. (Drawing by David Stuart 1996 Figure 14). 279 Figure 4.14. Quirigua Stela I recounts the capture and fire-drilling of Copan‘s patron gods Chante Ajaw and K‘uy Nik? Ajaw (drawing and translation by Mathew Looper 2003:79 Figure 3.4) 280 Figure 4.15. Yik‘in Chan K‘awiil of Tikal p roudly displays the captured battle palanquin representing Naranjo‘s patron god. Tikal Temple IV Lintel 2 (drawing by John Montgomery, courtesy of FAMSI). 281 16.Figure 4. represented by a turtle carapace. Detail of K731 (drawing by Marc Zender 2006:9 Figure 10c). Maize God resurrecting out of the earth. 282 . in McNeil 2010 Figure 11). Censers from Copan depicting deified ancestors as cacao trees.17. 283 .4. (Detail of photo by Cameron McNeil. upper south side (drawing by Elizabeth Newsome 2001 Figure 3. (a) Vision serpent and solar zoomorph that appear in Waxaklahuun Ubah K‘awiil‘s headdress. (b) Sun God emerging from double-headed serpent bar on north side (drawing by Linda Schele. courtesy of FAMSI). Detail of solar imagery from Copan Stela A. b.35b). Figure 4.18. 284 .a. Figure 4. Uk‘it K‘an Le‘k sits deified within a solar cartouche on Ek‘ Balam Stela 1. from Grube et al 2003 Figure 55).19. 285 . (Drawing by Alfonso Lacadena. Yaxchilan Hieroglyphic Stairway 3 Step III. The Sun God within the belly of the Starry Deer Crocodile.20. (Drawing by Ian Graham 1982:169.Figure 4. courtesy of CMHI) 286 . 287 .Figure 4. (Drawing by Linda Schele.21. Pakal resurrecting as the Maize God from the maw of the Underworld. courtesy of FAMSI). (Drawing by Linda Schele. Copan Stela 11. courtesy of FAMSI).Figure 4. 288 . Yax Pasaj emerging from the Underworld as both the Maize God and K‘awiil.22. Detail of sarcophagus lid.Figure 4.23. Temple of the Inscriptions (from Schele and Miller 1986:284 Plate 111e) 289 . Ancestors sprouting as trees. Deified ancestors in solar and lunar cartouches at Yaxchilán. Stela 4 (Drawing by C. b. (b) Detail of upper register.a. Tate 1992:192 Figure 86). (c) Detail of upper register.24. Tate 1992:193 Figure 88a) 290 . Stela 10 (drawing by C. Tate 1992:232 Figure 130b). Stela 6 (drawing by C. c. (a) Detail of upper register. Figure 4. Deified solar ancestor floats above the ruler‘s head on Tikal Stela 22. (Drawing by Jones and Satterthwaite 1982 Figure 33) 291 .Figure 4.25. (Drawing by Beetz and Satterthwaite 1981 Figure 6) 292 .Figure 4.26. Stela 5. The only depiction of a deified ancestor at Caracol. and they reinforced that divinity through their artistic programs and exploitation of sacred spaces (both natural and man-made). The ruler stood at the center of space and time. We then examined the process of becoming a sacred king and rejected the hypothesis that there was a ―precise ritual‖ that was observed from site to site. 293 . and the ways in which that ideal type was departed from. and brought order to the chaos through ritual warfare and ballplaying. They imbued themselves with divinity by the rituals they performed and the names and titles they bore. Site planning principles and architectural styles generally reflected the divine realm. The rituals. We ended with a discussion concerning the nature of gods. and ultimately the expectation that rulers had of becoming gods themselves. and regalia differed according to local ideologies. how rulers were to interact with them. accession phrases. but could also draw from powerful distant polities or reject those of neighboring polities. Rulers were both supreme leaders at their sites but also players on a larger field.Chapter 5 Summary and Conclusions Overview We began with an exploration of the concept of ―ideal types‖ with regards to kingdom and king. for virtually every aspect of Classic Maya society was affected by the way individual polities saw fit to worship the gods of their polity. that question opened the floodgate to more questions. What effect did having local variants of pan-Maya gods and local deified ancestors in each city‘s pantheon have on regional and pan -Maya socio-political relations? It is that question that this dissertation ultimately addresses. an answer to that question is an exercise in infinite regression. Pharo 2007:34). Of relevance to the question concerning the relationship between rulers and their gods is the issue concerning the divinity of kings. Religion and politics were not discreet institutions. and there was no conceptual distinction between the rituals of those two domains (Colas 1998:10. selfpossessed of divinity? Or were they perhaps avatars of particular gods? Or were they merely intermediaries between commoners and gods? We remain unable to answer that 294 . Were rulers literally gods on earth. In a very literal sense. Which ―Maya‖ are we talking about? How did the Classic Maya conceptualize divinity? How were the gods worshiped? Why does each polity have a unique set of gods? Was there a difference in the roles played by ‗major‘ gods and deified ancestors? How did rulers become deified ancestors? This line of inquiry ultimately led to the following overarching question. An unexpected finding of this research was how deeply the relationship between rulers and their gods influenced the cultural identity of each polity and how fundamentally it affected the heterogeneity of the Maya political landscape.Discussion The initial question that drove this dissertation was ―What was the relationsh ip between Maya rulers and their gods?‖ Unsurprisingly. question with full confidence, but I believe the evidence suggests that rulers were ―functionally divine‖ but not ―ontologically divine.‖ In other words, they were plenipotentiaries of the gods, imbued with their powers, but they were not self-possessed of divinity. Their divinity came piecemeal through ritual activity and by bearing the names, titulary, and regalia of different gods. They did not embody any particular god for the entirety of their lives, but rather summoned the powers of a number of different gods, which varied according to ritual circumstances and local traditions. That said, the debate about how divine the kings really were is perhaps moot due to the variations in local ideology. It is possible that some rulers may have attempted to elevate themselves to ontologically divine status, whereas others were content to present themselves as functionally divine (Sachse 2004:10-11). Maya rulers had the power to create new gods and modify pre-existing gods, and they subsequently defined themselves in relation to those very gods. As we have seen throughout this study, every aspect of their lives was colored by the gods they worshiped, from the mundane to the magnificent: the houses they slept in, the food they ate, the garb they donned, the names and titles they bore, the buildings and monuments they erected, the rituals they performed, the places they traveled to, the people they battled, the calendar they kept, the games they played, the regalia they displayed, the manner of burial they would receive, and the afterlife they expected. We have seen that some rulers drastically re-invented the ritual and material culture of kingship at their polities. At times the changes were quickly instituted after the death of an ineffective ruler in hopes of getting a fresh start, as in the case at Palenque. Conversely, it could be done in the midst 295 of a ruler‘s reign after defeating an oppressive enemy to boldly proclaim a re-ordering of the regional hierarchy, as was the case with Quirigua. Although the fundamental question driving this dissertation concerned the relationship between rulers and their gods, I‘ve spilt a good amount of ink concerning the relationships between polities. Superficially, this may seem to be an unrelated issue, but at its core it is cosmologically motivated. The concepts of duality (or more specifically, complementary opposition) and concentricity (center vs. periphery) are fundamental principles in Mesoamerican religions (Gossen 1986). Although the concept of duality requires the existence of two opposing forces or concepts to create a whole, it does not assume they are equally powerful. To the contrary, one force is frequently considered superior to the other, which lends cosmological support for human hierarchies. Complementary opposition is a creative act, both cosmologically and politically (Grove and Gillespie 2009:57-58). At its core, then, this has been a study of contrasts; human/god, past/present, commoner/ruler, self /other. The ―other‖ always varies, depending on the context. Grove and Gillespie (2009:28) note, ―One‘s center is one‘s house, neighborhood, community, even polity.‖ The periphery can be as close as one‘s own home garden or as distant as the heavens. Noble Women Although the focus of this study has been on male rulers, it is important to note that a few women did attain to the throne during the 6th through 8th centuries, either as ruling queens or regents. Palenque had two female rulers, Lady Yohl Ik‘nal (583 -604) and 296 Muwaan Mat (612-615). Yaxchilán, Naranjo, and Tikal had one each; Lady Ik‘ Skull (?751), Lady Six Sky (682-741), and Lady of Tikal (511-527), respectively. Miller and Martin (2004:93) suggest the appearance of female nobles in monumental iconography was a response to the increasingly crowded landscape of the era and the concomitant rise in conflict. Marriage alliances were used as alternatives to war, but by the 9th century, noble women became absent from the monuments and depictions of armed men predominate (ibid:94). It should be noted, however, that even when absent iconographically, elite women are named as frequently as men when rulers declare their parentage in the inscriptions (ibid.). The emphasis on male rulers throughout this study was not intended to be a slight, but rather was informed by the available data from the archaeological record, which is comprised mostly of male rulers. Commoners Commoners are likewise underrepresented in this study. Our focus has been on Classic Maya rulers and the identities they created for themselves and their polities, but it must be noted that commoners similarly used their agency to create and maintain their own identities through household ritual and material culture (Lucero 2010). As noted earlier, royal ritual was rooted in commoner ritual, albeit performed on a grander scale. Despite royal efforts to appropriate or even monopolize ritual activity, evidence from non-elite residential compounds demonstrates that there was resistance to local hegemonies (Hendon 1999). The broad strokes I used in discussing them throughout this study have unfortunately served to homogenize them as a group within their polities. In 297 defense of this approach, however, it is safe to say that the rulers of Tikal exerted great influence over the commoners at Tikal, yet they had little to no direct effect on the daily life of commoners at other sites such as Copán or Sayil (Lohse and Valdez 2004:5). Recommendations for Further Research Although focused studies of Maya gods have been undertaken in the past (Schellhas 1904; Taube 1992), the gods of the Classic period merit continued systematic research. A good number of Classic period deities, especially those that are unique to a region or a site, remain nameless due to undeciphered (and perhaps undecipherable) glyphs. As polities are defined in large measure by their gods, and events like warfare are often couched in beliefs that it is the gods themselves that are engaging in war, it might be worthwhile to systematically catalog the events, dates and locations associated with specific Classic period gods, and assign them unique identifying names when necessary. Patterns may or may not emerge, but until the work is done it remains uncertain. 298 Works Cited Acuña, René 1978 Farsas y Representaciones Escénicas de los Mayas Antiguos. Serie: Cuadernos, Inst. de Investigaciones Filológicas, Univ. Nacional Autónoma de México Aimers, James John 1993 Messages from the Gods: A Hermeneutic Analysis of the Maya E-Group Complex. M.A. thesis, Trent University, Peterborough, Canada. Aldana, Gerardo 2003 K‘uk‘ulkan at Mayapan: Venus and Postclassic Maya Statecraft. Journal for the History of Astronomy 34(1):33-52. 2005 Agency and the ―Star War Glyph‖: A historical reassessment of Classic Maya astrology and warfare. Ancient Mesoamerica 16. Pp. 305-320 Anaya Hernandez, Armando, Stanley Guenter, and Peter Mathews. 2002 An Inscribed Wooden Box from Tabasco, Mexico. Mesoweb Report. Electronic document,, accessed July 2009 Anderson, David S. 2010 The Middle Preclassic Ballgame: Yucatan and Beyond. Paper presented at the 75th Society for American Archaeology annual meeting, 2010, St. Louis. Aoyama, Kazuo 2005 Classic Maya Warfare and Weapons: Spear, Dart and Arrow Points of Aguateca and Copan. In Ancient Mesoamerica, 16:291-304. Cambridge University Press. Ashmore, Wendy 1986 Peten Cosmology in the Maya Southeast: An Analysis of Architecture and Settlement Patterns at Classic Quirigua. The Southeast Maya Periphery. Patricia A. Urban and Edward M. Schortman, eds. Pp. 35-49. Austin: University of Texas Press. 1989 Construction and Cosmology: Politics and Ideology in Lowland Maya Settlement Patterns. In Word and Image in Maya Culture: Explorations in Language, Writing, and Representation. William F. Hanks and Don S. Rice, eds. Pp. 272–286. Salt Lake City: University of Utah Press. 299 1991 Site-Planning Principles and Concepts of Directionality among the Ancient Maya. Latin American Antiquity 2(3):199-226. 1992 Deciphering Maya Architectural Plans. In New Theories on the Ancient Maya, 77. Ellen C. Danien and Robert J. Sharer, eds. Pp. 173–184. Philadelphia: University Museum, University of Pennsylvania. 2009 187 Mesoamerican Landscape Archaeologies. Ancient Mesoamerica 20:183 – Ashmore, Wendy, and Chelsea Blackmore 2008 Landscape Archaeology. In Encyclopedia of Archaeology, edited by Deborah Pearsall, pp. 1569–1578. Elsevier, Oxford Ashmore, Wendy, and Jeremy A. Sabloff 2002 Spatial Orders in Maya Civic Plans. Latin American Antiquity 13(2):201216. Aveni, Anthony 2010 The Measure of Time in Mesoamerica: From Teotihuacan to the Maya. In The Archaeology of Measurement: Comprehending Heaven, Earth and Time in Ancient Societies. Iain Morley and Colin Renfrew, eds. New York. Cambridge University Press. Aveni, Anthony, Anne S. Dowd, and Benjamin Vining 2003 Maya Calendar Reform? Evidence from Orientations of Specialized Architectural Assemblages. Latin American Antiquity 14(2):159-178. Aveni, Anthony, and Horst Hartung 1986 Maya City Planning and the Calendar. Transactions of the American Philosophical Society 76(7):1-87. Aveni, Anthony F., and Lorren Hotaling 1994 Monumental Inscriptions and the Observational Basis of Maya Planetary Astronomy. Archaeoastronomy 19:S21–S54. Ball, Joseph 1993 Pottery, Potters, Palaces, and Politics: Some Socioeconomic and Political Implications of Late Classic Maya Ceramic Industries. In Lowland Maya Civilization in the Eighth Century A.D. J.A. Sabloff and J.S. Henderson, eds. Pp. 243-272. Washington, DC: Dumbarton Oaks. 300 Ball, Joseph W. and Jennifer T. Taschek 1991 Late Classic Lowland Maya Political Organization and Central-place Analysis: New Insights from the Upper Belize Valley. Ancient Mesoamerica 2:149-165. Bardawil, Lawrence 1976 The Principle Bird Deity in Maya Art: An Iconographic Study of Form and Meaning. In The Art, Iconography, and Dynastic History of Palenque: Part III, ed. Merle Greene Robertson, 181-94. Pebble Beach, Calif.: Pre-Columbian Art Research, the Robertson Louis Stevenson School. Bardsley, Sandra 1994 Rewriting History at Yaxchilan: Inaugural Art of Bird Jaguar IV. In Seventh Palenque Round Table, 1989. M. G. Robertson and V.M. Fields, eds. Pp. 87-94. San Francisco: Pre-Columbian Art Research Institute. 1996 Benches, Brothers, and Lineage Lords of Copán. In Eighth Palenque Round Table, 1993. Martha J. Macri and Jan McHargue, eds. Pp. 195-201. San Francisco: Pre-Columbian Art Research Institute. Baudez, Claude-François 1984 "Le roi, la balle, et le maïs: Images du jeu de balle Maya." In Journal de la Sociétédes Américanistes, n.s. vol. 62, pp. 139-154. 1994 Maya Sculpture of Copan: The Iconography. Norman: University of Oklahoma Press. Becker, Marshall Joseph 2006 Comment on ―Plazas, Perfomers, and Spectators: Political Theaters of the Classic Maya.‖ Current Anthropology 47 (5). Beekman, Christopher 2000 The Correspondence of Regional Patterns and Local Strategies in Formative to Classic Period West Mexico. Journal of Anthropological Archaeology. 19. Pp. 385-412. 2004 Agricultural Pole Rituals and Rulership in Late Formative Central Jalisco. Ancient Mesoamerica 14(2):299. Beetz, Carl P., and Linton Satterthwaite 1981 The Monuments and Inscriptions of Caracol, Belize. Philadelphia: University of Pennsylvania Press. 301 E. 135-150. Krieger. Boot. www. Middle American Research Institute Publication. Boone. A. New York. Pp. In The Maya and Teotihuacan: Reinterpreting Early Classic Interaction. eds. In Archaeological Studies in Middle America. 302 . G. Journal de la Societé des Américanistes 59:107-135. Opladen: Westdeutscher Verlag. John 1992 History and Mythology of the Aztecs: The Codex Chimalpopoca : Tucson: University of Arizona Press. Chiapas. In Ritualtheorien.mayavase. American Antiquity 30:330-342 1970 The Tablet of the 96 Glyphs at Palenque. Biro. New Orleans. Philadelphia: The American Philosphical Society. James 2004 Images of Power and the Power of Images: Early Classic Iconographic Programs of the Carved Monuments of Tikal. 1989 Incarnations of the Aztec Supernatural: The Image of Huitzilopochtli in Mexico and Europe. Braswell.Bergesen. No. pt. Transactions of the American Philosphical Society 79. Austin: University of Texas Press. Mesoweb. Peter 2004 Boas.pdf Primitive Art. 49-76. Heinrich 1958 El glifo emblema en las inscripciones mayas. Ein einführendes Handbuch.com.mesoweb. S. ed. Elizabeth H. Tulane University. Mayavase.J. 2. 1963 The Palenque Triad.com/articles/biro/SakTzi. Dover Publications. Borowicz. 217-235. 26. Franz 1955 Sak Tz'i' in the Classic Period Hieroglyphic Inscriptions. Erik 2008 At the Court of Itzam Nah Yax Kokaj Mut: Preliminary Iconographic and Epigraphic Analysis of a Late Classic Vessel.pdf. Belliger and D. Albert 1998 Die rituelle Ordnung. Pp. Berlin. 1965 The Inscription of the Temple of the Cross at Palenque.com/God-D-Court-Vessel. URL:. Mexico. Journal de la Societé des Américanistes 47:111-119. Bierhorst. Los Angeles. 2007 Literary Continuities across the Transformation from Maya Hieroglyphic to Alphabetic Writing. and Fertility in the Olmec Ritual Ballgame. Barbara Kerr and Justin Kerr. Pp. Takeshi Inomata and Stephen D. Augustin. 2: Data and Case Studies. Ruth 1952 Chichicastenango: A Guatemalan Village. John Frederick Schwaller. Houston. Braswell. Volume 5. NY: J. 1989 An Investigation of Maya Ritual Cave Use with Specific Reference to Naj Tunich. 868-883. New York. 11-29. In The Sport of Life and Death: The Mesoamerican Ballgame. Thames and Hudson. CO: Westview Press. eds. dissertation. Proceedings of the American Philosophical Society. 303 . Bremer. Bricker. 2004 The Maya and Teotihuacan: Reinterpreting Early Classic Interaction. 2003 Sahagún and the Imagination of Inter-Religious Dialogues.D. CA: Academy of American Franciscan History. Pp. eds. pp.Bradley. Ed. Calvin. Geoffrey E. Whittington. 2001 Post-Classic Maya Courts of the Guatemalan Highlands: Archaeological and Ethnohistorical Approaches. Vol. edited by M. Bernardino de Sahagún. 1997 Settlement Configuration and Cosmology: The Role of Caves at Dos Pilas. Victoria R. Thomas S. American Anthropologist 99(3):602-618. Guatemala. 2001 Gender. Unpublished Ph. In The Maya Vase Book. 1. 308334. New York: Kerr Associates.J. Vol. Douglas E. Bunzel. Locust Valley. 151 No. In Sahagún at 500: Essays on the Quincentenary of the Birth of Fr. Power. James E. 33-39. University of California. Berkeley. Boulder. Brady. Inga 1997 Where the Wayob Live: A Further Examination of Classic Maya Supernaturals. Austin: University of Texas Press. In Royal Courts of the Ancient Maya. Carl, Peter, Barry Kemp, Ray Laurence, Robin Coningham, Charles Higham, and George L. Cowgill 2000 Viewpoint: Were Cities Built as Images? Cambridge Archaeological Journal 10:327-365. Carlsen, Robert S. 1997 The War for the Heart and Soul of a Highland Maya Town. Austin: University of Texas Press. Carlsen, Robert S., and Martin Prechtel 1991 The Flowering of the Dead: An Interpretation of Highland Maya Culture. Man 26(1):23-42. Carmack, Robert M. 1973 Quichean Civilization. Berkeley: University of California Press. 1981 The Quiche Mayas of Utatlan: The Evolution of a Highland Guatemala Kingdom. University of Oklahoma Press, Norman. Carrasco, David 1982 Quetzalcoatl and the Irony of Empire: Myths and Prophecy in the Aztec Tradition. University of Chicago Press, Chicago. Carrasco, Michael David 2005 The Mask Flange Iconographic Complex: The Art, Ritual, and History of a Maya Sacred Image. PhD dissertation, University of Texas at Austin. 2010 From Field to Hearth: An Earthly Interpretation of Maya and Other Mesoamerican Creation Myths. In Pre-Columbian Foodways: Interdisciplinary Approaches to Food, Culture, and Markets in Ancient Mesoamerica. J.E. Staller and M.D. Carrasco, eds. Pp. 601-634. New York: Springer. Carrasco, Michael D., and Kerry Hull 2004 Mak-―Portal‖ Rituals Uncovered: An Approach to Interpreting Symbolic Architecture and the Creation of Sacred Space among the. 131-142. Markt Schwaben, Germany: Verlag Anton Saurwien. Caso, Alfonso 1942 Definición y extensión del complejo ―Olmeca.‖ In Mayas y Olmecas: Segunda reunión de Mesa Redonda sobre problemas antropológicos de México y Centro América: 43–46. Talleres de la Editorial Stylo, México, D.F. 304 Charmaz, Kathy 2006 The Power of Names. Journal of Contemporary Ethnography Vol. 35 No. 4, pp. 396-399. Chase, Arlen F. 1992 Elites and the Changing Organization of Classic Maya Society. In Mesoamerican Elites: An Archaeological Assessment (Diane Z. Chase and Arlen F. Chase, eds.):30–49. University of Oklahoma Press, Norman Chase, Arlen F., and Diane Z. Chase 1995 External Impetus, Internal Synthesis, and Standardization: E Group Assemblages and the Crystallization of Classic Maya Society in the Southern Lowlands. In The Emergence of Lowland Maya Civilization: The Transition from the Pre-Classic to the Early Classic, edited by Nikolai Grube, pp. 87-101. Acta Mesoamericana, Vol. 8. Verlag Anton, Markt Schwaben 1996 More Than Kin and King: Centralized Political Organization Among the Late Classic Maya. Current Anthropology 37(5): 803-810. Chase, Arlen F., Nikolai Grube and Diane Z. Chase. 1991 Three Terminal Classic Monuments from Caracol, Belize. Research Reports on Ancient Maya Writing, 36. Center for Maya Research, Washington, DC. Chase, Diane Z., and Arlen F. Chase, eds. 1992 Mesoamerican Elites: An Archaeological Assessment. Norman: University of Oklahoma Press. Christenson, Allen J. 2001 Scaling the Mountain of the Ancients: The Altarpiece of Santiago Atitlan . Austin: University of Texas Press. 2003 Popol Vuh: The Sacred Book of the Maya. Winchester, NY: O Books. Clark, John E. 1997 The Arts of Government in Early Mesoamerica. Annual Reviews in Anthropology 26(1):211-234. Clark, John E., and Arlene Colman 2008 Time Reckoning and Memorials in Mesoamerica. Cambridge Archaeological Journal 18:1, pp. 93-99. 305 Clark, John E., and Richard D. Hansen 2001 The Architecture of Early Kingship: Comparative Perspectives on the Origins of the Maya Royal Court. In Royal Courts of the Ancient Maya, vol. 2: Data and Case Studies. Takeshi Inomata and Stephen D. Houston, eds. Pp. 1-45. Boulder, CO: Westview Press. Clark, John E., Richard D. Hansen, and Tomas Perez 2000 La zona maya en el preclasico. In Historia antigua de Mexico, vol. 1. Linda Manzanilla and L. Lopez Lujan, eds. Pp. 436-513. Mexico, D.F.: Universidad Autonoma de Mexico. Clark, John E., and Mary E. Pye 2000 The Pacific Coast and the OlmecQuestion. In Olmec Art andArchaeology in Mesoamerica, edited by John E. Clark and Mary Pye, pp.217-251. Studies in the History of Art, No. 58. National Gallery of Art,Washington, DC. Closs, Michael 1978 Venus in the Maya World: Glyphs, Gods and Associated Astronomical Phenomena. In Tercera Mesa Redonda de Palenque, Vol. IV, edited by Merle Greene Robertson, pp. 158–163. Pre-Columbian Art Research Center, Palenque. 1981 Venus Dates Revisited. Archaeoastronomy: The Bulletin of the Center for Archaeoastronomy 4(4):38– 41. 1994 A Glyph for Venus as Evening Star. In Seventh Palenque Round Table, 1989, edited by Merle Greene Robertson, pp. 229–236. Pre- Columbian Art Research Institute, San Francisco. Coe, Michael D. 1961 Social typology and the tropical forest civilization. Comparative Studies in Society and History 4(1):65-85. 1972 Olmec Jaguars and Olmec Kings. In The Cult of the Feline, edited by Elizabeth P. Benson, pp. 1-12. Dumbarton Oaks Research Library and Collections. Washington, DC. 1973 The Maya Scribe and his World. Grolier Club. New York 1977 Olmec and Maya: A Study in Relationships. In Origins of Maya Civilization. R. E. W. Adams, ed. Pp. 183-196. Albuquerque: University of New Mexico Press. 1978 Lords of the Underworld: Masterpieces of Classic Maya Ceramics . Princeton University Press, Princeton. 306 1982 Religion and the Rise of Mesoamerican States. In The Transition to Statehood in the New World. Grant D. Jones, Robert Kautz, eds. Pp. 155-179. Cambridge. Cambridge University Press. 1989 The Hero Twins: Myth and image. In The Maya Vase Book, vol. 1. B. Kerr and J. Kerr, eds. Pp. 161-184. New York: Kerr Associates. 2005 The Maya. Seventh Edition. Thames and Hudson. Coe, Michael D., and Richard A. Diehl 1980 In the Land of the Olmec. 2 vols. Austin: University of Texas Press. Coe, Michael. D, and Mark Van Stone 2001 Reading the Maya Glyphs. Thames and Hudson. Cohodas, Marvin 1976 The Iconography of the Panels of the Sun, Cross, and the Foliated Cross at Palenque. In The Art, Iconography and Dynastic History of Palenque, Part III. M.G. Robertson, ed. Pp. 155-176. Pebble Beach: The Robert Louis Stevenson School. 1980 Radial Pyramids and Radial-Associated Assemblages of the Central Maya Area. Journal of the Society of Architectural Historians. Vol. 39, No. 3. Colas, Pierre Robert 1998 Ritual and Politics in the Underworld. Mexicon 20(5):99–104. 2001 ―Name Acquisition amongst the Classic Maya Kings: An Anthropological Assessment.‖ Paper presented at the 66th Annual Meeting of the Society for American Archaeology, New Orleans. 2003a K‘inich and King: Naming Self and Person among Classic Maya Rulers. Ancient Mesoamerica 14:269-283 2003b Typologische Analyse von Anthroponymphrasen in den Hieroglypheninschriften der klassischen Maya-Kultur als Beitrag zur allgemeinen Onomastik. Ph.D. dissertation, University of Bonn, Germany. Colby, Benjamin N. 1976 The Anomalous Ixil—Bypassed by the Postclassic? American Antiquity 41:74-80. 307 Cortez, Constance 1986 The Principal Bird Deity in Preclassic and Early Classic Maya Art. Unpublished MA Thesis, Department of Art, the University of Texas at Austin. Covarrubias, Miguel 1942 Origen y desarrollo del estilo artistic ―Olmeca.‖ In Mayas y Olmecas: Segunda reunión de Mesa Redonda sobre problemas antropológicos de México y Centro América: 46–49. Talleres de la Editorial Stylo, México, D.F. Cuevas Garcia, Martha 2004 The Cult of Patron and Ancestor Gods in Censers at Palenque. In Courtly Art of the Ancient Maya. Mary Miller and Simon Martin, eds. Pp. 253-255. New York: Thames and Hudson. Culbert, T. Patrick 2005 Intervención política en las tierras bajas mayas. In Memorias de la V Mesa Redonda de Palenque, June 2-5, 2004. Mexico City: Instituto Nacional de Antropologia e Historia. Cyphers, Ann Guillén 1996 Reconstructing Olmec Life at San Lorenzo. In Olmec Art of Ancient Mexico (Elizabeth P. Benson and Beatriz de la Fuente, eds.): 61–71. National Gallery of Art, Washington, D.C. Davletshin, Albert 2003 Glyph for Stingray Spine. Mesoweb:. Accessed 03/22/2009. Demarest, Arthur A. 1989 The Olmec and the Rise of Civilization in Eastern Mesoamerica. In Regional Perspectives on the Olmec, edited by R. J. Sharer and D. C. Grove, pp. 303-344. School of American Research. Cambridge University Press, Cambridge. 1992 Ideology in Ancient Maya Cultural Evolution: The Dynamics of Galactic Polities. In Ideology and Pre-Columbian Civilizations. A.A. Demarest and G.W. Conrad, eds. Pp. 135-158. Santa Fe, NM: School of American Research Press. DeMarrais, E., L. J. Castillo, and T. Earle 1996 Ideology, Materialization, and Power Strategies. Current Anthropology 37(1):15. Diehl, Richard A., and Michael D. Coe 1995 Olmec Archaeology. In The Olmec World: Ritual and Rulership: 10–25. The Art Museum, Princeton University, Princeton. 308 Dornan, Jennifer L. 2004 Beyond Belief: Religious Experience, Ritual, and Cultural Neurophenomenology in the Interpretation of Past Religious Systems. Cambridge Archaeological Journal 14(01):25-36. Drucker, Philip 1952 La Venta, Tabasco; A Study of Olmec Ceramics and Art. Bureau of American Ethnology Bulletin no. 153. Washington, D.C., Smithsonian Institution. Drucker, Philip, Robert Heizer, Robert Squier 1959 Excavations at La Venta, Tabasco, 1955. Bureau of American Ethnology Bulletin no. 170. Washington, D.C.: Smithsonian Institution. Durkheim, Émile 1995[1912] The Elementary Forms of Religious Life. Karen E. Fields, trans. New York: Free Press. Eberl, Markus, and Daniel Graña-Behrens 2004 Proper Names and Throne Names: On the Naming Practice of Classic. 101-120. Markt Schwaben, Germany: Verlag Anton Sauerwein. Eliade, Mircea, Joseph M. Kitagawa, and Jerald C. Brauer 1959 The History of Religions: Essays in Methodology. Chicago: University of Chicago Press. 1963 Myth and Reality. Translated by Willard R. Trask. New York: Harper & Row, 1963 Escobedo, Hector L. 2004 Tales from the Crypt: The Burial Place of Ruler 4, Piedras Negras. In Courtly Art of the Ancient Maya. Mary Miller and Simon Martin, eds. Pp. 277280. New York: Thames and Hudson. Estrada-Belli, Francisco 2006 Lightning Sky, Rain, and the Maize God: The Ideology of Preclassic Maya Rulers at Cival, Peten, Guatemala. Ancient Mesoamerica. 17:57-78. 2009 Investigaciones arqueológicas en la región de Holmul, Petén: Holmul y Hamontun. Informe Preliminar de la temporada 2009. Electronic document available at 309 2011 The First Maya Civilization: Ritual and Power Before the Classic Period . New York: Routledge. Fash, Barbara 2005. Iconographic Evidence for Water Management and Social Organization at Copán. In Copán: The History of an Ancient Maya Kingdom, edited by E. Wyllys Andrews and William L. Fash, pp. 103-138. School of American Research, Santa Fe. Fash, Barbara, William Fash, Sheree Lane, Rudy Larios, Linda Schele, Jeffrey Stomper, and David Stuart 1992a Investigations of a Classic Maya Council House at Copán, Honduras. Journal of Field Archaeology 19(4):419-442. Fash, W. L., and B. Fash 1990 Scribes, Warriors, and Kings: The Lives of the Copán Maya. Archaeology 43(1):26–35. Fash, William 1991 Scribes, Warriors and Kings: The City of Copán and the Ancient Maya. London: Thames and Hudson. 2002 Religion and Human Agency in Ancient Maya History: Tales from the Hieroglyphic Stairway. Cambridge Archaeological Journal 12(01):5-19. 2005 Toward a Social History of the Copán Valley. In Copán: The History of an Ancient Maya Kingdom. E. Wyllys Andrews and William L. Fash, eds. Pp. 73102 .Santa Fe, NM: School of American Research Press. Fash, William L., David Stuart 1991 Dynastic History and Cultural Evolution at Copán, Honduras. In Classic Maya Political History (T. Patrick Culbert, ed.): 147–179. Cambridge University Press, New York. Fash, William, Ricardo Agurcia Fasquelle, Barbara W. Fash, and Rudy Larios Villalta 1996 The Future of the Maya Past: The Convergence of Conservation and Investigation. In Eighth Palenque Round Table, 1993. Martha J. Macri and Jan McHargue, eds. Pp. 203-211. San Francisco: Pre-Columbian Art Research Institute. Fash, William L., Richard V. Williamson, Carlos Rudy Larios, and Joel Palka 1992 The Hieroglyphic Stairway and Its Ancestors: Investigations of Copán Structure 10L–26. Ancient Mesoamerica 3:105–15. 310 1991 The Iconographic Heritage of the Maya Jester God. Pp. Fialko. 2005b Lords of Creation: The Origins of Sacred Maya Kingship. Scala. Kent V. Austin: University of Texas Press. In Lords of Creation: The Origins of Sacred Maya Kingship. Ancient Mesoamerica 9: 271–78.D. dissertation.D. eds. Ph. Virginia M. Fields and Dorie Reents-Budet. and Joyce Marcus 2000 Formative Mexican Chiefdoms and the Myth of the ―Mother Culture. Mayab 4:13-21. 1719.. Harvard University. 1989 The Origins of Divine Kingship among the Lowland Classic Maya. dissertation. Los Angeles: Los Angeles Museum of Art. Virginia M. Fitzsimmons. Tikal: Un ejemplo de complejos de conmemoracion astronomica. 2009 Death and the Classic Maya Kings. Ph. Pp. Annual Reviews in Anthropology 14(1):273313. Florescano. G. Fields. In Lords of Creation: The Origins of Sacred Maya Kingship. 20-27. and Dorie Reents-Budet 2005a Introduction: The First Sacred Kings of Mesoamerica. Vilma 1988 Mundo Perdido. eds. In Sixth Palenque Round Table. Fields.Feeley-Harnik. Virginia M. University of Texas at Austin. Enrique 2005 Images of the Ruler in Mesamerica. Los Angeles: Los Angeles Museum of Art. Fields. Los Angeles: Los Angeles Museum of Art. 311 .‖ Journal of Anthropological Archaeology 19(1):1-37. James L.. Fields and Dorie Reents-Budet. 2002 Death and the Maya: Language and Archaeology in Classic Maya Mortuary Ceremonialism. Flannery. edited by Merle Greene Robertson and Virginia M. 1985 Issues in Divine Kingship. Scala. Virginia M. Guatemala‘. Norman: University of Oklahoma Press. 1998 ‗Classic Maya Mortuary Anniversaries at Piedras Negras. Scala. 1986. Austin: University of Texas Press. In Ethnohistory: Supplement to the Handbook of Middle American Indians. 1992 The Trees of Life: Ahau as Idea and Artifact in Classic Lowland Maya Civilization. Demarest and G. eds.A. and Barbara Macleod 2000 Creation Redux: New Thoughts on Maya Cosmology from Epigraphy. The PARI Journal 1(2):1-8. ed.M. and John S. N. David. Chicago: The Oriental Institute of the University of Chicago. Philadelphia: University of Pennsylvania Museum. Conrad. David. Pp. 1972 Chorti (Mayan) Texts Vol. NM: School of American Research Press. Spores and P. 2002 Comment on Klein et al. American Antiquity 44(1):3654. Current Anthropology 43(3):403-404. In 24th Annual Maya Weekend. Fowler. 1890 The Golden Bough: A Study in Comparative Religion. 1. New York: Macmillan.W. 4. Freidel.Fought. 312 .A. 18. Justeson 1986 Classic Maya Dynastic Alliance and Succession. David 1979 Culture Areas and Interaction Spheres: Contrasting Approaches to the Emergence of Civilization in the Maya Lowlands. Fox. American Antiquity 52(2):229-248. John G. James A. eds. R. In Ideology and Pre-Columbian civilizations.. A. Freidel. In Religion and Power: Divine Kinghsip in the Ancient World and Beyond. James G. Oriental Institute Seminars. 2008 Maya Divine Kingship. 115-133. and Stanley Guenter 2006 Shamanic Practice and Divine Kingship in Classic Maya Civilization. Brisch. Freidel. and Archaeology. Don D. Andrews. Frazer. Philadelphia: University of Pennsylvania Press. 1987 Uses of the Past: Archaeology in the Service of the State. Iconography. Santa Fe. Andreas 2007 The Calculation of the Lunar Series on Classic Maya Monuments. CA. In Maya Iconography. Vision Quest and Auto-Sacrifice: Some Thoughts on Ritual Blood-Letting among the Maya. London: Hogarth. and Joy Parker 1993 Maya Cosmos: Three Thousand Years on the Shaman’s Path. Iconography and Dynastic History of Palenque. and Outline of Psycho-analysis. London: Hogarth Press for the Institute of Psycho-analysis. and Charles Suhler 1995 Crown of Creation: The Development of the Maya Royal Diadems in the Late Preclassic and Early Classic Periods. The Standard Edition of the Complete Psychological Works of Sigmund Freud. David. pp. 313 . Linda Schele. and Kingship. The Robert Louis Stevenson School. 1964[1937-1939] Moses and Monotheism. Part III. Masson and David A. London: Hogarth Press for the Institute of Psycho-analysis. 21. New York: W. 1945[1921] Group Psychology and the Analysis of the Ego. Grube. 181-193.Freidel. Elizabeth P. 41-86. London: Hogarth Press for the Institute of Psyco-analysis. In The Art. Treasure. Germany: Verlag Anton Saurwein. Ancient Mesoamerica 18(02):273-282. Lanham. 137-150. Freidel. Griffin. Pp. Kathryn Reese-Taylor. 1957[1910] Five Lectures on Psycho-analysis. N. In Ancient Maya Political Economies. 1976 Fertility. edited by Merle Greene Robertson. Princeton. eds. and David Mora-Marín 2002 The Origins of Maya Civilization: The Old Shell Game. In The Emergence of Lowland Maya Civilization from the Preclassic to Early Classic. Leonardo da Vinci and other Works. David. MD: Rowman Altamira. Furst. Commodity. Pp. Freud. 44–93. eds. NJ: Princeton University Press. Marilyn A. Freidel. Mockmuhl. Pebble Beach. ed. Peter T. and Linda Schele 1988 Symbol and Power: A History of the Lowland Maya Cosmogram. Benson and Gillett G. Pp. Fuls. Freidel. David. David. Sigmund 1930 Civilization and Its Discontents. Morrow. Freidel. 3. 9. Antigua Libreria Robredo. Rafael 1949 Los Chortis Ante el Problema Maya. University of Oklahoma Press. MA. Ana. and Lucia Henderson 2006 Corpus of Maya Hieroglyphic Inscriptions. No. 1986 Corpus of Maya Hieroglyphic Inscriptions. Norman. No. In Symbol and Meaning Beyond the Closed community: Essays in Mesoamencan Ideas: 1-8 Studies onf Culture and Socitey. 5 vols. Albany (NY) Institute for Mesoamerican Studies. Vol.pdf Accessed 11/02/07 Geertz. No. Gossen. Corpus of Maya Hieroglyphic Inscriptions. Harvard University. 3. and Peter Mathews 1999 Corpus of Maya Hieroglyphic Inscriptions.Ortiz de Montellano and Thelma Ortiz de Montellano. Peabody Museum of Archaeology and Ethnology. Peabody Museum of Archaeology and Ethnology.org/reports/03101/61garcia_barrios/61garcia_barrios. FAMSI Reports. Mexico City. and Rosemary Joyce 1998 Deity Relationships in Mesoamerican Cosmologies: The Case of the Maya God L. 314 . Translated by Bernard R. Susan D. Ancient Mesoamerica 9:279-296. 13. Peabody Museum of Archaeology and Ethnology. Cambridge. MA.García Barrios. Graham. and Ana Martín Díaz and Pilar Asensio Ramo 2004 The Royal Names of the Classic: Reading and Mythological Interpretation. 3. Ian.. Girard. Vol. Ian 1977-1982 Yaxchilan. Gillespie. CA: Continuum Foundation. 5. PM. Graulich. Clifford 1980 Negara: The Theatre State in Nineteenth-century Bali. Ian. Vol. 6. Cambridge. Vol. Graham. 1995 The People of Chan. Cambridge. NJ: Princeton University Press. 1986 Mesoamencan Ideas as a Foundation for Regional Synthesis.. Graham. 2. Harvard University. Harvard University. Nos. Chino Valley. MA. Gary H. Princeton. Michel 1997 Myths of Ancient Mexico.famsi. 1997 Olmec Archaeology: A Half Century of Research and Its Accomplishments. 2004 Akan . University of Bonn. In Notebook for the XXVIIth Maya Hieroglyphic Forum at Texas. Settlement. Germany: Verlag Anton Sauerwein. 59-76. Grove. Alfonso Lacadena and Simon Martin 2003 Chichen Itza and Ek Balam: Terminal Classic Inscriptions from the Yucatán. eds. Nikolai. Maya Workshop Foundation. Nikolai 1992 Classic Maya Dance: Evidence from Hieroglyphs and Iconography. Ancient Mesoamerica 3(20):1-2. Pp. Grube. Acta Mesoamericana. and E. N.The God of Drinking. C. and Linda Schele 1990 Royal Gifts to Subordinate Lords. Sven.Gronemeyer. D. Dumbarton Oaks. Disease and Death. and Art at Middle Formative Period Chalcatzingo. Nikolia. Teufel. Grube. William L. Prager. Texas. David C. In Eighth Palenque Round Table. Tegucigalpa. Grove. 1993. S. 1996 Palenque in the Maya world. 53-76. and Susan Gillespie 2009 People of the Cerro: Landscape. eds. 315 . 14. Wayeb Notes No. Austin. and Barbara MacLeod 2010 What Could Happen in 2012: A Re-Analysis of the 13-Bak‘tun Prophecy on Tortuguero Monument 6. Pp. Grube. Fash and Leonardo Lopez Lujan. eds. Sachse. Grube. Copan Note 87. Copan Acropolis Archaeological Project and the Instituto Hondureño de Antropología.‖ Paper presented at the 45th Maya Hieroglyphic Forum at Austin. Martha J. San Francisco: Pre-Columbian Art Research Institute. December 2000. 34. Pp. Grube. Graña-Behrens. F. Honduras. 1–13.. Nikolai. David C. Wagner. Markt Schwaben. In Continuity and Change: Maya Religious Practices in Temporal Perspective. In The Art of Urbanism: How Mesoamerican Kingdoms Represented Themeselves in Architecture and Imagery. and Simon Martin 2001 ―The Coming of Kings: Writing and Dynastic Kingship in the Maya Area Between the Late Preclassic and Early Classic. Fifth European Maya Conference. Journal of World Prehistory 11:51-101. Macri and Jan McHargue.M. Norman 1981 Pom for the Ancestors: A Reexamination of Piedras Negras Stela 40. Guderjan.pdf. 369-387. Ancient Mesoamerica 17:97-104. Guatemala: Ministerio de Cultura y Deportes. 316 . Current Anthropology 43(3):351-382. Pp. 74.P.pdf. 1994 Las dinámicas culturales y ambientales de los orígines mayas: Estudios recientes del sitio arqueolόgico Nakbe. 2007.L. 1988 Ancient Maya Civilization. 2007 The Tomb of K‘inich Janaab Pakal: The Temple of the Inscriptions at Palenque.com/features/guenter/DosPilas. Pseudo-E-Groups. Guiteras-Holmes. NJ: Rutgers University Press. The Free Press of Glencoe... Byron 2002 The Social Life of Pre-Sunrise Things: Indigenous Mesoamerican Archaeology. C. Instituto de Antropologia e Historia. Laporte and H. Thomas 2006 E-Groups.com/articles/guenter/TI. Texas Notes on Precolumbian Art. and Culture No. Julia 2006 Ritual and Power in Stone: The Political and Cosmological Significance of Late Preclassic Izapan-Style Monuments.1994 New Observations on the Loltun Relief. Hammond. Stanley 2003 The Inscriptions of Dos Pilas Associated with B‘ajlaj Chan K‘awiil. Writing. Accessed August 13. 2009.mesoweb. J. Austin: University of Texas Press.mesoweb. Escobedo. Mexicon 3(5): 77-79. 1961 Perils of the Soul: the World View of a Tzotzil Indian. Hamann. In VII Simposio de Investigaciones Arqueologicas en Guatemala. and the Development of the Classic Maya Identity in the Eastern Peten. Richard D. eds. Asociacion Tikal. New Brunswick. Guenter. New York. Accessed January 11. Electronic document. Electronic document. Guernsey. Hansen. Washington. CO: Westview Press. eds. I. Harrison. Hendon. Boulder. 97–125. Wyllys Andrews 2004 Palaces of Tikal and Copan. October 7-8. Function and Meaning in Classic Maya Architecture: A Symposium at Dumbarton Oaks. Simon 2003 Cultural Difference as Denied Resemblance: Reconsidering Nationalism and Ethnicity. 1999 The Pre-Classic Maya Compound as the Focus of Social Identity. edited by Stephen D. Houston. Harrison. Washington. Pp.1998 Continuity and Disjunction: The Pre-Classic Antecedents of Classic Maya Architecture. 1983 A Reading for the Flint-Shield Glyph. and E. In Palaces of the Ancient New World. 2001 Thrones and Throne Structures in the Central Acropolis of Tikal as an Expression of the Royal Court. Jane H. 1993 Hieroglyphs and History at Dos Pilas: Dynastic Politics of the Classic Maya.C. Julia A. Philadelphia: Univ. 317 . Houston. New Heaven. In Royal Courts of the Ancient Maya. vol. Pp. Peter D. Stephen D.) Social Patterns in Pre-Classic Mesoamerica. and John Monaghan 1987 Continuities in Highland Maya Social Organization: Ethnohistory in Sacapulas. Peter D. 1992 The Flower World of Old Uto-Aztecan. Robert M. Comparative Studies in Society and History 45(2):343-361. 2: Data and Case Studies. Houston. eds.C. London: Thames & Hudson. 74-101. DC. pp. pp. 1999 The Lords of Tikal: Rulers of an Ancient Maya City. 113-148. Washington D. in D. Takeshi Inomata and Stephen D. Hill. 1994. DC: Dumbarton Oaks. 13-25. of Pennsylvania Press. Grove (ed.. Harrison. Susan Toby Evans and Joanne Pillsbury. Journal of Anthropological Research 48:117-144.. Dumbarton Oaks. Austin: University of Texas Press. In Contributions to Maya Hieroglyphic Decipherment. Hill. Guatemala. Human Relations Area Files Books. Cambridge University Press. Dance. Coben. and David Stuart 2000 The Language of Classic Maya Inscriptions 1. Res 22:73-101. and Takeshi Inomata. 135-158. And Politics. 271-276. No. John Robertson. eds. In Archaeology of Performance: Theaters of Power. New York: Thames and Hudson. Houston. 54-83. Lanham. 2000 Into the Minds of Ancients: Advances in Maya Glyph Studies.. Mary Miller and Simon Martin. 1997 Ancestors and the Afterlife. In Courtly Art of the Ancient Maya. 318 . 1999 Classic Maya Religion: Beliefs and Practices of an Ancient American People. Houston. Glyphs. 2006 Impersonation. 2001 Peopling the Classic Maya court.C. Latin American Antiquity 7(2):132-151. Antiquity 70(268):289-312. BYU Studies 38(4):43-72. Takeshi Inomata and Lawrence S. Brigham Young University. and Synthesis. Takeshi Inomata and Stephen D. Boulder. Stephen D. Research Reports on Ancient Maya Writing. 1996 Of Gods. and David Stuart 1989 The Way Glyph Evidence for Co-Essences Among the Classic Maya. eds. 2009 The Classic Maya. Comparison. Washington. Pp. and the Problem of Spectacle among the Classic Maya. Pp. 30. Pp.1996 Symbolic Sweatbaths of the Maya: Architectural meaning in the Cross Group. In Royal Courts of the Ancient Maya. D. Houston. vol. eds. MD: Rowman Altamira. Mexico. Current Anthropology 41(3):321-356. In Classic Maya Religion Symposium. 1998 The Ancient Maya Self: Personhood and Portraiture in the Classic Period. Cambridge. and Kings: Divinity and Rulership among the Classic Maya. Journal of World Prehistory 14(2):121-201 2004 The Acropolis of Piedras Negras: Portrait of a Court System. Houston.: Center for Maya Research. Community. CO: Westview Press. 1: Theory.. Palenque. Stephen D. Stephen D. Stephen D. Takeshi. and Synthesis. CO: Westview Press. Inomata.D. In Continuity and Change: Maya Religious Practices in Temporal Perspective. Current Anthropology 47(5):805-842. Austin: University of Texas Press. Kerry M. Vol. University of Texas at Austin. Nicholas Thomas and Caroline Humphrey. History. Fernando de Alva 1975 Obras históricas de Don Fernando de Alva Ixtlilxóchitl. In Shamanism. December 2000. and Karl Taube 2006 The Memory of Bones: Body. Kerry 2003 Verbal Art and Performance in Ch’orti’ and Maya Hieroglyphic Writing. Germany Dec. Mexico: n. University of Bonn. Houston 2001 Royal Courts of the Ancient Maya. vol. Performers. Arild 1958 Teotl and Ixiptlatli: Some Central Concepts in Ancient Mexican Religion . Caroline 1994 Shamanic Practices and the State in Northern Asia: Views from the Center and Periphery. 2000. 2 vols. 2004 Mak-―Portal‖ Rituals Uncovered: An Approach to Interpreting Symbolic Architecture and the Creation of Sacred Space Among the Maya. Ann Arbor: University of Michigan Press. Hvidfeldt.. and Spectators. 319 . Pp. Acta Mesoamericana. Takeshi Inomata and Stephen D. Copenhagen: Munskgaard. CO: Westview Press. Houston. Carrasco. eds. 5th European Maya Conference. Boulder. Hull. M. Inomata. 1: Theory. Hull. D. 14. and Michael D. and Stephen D. Ixtlilxóchitl. Jiménez-Sánchez. Acta Mesoamericana. 2006 Plazas.. Saurwein Verlag Markt Schwaben. Ajb‘ee Odilio 2004 The Politics of Maya Religion in Contemporary Guatemala. Comparison. In Royal Courts of the Ancient Maya. and the State. and Experience among the Classic Maya. 191-228. Takeshi 2001 King‘s People: Classic Maya Courtiers in a Comparitive Perspective. David Stuart.p. dissertation. 27-53. Pp. Fifth European Maya Conference.Houston. eds. Being. Humphrey. 14. Boulder. University of Bonn. In Continuity and Change: Maya Religious Practices in Temporal Perspective. Ph. Joyce. Teufel. 1986. Joyce. Wagner. London: Routledge. Peter D. Philip Warner. M. pt.D.M. Jones. Graña-Behrens. Thomas A. California: Robert Louis Stevenson School. and Karl Lorenz 1991 Olmec Bloodletting: An Iconographic Study. In Primera Mesa Redonda de Palenque. ed. Sachse. In Sixth Palenque Round Table. 1974 Ritual Blood-Sacrifice among the Ancient Maya. Rosemary. Markt Schwaben. Pebble Beach. 2005 What Kind of Subject of Study is ―The Ancient Maya‖? Reviews in Anthropology 34(4):295-311.G. 1914 Mexican Archaeology: An Introduction to the Archaeology of the Mexican and Mayan Civilizations of Pre-Spanish America. Pp. Joyce. Siân 1997 The Archaeology of Ethnicity: Constructing Identities in the Past and Present. and Linton Satterthwaite 1982 The Monuments and Inscriptions of Tikal: The Carved Monuments. Grube. Philadelphia. 143-150. Pp. Robertson. eds. Jones. Rosemary 2000 Gender and Power in Prehispanic Mesoamerica: Austin: University of Texas Press. Norman: University of Oklahoma Press. N. F. Kaplan. 1. and E. 320 . 184-191. 2. Jonathan 2001 Monument 65: A great emblamitic depiction of throned rule and royal sacrifice at Late Preclassic Kaminaljuyu. Christopher 1977 Inauguration Dates of Three Late Classic Rulers of Tikal. Fields. eds. Germany: Verlag Anton Sauerwein. S. Joralemon. Guatemala. Richard Edging. London. Merle Greene Robertson and Virginia M. C. American Antiquity 42:28-60. Prager. PA: University Museum of the University of Pennsylvania. pt. Christopher. Ancient Mesoamerica 11(02):185-198. Jones. Austin. Visible Language 16(1):39-48. State University of New York at Albany. Jorge Klor de Alva. San Francisco. Eulogio Guzmán. Julia G. Delvendahl. David H. In The Sacred and the Profane: Architecture and Identity in the Maya Lowlands. 10. Long Grove. eds. Markt Schwaben. In: Phoneticism in Mayan Hieroglyphic Writing. Mandell. and A. 321 . Wayeb. 1997 Of Macaws and Men: Late Preclassic Cosmology and Political Ideology in Izapan-style Monuments. IL: Waveland Press. Harri. Justin 2000 The Transformation of Xbalanque. 2000 Shamans and Religion: An Anthropological Exploration in Critical Thinking. eds. Kaufman. dissertation. [First read at the 38th Annual Meeting of the Society for American Archaeology. Albany: Institute for Mesoamerican Studies.. Aveni.. Keber. and Christophe Helmke 2010 Introduction to Maya Hieroglyphs. 57–74. The Work of Bernardino de Sahagun: Pioneer Ethnographer of SixteenthCentury Aztec Mexico. Kelley. Pp. Kuhnert.. In J. pp.Kappelman. P. Schubart. and William Norman. Elisa C. and Maya Stanfield-Mazzi 2002 The Role of Shamanism in Mesoamerican Art: A Reassessment. 1-16. edited by Anthony F. M.D. Cecelia F. Current Anthropology 43(3):383-419. University of Hamburg. morphology and vocabulary. Kehoe. 1982. CA. University of Texas Press. 1977 Maya Astronomical Tables and Inscriptions. Colas. 53-63. University of Texas at Austin. Kettunen. B. 1982 Costume and Name in Mesoamerica. K. Acta Mesoamericana. pp. Terrence. Alice B. Quinones Keber. John 1988 Sahagun and Hermeneutics: A Christian Ethnographer's Understanding of Aztec Culture. 1998. In Native American Astronomy. Klein. Germany: Verlag Anton Sauerwein. Ph. H. SUNY. Third European Maya Conference. Nicholson and E. edited by John Justeson and Lyle Campbell. 1984 An outline of proto-Cholan phonology.] Kerr. In The Sacred and the Profane: Architecture and Identity in the Maya Lowlands . Markt Schwaben. Lynne 1973 Letters from Prison. Antonio Gramsci. Leach. F. Markt Schwaben. London: Bell and Son.‖ Unpublished paper presented at the 6th European Maya Conference in Hamburg.: 27-41. Grube. 322 . C. 2002 El traje real entre los Mayas de la época clásica (250-900 d. P. University of Texas at Austin. Le Fort. Edmund R. Alfonso 2004a The Glyphic Corpus from Ek‘ Balam. December 2001. New York: Noonday Press. Guatemala. 23.M. 10. Victoria Solanilla Demestre ed. and E. In: Actas de las IIas Jornadas internacionales sobre textiles precolombinos . Sachse. Juan Pedro.html. eds. Germany. Graña-Behrens. D. Chicago. 2000 The Classic Maya Accession Ceremony as a Rite of Passage. Third European Maya Conference. University of Hamburg. Laporte. FAMSI. Germany: Verlag Anton Sauerwein.org/reports/01057/index. Fifth European Maya Conference. 1998. MA Thesis.). The University of Chicago Press. Delvendahl. Schubart. Oliver 1965 Santa Eulalia the Religion of a Cuchumatan Indian Town. Prager. eds. December 2000. Teufel. 87-98. N.LaFarge. 17-23. and A.. Genevieve 1994 Accession Ritual among the Classic Maya. Barcelona. Kuhnert. 14. Acta Mesoamericana. Lacadena. Acta Mesoamericana. Tikal. Accessed 06/09/08 2004b On the Reading of Two Glyphic Appellatives of the Rain God. Lawner. K. Germany: Verlag Anton Sauerwein. Pp.famsi. C. 1954 Political systems of Highland Burma. M. S. Wagner. 2001 ―Sacred versus Divine: Comments on Classic Maya Kingship. Colas. Ancient Mesoamerica 6:41-94. In Continuity and Change: Maya Religious Practices in Temporal Perspective. University of Bonn. and Vilma Fialko 1995 Un reencuentro con Mundo Perdido. Pp. 24 y 25 de abril de 2001. Los Angeles. Department of Art History. Luís and Albert Davletshin 2004 The Glyph for Antler in the Mayan Script. Department of Anthropology. Jr. edited by J. Lévi-Strauss. Brandon 1995 The Role of Specialized Production in the Development of Sociopolitical Complexity: A Test Case fromthe Late Classic Maya. and Fred Valdez. Malden. Livingston. Sylvia Modelski [trans]. Austin 1999 New Perspectives on the Late Classic Political History of Quirigua. 1991 The Dances of the Classic Maya Gods Chak and Hun Nal Ye. Looper. Lewis. NJ: Pearson Prentice Hall. Mesoweb: www. 5. Performers and Spectators: Political Theaters of the Classic Maya by Takeshi Inomata. Austin: University of Texas Press. Lohse. Lopes. 2009 To Be Like Gods: Dance in Ancient Maya Civilization. In Mesoamerican Archaeology: Theory and Practice. Guatemala. Austin: University of Texas Press.com/articles/lopes/Stinger. A. 2004 Ancient Maya Commoners. Luís 2005 A Reading for the "STINGER" Glyph. 2004 Shared Art Styles and Long-Distance Contact in Early Mesoamerica. Austin: University of Texas Press. Unpublished Master's thesis. 73-96. Lopes. pp. University of Texas. Upper Saddle River. Joyce. Accessed 05/15/08.wayeb. University of California.. Blackwell Publishing.mesoweb. Jon C. Richard G. 2003 Lightning Warrior: Maya Art and Kingship at Quirigua. Wayeb Notes.org/notes/wayeb_notes0011. Ancient Mesoamerica 10:263-280.. A.Lesure. Hendon and R. Claude 1982 The Way of the Masks. Current Anthropology 47.pdf. 2006 Comments to Plazas. Matthew G. 2005 Anatomy of the Sacred: An Introduction to Religion. James C. Seattle: University of Washington Press. 11. No.pdf 323 . PhD dissertation. Senner. Translated by Thelma Ortiz de Montellano and Bernard Ortiz de Montellano. México. In Third Palenque Round Table. ed.J. Lincoln: University of Nebraska Press. Macri. Macri and A. 2003 The Politics of Ritual: The Emergence of Classic Maya Rulers. In The Language of Maya Hieroglyphs. Mexico. Cambridge. Latin American Antiquity. Lounsbury. Pp. Floyd 1980 Some Problems in the Interpretation of the Mythological Portion of the Hieroglyphic Text of the Temple of the Cross at Palenque. 143–169. Austin: University of Texas Press.López Austin. Robertson. Lisa J. Macri. Ford. W. Lucero. 1997 Noun Morphology and Possessive Constructions in Old Palenque Ch‘ol. Berkeley. Politics. Martha. Pp. 4. 1989 The Ancient Writing of Middle America. and the Voice of the People. G. 99-115. Martha 1988 A Descriptive Grammar of Palenque Mayan. 203-237. 2 vols. M. López Luján. Alfredo 1988 Human Body and Ideology: Concepts of the Ancient Nahuas. Pre-Columbian Art Research Institute. Unpublished PhD dissertation. pp. pp. ed. 1978. pp. Ancient Mesoamerica 14:285-297. Instituto Nacional Antropología e Historia. Journal of Social Archaeology Vol. Leonardo 1989 La recuperación mexica del pasado teotihuacano. University of Utah Press. Cambridge University Press. Vol. University of California. 18 No. In The Origins of Writing. and Matthew Looper 2003 Nahua in Ancient Mesoamerica: Evidence from Maya Inscriptions. 407-427 2010 Materialized Cosmology among Ancient Maya Commoners. San Francisco. M. In Archaeoastronomy in the New World. Current Anthropology 44(4):523-558. 1982 Astronomical Knowledge and Its Uses at Bonampak. 8996. Aveni. edited by Anthony F. 2007 Classic Maya Temples. 324 . 10(1):138-167. edited by M. Salt Lake City. Pp. Cologne. 221-237. and M. 1992 Royal Families. edited by Nikolai Grube. 1995 Where Is Lowland Maya Archaeology Headed? Journal of Archaeological Research 3(1):3-53.Marcus. Joyce 1976 Emblem and State in the Classic Maya Lowlands. In Mesoamerican Elites: An Archaeological Assessment. V. Philadelphia. 2002 Comment on Klein et al. D. University of Pennsylvania Museum of Archaeology and Anthropology. Boulder. R. pp. Pp.C. 5. eds.: Dumbarton Oaks. Comparison. B. Journal of Archaeological Research 11(2):71-148. Royal Texts: Examples from the Zapotec and Maya. 2003 Recent Advances in Maya Archaeology. Chase and Arlen F. The PARI Journal 2(1):7-12. vol. Cobos. March 23. Könemann. Eva Eggebrecht and Matthias Seidel. Simon 1997 The Painted King List: A Commentary on Codex-style Dynastic Vases. 2001d Under a Deadly Star – Warfare Among the Classic Maya. coloniales y modernos. 846-863. Norman: University of Oklahoma Press.‖ Ruler of Tikal. eds. Memoria de la Tercera Mesa Redonda de Palenque. Takeshi Inomata and Stephen D. Martin. CO: Westview Press. eds. 1: Theory. Kerr and J. 174-185. Current Anthropology 43(3):409. T. Washington. 2001a Court and Realm: Architectural Signatures in the Classic Maya Southern Lowlands. New York: Kerr Associates. eds. Mexico City: Consejo Nacional para la Cultura y las Artes-Instituto Nacional de Antropología e Historia. vol. In La organización social entre los mayas prehispánicos. 49-78. Robertson. In Royal Courts of the Ancient Maya.‖ Paper presented at the Nineteenth Maya Weekend: The Four Corners of the Maya World. 325 . 2001c ―The War in the West: New Perspectives on Tonina and Palenque. Diane Z. Pp. and Synthesis. In Maya: Divine Kings of the Rainforest. Chase. In The Maya Vase Book. G. Houston. 168-194. Pp. Kerr. 2001b Unmasking ―Double Bird. 2002 The Baby Jaguar: An Exploration of Its Identity and Origins in Maya Art and Writing. Blos. London: Thames and Hudson. 154-183. eds. 9. 2006 Cacao in Ancient Maya Religion: First Fruit from the Maize Tree and other Tales from the Underworld. edited by M. Gainsville: University Press of Florida. Mathews. The PARI Journal 6(1):1-9. Peter. State University of New York. 2003b In Line of the Founder: A View of Dynastic Politics at Tikal. Institute for Mesoamerican Studies.‖ In Phoneticism in Mayan Hieroglyphic Writing. 3-46. and Affairs of State: Advancing Maya Archaeology. and Nikolai Grube 2000 Chronicle of the Maya Kings and Queens: Deciphering the Dynasties of the Ancient Maya. In Primera Mesa Redonda de Palenque. Arqueologia Mexicana 61:44-47. and James F. ed. In Tikal: Dynasties. New York: Thames and Hudson. Mathews. John Justeson and Lyle Campbell. California. pp. McNeil. pp.). 326 .G. In Chocolate in Mesoamerica: A Cultural History of Cacao.. Martin. Mathews. and John Justeson 1984 Patterns of Sign Substitution in Maya Hieroglyphic Writing: ―The Affix Cluster. Pebble Beach. Robert Louis Stevenson School. Sabloff (ed. Pp. Monograph.2003a Moral-Reforma y la contienda por el oriente de Tabasco. Peter 1977 The Inscription on the Back of Stela 8. 185-231. Part 1. 2005b Of Snakes and Bats: Shifting Identities at Calakmul. Unpublished manuscript. and Linda Schele 1974 The Lords of Palenque: The Glyphic Evidence. 2008 Chronicle of the Maya Kings and Queens. Robertson. Albany: Institute for Mesoamerican Studies. 2nd edition. Peter. J. The PARI Journal 6(2):5-15. Garber 2004 Models of Cosmic Order: Physical expression of sacred space among the ancient Maya. L. Jennifer P. School of American Research Press. 63-76. Simon. C. Santa Fe. 2005a Caracol Altar 21 Revisited: More Data on Double-Bird and Tikal‘s Wars of the Mid-Sixth Century. Mathews. Ancient Mesoamerica 15:49-59. Foreigners. Pp. Cameron L. Mendieta. and Markets in Ancient Mesoamerica. Robert Wauchope and Gordon R. Houston. Patricia Ann 1995 Living with the Ancestors: Kinship and Kingship in Ancient Maya Society. Kathleen Berrin and Esther Pasztory. D. University of Texas Press.E. eds. in E. Honduras. In Handbook of Middle American Indians. New York: Norton. McAnany (ed. Suzanne W.) Dimensions of Ritual Economy (Research in Economic Anthropology. Ed. 237-275. pp. New York: Kluwer Academic/Plenum Publishers. McAnany. Washington. Stephen D. and Associated Hieroglyphs. Marcel 1990 The Gift: the Form and Reason for Exchange in Archaic Societies. Patricia A. 2008 Shaping Social Difference: Political and Ritual Economy of Classic Maya Royal Courts. Staller and M.Matos Moctezuma. Pp. Emerald Group Publishing Limited. Vol 2. Thames and Hudson. Austin. Christian Wells. Eduardo. Miles. Culture. New York Mauss. Pp. In Function and Meaning in Classic Maya Architecture. J. Gerόnimo de 1870 Historia eclesiastica indiana.E. Dumbarton Oaks. Eds. 125-148. Volume 27). 2001 Cosmology and the Institutionalization of Hierarchy in the Maya Region. 1998 Ancestors and the Classic Maya Built Environment. and Leonardo López Luján 1993 Teotihuacan and Its Mexica Legacy. 2010 Death and Chocolate: The Significance of Cacao Offerings in Ancient Maya Tombs and Caches at Copan. Willey. Austin: University of Texas Press. ed. Jonathan Haas. In Teotihuacán: Art from the City of Gods. pp. 156-165. 327 .219-247 McNeil. In Pre-columbian Foodways: Interdiscipilanary Approaches to Food. Carrasco Eds. Mexico: Antigua Libreria. In From Leaders to Rulers. 1965 Sculpture of the Guatemala-Chiapas Highlands and Pacific Slopes.C. and Karl Taube 1993 The Gods and Symbols of Ancient Mexico and the Maya: An Illustrated Dictionary of Mesoamerican Religion. London. In Royal Courts of the Ancient Maya. Austin: University of Texas Press. Morley. Houston 1987 The Classic Maya Ballgame and its Architecural Setting.187–222. Washington. University of Oklahoma Press. and Stephen D. Monaghan. Monaghan. 1980 K'e?s: Quiche Naming. and Revelation in Mixtec Sociality. 1995 The Covenants with Earth and Rain: Exchange. 328 . edited by Stephen D.Miller. Journal of the Royal Anthropological Institute 16:588-608. American Journal of Archaeology 15:195–214. CO: Westview Press. In Supplement to the Handbook of Middle American Indians.L. ed. DC. 6: Ethnology. and Simon Martin 2004 Courtly Art of the Ancient Maya. Houston. In Function and Meaning in Classic Maya Architecture. Pp. 2000 Theology and History in the Study of Mesoamerican Religions. Mondloch. 1999 Maya Art and Architecture. Christopher T. 24-49. and Noah Butler 2010 Ritual exchange and the fourth obligation: ancient Maya food offering and the flexible materiality of ritual. Boulder. Carnegie Institution of Washington. Sylvanus G. vol. Morehart. 201-222. J. 2: Data and Case Studies. London: Thames and Hudson. Dumbarton Oaks. D. Sacrifice.C. John D. Washington. Miller. New York: Thames and Hudson. Takeshi Inomata and Stephen D. Pp.. Mary Ellen. eds. D. 1920 The Inscriptions at Copan. Res 14:46-65 Miller. 1911 The historical value of the books of Chilan Balam. pp. Houston. Mary Ellen. Norman. Mary Ellen. Mary Ellen 1998 A design for meaning in Maya architecture. Journal of Mayan Linguistics 2:9-25. Thames and Hudson. vol.J. 2001 Life at Court: The View from Bonampak. Miller. Jonaitis and Z. 33. Pasztory. Mejía. Sylvanus G. 1250-1630. Esther 1982 Shamanism and North American Indian Art. Mónica 2006 El Grupo Jabalí: Un complejo arquitectónico de patrón triádico en San Bartolo. CA: Stanford University Press. Orellana. Austin: University of Texas Press.Morley. No.. Laporte. Elizabeth A 1998 The Ontology of Being and Spiritual Power in the Stone Monument Cults of the Lowland Maya. 2007 Olmec Archaeology and Early Mesoamerica. Revised by Robert J. 2005. Pellecer Alecio. Brady. In Stone Houses and Earth Lords: Maya Religion in the Cave Context. In Native North American Art History: Selected Readings. Pharo. Newsome. 115-136. pp. Palo Alto: Peek.P. 187-211. Res: Anthropology and Aesthetics. and George W. In XIX Simposio de Investigaciones Arqueológicas en Guatemala. Arroyo y H. Pp. Mexicon 16:6–10. Holley 2005 The Sweatbath in the Cave: A Modified Passage in Chechem Ha Cave.. Prufer and James E. Sandra 1984 The Tzutujil Mayas: Continuity and Change. 2001 Trees of Paradise and Pillars of the World: The Serial Stelae Cycle of “18-Rabbit-God K. Moyes. eds. Pearlstone.937-948. Cambridge University Press. Cambridge. pp. Palo Alto. J. Norman: University of Oklahoma Press. B. A. Nahm.” King of Copán. 7-30. Belize. Sharer. Lars Kirkhusmo 2007 The Concept of ―Religion‖ in Mesoamerican Languages. Numen 54(1):2870. edited by Keith M. P. 329 . Pool. Petén. Werner 1994 Maya Warfare and the Venus Year. Christopher A. pp. Boulder: University Press of Colorado. Museo Nacional de Arqueología y Etnología. eds. Brainerd 1983 The Ancient Maya. Guatemala. Pre-Columbian States of Being. In Mesoamerican Writing Systems. Preus. Elizabeth P. University of Texas at Austin. 113117. 19–30. 1989 Olmec Colossal Heads as Recarved Thrones: ―Mutilation. and Garman Harbottle 1979 Thematic and Compositional Variation in Palenque Region Incensarios. Labyrinthos. Houston. and Genevieve Le Fort 1997 Rebirth and Resurrection in Maize God Iconography. Quenon. Benson. Comparison. In Codex Wauchope: A Tribute Roll.): 65– 72. Beyond Indigenous Voices: LAILA/ALILA Eleventh International Symposium on Latin American Indian Literatures. In Royal Courts of the Ancient Maya. Barbara Edmonson. Tercera Mesa Redonda de Palenque. IV. Kerr. Belize. eds. 195-236. Pp. Monterrey. and Winifred Creamer. 165178. Tulane University. vol. Durham: Duke University Press. D. vol. 1996 Celtiform Stelae: A New Olmec Sculpture Type and Its Implication for Epigraphers. Kathryn V. 2001 Classic Maya Concepts of the Royal Court: An Analysis of Renderings on Pictorial Ceramics. 1996 Narratives of Power: Late Formative Public Architecture and Civic Center Design at Cerros. pp. pp. James B. Robert L. Washington. Kerr and J. Res: Anthropology and Aesthetics 17–18: 23–29. Pp. Ph.‖ Revolution. Tatiana 1950 A Study of Classic Maya Sculpture. ed. Takeshi Inomata and Stephen D.. Reese.. Washington. Dorie 1994 Painting the Maya Universe: Royal Ceramics of the Classic Period. Boulder. Michel. CO: Westview Press. 1978 Olmec Gods and Maya God-Glyphs. 884-902. In The Maya Vase Book. Mexico. Ronald L. Bishop. Guatemala. 1994 (Mary H. DC: Dumbarton Oaks. DC: Carnegie Institution of Washington. ed. Proskouriakoff. 1973 The ―Hand-grasping Fish‖ and Associated Glyphs on Classic Maya Monuments. and Synthesis. New York: Kerr Associates. American Antiquity 25(4):454-475. 330 . LA. New Orleans. 1: Theory. eds. and Recarving. Rands. Pp.Porter. 5. edited by Marco Giardino. Lancaster. B. Reents-Budet. Calif. 1960 Historical Implications of a Pattern of Dates at Piedras Negras. Shamanism. Dumbarton Oaks Research Library and Collection. Joyce. Prudence M. eds. Washington. Ringle. dissertation. Kent. In Ancient Maya Political Economies. Pp. Rivera Dorado. Berthold 1986 Late Classic Relationship Between Copán and Quirigua: Some Epigraphic Evidence. and Debra S. ed. Performers. David C. Ricketson Jr. 1928 Astronomical Observatories in the Maya Area. and Rulership in the Olmec World. Willey. Freidel. University of Texas at Austin. Grove and Rosemary A. 1988 Epigraphy of the Southeast Zone in Relation to Other Parts of Mesoamerica. 27-45. edited by Elizabeth Hill Boone and Gordon R. 183-224. Pp. F. William M. Reilly. DC. Princeton University. 67–94. eds.D. and Political Power in Middle Formative Mesoamerica. 1999 Pre-Classic City Scapes: Ritual Politics among the Early Lowland Maya. Lanham. III 1994 Visions to Another World: Art. Miguel 2006 Comments on ―Plazas. Kathryn. Ancient Mesoamerica 10:25-50.Reese-Taylor. Princeton. and Spectators: Political Theaters of the Classic Maya‖ by Takeshi Inomata. In The Southeast Maya Periphery. eds. Rice. Geographical Review 18(2):215-225. Washington. Walker 2002 The Passage of the Late Preclassic in the Early Classic. Schortman. pp. 9 and 10 October 1993. In The Olmec World: Ritual and Rulership. Marilyn A. Riese. 1995 Art. Ph. Urban and Edward M. DC: Dumbarton Oaks. Current Anthropology 47(5):829. Ritual. Michael Coe. Austin: University of Texas Press. Masson and David A. Patricia A. Pp. In Social Patterns in Pre-Classic Mesoamerica: A Symposium at Dumbarton Oaks. MD: Rowman Altamira. Pp. Oliver G. In The Southeast Classic Maya Zone. 87-122. 94-101. 331 . 1999 Rethinking Classic Lowland Maya Pottery Censers. NJ: The Art Museum. J. 3: The Late Buildings of the Palace. 222231. 523. 1940 Personal Names of the Maya of Yucatan. 109–116. Contribution 31. Pebble Beach. Princeton: Princeton University Press. 1986 Interaction among Classic Maya Polities: A Preliminary Examination. Karl 1940 A Special Assemblage of Maya Structures. In The Art. vol. Cambridge: Cambridge University Press. In Peer Polity Interaction and Socio-political Change. eds. 1976 Physical Deformities in the Ruling Lineage of Palenque. and the Dynastic Implications. Washington. Rosenblum Scandizzo and John R. Mexico City. Appleton-Century New York. 1985 The Sculpture of Palenque. Merle Greene 1983 The Sculpture of Palenque. pp. Roys. Iconography and Dynastic History of Palenque Part III. Brill.Robertson. Leopold 1973 Priesthood: A Comparative Study. Universidad Nacional Autonoma de Mexico. Romero Molina. Carnegie Institution of Washington Pub. The Netherlands: E. Mexico City. Cherry. and George Vaillant. Harry Shapiro. Princeton: Princeton University Press. Roberston. Ruz Lhuillier. Colin Renfrew and John F. 1933 The Book of Chilam Balam of Chumayel. D. Jeremy A. Washington D. ed.: Carnegie Institution. Sabloff. Ralph L. Javier 1986 Catálogo de la Colección de Dientes Mutilados Prehispánicos IV Parte. Pp. Merle Greene Roberston. Colección Fuentes Instituto Nacional de Antropología e Historia. vol. Samuel K. and Marjorie S. Scandizzo. Robert Louis Stevenson School. Leiden. Merle Greene. 332 .C. 59-86. Alberto 1968 Costumbres funerarias de los antiguos mayas. Lothrop. Pp. edited by Ralph Linton. California. 1: The Temple of the Inscriptions. In The Maya and Their Neighbors: Essays on Middle American Anthropology and Archaeology. DC: Carnegie Institution of Washington. Sabourin. Ruppert. Chiapas. Dibble. Frauke 2004 Interpreting Maya Religion: Methodological Remarks on Understanding Continuity and Change in Maya Religious Practices. and Karl A. California. and Heather Hurst 2005 The Murals of San Bartolo. Santa Fe. Pp. University of Pennsylvania. Mesoweb. N. eds. Teufel. 1991 Courting the Southern Lowland Maya Lowlands: A Study in Pre-Hispanic Ballgame Architecture. 129-144. Sachse. Frauke. Germany: Verlag Anton Sauerwein. Prager. NM. Pp. vol. Acta Mesoamericana. Pre-Columbian Art Research. Linton. Anderson and Charles E. December 2000. Palenque.Sachse. School of American Research and the University of Utah. Scarborough. C. and Allen Christenson 2005 Tulan and the Other Side of the Sea: Unraveling a Metaphorical Concept from Colonial Guatemalan Highland Sources. F.O. 1989 Some Further Thoughts on the Copán-Quirigua Connection. Pre-Columbian Art Research Center. Wagner.com/articles/tulan/Tulan. Grube. and E. The University Museum. Sax. D. William S. 1998 The Hall of Mirrors: Orientalism. 7:1-56. 1-21. Schele. Sharer. www. 1979 Quirigua Altar L (Monument 12). Part 1: The North Wall. translated by Arthur J. Guatemala. Linda 1978 Genealogical Documentation on the Tri-figure Panels at Palenque. Graña-Behrens. Scarborough and David R Wilcox. Copán Mosiacs Project. Edited by Wendy Ashmore. Monterey.pdf Sahagún.mesoweb. Philadelphia. 14. 11 vols. In The Mesoamerican Ballgame. In Quirigua Reports. American Anthropologist 100(2):292-301. University of Bonn. Copán. In Continuity and Change: Maya Religious Practices in Temporal Perspective. Ancient America No. Fifth European Maya Conference. In: Tercera Mesa Redonda de Palenque Vol. Fray Bernardino de 1950–1982 (1575–1578) Florentine Codex: General History of the Things of New Spain. Satterthwaite. Vernon L. 1. Herald Printers. eds. Copán Note 67. IV: 41-70. El Peten. Pp. William. general editor Robert J.M. David Stuart. Honduras. Vernon L. Sachse. S. Markt Schwaben. Mexico. Saturno. 39-43. 333 . Tucson: The University of Arizona Press. Taube. Anthropology. and the Other. New York: Morrow. 334 . ed. N. eds. Austin: Department of Art History. 1991 The Demotion of Chac-Zutz‘: Lineage Compounds and Subsidiary Lords at Palenque. 479-517. Pp. Freidel 1990 A Forest of Kings: The Untold Story of the Ancient Maya. Fields.1990 The Early Classic Dynastic History of Copán: Interim Report. Linda. with Commentaries on the Dynastic History of Palenque. College of Fine Arts. Schele. Austin: Department of Art. In Sixth Palenque Round Table. TX. and Nikolai Grube 1982 Copán Mosaics Project. In The Emergence of Lowland Maya Civilization: The Transition from the Preclassic to the Early Classic. and Institute of Latin American Studies. Austin. Schele. 1995 Sprouts and the Early Symbolism of Rulers in Mesoamerica. Grube. Schele. Merle Greene Robertson and Virginia M. University of Texas at Austin. Copán Note 70. 1995. Linda. and David A. 1994 The Peten Wars: Notebook for the XVIIIth Maya Hieroglyphic Workshop at Texas. In Function and Meaning in Classic Maya Architecture. 117-135. 1993. Washington. Copán Mosaics Project. 1993b The Workbook for the XVIIth Maya Hieroglyphic Workshop at Texas. Pp. Linda. Germany: Verlag Anton Saurwein. Houston. Stephen D. Austin: University of Texas. and Matthew Looper 1996 Workbook for the XXth Maya Hieroglyphic Forum. Austin: Department of Art and Art History. Linda. 1994. Austin: Art Department. Norman: University of Oklahoma Press. 1986. 151-166. 1998 The Iconography of Maya Architectural Facades During the Late Classic Period. 1995 The Proceedings of the Maya Hieroglyphic Workshop: Late Classic and Terminal Classic Warfare. Schele. Dumbarton Oaks. Copán Note 108: Instituto Hondureño de Antropología e Historia. Mockmuhl. March 11-12. University of Texas at Austin. March 13-14. ed. and Peter Mathews 1993a The Proceedings of the Maya Hieroglyphic Workshop: The Dynastic History of Palenque. University of Texas at Austin. D.C. University of Texas at Austin. Norman: University of Oklahoma. No. University of Texas at Austin. the Rabbit. World Archaeology 36(3):399-415. Copán. Edward M. 335 . Schortman. and the Bundle: “Accession” Expressions from the Classic Maya Inscriptions. Schele. Roys 1968 The Maya Chontal Indians of Acalan-Tixchel: A Contribution to the History and Ethnography of the Yucatan Peninsula. Harvard University. MA. Villela 1992 Some New Ideas about the T713/757 ―Accession‖ Phrases. and the Department of Art and Art History.C. American Antiquity 54(1):52-65. Linda. Washington D. and Jeffrey Miller 1983 The Mirror. Copán Note 96. Writing and Culture No. and Mary Ellen Miller 1986 The Blood of Kings: Dynasty and Ritual in Maya Art. and David Stuart 1986 Te-Tun as the Glyph for Stela. Linda. Fort Worth: Kimbell Art Museum. John 2004 New Dramas for the Theatre Atate: The Shifting Roles of Ideological Power Sources in Balinese Polities. Cambridge. Schele. Vol. Copán Acropolis Project and the Instituto Hondureño de Antropología e Historia. Linda.: Dumbarton Oaks. Linda. New York: Scribner. 1989 Interregional Interaction in Prehistory: The Need for a New Perspective. Schele. Center for the History and Art of Ancient American Culture. Papers of the Peabody Museum of Archaeology and Ethnology. Paul 1904 Representation of Deities in the Maya Manuscripts. 1. Schoenfelder. and Khristaan D. Linda and Elizabeth Newsome 1991 Taking the Headband at Copán. Copán Note 1. 27. Schele. Texas Notes on Precolumbian Art.1998 The Code of Kings: The Language of Seven Sacred Maya Temples and Tombs. 4. and Ralph L. France V. Copán Mosaics Project and the Instituto Hondureno de Antropologia e Historia. Honduras Schele. Schellhas. Scholes.. DC. Santa Fe. Stanford: Stanford University Press.html.. Honduras. Robert J. Ellen E. W. 23-50. Joel 2003 Major Find in Palenque‘s Temple XXI... M. (Eds. Robert J. Kaminalijuyu. Publication 596. 13-32. and A. Traxler. In Religion and Power: Divine Kingship in the Ancient World and Beyond.Selz. Golden and Greg Borstede. Marcello A. Carnegie Institution of Washington Yearbook 54:289-295. Edwin M. Sharer. Sharer. Copan: The History of an Ancient Maya Kingdom.com/reports/discovery2. In Continuities and Changes in Maya Archaeology: Perspectives at the Millennium. Sedat. Pp.. Guatemala. Bell. Shook. 6th Edition.W. Brasswell. pp. David W. North Carolina. Gebhard J. Edwin M. 139–199. Ellen E..V. Shook. 1990 Quirigua: A Classic Maya Center and its Sculptures.. Robert J.. 3. Kidder 1952 Mound E-III-3. Pp. School of American Research. New York: Routledge. 2009. Charles W. Austin: University of Texas Press. In: Andrews. ed. and Loa P. Robert J. Carnegie Institution. Washington. Bell. Canuto. vol. Contributions to American Anthropology and History.). 2008 The Divine Prototypes.. Accessed October 10. Sedat. Chicago: The Oriental Intitute of the University of Chicago. David W. and Christopher Powell 1999 Early Classic Architecture Beneath the Copán Acropolis: A Research Update. Robert J. N. Sharer. Golden 2004 Kingship and Polity: Conceptualizing the Maya Body Politic. Brisch. eds. In The Maya and Teotihuacan: Reinterpreting Early Classic Interaction .L. 2004 Founding Events and Teotihuacan Connections at Copan. 2005 Early Classic royal power at Copan: the origins and development of the Acropolis. 143-165.. ed. 1955 Yucatan and Chiapas. Sharer. Traxler 2006 The Ancient Maya. Sharer. Miller. Skidmore. E. no. Loa P. Mesoweb Reports.mesoweb. Ancient Mesoamerica 10:3–23. and Charles W. Loa P. Julia C.. 9. Traxler. Electronic document. 336 . Fash. Carolina Academic Press: Durham. Geoffrey E. Pp.. 1985 The Maya Sky. the Maya World: A Symbolic Analysis of Yucatec Maya Cosmology. Kaylee R. Ortwin 1975 El Maya–Chontal de Acalan: Análisis lingüístico de un document de los años 1610–12. Sosa. Mineola.2011 Earliest Jester God Found at K‘o.pdf. 9. Stirling. 2005 Did the Maya Build Architectural Cosmograms? Latin American Antiquity 16(2):217-224. National Geographic 78 (3): 309–334. Latin American Antiquity 14(2):221-228. Thesis. Jon 2006 The Gift in the Cave for the Gift of the World: An Economic Approach to Ancient Maya Cave Ritual in the San Francisco Hill-Caves. Albany. Florida State University. Centro de Estudios Mayas. Universidad Nacional Autónoma de México. Spenard. Smith. Coordinación de Humanidades. Michael E.D. Vol. 2003 Can We Read Cosmology in Ancient Maya City Plans? Comment on Ashmore and Sabloff. Mexico. Stern. John R. University of Texas at Austin Spinden. Mesoweb:. dissertation. Ph. MA. Cancuén Region. Matthew 1940 Great Stone Faces of the Mexican Jungle. 2007 Framing the Portrait: Towards and Understanding of Elite Late Classic Maya Representation at Palenque. 337 . Unpublished PhD dissertation. Mexico City. Seattle: University of Washington Press. State University of New York. Smailus.com/reports/EarliestJesterGod. NY: Dover. Guatemala. Guatemala. Spencer. Herbert Joseph 1913[1975] A Study of Maya Art.mesoweb. Theodore 1966 Ball Games of the Americas. Accessed 5/29/11. harvard.C. 1996b Kings of Stone: A Consideration of Ancient Stelae in Maya Ritual and Representation. M. Ph. The PARI Journal 1(1):13-19. 338 . 153-172.D. Richard A. PARI. Arqueologia Mexicana VIII(45):28-33. Diehl and Catherine Janet Berlo. Palenque. accessed Month X. and Scott Sessions. pp 1-11. 2002 Comment on Klein et al.. Ancient Mesoamerica 3:169-184. 1988 The Rio Azul Cacao Pot: Epigraphic Observations on the Function of a Maya Ceramic Vessel. Andrea 1989 Disconnection. Antiquity 62:153-157. 2000b Las nuevas inscripciones del Templo XIX.. 14. 1996a Hieroglyphs and History at Copán. 2000a ―The Arrival of Strangers‖: Teotihuacan and Tollan in Classic Maya history. 1987 Ten Phonetic Syllables. Lindsay Jones. Department of Anthropology. Res 29-30:148-171. and Political Expansion: Teotihuacan and the Warrior Stelae of Piedras Negras. David 1984 Royal Auto-Sacrifice among the Maya: A Study in Image and Meaning. dissertation. Stuart. 1992 Hieroglyphs and Archaeology at Copan. eds. Washington. no. 1995 A Study of Maya Inscriptions. ―The Role of Shamanism in Mesoamerican Art: A Reassesment.html. 465-514. 2000c Ritual and History in the Stucco Inscription from Temple XIX at Palenque. Vanderbilt University. Electronic document. Ford. David Carrasco. Foreign Insignia. Pp. Pp. D.J. In Mesoamerica’s Classic Heritage: From Teotihuacan to the Aztecs.Stone. Washington. 1997 Kinship Terms in Maya Inscriptions. 200X.. Center for Maya Research.‖ Current Anthropology 43(3):410-411. eds.peabody . Macri and A. eds.edu/Copán/text. Research Reports on Ancient Maya Writing. Boulder: University Press of Colorado. AD 700-900. In Mesoamerica after the Decline of Teotihuacan. DC: Dumbarton Oaks. Res 7-8:6-20. In The Language of Maya Hieroglyphics. 58. 2008 Copán Archaeology and History: New Finds and New Research. Houston 1994 Classic Maya Place Names. David. Copán. San Francisco: PreColumbian Art Research Institute. Sourcebook for the 2008 Maya Meetings at the University of Texas at Austin . 2009. Stuart. Accessed May 19.com/stuart/notes/Throne. and Stephen D. London. Taladoire. New York: Thames and Hudson. Stephen D. edited by Ellen E. Pp. Stuart. Eric 1979 Orientation of Ball-Courts in Mesoamerica. 261264. Mythology. 2007 The Stucco Portraits on the Temple of the Inscriptions. Stuart. In Courtly Art of the Ancient Maya. Mary Miller and Simon Martin. Austin: Maya Workship Foundation. Copán Mosaics Project. Thames and Hudson. Maya Decipherment <. Marcello A. and George Stuart 2008 Palenque: Eternal City of the Maya. Austin. Philadelphia: University of Pennsylvania Museum of Archaeology and Anthropology.wordpress. 2004a Longer Live the King: The Questionable Demise of K‘inich K‘an Joy Chitam of Palenque. Houston. and Linda Schele 1989 A Substitution Set for the “Macuch / Batab” Title.2003 A Cosmological Throne at Palenque. Nikolai Grube. 1-96. The PARI Journal 4(1):1-4. David. 339 . eds. 2005 The Inscriptions of Temple XIX at Palenque. and Robert J. Bell.pdf. In Understanding Early Classic Copán. and Royal Legitimization at Palenque‘s Temple 19. Honduras. DC: Dumbarton Oaks. In Notebook for the XXIIIrd Maya Hieroglyphic Forum at Texas. and John Robertson 1999 Recovering the Past: Classic Maya Language and Classic Maya Gods. pp. Mesoweb: www. Archaeoastronomy. David. Washington.com/2007/05/17/the-stuccoportraits-on-the-temple-of-the-inscriptions-part-i/.mesoweb. Canuto. Stuart. Pp. 2004b History. Sharer. 2004c The Beginnings of the Copán Dynasty A Review of the Hieroglyphic and Historical Evidence. Copán Note No. 215–248. David. 2:12-13. pt 2. DC: Dumbarton Oaks. 1986 The Teotihuacan Cave of Origin. eds. 6. 171–181. Washington. 4. No. Ph. Ancient Mesoamerica 10(2):169-188. Tambiah. 1988b A Prehispanic Maya Katun Wheel. Kerr. Pp. 331-351. D. Yale University. In The Sport of Life and Death: The Mesoamerican Ballgame. J. Washington. Elizabeth P.2001 The Architectural Background of the Pre-Hispanic Ballgame: An Evolutionary Perspective. Thought and Social Action: An Anthropological Perspective. Tate. 1992 1993 The Major Gods of Ancient Yucatan. Thames and Hudson. Cambridge: Harvard University Press. Stanley Jeyaraja 1985 Culture. In Maya Iconography.C. Austin: University of Texas Press. 1994 The Birth Vase: Natal Imagery in Ancient Maya Myth. Aztec and Maya Myths. 652-685. 1987 A Representation of the Principle Bird Deity in the Paris Codex. 1983. edited by E. Benson and Gillett G. 340 . pp. Karl 1985 The Classic Maya Maize God: A Reappraisal. NJ: Princeton University Press. In The Maya Vase Book. Journal of Anthropological Research 44(2):183-203. Carolyn E. Pp. ed. dissertation. 1999 Patrons of Shamanic Power: La Venta's supernatural entities in light of Mixe beliefs. Griffin. eds. Pp.D. 1988a The Ancient Yucatec New Year Festival: The Liminal Period in Maya Ritual and Cosmology. Fields. Princeton. In Fifth Palenque Round Table. Austin: University of Texas Press. 1988c A Study of Classic Maya Scaffold Sacrifice. San Francisco: Pre-Columbian Art Research Institute. London. Virginia M. New York: Kerr Associates. Res 12:51-82. M. Research Reports on Ancient Maya Writing. Taube. 1992 Yaxchilan: The Design of a Maya Ceremonial City. Whittington. 97-115. vol. Pp. In Antropologia de la Eternidad: La Muerte en la Cultura Maya. Albuquerque: University of New Mexico Press. Andrés Ciudad Ruiz. and the Classic Maya Temple. Princeton. A. 2004a Flower Mountain: Concepts of Life. E. E. Pp. Mario Humberto Ruz. In Lowland Maya Area: Three Millenia at the Human-Wildland Interface. Jiménez-Osornio. and Paradise among the Classic Maya. Allen. 2003a Ancient and Contemporary Maya Conceptions about Field and Forest. Sharer. Art Museum. Res 45:69-98. L. Pye. 83–103. Washington. 2001a The Breath of Life: The Symbolism of Wind in Mesoamerica and the American Southwest.E. A. 1996 The Olmec Maize God: The Face of Corn in Formative Mesoamerica. M. Proceedings of the VI Mesa Redonda de la SEEM. Pp. M. eds. held Oct. Res 29–30:39–81. Fields and Victor Zamudio-Taylor. edited by Elizabeth Benson. DC: Dumbarton Oaks. Pp. In Olmec Art and Archaeology: Social Complexity in the Formative Period. 427-478. S. eds. Houston. 1. Clark and M. Bell. Gómez-Pompa. Pp. eds. and María Josefa Iglesias Ponce de León. 2000 Lightning Celts and Corn Fetishes: The Formative Olmec and the Development of Maize Symbolism in Mesoamerica and the American Southwest. ed. 405-442. pp. 265-95. In The Olmec World: Ritual and Rulership. and R. In Maya: Divine Kings of the Rain Forest. 2003b Maws of Heaven and Hell: The Symbolism of the Centipede and the Serpent in Classic Maya Religion. 2001b The Classic Maya Gods. Washington. eds. 262-277. 2002. 341 . Mexico City:Universidad Nacional Autónoma de México.1995 The Rainmakers: The Olmec and Their Contribution to Mesoamerican Belief and Ritual. Philadelphia: University of Pennsylvania Museum. 102-123. Beauty. ed. and J. 58. ed. F. Virginia M. J. 296-337. N. Rulership. New York: Haworth Press. DC: National Gallery of Art. Canuto. 1998 The Jade Hearth: Centrality. Stephen D. 2004b Structure 10L-16 and Its Early Classic Antecedents: Fire and the Evocation and Resurrection of K‘inich Yax K‘uk‘ Mo‘. Princeton University. Fedick. J. Grube. In Understanding Early Classic Copán. J. Pp. Cologne: Könemann. In The Road to Aztlan. 28Nov. 461-492. Studies in the History of Art. pp. NJ. In Function and Meaning in Classic Maya Architecture. NC: Boundary End Archaeology Research Cente Taussig. 153-170. Michael 1993 Mimesis and Alterity: A Partiular History of the Senses. Ann Arbor: University of Michigan Press. William A. Barnardsville. 342 . John 1930 Maya Astronomy. New York. Albuquerque: University of New Mexico Press. Barbara 1982 Time and the Highland Maya. Tezozomoc. Carnegie Institution of Washington.C. Nicholas. edition. Mexico City: Instituto Nacional de Antropología e Historia. 2006 Climbing Flower Mountain: Concepts of Resurrection and the Afterlife in Ancient Teotihuacan. and the State. Karl A. Davíd Carrasco. pp. David Stuart. Tedlock. Ancient Mesoamerica 16:23-50. Ancient America 10. and Heather Hurst 2010 The Murals of San Bartolo. Guatemala. Washington. El Petén. and Caroline Humphrey 1994 Shamanism. Rev. Thomas. Dennis 1985 Popol Vuh: The Definitive Edition of the Mayan Book of the Dawn of Life and the Glories of Gods and Kings. edited by Leonardo López Luján. and Lordes Cué. New York: Simon and Schuster. New York: Simon and Schuster. In Arqueología e historia del Centro de México: Homenaje a Eduardo Matos Moctezuma. History. Saturno.. 2005 The Symbolism of Jade in Classic Maya Religion. Washington. DC. D. Taube. Tedlock. 1996 Popol Vuh: The Definitive Edition of the Mayan Book of the Dawn of Life and the Glories of Gods and Gings. Carnegie Institution of Washington Publication 103. Dumbarton Oaks. Alvarado 1878 Crónica Mexicana. Part 2: The West Wall. Routledge. Mexico: n. Teeple.p.2004c Olmec Art at Dumbarton Oaks. Cambridge. Cambridge. 1929 Maya Chronology: Glyph G of the Lunar Series. Regional Perspectives on the Olmec. 2003 A Classic Maya Term for Public Performance. The Metropolitan Museum of Art. D. and Architecture. Elizabeth Hill Boone. The PARI Journal 7(4):1–14. Mesoweb: <www. 18. ed. 8th and 9th October 1983. Electronic document. and Grove. J. (eds. pp. 2008 The Power of Place: Political Landscape and Identity in the Classic Maya Inscriptions. C. Cambridge University Press.com/features/tokovinine/ballgame. 343 . The PARI Journal 7(4):1-14.pdf> 2007 Stela 45 of Naranjo and the Early Classic Lords of Sa‘aal. Paul 1989 Coapexco and Tlatilco: Sites with Olmec materials in the Basin of Mexico. The Civilization of the American Indian Series. MA: Harvard University. 85–121. Tokovinine. In The Aztec Templo Mayor. Townsend. American Anthropologist 31:223-231 1970 Maya History and Religion. J. In Sharer.mesoweb. A Symposium at Dumbarton Oaks.com/features/tokovinine/Performance. 371409. New York. R. Tokovinine. Norman: University of Oklahoma Press. Tozzer. Pp. 1973 Maya Rulers of the Classic Period and the Divine Right of Kings. 99. Alexandre 2002 Divine Patrons of the Maya Ballgame.Thompson.. Ph. Alfred M. 1987 Coronation at Tenochtitlan. Eric S. Washington. accessed Month X.).D Dissertation. 200X. Harvard University.mesoweb. In The Iconography of Middle American Sculpture. Alexandre. Richard F. Papers of the Peabody Museum of American Archaeology and Ethnology. . and Vilma Fialko 2007 Stela 45 of Naranjo and the Early Classic Lords of Sa‘aal.pdf. Imagery. Tolstoy. DC: Dunbarton Oaks. 1941 Landa’s relación de las cosas de Yucatán. 344 . 1981 Some Aspects of the Sacred Geography of Highland Chiapas. Takeshi Inomata and Stephen D. 2: Data and Case Studies. Mass. vol. Loa 2001 The Royal Court of Early Classic Copán. Man Vol 65 pp. Arnold 1960 Rites of Passage. 138-164. Cambridge: Cambridge University Press. Piers 2001 Shamanism. Norman: University of Oklahoma Press. Valdés. revivals.Traxler. CO: Westview Press. Emily 1987 Antiques. In Royal Courts of the Ancient Maya. CO: Westview Press. Evon Z. In Royal Courts of the Ancient Maya. Trigger. vol. Ancient Mesoamerica 11:123-147. Vail. 46-73. 1969 Zinacantan: A Maya Community in the Highlands of Chiapas. Pp. Umberger. Cambridge. Bruce 2003 Understanding Early Civilizations: A Comparative Study. Gabrielle 2000 Pre-Hispanic Maya Religion: Conceptions of Divinity in the Postclassic Maya Codices. Van Gennep. Vogt. 2: Data and Case Studies. Boulder. René H. 1965 Zinacanteco ‗Souls‘. ed. 1999 The pectorals of Altar Q and Structure 11: An interpretation of the political organization at Copan. Takeshi Inomata and Stephen D. Pp. London: Routledge and Kegan Paul. Res: Anthropology and Aesthetics 13: 63–106. DC: Dumbarton Oaks Research Library and Collections. Belknap Press of Harvard Univerity Press. Benson. 33-35. Vitebsky. and references to the past in Aztec art. Latin American Antiquity 10: 377–399. Elizabeth P. eds. eds. Juan Antonio 2001 Palaces and Thrones Tied to the Destiny of the Royal Courts in the Maya Lowlands. Houston. Honduras. In Mesoamerican Sites and World Views. Washington. Houston. Viel. Boulder.. 25-49. Kay 1989 The Symbolism of Subordination: Indian Identity in a Guatemalan Town. Comparison. vol.org/reports/00077/wanyerka_full. Max 1969 ―Objectivity in Social Science and Social Polity. Pp. pp. Carbondale. Accessed 08/27/08. John M. Phil 2004 The Southern Belize Epigraphic Project: The Hieroglyphic Inscriptions of Southern Belize. 130-167. David 2000 The Not So Peaceful Civilization: A Review of Maya War. Takeshi Inomata and Stephen D. Weeks. Austin: University of Texas Press. Journal of World Prehistory 14(1):65-119. and Synthesis. 2001 The Past and Present Maya: Essays in Honor of Robert M.Wagner. Southern Illinois University. PhD Dissertation. Weber. New York: The Free Press. Austin: University of Texas Press. Marcus Kuhnert & Annette Schubart (eds.). Vol. 49–112. 10. Report Submitted to FAMSI. Copan. 1: Theory. Honduras.‖ In The Methodology of the Social Sciences. In: Colas. Houston. eds. Boulder.famsi. 1992 Maya Saints and Souls in a Changing World. 1978 Economy and Society: An Outline of Interpretive Sociology. Pierre Robert. Berkeley: University of California Press. CA: Labyrinthos. Carmack. Lancaster. Markt Schwaben: Verlag Anton Saurwein Warren. Wanyerka. pp. CO: Westview Press. The Sacred and the Profane. 345 . 2001 Spatial Dimensions of Maya Courtly Life: Problems and Issues. Elisabeth 2000 An alternative view on the meaning and function of Structure 10L-22A. Webster. Watanabe.pdf. Kai Delvendahl. John M. In Royal Courts of the Ancient Maya. 2009 Classic Maya Political Organization: Epigraphic Evidence of Hierarchical Organization in the Southern Maya Mountains Region of Belize. Acta Mesoamericana. Jocelyn S. Proceedings of the Third International Congress. 1: Archaeology. Søren 2006 Mayan Historical Linguistics and Epigraphy: A New Synthesis. American Antiquity 32(3):289-315. Wilson-Mosley. edited by Charles E. Pp. New York. Guatemala: Defining Local Variability in Strontium Isotope Ratios of Human Tooth Enamel. Warren. 139-151. Patrick Culbert. In Papers for the Director: Research Essays in Honor of James B. Greece. Sakellarakis. Paul 1957 Ideas fundamentales del arte prehispánico en México. Annual Review of Anthropology 2006.. Journal of Archaeological Science 32(4):555-566. Doumas. British Archaeological Reports. Ancient Mesoamerica Vol. Griffin. Guatemala City. G. México: Biblioteca Era. and P. D. BAR International Series 409. vol. Chase. Gordon R.Cambridge University Press. Wobst. Academic Press. 17. C. pp. Bruce M.Welsh. Willey. Research Reports in Belizean Archaeology 7:25-36 Wisdom. Williams. eds. and Diane Z. London: Thera Foundation.. Arlen F. H. Belize. 3-9 September 1989. 346 . T. Serie mayor. Pp. 35:279–94. Cleland. A. Adams 1967 Maya Lowland Ceramics: A Report from the 1965 Guatemala City Conference. In Thera and the Aegean World III. Lori E. Martin 1977 Stylistic Behavior and Information Exchange. Charles 1961 Los Chortis de Guatemala. Wiener. 128-61. 317–342. M. W. Chase 2010 Ancient Maya Underworld Iconography: Traveling Between Worlds. and Christine D. Santorini. Wichmann. Westheim. Malcolm 1990 The Isles of Crete? The Minoan Thalassocracy Revisited. White 2006 Dental Modification in the Postclassic Population from Lamanai. and Richard E. Oxford. Dianna. Wright. J. Pineda Ibarra. A. 1988 An Analysis of Classic Lowland Maya Burials. Hardy. W. 2005a Identifying Immigrants to Tikal. Washington. D.pdf 347 . 2004b Sport.D. Yasugi. Spectacle and Political Theater: New Views of the Classic Maya Ballgame. Yoshiho.: Center for Maya Research. dissertation. 2006 Teasing the Turtle from its Shell: AHK and MAHK in Maya Writing. Electronic version:. The PARI Journal 4(4):10-12. Ph. The PARI Journal 6(3):1-14. University of Calgary. 34 and 35.2005b In Search of Yax Nuun Ayiin I: Revisiting the Tikal Project‘s Burial 10. No. Ancient Mesoamerica 16(01):89-100. and Kenji Saito 1991 Glyph Y of the Maya Supplementary Series.com/pari/publications/journal/603/Turtle_e. Zender. Marc 2004 A Study of Classic Maya Preisthood. Research Reports on Ancient Maya Writing.mesoweb. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/document/152953720/Wright-A-Study-of-Classic-Maya-Rulership-PhD-Dissertation-2011-pdf
CC-MAIN-2017-04
refinedweb
75,829
60.21
Details - Type: Bug - Status: Closed - Priority: Major - Resolution: Fixed - Affects Version/s: 0.9.2, 0.10.0 - - Component/s: None - Labels:None - Environment: pig-0.9.2 and pig-0.10.0, hadoop-0.20.2 from Clouderas distribution cdh3u3 on Kubuntu 12.04 64Bit. - Hadoop Flags:Reviewed - Release Note:Import search path property pig.import.search.path is now correctly used... Description org.apache.pig.test.TestMacroExpansion, in function importUsingSearchPathTest the import statement is provided with the full path to /tmp/mytest2.pig so the pig.import.search.path is never used. I changed the import to import 'mytest2.pig'; and ran the UnitTest again. This time the test failed as expected from my experience from earlier this day trying in vain to get pig eat my pig.import.search.path property! Other properties in the same custom properties file (provided via -propertyFile command line option) like udf.import.list get read without any problem. Activity - All - Work Log - History - Activity - Transitions. Johannes, Do you have the updated patch which fixes the unit tests also? The static map in QueryParserDriver which caches the macro files is the reason for the test failure once the importUsingSearchPathTest is corrected. String srchPath = pigContext.getProperties().getProperty("pig.import.search.path"); + if (!fname.startsWith("/") && !fname.startsWith(".") && srchPath != null) { + String[] paths = srchPath.split(","); + for (String path : paths) { + String resolvedPath = path + File.separator + fname; + if ((new File(resolvedPath)).exists()) { + fname = resolvedPath; + break; + } + } + } The above code also does not handle "../". If the script had "import ../readme.pig" and pig.import.search.path was "/x/y", then /x/y/../readme.pig will be searched for. Also need to remove the redundant QueryParserUtils.getImportScriptAsReader code as getMacroFile will now return a absolute path. Hi Rohini, I attached a new patch that fixes the issue with relative paths. It also includes the patch for TestMacroExpansion. Further I removed the redundant code in QueryParserUtils. The tests in TestQueryParser and TestMacroExpansion all succeed. All tests should be run though, to verify that I have not broken other things... As to the failing importTwoFilesTest I mentioned earlier: I cannot reproduce this right now. Could you verify that the tests work as expected Rohini? Thanks, Johannes Johannes, You need to do "git diff --no-prefix" to get the patch so that it can be applied on svn. And it would be easier to review if you can also post the patch in reviewboard. 1) Small nitpick. The paths variable need not be defined outside the if block. String[] paths = {}; + if (srchPath != null) { + paths = srchPath.split(","); //Could just be String[] paths = srchPath.split(","); 2) The problem I mentioned in the previous comment about "../" still exists. You have also removed the f.exists() || f.isAbsolute() || scriptPath.startsWith("./") checks. They are required. Now the search will be looking at the wrong paths even if the file existed or was an absolute path and makes the behavior unpredictable. For eg: If there was a statement, import '/dir1/file1.pig' and the pig.import.search.path was '/dir2,/dir3', then you would be considering files /dir2/dir1/file1.pig and /dir3/dir1/file1.pig. The same thing will happen for relative paths from base dir and ./ and ../. 3) Doing a canonical path for f.exists() is not required. canonicalize results internally in a native call and would just add overhead. Thanks, Rohini Hi Rohini, sorry I didn't know about svn having problems with git diffs - I will fix that and post patches on reviewboard from now on... 1. Will fix that. 2. Sorry, I think I missunderstood you: I somehow thought that you wanted /x/y/../readme.pig beeing resolved to /x/readme.pig for "import '../readme.pig'; if the import path contained /x/y. This is obvoiusly not the case... So the correct behaviour is: 1. Check if fname points to an existing file, is absolute, or relative yes => return localFileRet no => goto 2. 2. For each importPath in pig.import.search.path - concatenate: importPath + File.separator + fname - check if file exists yes => return localFileRet no => continue with 2. 3. Return localFileRet for fname. 4. While doing 1.-3. throw RuntimeException if an IOException was encountered Have I understood this correctly? 3. Yes, i removed this. Thanks, Johannes No worries. For future reference, has all the instructions. Its a really nice writeup and I had found it very helpful. You are right with 1 and 2. It makes it same as the old logic. I was thinking it would keep it simpler if instead of copying all the logic to getMacroFile method, we could just change the name of QueryParserUtil.getImportScriptAsReader to something like getFileFromSearchImportPath and make it return a file instead of bufferedReader and null instead of FileNotFoundException. That way the logic remains exactly same and we don't have to worry about missing something. QueryParserUtils.java - static BufferedReader getImportScriptAsReader(String scriptPath) - throws FileNotFoundException { + + static File getFileFromSearchImportPath(String scriptPath) { - return new BufferedReader(new FileReader(f)); + return f; - return new BufferedReader(new FileReader(f1)); + return f1; - - throw new FileNotFoundException("Can't find the Specified file " - + scriptPath); + return null; QueryParserDriver.java getMacroFile(): File localFile = QueryParserUtils.getFileFromSearchImportPath(fname); localFileRet = localFile == null ? FileLocalizer.fetchFile(pigContext.getProperties(), fname) : new FetchFileRet(localFile.getCanonicalFile(), false); And I checked. importTwoFilesTest still fails. I had to make mytest1.pig and mytest2.pig to mytest4.pig and mytest5.pig to get it to pass. The cleaner thing to do would be to clear the cache in QueryParserDriver before each test. But I think this should be ok for now as the cache is private. You can verify your patch by running ant -Djavac.args="-Xlint -Xmaxwarns 1000" clean jar-withouthadoop test -Dtestcase=TestMacroExpansion -logfile /tmp/log Hi Rohini, I changed the PIG to your suggestion. I would post this on the review board, but I currently get an Error 500 everytime I try to submit. Test cases in TestMacroExpansion all succeed. Could you take a look again please? Thanks, Johannes Few comments: 1) Exception should not be thrown here as it will break Amazon s3 filesystem support. File macroFile = QueryParserUtils.getFileFromSearchImportPath(fname); + if (macroFile == null) { + throw new FileNotFoundException("Could not find the specified file '" + + fname + "' using import search path"); + } + localFileRet = FileLocalizer.fetchFile(pigContext.getProperties(), + macroFile.getAbsolutePath()); It should be File localFile = QueryParserUtils.getFileFromSearchImportPath(fname); localFileRet = localFile == null ? FileLocalizer.fetchFile(pigContext.getProperties(), fname) : new FetchFileRet(localFile.getCanonicalFile(), false); The reason is the macro path could be fully qualified s3 or some other supported file system path. So if we could not find it in the local filesystem with getFileFromSearchImportPath, then FileLocalizer.fetchFile will take care of looking at other filesystems and downloading it locally and returning the local file path. Also it will throw the FileNotFoundException if the file is missing. 2. Again for the same reason of s3 support, it is incorrect to use getFileFromSearchImportPath in this code. And getMacroFile already fetches the file. FetchFileRet localFileRet = getMacroFile(fname); File macroFile = QueryParserUtils.getFileFromSearchImportPath( + localFileRet.file.getAbsolutePath()); try { - in = QueryParserUtils.getImportScriptAsReader(localFileRet.file.getAbsolutePath()); + in = new BufferedReader(new FileReader(macroFile)); should be in = new BufferedReader(new FileReader(localFileRet.file)); 3. For the tests, can you extract out the common code to a method to cut down on the repetition of code. Something like importUsingSearchPathTest() { verifyImportUsingSearchPath("/tmp/mytest2.pig", "mytest2.pig", "/tmp"); } importUsingSearchPathTest2() { verifyImportUsingSearchPath("/tmp/mytest2.pig", "./mytest2.pig", "/tmp"); } importUsingSearchPathTest3() { verifyImportUsingSearchPath("/tmp/mytest2.pig", "../mytest2.pig", "/tmp"); } importUsingSearchPathTest4() { verifyImportUsingSearchPath("/tmp/mytest2.pig", "/tmp/mytest2.pig", "/foo/bar"); } verifyImportUsingSearchPath(String macroFilePath, String importFilePath, String importSearchPath) { ..... } 4) negtiveUsingSearchPathTest2 and 3 are not very useful, unless some file with same name and garbage text are created in the search path location. That way we can ensure that the right file is being picked up and not the other file. Hi Rohini, thank you very much for your comments! I am still new to the project so some things slip my attention - your advice and patience are much appreciated! I attached the new patch incorporating your corrections. Could you take a look again? On a side note: Do you know what is the matter with reviews.apache.org? I still always get the "Error 500" message when I try to submit my patch for review. Thanks! No issues. Even I am new to pig . I was just applying what I learnt from the previous jira that I was working on about s3 support. I uploaded a patch in review board yesterday and it works fine. Not sure what problem you are facing. The patch looks good. Still have few comments though. Won't bother you more. These are the last ones from me . 1) Can we add createFile("/tmp/mytest2.pig", garbageMacroContent); as the first line in importUsingSearchPathTest, importUsingSearchPathTest2 and importUsingSearchPathTest3 and createFile("/foo/bar/tmp/mytest2.pig", garbageMacroContent); in importUsingSearchPathTest4. Just an additional way to ensure the right file is being picked up. 2) Delete the mytest3.pig file in negativeUsingSearchPathTest, just in case negativeUsingSearchPathTest2 is executed first and a garbage mytest3.pig file is created. ie: public void negativeUsingSearchPathTest() throws Exception { new File("mytest3.pig").delete(); assertFalse(verifyImportUsingSearchPath("/tmp/mytest3.pig", "mytest3.pig", null)); } 3) Use Assert.assertFalse instead of assertTrue(!verifyImportUsingSearchPath(..)) in negativeTests. 4) Minor nitpick. It would be nice to declare the static variables (groupAndCountMacro and garbageMacroContent) in the beginning of the class. Not a big deal though. I included your corrections and good advice. I think the patch has evolved a lot thanks to you Rohini! Thanks Johannes. My +1. I will ask Daniel to review and commit it. Will also ask you to add to the contributors list in jira so that this jira can be assigned to you. Thanks Rohini! Meanwhile I was able to create a review request after a hint on the mailing list. Attached scripts to further illustrate this issue. To test this extract to your home. Then execute ./run-me .
https://issues.apache.org/jira/browse/PIG-2729
CC-MAIN-2017-39
refinedweb
1,630
53.47
Daizu - class for accessing Daizu CMS from Perl Daizu CMS is an experimental content management system. It uses content stored in a Subversion repository, and keeps track of it in a PostgreSQL database. It is an attempt to solve some of the underlying problems of content management once and for all. As such the development so far has focused on the 'back end' parts of the system, and it doesn't really have a user interface to speak of. It's certainly not ready for less technical users yet. More information is available on the Daizu website: Most access to Daizu functionality requires a Daizu object. It provides a database handle for access to the 'live' content data, and a SVN::Ra object for access to the Subversion repository. Some other classes are documented as requiring a $cms value as the first argument to their constructors or methods. This should always be a Daizu object. The version number of Daizu CMS (as a whole, not just this module). The full path and filename of the config file which will be read by default, if none is specified in the constructor call or the environment. Value: /etc/daizu/config.xml The URI used as an XML namespace for the elements in the config file. Value: The URI used as an XML namespace for special elements in XHTML content. Value: A list of file and directory names which prevent any publication of files with one of the names, or anything inside a directory so named. Separated by '|' so that the whole string can be included in Perl and PostgreSQL regular expressions. Value: _template|_hide A hash describing which pieces of metadata can be overridden by article loader plugins. The keys are the names of Subversion properties, and the values are the names of columns in the wc_file table. Return a Daizu object based on the information in the given configuration file. If $config_filename is not supplied, it will fall back on any file specified by the DAIZU_CONFIG environment variable, and then by the default config file (see $DEFAULT_CONFIG_FILENAME above). The value returned will be called $cms in the documentation. For information about the format of the configuration file, see the documentation on the website: Return the Subversion remote access (SVN::Ra) object for accessing the repository. Return the DBI database handle for accessing the Daizu database. Returns a string containing the filename from which the configuration was loaded. The filename may be a full (absolute) path, or may be relative to the current directory at the time the Daizu object was created. Return a Daizu::Wc object representing the live working copy. Load information about revisions and file paths for any new revisions, upto $update_to_rev, from the repository into the database. If no revision number is supplied, updates to the latest revision. This is called automatically before any working copy updates, to ensure that the database knows about revisions before any working copies are updated to them. It is idempotent. This is a simple wrapper round the code in Daizu::Revision. Plugins can use this to register themselves as a 'property loader', which will be called when a property whose name matches $pattern is updated in a working copy. Currently it isn't possible to localize property loader plugins to have different configuration for different paths in the repository using the normal path configuration system. The pattern can be either the exact property name, a wildcard match on some prefix of the name ending in a colon, such as svn:*, or just a * which will match all property names. There isn't any generic wildcard or regular expression matching capability. $object should be an object (probably of the plugin's class) on which $method can be called. Since it is called as a method, the first value passed in will be $object, followed by these: A Daizu object. The ID number of the file in the wc_file database table for which the new property values apply. A reference to a hash of the new property values. Only properties which have been changed during a working copy update will have entries, so the file may have other properties which haven't been changed. Properties which have been deleted during the update will have an entry in this hash with a value of undef. An example of a property loader method is _std_property_loader in this module. It is always registered automatically. Plugins can use this to register a method which will be called whenever an article of type $mime_type needs to be loaded. The MIME type can be fully specified, or be something like image/* (to match any image format), or just be * to match any type. These aren't generic glob or regex patterns, so only those three levels of specificity are allowed. The most specific plugin available will be tried first. Plugins of the same specificity will be tried in the order they are registered. The plugin methods can return false if they can't handle a particular file for some reason, in which case Daizu will continue to look for another suitable plugin. The plugin registered will only be called on for files with paths which are the same as, or are under the directory specified by, $path. Plugins should usually just pass the $path value from their register method through to this method as-is. $method (a method name) will be called on $object, and will be passed $cms and a Daizu::File object representing the input file. The method should return a hash of values describing the article. Alternatively it can return false to indicate that it can't handle the file. The hash returned can contain the following values: Required. All the other values are optional. This should be an XHTML DOM of the article's content, as it will be published. It should be an XML::LibXML::Document object, with a root element called body in the XHTML namespace. It can contain extension elements to be processed by article filter plugins. It can contain XInclude elements, which will be processed by the expand_xinclude() function. Entity references should not be present. The title to use for the article. If this is present and not undef then it will override the value of the dc:title property. The 'short title' to use for the article. If this is present and not undef then it will override the value of the daizu:short-title property. The description to use for the article. If this is present and not undef then it will override the value of the dc:description property. The URL to use for the first page of the article, and which will also be used to generate URLs for subsequent pages (if any). This can be absolute, or relative to the file's base URL. A reference to an array of URL info hashes describing extra URLs generated by the file in addition to the actual pages of the article. These are stored in the wc_article_extra_url table. A reference to an array of filenames of extra templates to be included in the article's 'extras' column. These are stored in the wc_article_extra_template table. See Daizu::Plugin::PodArticle or Daizu::Plugin::PictureArticle for examples of registering and writing article loader plugins. Plugins can use this to register a method which will be called whenever an XHTML file is being published. $method (a method name) will be called on $object, and will be passed $cms, a Daizu::File object for the file being filtered, and an XML DOM object of the source, as a XML::LibXML::Document object. The plugin method should return a reference to a hash containing a content value which is the filtered content, either a completely new copy of the DOM or the same value it was passed (which it might have modified in place). The returned hash can also contain an extra_urls array, in the same way as an article loader, if the filter adds additional URLs for the file. The plugin registered will only be called on for files with paths which are the same as, or are under the directory specified by, $path. Plugins should usually just pass the $path value from their register method through to this method as-is. See Daizu::Plugin::SyntaxHighlight for an example of registering and implementing a DOM filter method. Calls the plugin methods which wish to be informed of property changes on a file, where $id is a file ID for a record in the wc_file table, and $props is a reference to a hash of the format described for the add_property_loader() method. Return the entity to be used for minting GUID URLs for the file at $path. This finds the best match from the guid-entity elements in the configuration file and returns the corresponding entity value. Return information about where the published output for $url (a string or URI object) should be written to. If there is a suitable output element in the configuration file then this will return a hash containing information from that element, followed by a list of three strings, which will all be defined. If you join these strings together (by passing them to the file function from Path::Class for example) to form a complete path then it will be the path to the file (never directory) which the output should be written to. The first value returned will be a reference to a hash containing the following keys: The value from the url attribute in the configuration file, as a URI object. The value from the path attribute. The value from the index-filename attribute, or the default value index.html if one isn't set. The value from the redirect-map attribute, or undef if there isn't one. The value from the gone-map attribute, or undef if there isn't one. The other three values are: pathattribute in the appropriate outputelement in the configuration file. This is the same as the pathvalue in the hash. filefunction mentioned above will correctly elide it for you in that case. If the configuration doesn't say where $url should be published to then this will return nothing. TODO - this doesn't use file itself, so the results aren't portable across different platforms. This software is copyright 2006 Geoff Richards <geoff@laxan.com>. For licensing information see this page:
http://search.cpan.org/~geoffr/Daizu-0.3/lib/Daizu.pm
CC-MAIN-2016-50
refinedweb
1,731
62.68
BOSS 33 - The honest rocking!! Discussion in 'HTML' started by vikram singh, Nov 8, 2010. Want to reply to this thread or ask your own question?It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum. - Similar Threads Need help resolving accidental (honest!) language pissing matchhas, Jun 2, 2004, in forum: Python - Replies: - 7 - Views: - 362 - has - Jun 4, 2004 Mucking with the calling scripts namespace (For a good reason, honest!)Doug Rosser, Aug 2, 2004, in forum: Python - Replies: - 7 - Views: - 295 - Christopher T King - Aug 4, 2004 - Replies: - 29 - Views: - 895 - Jeffrey Schwab - Sep 16, 2006 Honest opinionsoulfly73, Jun 23, 2009, in forum: .NET - Replies: - 0 - Views: - 279 - soulfly73 - Jun 23, 2009 3 videos that are rocking the webRico, May 4, 2007, in forum: Ruby - Replies: - 0 - Views: - 100 - Rico - May 4, 2007
http://www.thecodingforums.com/threads/boss-33-the-honest-rocking.737482/
CC-MAIN-2014-49
refinedweb
158
79.4
31 August 2012 04:24 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> On a month-on-month basis, production in the mining, manufacturing, gas and electricity industries fell by 1.6% in July, compared with June when it dropped by 0.6%, according to Statistics Korea. “Production fell solidly at manufacturing firms in “The pace of contraction was the fastest recorded since December 2011. Panellists attributed lower production to the global economic slowdown,” HSBC said. The HSBC South Korea PMI registered 47.2 in July, down from 49.4 in June, indicating a further deterioration in the health of the manufacturing sector. PMI readings above 50.0 signal an improvement in business conditions, while readings below 50.0 signal deterioration. The South Korea PMI also showed that new orders in July declined at the fastest rate since last December, while new export business decreased for the second straight month amid reports of a downturn in the international economic
http://www.icis.com/Articles/2012/08/31/9591484/s-korea-industrial-output-up-0.3-in-july-falls-1.6-from.html
CC-MAIN-2015-22
refinedweb
158
51.55
JustLinux Forums > Community Help: Check the Help Files, then come here to ask! > Programming/Scripts > Binding keystrokes to keystrokes. PDA Click to See Complete Forum and Search --> : Binding keystrokes to keystrokes. Bill Case 06-23-2011, 03:26 PM I want to find a simple, quick, on the fly, way to bind a series of keystrokes to one keystroke. Below is this moments problem, but I have run into this before so I would like a methodology. Problem: FaceBook and other messaging programs remove excess spaces. That is fine for most posts, but occasionally I want to retain my columnar formatting. I am willing to insert a ctl-u unicode formula for space or tab if such can be found. I know I can send my data as an image, but I am looking for something that is quick and dirty that I can use on the fly. U+00a0 seems to solve my initial problem. Now I would like to bind <ctrl><shift>u00a0 <space> to one key and have it execute. -- <mod4, or Super, or Win>+SPACE would be nice, but any combination will do. How do I do this? furrycat 06-23-2011, 06:36 PM You can use xmacroplay (). Some window managers will let you bind arbitrary keypresses to run commands (eg xmacroplay) but an alternative is to run xbindkeys () in the background to listen for the keypress you want and have it launch xmacroplay to send the keys. One gotcha is that the keys you use in your xbindkeys trigger are still classed as pressed when your script runs so either you will have to do a sleep or have your script release the trigger key(s) first. Here I tell xbindkeys to call xmacroplay on the mao script when I press XF86Launch6 (which happens to be what xev told me was the result of pressing F15 on my Apple keyboard). $ cat ~/.xbindkeysrc "xmacroplay $DISPLAY < ~/.xbindkeys/mao" XF86Launch6Here's the script:$ cat ~/.xbindkeys/mao KeyStrRelease XF86Launch6 KeyStrPress Control_L KeyStrPress Shift_L KeyStr U KeyStrRelease Shift_L KeyStrRelease Control_L KeyStr 8 KeyStr C KeyStr 9 KeyStr 3 KeyStr spaceAnd I runxbindkeysHere's a magic cat to prove it works:貓By the way, xmacroplay is ancient and probably won't compile without help. I have an almost-equally-ancient binary kicking around but to recompile it on my Fedora 15 machine I had to create config.h with #define HAVE_IOSTREAM using namespace std;then modify all g++ lines in the Makefile to include -DHAVE_CONFIGMaybe your vendor has a package which will save you the hassle. justlinux.com
http://justlinux.com/forum/archive/index.php/t-153779.html
crawl-003
refinedweb
428
69.72
Need to add a series of spaces and a single digit at a specific character count to the end of every line Hello, I’ve got a txt doc with a few thousand lines of barcode data. The length of the data varies from line to line. I need to add a series of spaces, followed by a “1” at precisely the 35th character (from the margin) at the end of every line. Any thoughts as to the best way to do this? I have a ^ character that is at the end of every line for “find & replace” purposes, but the variable length situation is throwing me. Thanks in advance. - Claudia Frank a simple python script would look like position = 34 spacer = ' ' def add_text(content, line, total): pos=editor.positionFromLine(line) length=len(editor.getLine(line).strip()) if length <= position: editor.insertText(pos+length, '{0}1'.format(spacer*(position-length))) editor.forEachLine(add_text) As long as the text in the line doesn’t exceed 34 chars it will fill the line with spaces and then add the number 1. Cheers Claudia Thanks Claudia - That looks like exactly the kind of thing I’m looking for. When I run the script, it kicks a “NameError: name ‘editor’ is not defined.” How would I go about defining that in order for this to function? Forgive me, as I’m brand-spankin’-new to python… I think that what you need to do is put the following line at the top of the python script: from Npp import * I have that line in my startup.py so that I don’t have to put it in every single python script I develop. Once executed (from any single script), it is good for the entire Notepad++ session (that’s why I found startup.py a good place for it). - Claudia Frank Scott, afaik this is the default. I can’t remember adding this to startup.py and it is there. @Justin-Tabor I assume that the plugin installation failed. May I ask you how you did the install? Via Plugin Manager? If so, please use the msi. You don’t have to revert the plugin manager install, the msi will override it. Cheers Claudia - Scott Sumner While the pythonscript (a plugin which I am a big BIG fan of!) works, I’m not a big fan of suggesting it as solutions to problems that might be solved another way. This is because not everybody is into pythonscript, and, if not using it for other purposes, might balk at the burden of installing it. Here’s how I might solve your problem another way, with the big inference being that all of your original lines are LESS than 35 columns long (maybe this is easily assumed from your original problem statement). Anyway, on line 1 I would add spaces so that you get to column 35. Then from that caret position, invoke the Column Editor (default keycombo: Alt+C) and insert some very-unique text (that won’t occur elsewhere in your document) using the “Text to insert” box. This will add a variable amount of spaces out to column 35 and then your very-unique text on each line. From there it is easy to do a Find+Replace on the very-unique text and replace it with your desired “1”. I’m sure you are (as usual) correct about the “import”. Since Justin said nothing about Pythonscript failing to install, I was just trying to debug it from the point of view of the error he was getting. - Claudia Frank I agree with your column editor solution - didn’t thought about it. BUT why adding some unique text if he can add the needed 1 ;-) Cheers Claudia Yes, very good point. At first I was going to suggest inserting number sequences (because that is what I typically do with the column editor) and then using a \d+$ regex to replace those with ‘1’, but then I noticed the “Text to insert” choice, and, well, I don’t know…I had my mind wrapped around having to do some sort of Find+Replace solution and…ugh! :-) Dang - You guys are awesome! Scott’s method was the most painless. Thanks for all the help! Hello, Claudia, Justin and Scott, Justin, in addition to the Python script and the native N++ column editor feature, here is a regex S/R equivalent :-)) So, let’s suppose that we start with the original text, below : BEGINNING This is a test A line with 25 characters an another try + a COMPLETE line of 34 characters_1 END Open the Replace dialog In the Find what : field, type : (?-s)^(?!.{34}( |1))(.+)|^.{34}\K + - In the Replace with : field, type : ?2\2 1 , with 34 SPACES, between \2 and the digit 1, that should be ADDED Select the Regular expression search mode Click, TWICE, on the Replace All button ( IMPORTANT ) You should obtain the modified text, below : BEGINNING 1 This is a test 1 A line with 25 characters 1 an another try 1 + 1 a COMPLETE line of 34 characters_11 END 1 NOTES : The (?-s)syntax ensures that the dot ( .) will stand for standard characters, only ! The ^is the assertion beginning of line, which must be verified The negative look-ahead ( (?!.{34}( |1))) verifies if the condition NO space NOR the 1 digit, at position 35, is true. This case occurs, ONLY, on the original text, before any S/R So, the regex catches, first, all the standard characters ( .+), of any non-empty line, stored in group 2 In replacement, as group 2 exists, it rewrites the current line, then adds a minimum of 34 spaces and the final digit 1 When you click a second time, on the Replace all button, the left part of the alternative cannot be achieved, as the look-ahead condition is, this time, false So, the regex engine tries to match the right part of the alternative ( ^.{34}\K +) The first part ( ^.{34}) select the first 34 characters of each line Due to \K syntax, this range is forgotten and the regex engine, now, matches any consecutive non-null range of space characters ( +), from the 35th position, included In replacement, as the group 2 is not used any more and that the conditional replacement, ?2..., do not have an ELSE part, these space characters are simply deleted ! REMARKS : The nice thing is that you may add, as many spaces, as you want, after the 34 first spaces, in the replacement field ! And, any additional click, after the second one, on the Replace all button, does not match anything else :-)) Cheers, guy038
https://notepad-plus-plus.org/community/topic/12955/need-to-add-a-series-of-spaces-and-a-single-digit-at-a-specific-character-count-to-the-end-of-every-line
CC-MAIN-2018-39
refinedweb
1,106
68.7
- 20 Jul, 2016 1 commit - Nicholas Bellinger authored During transport_generic_free_cmd() with a concurrent TMR ABORT_TASK and shutdown CMD_T_FABRIC_STOP bit set, the caller will be blocked on se_cmd->cmd_wait_stop completion until the final kref_put() -> target_release_cmd_kref() has been invoked to call complete(). However, when ABORT_TASK is completed with FUNCTION_COMPLETE in core_tmr_abort_task(), the aborted se_cmd will have already been removed from se_sess->sess_cmd_list via list_del_init(). This results in target_release_cmd_kref() hitting the legacy list_empty() == true check, invoking ->release_cmd() but skipping complete() to wakeup se_cmd->cmd_wait_stop blocked earlier in transport_generic_free_cmd() code. To address this bug, it's safe to go ahead and drop the original list_empty() check so that fabric_stop invokes the complete() as expected, since list_del_init() can safely be used on a empty list. Cc: Mike Christie <mchristi@redhat.com> Cc: Quinn Tran <quinn.tran@qlogic.com> Cc: Himanshu Madhani <himanshu.madhani@qlogic.com> Cc: Christoph Hellwig <hch@lst.de> Cc: Hannes Reinecke <hare@suse.de> Cc: stable@vger.kernel.org # 3.14+ Tested-by: Nicholas Bellinger <nab@linux-iscsi.org> Signed-off-by: Nicholas Bellinger <nab@linux-iscsi.org> - 05 Jun, 2016 7 commits - - - Eric W. Biederman authored The /dev/ptmx device node is changed to lookup the directory entry "pts" in the same directory as the /dev/ptmx device node was opened in. If there is a "pts" entry and that entry is a devpts filesystem /dev/ptmx uses that filesystem. Otherwise the open of /dev/ptmx fails. The DEVPTS_MULTIPLE_INSTANCES configuration option is removed, so that userspace can now safely depend on each mount of devpts creating a new instance of the filesystem. Each mount of devpts is now a separate and equal filesystem. Reserved ttys are now available to all instances of devpts where the mounter is in the initial mount namespace. A new vfs helper path_pts is introduced that finds a directory entry named "pts" in the directory of the passed in path, and changes the passed in path to point to it. The helper path_pts uses a function path_parent_directory that was factored out of follow_dotdot. In the implementation of devpts: - devpts_mnt is killed as it is no longer meaningful if all mounts of devpts are equal. - pts_sb_from_inode is replaced by just inode->i_sb as all cached inodes in the tty layer are now from the devpts filesystem. - devpts_add_ref is rolled into the new function devpts_ptmx. And the unnecessary inode hold is removed. - devpts_del_ref is renamed devpts_release and reduced to just a deacrivate_super. - The newinstance mount option continues to be accepted but is now ignored. In devpts_fs.h definitions for when !CONFIG_UNIX98_PTYS are removed as they are never used. Documentation/filesystems/devices.txt is updated to describe the current situation. This has been verified to work properly on openwrt-15.05, centos5, centos6, centos7, debian-6.0.2, debian-7.9, debian-8.2, ubuntu-14.04.3, ubuntu-15.10, fedora23, magia-5, mint-17.3, opensuse-42.1, slackware-14.1, gentoo-20151225 (13.0?), archlinux-2015-12-01. With the caveat that on centos6 and on slackware-14.1 that there wind up being two instances of the devpts filesystem mounted on /dev/pts, the lower copy does not end up getting used. Signed-off-by: "Eric W. Biederman" <ebiederm@xmission.com> Cc: Greg KH <greg@kroah.com> Cc: Peter Hurley <peter@hurleysoftware.com> Cc: Peter Anvin <hpa@zytor.com> Cc: Andy Lutomirski <luto@amacapital.net> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Serge Hallyn <serge.hallyn@ubuntu.com> Cc: Willy Tarreau <w@1wt.eu> Cc: Aurelien Jarno <aurelien@aurel32.net> Cc: One Thousand Gnomes <gnomes@lxorguk.ukuu.org.uk> Cc: Jann Horn <jann@thejh.net> Cc: Jiri Slaby <jslaby@suse.com> Cc: Florian Weimer <fw@deneb.enyo.de> Cc: Konstantin Khlebnikov <koct9i@gmail.com> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> Signed-off-by: Helge Deller <deller@gmx.de> One of the debian buildd servers had this crash in the syslog without any other information: Unaligned handler failed, ret = -2 clock_adjtime (pid 22578): Unaligned data reference (code 28) CPU: 1 PID: 22578 Comm: clock_adjtime Tainted: G E 4.5.0-2-parisc64-smp #1 Debian 4.5.4-1 task: 000000007d9960f8 ti: 00000001bde7c000 task.ti: 00000001bde7c000 YZrvWESTHLNXBCVMcbcbcbcbOGFRQPDI PSW: 00001000000001001111100000001111 Tainted: G E r00-03 000000ff0804f80f 00000001bde7c2b0 00000000402d2be8 00000001bde7c2b0 r04-07 00000000409e1fd0 00000000fa6f7fff 00000001bde7c148 00000000fa6f7fff r08-11 0000000000000000 00000000ffffffff 00000000fac9bb7b 000000000002b4d4 r12-15 000000000015241c 000000000015242c 000000000000002d 00000000fac9bb7b r16-19 0000000000028800 0000000000000001 0000000000000070 00000001bde7c218 r20-23 0000000000000000 00000001bde7c210 0000000000000002 0000000000000000 r24-27 0000000000000000 0000000000000000 00000001bde7c148 00000000409e1fd0 r28-31 0000000000000001 00000001bde7c320 00000001bde7c350 00000001bde7c218 sr00-03 0000000001200000 0000000001200000 0000000000000000 0000000001200000 sr04-07 0000000000000000 0000000000000000 0000000000000000 0000000000000000 IASQ: 0000000000000000 0000000000000000 IAOQ: 00000000402d2e84 00000000402d2e88 IIR: 0ca0d089 ISR: 0000000001200000 IOR: 00000000fa6f7fff CPU: 1 CR30: 00000001bde7c000 CR31: ffffffffffffffff ORIG_R28: 00000002369fe628 IAOQ[0]: compat_get_timex+0x2dc/0x3c0 IAOQ[1]: compat_get_timex+0x2e0/0x3c0 RP(r2): compat_get_timex+0x40/0x3c0 Backtrace: [<00000000402d4608>] compat_SyS_clock_adjtime+0x40/0xc0 [<0000000040205024>] syscall_exit+0x0/0x14 This means the userspace program clock_adjtime called the clock_adjtime() syscall and then crashed inside the compat_get_timex() function. Syscalls should never crash programs, but instead return EFAULT. The IIR register contains the executed instruction, which disassebles into "ldw 0(sr3,r5),r9". This load-word instruction is part of __get_user() which tried to read the word at %r5/IOR (0xfa6f7fff). This means the unaligned handler jumped in. The unaligned handler is able to emulate all ldw instructions, but it fails if it fails to read the source e.g. because of page fault. The following program reproduces the problem: #define _GNU_SOURCE #include <unistd.h> #include <sys/syscall.h> #include <sys/mman.h> int main(void) { /* allocate 8k */ char *ptr = mmap(NULL, 2*4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); /* free second half (upper 4k) and make it invalid. */ munmap(ptr+4096, 4096); /* syscall where first int is unaligned and clobbers into invalid memory region */ /* syscall should return EFAULT */ return syscall(__NR_clock_adjtime, 0, ptr+4095); } To fix this issue we simply need to check if the faulting instruction address is in the exception fixup table when the unaligned handler failed. If it is, call the fixup routine instead of crashing. While looking at the unaligned handler I found another issue as well: The target register should not be modified if the handler was unsuccessful. Signed-off-by: Helge Deller <deller@gmx.de> Cc: stable@vger.kernel.org drm/omap: include gpio/consumer.h where needed drm/omap: include linux/seq_file.h where needed Revert "drm/omap: no need to select OMAP2_DSS" drm/omap: Remove regulator API abuse OMAPDSS: HDMI5: Change DDC timings ... - 23:: Michal Hocko <mhocko@suse.com> Suggested-by: Oleg Nesterov <oleg@redhat.com> Cc: Tetsuo Handa <penguin-kernel@i-love.sakura.ne.jp> Cc: David Rientjes <rientjes@google.com> Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> - Vlastimil Babka authored ("mm, page_alloc: defer debugging checks of pages allocated from the PCP") Link::> -:: Corey Minyard <cminyard@mvista.com> Cc: Dave Young <dyoung@redhat.com> Cc:: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org> - ->> Commit ab893fb9 ("arm64: introduce KIMAGE_VADDR as the virtual base of the kernel region") logically split KIMAGE_VADDR from PAGE_OFFSET, and since commit f9040773 (>
https://gitlab.flux.utah.edu/xcap/xcap-capability-linux/-/commits/5e2c956b8aa24d4f33ff7afef92d409eed164746
CC-MAIN-2020-45
refinedweb
1,185
51.44
posix_spawn_file_actions_adddup2() Add a duplicate a file descriptor action to a spawn file actions object Synopsis: #include <spawn.h> int posix_spawn_file_actions_adddup2( posix_spawn_file_actions_t *fact_p, int fd, int new_fd); Arguments: - fact_p - A pointer to the spawn file actions object that you want to update. You must have already initialized this object by calling posix_spawn_file_actions_init(). - fd - The file descriptor that you want to duplicate. - new_fd - The number that you want to use for the new file descriptor. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The posix_spawn_file_actions_adddup2() function adds a dup2() action to the object referenced by fact_p that causes the file descriptor fd to be duplicated as new_fd (as if a call were made to dup2(fd, new_fd)) when a new process is spawned using this file actions object. Returns: - EOK - Success. - EBADF - The value specified by fd or new_fd is negative or greater than or equal to {OPEN_MAX}. - EINVAL - An argument was invalid. The value specified by file actions is invalid. - ENOMEM - The action couldn't be added to the file actions object, or insufficient memory exists to add to the spawn file actions object. It isn't considered an error for the fd argument to specify a file descriptor for which the specified operation couldn't be performed at the time of the call. Any such error will be detected when the associated file actions object is later used during a posix_spawn() or posix_spawnp() operation.
http://developer.blackberry.com/native/reference/bb10/com.qnx.doc.neutrino.lib_ref/topic/p/posix_spawn_file_actions_adddup2.html
CC-MAIN-2013-20
refinedweb
247
55.13
RNNs, LSTMs and Deep Learning are all the rage, and a recent blog post by Andrej Karpathy is doing a great job explaining what these models are and how to train them. It also provides some very impressive results of what they are capable of. This is a great post, and if you are interested in natural language, machine learning or neural networks you should definitely read it. Go read it now, then come back here. You're back? good. Impressive stuff, huh? How could the network learn to immitate the input like that? Indeed. I was quite impressed as well. However, it feels to me that most readers of the post are impressed by the wrong reasons. This is because they are not familiar with unsmoothed maximum-liklihood character level language models and their unreasonable effectiveness at generating rather convincing natural language outputs. In what follows I will briefly describe these character-level maximum-likelihood langauge models, which are much less magical than RNNs and LSTMs, and show that they too can produce a rather convincing Shakespearean prose. I will also show about 30 lines of python code that take care of both training the model and generating the output. Compared to this baseline, the RNNs may seem somehwat less impressive. So why was I impressed? I will explain this too, below. The name is quite long, but the idea is very simple. We want a model whose job is to guess the next character based on the previous $n$ letters. For example, having seen ello, the next characer is likely to be either a commma or space (if we assume is is the end of the word "hello"), or the letter w if we believe we are in the middle of the word "mellow". Humans are quite good at this, but of course seeing a larger history makes things easier (if we were to see 5 letters instead of 4, the choice between space and w would have been much easier). We will call $n$, the number of letters we need to guess based on, the order of the language model. RNNs and LSTMs can potentially learn infinite-order language model (they guess the next character based on a "state" which supposedly encode all the previous history). We here will restrict ourselves to a fixed-order language model. So, we are seeing $n$ letters, and need to guess the $n+1$th one. We are also given a large-ish amount of text (say, all of Shakespear works) that we can use. How would we go about solving this task? Mathematiacally, we would like to learn a function $P(c | h)$. Here, $c$ is a character, $h$ is a $n$-letters history, and $P(c|h)$ stands for how likely is it to see $c$ after we've seen $h$. Perhaps the simplest approach would be to just count and divide (a.k.a maximum likelihood estimates). We will count the number of times each letter $c'$ appeared after $h$, and divide by the total numbers of letters appearing after $h$. The unsmoothed part means that if we did not see a given letter following $h$, we will just give it a probability of zero. And that's all there is to it. from collections import * def train_char_lm(fname, order=4): data = file(fname).read() lm = defaultdict(Counter) pad = "~" * order data = pad + data for i in xrange(len(data)-order): history, char = data[i:i+order], data[i+order] lm[history][char]+=1 def normalize(counter): s = float(sum(counter.values())) return [(c,cnt/s) for c,cnt in counter.iteritems()] outlm = {hist:normalize(chars) for hist, chars in lm.iteritems()} return outlm Let's train it on Andrej's Shakespears's text: !wget --2015-05-23 02:05:18-- Resolving cs.stanford.edu (cs.stanford.edu)... 171.64.64.64 Connecting to cs.stanford.edu (cs.stanford.edu)|171.64.64.64|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 4573338 (4.4M) [text/plain] Saving to: ‘shakespeare_input.txt’ shakespeare_input.t 100%[=====================>] 4.36M 935KB/s in 8.8s 2015-05-23 02:05:49 (507 KB/s) - ‘shakespeare_input.txt’ saved [4573338/4573338] lm = train_char_lm("shakespeare_input.txt", order=4) Ok. Now let's do some queries: lm['ello'] [('!', 0.0068143100511073255), (' ', 0.013628620102214651), ("'", 0.017035775127768313), (',', 0.027257240204429302), ('.', 0.0068143100511073255), ('r', 0.059625212947189095), ('u', 0.03747870528109029), ('w', 0.817717206132879), ('n', 0.0017035775127768314), (':', 0.005110732538330494), ('?', 0.0068143100511073255)] lm['Firs'] [('t', 1.0)] lm['rst '] [("'", 0.0008025682182985554), ('A', 0.0056179775280898875), ('C', 0.09550561797752809), ('B', 0.009630818619582664), ('E', 0.0016051364365971107), ('D', 0.0032102728731942215), ('G', 0.0898876404494382), ('F', 0.012038523274478331), ('I', 0.009630818619582664), ('H', 0.0040128410914927765), ('K', 0.008025682182985553), ('M', 0.0593900481540931), ('L', 0.10674157303370786), ('O', 0.018459069020866775), ('N', 0.0008025682182985554), ('P', 0.014446227929373997), ('S', 0.16292134831460675), ('R', 0.0008025682182985554), ('T', 0.0032102728731942215), ('W', 0.033707865168539325), ('a', 0.02247191011235955), ('c', 0.012841091492776886), ('b', 0.024879614767255216), ('e', 0.0032102728731942215), ('d', 0.015248796147672551), ('g', 0.011235955056179775), ('f', 0.011235955056179775), ('i', 0.016853932584269662), ('h', 0.019261637239165328), ('k', 0.0040128410914927765), ('m', 0.02247191011235955), ('l', 0.01043338683788122), ('o', 0.030497592295345103), ('n', 0.020064205457463884), ('q', 0.0016051364365971107), ('p', 0.00882825040128411), ('s', 0.03290529695024077), ('r', 0.0072231139646869984), ('u', 0.0016051364365971107), ('t', 0.05377207062600321), ('w', 0.024077046548956663), ('v', 0.002407704654895666), ('y', 0.002407704654895666)] So ello is followed by either space, punctuation or w (or r, u, n), Firs is pretty much deterministic, and the word following ist can start with pretty much every letter. from random import random def generate_letter(lm, history, order): history = history[-order:] dist = lm[history] x = random() for c,v in dist: x = x - v if x <= 0: return c To generate a passage of $k$ characters, we just seed it with the initial history and run letter generation in a loop, updating the history at each turn. def generate_text(lm, order, nletters=1000): history = "~" * order out = [] for i in xrange(nletters): c = generate_letter(lm, history, order) history = history[-order:] + c out.append(c) return "".join(out) lm = train_char_lm("shakespeare_input.txt", order=2) print generate_text(lm, 2) Fif thad yourty Fare sid on Che as al my he sheace ing. Thy your thy ove dievest sord wit whand of sold iset? Commet laund hant. KINCESARGANT: Out aboy tur Pome you musicell losts, blover. How difte quainge to sh, And usbas ey will Chor bacterea, and mens grou: Princeser, 'Tis a but be; I hends ing noth much? Lo, withiell thicest to an, se nourink of a gray that, the's ge, fat a to to and requand pink my menis of lat sall favere, I whathews be frevisars. FLAVIIIII: Whout les: your MACUS: O,-- Hie an an thout nown mis yought, the Phimne, shappy bley sirs,--Ha! Hart, frow mas gen the me? SEY: Herfe, inese vereat a voter'd theave, shashall er, ist hem thdre of mare to. Lovenat me bree shatteed. Besat's the a giverve se. FLANY: Whis I'll-volover to of you man hitinut, To thadarthopeatund me wing of pourisforniners dinguent my so liked withe brave heiry, and fore ist. Fain Thess kno st, will be witund nothousto yesty, art To stry all son ford bas sood cal love thys; as of th tund lm = train_char_lm("shakespeare_input.txt", order=4) print generate_text(lm, 4) First, the devishin it son? MONTANO: 'Tis true as full Squellen the rest me, my passacre. and nothink my fairs,' done to vision of actious to thy to love, brings gods! THUR: Will comfited our flight offend make thy love; Brothere is oats at on thes:'--why, cross and so her shouldestruck at one their hearina in all go to lives of Costag, To his he tyrant of you our the fill we hath trouble an over me? KING JOHN: Great though I gain; for talk to mine and to the Christ: a right him out To kiss; And to a kindness not of loves you Gower and to the stray Than hers of ever in this flight? I do me, After, wild, Or, if I into ebbs, by fair too me knowned worship asider thyself-skin ever is again, and eat behold speak imposed thy hand. Give and cours not sweet you of sorrow then; for they are gone! Then the prince, I see your likewis, is thee; and him for is them hearts, we have a kiss, And it is the come, some an eanly; you that am fire: prince when 'twixt young piece, that honourish we fort lm = train_char_lm("shakespeare_input.txt", order=4) print generate_text(lm, 4) First Office, masters To part at that she may direct my brance I would he dead. Pleaseth profit, Then we last awaked you to again, Far that night I'll courteous Herneath, Of circle off. SPEED: Not you. DON PEDRO: How to your preferment. DUCHESS QUICKLY: Now Rome Such other's chamber tears. A head. VIRGILIA: O, we show the bowls thouse two hones, if you loved: a proned speaking shrought upon that shall affect, onest, that I am a man is at Milford's worth. Am boundeserts are you, or woman great that's noble upon me burth one of the well surfew-begot of thy daughed with trib, trumpet they the Sever heave down? First what down, on for truth of marry, which I have Troilus' mouth'd To rever hang that cond Malvolio? EXETER: Blists: but speak morn back; would your soverdities, fatherefore the pate rever mirth, let her thoughts: Orsino's heard make methink, being of an Oxford or a name. GONZALO: What I reason, His known: Yet I care the Moor-worm. DUCHESS: O, partles their father not our lm = train_char_lm("shakespeare_input.txt", order=7) print generate_text(lm, 7) First Citizen: One graves Within rich Pisa walls, Your noses snapper-up of uncurrent roar'd! HOTSPUR: Hath he call you I bear; the admiration; but young. BIRON: One word to all! FALSTAFF: Ay, my good Lord, sir? OCTAVIUS: Philarmonus! Soothsayer that Worthy's thumb-ring: all the green-a box. MISTRESS QUICKLY: Ay, sir. CADE: I would unstate myself. Vexed I am one of your royal cheer yon strangers from boast: And God speed? CHIRON: And our virtue of your years, prodigious, the farthing whether deigned him already. Widow: Your master's pleasure. COUNTESS: Why me, Timon: If he were else this do? FALSTAFF: Prithee, be gone. CONSTANCE: You have compiled iniquity have walked? Gentleman: Ay, at Philip of Madam Juliet, go and thou shall forth. Silvia, Silvia--witness to come To know in heart-string to you picked. I must nothing but valour. Do you put me to all the opening it. Widow: Thus we met My wife' there's Bohemia: who, if I were much more than my bosom Be as we stay, her brav lm = train_char_lm("shakespeare_input.txt", order=10) print generate_text(lm, 10) First Citizen: Nay, then, that was hers, It speaks against your other service: But since the youth of the circumstance be spoken: Your uncle and one Baptista's daughter. SEBASTIAN: Do I stand till the break off. BIRON: Hide thy head. VENTIDIUS: He purposeth to Athens: whither, with the vow I made to handle you. FALSTAFF: My good knave. MALVOLIO: Sad, lady! I could be forgiven you, you're welcome. Give ear, sir, my doublet and hose and leave this present death. Second Gentleman: Who may that she confess it is my lord enraged and forestalled ere we come to be a man. Drown thyself? APEMANTUS: Ho, ho! I laugh to see your beard! BOYET: Madam, in great extremes of passion as she discovers it. PAROLLES: By my white head and her wit Values itself: to the sepulchre!' With this, my lord, That I have some business: let's away. First Keeper: Forbear to murder: and wilt thou not say he lies, And lies, and let the devil would have said, sir, their speed Hath been balm to heal their woes, B With an order of 4, we already get quite reasonable results. Increasing the order to 7 (~word and a half of history) or 10 (~two short words of history) already gets us quite passable Shakepearan text. I'd say it is on par with the examples in Andrej's post. And how simple and un-mystical the model is! Generating English a character at a time -- not so impressive in my view. The RNN needs to learn the previous $n$ letters, for a rather small $n$, and that's it. However, the code-generation example is very impressive. Why? because of the context awareness. Note that in all of the posted examples, the code is well indented, the braces and brackets are correctly nested, and even the comments start and end correctly. This is not something that can be achieved by simply looking at the previous $n$ letters. If the examples are not cherry-picked, and the output is generally that nice, then the LSTM did learn something not trivial at all. Just for the fun of it, let's see what our simple language model does with the linux-kernel code: !wget --2015-05-23 02:07:59-- Resolving cs.stanford.edu (cs.stanford.edu)... 171.64.64.64 Connecting to cs.stanford.edu (cs.stanford.edu)|171.64.64.64|:80... connected. HTTP request sent, awaiting response... 200 OK Length: 6206996 (5.9M) [text/plain] Saving to: ‘linux_input.txt’ linux_input.txt 100%[=====================>] 5.92M 1.10MB/s in 9.3s 2015-05-23 02:08:09 (654 KB/s) - ‘linux_input.txt’ saved [6206996/6206996] lm = train_char_lm("linux_input.txt", order=10) print generate_text(lm, 10) ~~/* * linux/kernel/time.c * Please report this on hardware. */ void irq_mark_irq(unsigned long old_entries, eval); /* * Divide only 1000 for ns^2 -> us^2 conversion values don't overflow: seq_puts(m, "\ttramp: %pS", (void *)class->contending_point]++; if (likely(t->flags & WQ_UNBOUND)) { /* * Update inode information. If the * slowpath and sleep time (abs or rel) * @rmtp: remaining (either due * to consume the state of ring buffer size. */ header_size - size, in bytes, of the chain. */ BUG_ON(!error); } while (cgrp) { if (old) { if (kdb_continue_catastrophic; #endif /* * for the deadlock.\n"); return 0; } #endif if (!info->hdr))) return diag; } /* We are sharing problem where roundup (the collection is * better readable */ for (i = 0; i < rp->maxactive = max_t(u64, delay, 10000LL); __hrtimer_get_res - get the timer * @timer: hrtimer to sched_clock_data *my_rdp) { bool oneshot = tick_oneshot_mask, GFP_KERNEL)) { free_cpumask_v lm = train_char_lm("linux_input.txt", order=15) print generate_text(lm, 15) ~/* * linux/kernel/power/snapshot.c * * This file is licensed under the terms of the GNU General Public License for more detailed information * on memory ordering guarantees * cgroups with bigger numbers are newer than those with smaller numbers. * Also, as csses are always appended to the parent, and put the ref when * this cgroup is being freed, so let's make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This condition is satisfied when called through * perf_event_init_context(child, ctxn); if (ret) { pr_err("Module len %lu truncated\n", info->len); return -ENOMEM; env->prog = *prog; /* grab the mutex to protect coming/going of the the jump_label table */ static const struct user_regset * find_regset(const struct cpumask *cpu_map) { int i; if (diag >= 0) { kdb_printf("go must execute on the entry cpu, " "please use \"cpu %d\" and then execute go\n", kdb_initial_cpu. Used to * single threaded, lm = train_char_lm("linux_input.txt", order=20) print generate_text(lm, 20) /* * linux/kernel/irq/spurious.c * * Copyright (C) 2004 Nadia Yvette Chambers */ #include <linux/irq.h> #include <linux/mutex.h> #include <linux/capability.h> #include <linux/suspend.h> #include <linux/shm.h> #include <asm/uaccess.h> #include <linux/interrupt.h> #include "kdb_private.h" /* * Table of kdb_breakpoints */ kdb_bp_t kdb_breakpoints[KDB_MAXBPT]; static void kdb_setsinglestep(struct pt_regs *regs) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); swhash->online = true; if (swhash->hlist_refcount) swevent_hlist_release(swhash); mutex_unlock(&show_mutex); return 0; } /* * Unshare file descriptor table if it is being shared */ static int unshare_fs(unsigned long unshare_flags, struct cred **new_cred) { struct cred *cred = current_cred(); retval = -EPERM; if (rgid != (gid_t) -1) { if (gid_eq(old->gid, kegid) || gid_eq(old->sgid, kegid) || gid_eq(old->sgid, kegid) || gid_eq(old->egid, print generate_text(lm, 20) /* * linux/kernel/irq/chip.c * * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina. * All Rights Reserved. * Copyright (c) 2009 Wind River Systems, Inc. * Copyright (C) 2008 Thomas Gleixner <[email protected]> * * This code is based on David Mills's reference nanokernel * implementation. It was mostly rewritten but keeps the same idea. */ void __hardpps(const struct timespec *tp) { ktime_get_real_ts(tp); return 0; } /* * Walks through iomem resources and calls func() with matching resource * ranges. This walks through whole tree and not just first level children. * All the memory ranges which overlap start,end and also match flags and * name are valid candidates. * * @name: name of resource * @flags: resource flags * @start: start addr * @end: end addr */ int walk_iomem_res(char *name, unsigned long val); static int alloc_snapshot(struct trace_array *tr) { struct dentry *d_tracer; d_tracer = tracing_init_dentry(void) { struct trace_array *tr = wakeup_t print generate_text(lm, 20, nletters=5000) /* * linux/kernel/irq/resend.c * * Copyright (C) 2008 Steven Rostedt <[email protected]> * Copyright (C) 2002 Khalid Aziz <[email protected]> * Copyright (C) 2002 Richard Henderson Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM. This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License as published by the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA * */ #include <linux/cpuset.h> #include <linux/sched/deadline.h> #include <linux/ioport.h> #include <linux/fs.h> #include <linux/export.h> #include <linux/mm.h> #include <linux/ptrace.h> #include <linux/profile.h> #include <linux/smp.h> #include <linux/proc_fs.h> #include <linux/interrupt.h> #include "kdb_private.h" /* * Table of kdb_breakpoints */ kdb_bp_t kdb_breakpoints[KDB_MAXBPT]; static void kdb_setsinglestep(struct pt_regs *regs); static int uretprobe_dispatcher(struct uprobe_consumer *con; int ret = -ENOENT; do { spin_lock(&hash_lock); if (tree->goner) { spin_unlock(&hash_lock); fsnotify_put_mark(&parent->mark); } static void cpu_cgroup_css_offline, .fork = cpu_cgroup_fork, .can_attach = cpu_cgroup_can_attach(struct cgroup_subsys_state *last; do { last = pos; /* ->prev isn't RCU safe, walk ->next till the end */ pos = NULL; css_for_each_child(pos, css) { struct freezer *parent = parent_freezer(freezer); mutex_lock(&freezer_mutex); rcu_read_lock(); list_for_each_entry_safe(owatch, nextw, &parent->watches, wlist) { if (audit_compare_dname_path(const char *dname, const char *path, int parentlen) { int dlen, pathlen; const char *p; dlen = strlen(dname); pathlen = strlen(path); if (pathlen < dlen) return 1; parentlen = parentlen == AUDIT_NAME_FULL ? parent_len(path) : parentlen; if (pathlen - parentlen != dlen) return 1; p = path + parentlen; return strncmp(p, dname, dlen); } static int audit_log_pid_context(context, context->target_pid, context->target_sessionid, context->target_auid, context->target_uid, context->target_sessionid, context->target_sid, context->target_comm, t->comm, TASK_COMM_LEN); return 0; } spin_lock_mutex(&lock->wait_lock, flags); schedule(); raw_spin_lock_init(&rq->lock); rq->nr_running = 0; rq->calc_load_active = nr_active; } return delta; } /* * a1 = a0 * e + a * (1 - e)) * e + a * (1 - e) * = (a0 * e^2 + a * (1 - e) * (1 - e^n)/(1 - e) * = a0 * e^2 + a * (1 - e) * (1 + e + ... + e^n-1) [1] * = a0 * e^n + a * (1 - e) * (1 + e + e^2) * * ... * * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1] * = a0 * e^n + a * (1 - e) * (1 + e) * * a3 = a2 * e + a * (1 - e) * * a2 = a1 * e + a * (1 - e) * = (a0 * e^2 + a * (1 - e) * (1 - e^n)/(1 - e) * = a0 * e^2 + a * (1 - e) * (1 + e + e^2) * * ... * * an = a0 * e^n + a * (1 - e^n) * * [1] application of the geometric series: * * is not a '0' or '1')\n"); } static void *l_start(struct seq_file *file, void *v, loff_t *offset) { unsigned long flags; spin_lock_irqsave(&timekeeper_lock, flags); if (global_trace.stop_count; } /** * tracing_is_enabled - Show if global_trace has been disabled * * Shows if the global trace has been enabled or not. It uses the * mirror flag "buffer_disabled" to be used in fast paths such as for * the irqsoff tracer. But it may be inaccurate due to races. If you * need to know the accurate state, use tracing_is_on() which is a little * slower, but accurate. */ int tracing_is_enabled()) tracer_enabled = 0; unregister_wakeup_function(tr, graph, 0); if (!ret && tracing_is_enabled()) return; local_irq_save(flags); gdbstub_msg_write(s, count); local_irq_restore(flags); } /* -ENOENT from try_to_grab_pending(work, is_dwork, &flags); /* * If someone else is already canceling, wait for it to * finish. flush_work() doesn't work for PREEMPT_NONE * because we may get scheduled between @work's completion * and the other canceling task resuming and clearing * CANCELING - flush_work() will return false immediately * as @work is no longer busy, try_to_grab_pending(struct work_struct *work) { unsigned long data = atomic_long_read(&rsp->expedited_done); if (ULONG_CMP_GE(jiffies, rdp->rsp->gp_start + 2, jiffies)) return 0; /* Grace period is not old enough. */ barrier(); if (local_read(&cpu_buffer_a->committing)) goto out_dec; if (local_read(&cpu_buffer->overrun); local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes); /* * The entries will be zeroed out when we move the * tail page. */ /* still more to do */ break; case RB_PAGE_UPDATE: /* * This is not really a fixup. The work struct was * statically initialized. We just make sure that it * is tracked in the object tracker. */ debug Order 10 is pretty much junk. In order 15 things sort-of make sense, but we jump abruptly between the and by order 20 we are doing quite nicely -- but are far from keeping good indentation and brackets. How could we? we do not have the memory, and these things are not modeled at all. While we could quite easily enrich our model to support also keeping track of brackets and indentation (by adding information such as "have I seen ( but not )" to the conditioning history), this requires extra work, non-trivial human reasoning, and will make the model significantly more complex. The LSTM, on the other hand, seemed to have just learn it on its own. And that's impressive.
http://nbviewer.jupyter.org/gist/yoavg/d76121dfde2618422139
CC-MAIN-2016-22
refinedweb
3,583
67.65
Designing User Interfaces With React Stay connected There it, and love its feature set. There are multiple tiers to what React can do, but I’d love to focus on how React can enable any developer to design modular and functional user interfaces. What Exactly Is React? Before we talk about creating things with React, let's explore what exactly what React is. Facebook’s definition of React looks something like: “React is a JavaScript library for building user interfaces.” While this billing could be dismissed as trendy jargon, I think it's actually an excellent description about what the framework actually does! React asks you to break up user interfaces into different state-driven components. We then leverage the library to help us transition between these component states. It's a noticeably different way of thinking when it comes to building the frontend of your application. Let’s take a login flow for example: A user visits your site and is presented with the login component. If the user enters a correct email/password, the component then submits that data for authentication. Depending on the response it receives from the authentication API, the component responds accordingly. When we break up an application into states, there’s a need to also separate each piece of the view into components. Now, components aren’t really a brand new idea in web development. Developers have been breaking their views into reusable pieces for years. In this context, React is simply executing the process of interacting with these reusable views really well. There’s also the matter of the JSX syntax that makes React unique. You can read a basic rundown on JSX here. JSX helps us better digest and interact with variable data in our applications. A Technical Example in Bb Remember that user login flow that I mentioned earlier? Let’s build it! To set up a pretty basic environment to run React in, there’s an excellent piece of documentation that I used. I prefer to utilize Facebook’s create-react-app package in this article, but you’re free to roll your own solution as well! Looking at App.js Now to get down to coding. We’re going to start with a focus on App.js . This file is where we’re going to define a few classes and functions that will help us design and implement the login flow. Initially, the file will look something like this: App.js import React, { Component } from 'react'; // Importing in some of our styling assets. import logo from './logo.svg'; import './App.css'; class App extends Component { // When the component is rendered, this is what will appear render() { return ( <div className="App"> <div className="App-header"> <img src={logo} <h2>React Login Flow</h2> </div> </div> ); } } // Export this into the global namespace export default App; In React, we can design components by declaring them as classes. In the example above, we’re only leveraging the render() function to create the HTML logic. From here, we want to create another component that presents the user with a login form, assuming they’re not authenticated. Let’s design the actual login form component first. App.js class LoginForm extends Component { render() { return ( <div className="login-form"> <input type="text" placeholder="email"></input> <input type="text" placeholder="password"></input> </div> ) } } At initial glance, our login form class is very simple. That’s alright. We’re going to make it a bit more robust in a second. First, we’ll need to render it in our App class. App.js class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <img src={logo} <h2>React Login Flow</h2> </div> <LoginForm /> </div> ); } } The way we render classes or components in the React, follows the syntax of: <MyComponentClass />. I really like this syntax because it's clean and pretty straightforward. We can pass in arguments too. Example: <MyComponentClass argument_1=“foo” argument_2=“bar” />. Now we’re going to add some functionality to our new component. Adding more functionality to our views So far, we’ve only mapped out classes that render certain sets of generated HTML. In this sense alone, React is an excellent tool for designing client-side views. However, there’s so much more to the functionality that React offers. Let’s focus on updating the LoginForm class that we just wrote. App.js // Previous code class LoginForm extends React.Component { constructor(props) { super(props); // Sets the default state of the Component. this.state = { email: '', password: '' }; // Tells the handleInputChange method to bind / listen for events on this // Component. this.handleInputChange = this.handleInputChange.bind(); } // Renders HTML markdown for our Login Form. // Notice where we call the above methods within the HTML Markup. render() { return ( <div className="login-form"> </div> ); } } There’s a lot of talk about here, so we’re going to break it down into small sections. First up: the constructor. Constructors and you One aspect of React’s functionality that might stick out to a lot of programmers is its unique use of constructors. constructor(props) { super(props); // Sets the default state of the Component. this.state = { email: '', password: '' }; // Tells the handleInputChange method to bind / listen for events on this // Component. this.handleInputChange = this.handleInputChange.bind(this); } If you’ve never dealt with constructors before, don’t panic! We simply leverage the constructor function to initialize our component class while also setting up the required logic to achieve the component’s purpose. Think of it like booting up your phone. We’re just setting things up for use! In our example, we’re setting up handleInputChange function. Adding listeners on functionality With our component class initialized, let’s explore the logic that it's going to depend(); } The comments in the code block explain a bit about the code’s purpose. However, there are a few more things to note here: For one, there’s this idea of an event object. We’re forwarding some form of a JavaScript event (be it a click, input change, hover, etc.) and probing it for information. In the case of our example, we’re seeing what the state of the email and password fields are at the time of submission. We need the event to track the changes of the input fields and then update the Component state to reflect that. Trying things out By now, we should have the resources needed to input an email/password combination and have the results printed in the console, upon submission. What we’re wanting to exercise with this demonstration is that we’re evaluating our LoginForm Component state as we interact with it. What’s The Point of React? So, what’s the big deal about all of this? As we saw with our example, React can be a bit intimidating at first. There are a few new ideas presented, as well as refined old ones. While diving into the technical functionality can be a ton of fun, there are some common themes that emerge from usage. React makes you think about design A lot of programmers aren’t good at design. While not every programmer should be a designer (and vice versa), it's incredibly useful to think about designing something before implementing it. React asks you to sit down and create each piece of your application in terms of HTML and functionality. This thought process helps you break down and design a step at a time. These designed components should hopefully be reusable in the long run as well. It could be said that designing in React takes longer, but you’re gifted with concise and functional building blocks at the end. React is really well engineered In the development community, it's no secret that React has been executing really well on all of its technical ideas. When I first explored the framework, I was frustrated with this lack of a application structure. However, awesome ideas like Redux have helped solve my frustrations. React has also learned what they do best and how to somehow better execute on those strengths. So many frameworks and libraries live and die by responding to community feedback. React, in particular, has been able to thrive as time passes. As a social media user, I’m a big fan of the current state of Facebook and Instagram’s current web functionality. I believe a lot of that is due to the growth and continued success of React’s engineering. React is not the only option In this article, I’ve written a lot of praise for React. The framework is a really unique and acquired taste. Its also not the only option out there. I’m fairly involved with developing EmberJS applications. Ember is way different than React, and at times has been much slower than React. However, React’s feature set has driven Ember to keep the pace with React. Other developers might say the same when comparing AngularJS to React. Either way, the prominence of React has lead to the development of better options in the JavaScript community. Again, React isn’t for everyone, but it's worth understanding. If the concepts and workflow that React encourages strikes a note with you, give it a shot! At the very least, you’ll walk away with a better perspective on how to create awesome user interfaces. Stay up to date We'll never share your email address and you can opt out at any time, we promise.
https://www.cloudbees.com/blog/designing-user-interfaces-with-react
CC-MAIN-2022-40
refinedweb
1,579
56.55
Rails StringIO File Upload # UPDATE It turns out the method below works unless your file is below a certain file size (which I haven’t figured out yet but it’s around 15k). If your file is too small it will be StringIO not a Tempfile. So how do we check it then? By the file size, if it’s 0 then don’t run the image upload code. Replace with # END UPDATE Coming from PHP getting file uploads to work with Rails was a bit of a mind funk. The biggest issue is that a file upload field returns different objects depending on if you browsed for a file or left it blank. If you browsed and chose a file the object will be a ‘Tempfile’, if it’s blank it will be ‘StringIO’. That took a couple of hours to figure out. The next step was figuring out how to check the object type, that’s when I stumbled upon some beauty Ruby code object.kind_of? Simple once you know how. The file field from the form in my view: Here’s my controller code for updating data from the form (the controller is products_controller.rb so I’m setting a relationship to the Image ‘product_id’): def update #save image params[:image][:product_id] = params[:id] #upload it unless it's StringIO @image = Image.create params[:image] unless params[:image][:file_data].kind_of? StringIO #save product params @product = Product.find(params[:id]) #update params that have changed if @product.update_attributes(params[:product]) #flash and redirect flash[:notice] = 'Product was successfully updated.' redirect_to :controller => 'cms', :action => 'index' else render :action => 'edit' end end The line to notice is It translates to; save the image model unless file_data is a StringIO object (if it’s not StringIO then it’s a Tempfile) This post helped me out more than you know. I’m not sure why file uploading in Rails is such a black-box area filled with weird special cases, but it’s nice to know I wasn’t the only one with the problem. Comment by Adam T. — November 26, 2006 @ 10:29 pm Definitely a big help. I was having trouble getting firefox tell whether a file was really being uploaded, and this was the path…thanks! Comment by ira S. — December 3, 2006 @ 7:22 pm i also encountered the same problem as you, but you could try @image = Image.create params[:image] unless params[:image][:file_data].size == 0 there are .size method for both StringIO and TempFile, and it return zero if it is empty Comment by chiamingen — February 22, 2007 @ 11:58 pm If you’re file is small, you get a StringIO object. So only saving if you don’t have StringIO will not save small files. Comment by Bart — March 14, 2007 @ 10:51 pm Like Bart said, I am having that problem now. Some files actually come across as StringIO. I don’t know if it is based on the File Type or the Size of the file, but I can’t figure out how to get it back as a file object. Comment by Tom — May 2, 2007 @ 12:26 pm It is indeed the case that small files are StringIO objects while larger files get passed as a Tempfile object. This is done for performance reasons (small files can be kept in the buffer since they don’t take up too much space there, this saves us from filesystem operations which always carry some overhead (disk seek and the like)). A universal way to process the uploaded data is: File.open(”your/file/goes/here”, “wb”) { |f| f.write(params[:your_file_form_field].read) } No matter whether you are working with a Tempfile or StringIO object, the CGI handler always provides params[:your_file_form_field].original_filename and .content_type for your processing pleasure. Comment by Niels — July 22, 2007 @ 8:36 am Thanks a lot Niels! That’s exactly what I needed. I couldn’t figure out for the life of me how to deal with small files that come in as StringIO objects. Comment by Eric — October 2, 2007 @ 10:05 am [...] [...] Pingback by Rails and file uploads « 41 technologies — April 9, 2008 @ 10:05 pm Thanks a lot. What i had to add was a nil check, cause it throwed an exception when accessing the ’size’ property. params[:image][:file_data].nil? cheers daniel Comment by Daniel — February 26, 2009 @ 3:41 pm
http://blog.vixiom.com/2006/07/26/rails-stringio-file-upload/
crawl-002
refinedweb
738
72.56
Hi all I have a ListViewwith a TemplateSelectorand two different DataTemplates (ViewCells). Behind the ListViewis a ViewModel for the ConentPagewith an ObservableCollectionwhich contains some item-models. The Binding to this Item-Model in my templates work like a charm. What I want: My ContentPage-ViewModel has some commands. The DataTemplate should use this command. How can I bind to this commands? I know, that I can make the commands static and reference with x:Static to it. Or I can add the Command to my Item-Model. But both are no Option for my solution. Thanks in advance I have found a way to achive this. I made a Basic class for my templates and added a BindableProperty to it: public class BaseTemplate : ViewCell { public static BindableProperty ParentBindingContextProperty = BindableProperty.Create(nameof(ParentBindingContext), typeof(object), typeof(BaseTemplate), null); public object ParentBindingContext { get { return GetValue(ParentBindingContextProperty); } set { SetValue(ParentBindingContextProperty, value); } } } And in my TemplateSelector I do the following: protected override DataTemplate OnSelectTemplate(object item, BindableObject container) { var mytemplate = new DataTemplate(typeof (MyTemplateType)); mytemplate .SetValue(BaseTemplate.ParentBindingContextProperty, container.BindingContext); return mytemplate; } Now I can Access the parent ViewModel with the property ParentBindingContext. Is there a better way to do this? Answers I have found a way to achive this. I made a Basic class for my templates and added a BindableProperty to it: And in my TemplateSelector I do the following: Now I can Access the parent ViewModel with the property ParentBindingContext. Is there a better way to do this? thanks for @MichaelJhl,you are great! @MJoehl how can I do it with XAML? I tried the code below but it didn't work: It does work, thanks alot! But I found one downside: You cant use CachingStrategy="RecycleElement"on the listview if you use this custom view cell Any thoughts on that? @MichaelJhl, did you inherit from BaseTemplate for your datatemplates? When I do, I get Error CS0260: Missing partial modifier on declaration of type 'SomeDataTemplate'; another partial declaration of this type exists. I was able to get this going and it works very well (code behind and xaml), thanks @MichaelJhl for sharing! Hi ! Thanks for this tip, in theory I'm agree with it... but impossible to make it works on my side :-( First, in your override "DataTemplate OnSelectTemplate", you can't create a new DataTemplate for each row... because on Android you will reach the "23 template count limit"... and I don't use RecycleElement as @Lippel suggested So this is my code 'public class CheckItem_DatatemplateSelector : DataTemplateSelector { DataTemplate Acceptedtemplate { get; set; } DataTemplate Refusedtemplate { get; set; } DataTemplate Uncheckedtemplate { get; set; } The binding seems to work. But in my "CkeckItem_accepted" (or in the two other templates too), I try to bind a button with my "ParentBindingContext.m_CallExpCommand" and I don't know why but the command is never executed... '' Does anybody that has made this tips working, can post a complete sample ? (or help if you see errors...) Thanks in advance @RianDutra Insted of ParentBindingContext u should use BindingContext. Is RecycleElementAndDataTemplate a suitable fix to the issue @Lippel and @Liger_Jerome mention? "The RecycleElementAndDataTemplate caching strategy builds on the RecycleElement caching strategy by additionally ensuring that when a ListView uses a DataTemplateSelector to select a DataTemplate, DataTemplates are cached by the type of item in the list. Therefore, DataTemplates are selected once per item type, instead of once per item instance." @UnreachableCode Quite some time passed since I added my comment. I believe RecycleElementAndDataTemplate didnt exist at that time. You should give it a try, it seems very promising. Hum... yes there was some time passed ... But I remember that I finally got this working (and this is in production since months) Opening the source-code (my memory is failing), I can see that : If you want some sample code, MP-me Hm, I'm getting a pretty big performance hit when set to RecycleElementAndDataTemplate. I'm not sure I can use this. Will I have problems if I leave it set to RetainElement? Hey Folks, Thank you very much for your update here I was stuck by too days to get call to command in from a partial class to public class TheClassViewModel : BindableObject So with your bread sticks here I could made it work. So, here is the code: public partial class TheClassCellOption : ViewCell { } Here is the selection class public class TheClassDataTemplateSelector : DataTemplateSelector { private readonly DataTemplate TheClassCellOption; private readonly DataTemplate OtherClassCellOption; the view model class . . . . . . }
https://forums.xamarin.com/discussion/comment/350550/
CC-MAIN-2020-50
refinedweb
734
55.64
tag:blogger.com,1999:blog-11776919197682417682017-05-25T02:20:08.690-07:00Ben's blogTelling the epic tales of science, programming and life. May quite possibly contain some ranting.Ben plot updates using GnuplotSometimes it's very convenient to see real time updates of your gnuplot graphs, for example if you're doing Monte Carlo simulations or if you have are monitoring stocks. Below I'll show you the way I do it, by only using gnuplot commands.<br /><br />First, create a gnuplot configuration file called '<i>loop.plt</i>', containing:<br /><br /><pre class="brush: bash">pause 2<br />replot<br />reread<br /></pre>Let's assume we have already given gnuplot the commands to plot something. What this piece of configuration file then does, is wait two seconds, then replot and then reread the <i>loop.plt</i> file. This will cause these three commands to be executed in an infinite loop. Reread is a very useful command. You can read more about it <a href="">here</a>.<br /><br />Now, how do we give the first plot command? Well, there are various options. You could for example add the plot command to the '<i>loop.plt</i>' file (which makes it less portable), but I like to give the instructions through the command line:<br /><pre class="brush: bash">gnuplot -persist -e "plot 'data.dat'" loop.plt</pre>where <i>data.dat</i> is a file that is continuously updated by some process. The nice thing about this is that you can recycle the '<i>loop.plt</i>' without making any changes to it.<br /><br /><h3>Passing a configuration file</h3><div>If you have a lot of settings, a better alternative is to let the loop configuration file load your own configuration file. We make the following adjustments:</div><div><br /></div><pre class="brush: bash">load config<br />pause 2<br />replot<br />reread<br /></pre>and we call gnuplot with:<br /><br /><pre class="brush: bash">gnuplot -persist -e "config='config.plt'" loop.plt</pre>Which sets the variable <i>config</i> to your own configuration file. Using this method we have the option to just call <i>gnuplot 'config.plt'</i> to draw the plot once, or use the above command to keep refreshing without having to change any of the files. If you want to have even more control, you could also make the pause time a variable. See you next time!<img src="" height="1" width="1" alt=""/>Ben the Countdown problem in Haskell<h3>Introduction</h3>One of the challenges in the British game show Countdown was to find a way to create a number using other numbers and basic mathematical operators. For example, given the set {2,3,4,5} generate 14, using +, -, *, /. A solution is 5 *4 - 2 * 3. Note that each number should be used exactly once.<br /><br />An interesting problem is writing an application that lets the computer do all the work for you, so that it finds a solution for a given target number, or maybe even <i>all </i>the<i> </i>solutions!<br /><br /><h3>Problem analysis</h3><div>To find all the ways to combine numbers to yield a certain result we have to generate all the possible ways of combining the numbers (subproblem 1) and then filter out the ones that have our desired result (subproblem 2). But how do we generate all possibilites? What we really want is to generate all the possible valid <u>mathematical expression</u>s with our numbers. We recognize that these expressions can be written as a tree:</div><div><br /></div><div>For example, $$5 \cdot 6 - 2 \cdot;">Tree representation of mathematical expression</td></tr></tbody></table><div>Since the operators we have chosen all have two elements, our expressions are binary trees. Thus, this means that our algorithm has to generate all possible trees.</div><div><br /></div><div>For this task I have chosen Haskell, since it is by far the easiest language to work with trees, as we will soon see. If you are interested in another example why Haskell - or other functional languages - are very convenient to work with if you have trees, check out my fully fledged <a href="">spl compiler</a>. This project is a compiler for a custom programming language, written in Haskell in only 900 lines! I have written my own parser, abstract syntax tree and Intel backend using the same techniques you'll see below. If you are interested in this project, let me know, and I may write a tutorial on this.</div><div><br /></div><h3>Implementation</h3><div>First, we have to define the grammar of our mathematical expressions:</div><pre class="brush:haskell">data Exp = Num Int | Plus Exp Exp | Sub Exp Exp | Mul Exp Exp | Div Exp Exp deriving Eq<br /></pre><div><br />Our expression is defined as being a number, or any of our binary operators. The elements (branches) of each operator are mathematical expressions themselves as well. You can immediately see that this recursive definition of a tree structure is much, much smaller than it would have been in for example Java or C.<br /><br />In an object oriented language the solution for such a structure would be to make a base class Exp, that has 5 subclasses. Each subclass then has two variables of type Exp, except for the Num subclass which has an integer variable.<br /><br />Before moving to the main algorithm, I'll show some code for convenience functions. The first implements a Show function for our custom data type, making a tree easier to read:<br /><pre class="brush:haskell">instance Show Exp where<br /> show (Num n) = show n<br /> show (Plus a b) = "(" ++ show a ++ "+" ++ show b ++ ")"<br /> show (Sub a b) = "(" ++ show a ++ "-" ++ show b ++ ")"<br /> show (Mul a b) = "(" ++ show a ++ "*" ++ show b ++ ")"<br /> show (Div a b) = "(" ++ show a ++ "/" ++ show b ++ ")"<br /></pre><br />If you now type<br /><pre class="brush:haskell">show (Plus (Num 5) (Mul (Num 6) (Num 2)))</pre></div><div><br /></div><div>in the Haskell interpreter, the result would be<i> (5 + (6 * 2))</i>. In the code above you can see <i>pattern matching</i>. If you are not familiar with functional languages, you can read about this feature <a href="">here</a>.<br /><br />We also need a function that actually calculates the result of our abstract expression. Using pattern matching again:<br /><pre class="brush:haskell">reduce :: Exp -> Int<br />reduce (Num n) = n<br />reduce (Plus a b) = reduce a + reduce b<br />reduce (Sub a b) = reduce a - reduce b<br />reduce (Mul a b) = reduce a * reduce b<br />reduce (Div a b) = reduce a `div` reduce b<br /></pre><br />Now we can think about the algorithm itself. We want to use all the numbers and use them only once, so we have to generate all the possible ways to select an element from a list and also keep track of which items we have not used yet. That's what the following function is for:<br /><pre class="brush:haskell">-- list should have at least 2 elements<br />split :: [a] -> [a] -> [(a, [a])]<br />split [] _ = []<br />split (x:xs) acc = [(x, acc ++ xs)] ++ (split xs (acc ++ [x]))<br /></pre>Split turns a list [1,2,3] into [(1, [2,3]), (2,[1,3]), (3, [1,2]). Thus, when we select a binary operator, we use the first number of the tuple as its left branch and we can use the list of remaining number to generate a subtree for the right branch:<br /><pre class="brush:haskell">pos :: [Int]-> [Exp]<br />pos [n] = [Num n] -- one number left? no binary operators possible<br />pos n = concatMap allpos subtree<br /> where<br /> subtree = map (\(a,r) -> (Num a, pos r)) (split n [])<br /> allpos (a,b) = concatMap (\e -> pos' a e) b<br /> pos' a b = [Plus a b, Sub a b, Sub b a, Mul a b, Div a b, Div b a]<br /></pre>Let's look at the <span style="font-family: Courier New, Courier, monospace;">subtree</span> function first. This generates all possible subtrees where the left branch is a given number. The function <i>pos'</i> gives all the possible binary operators where <span style="font-family: Courier New, Courier, monospace;">a</span> and <span style="font-family: Courier New, Courier, monospace;">b</span> are branches. As you can see, for the subtraction and division operator, the left and right branches interchanged is also a valid option. That's because 1 - 2 != 2 - 1. <br /><br />Finally, the <span style="font-family: Courier New, Courier, monospace;">allpos</span> function generates puts all these possiblities in a list. Of course, some of these expressions may be invalid due to the rules of the game. For example, it's not allowed to have a negative value or a fractional values in any of the subresults. Another thing that should be filtered is duplicates: 1 + 2 is the same expression as 2 + 1, so it should appear only once. That's why we have the following filter function:<br /><br /><pre class="brush:haskell">-- remove illegal attempts and attempts that are the same<br />valid :: Exp -> Bool<br />valid (Num n) = True<br />valid (Plus a b) = valid a && valid b && reduce a > reduce b -- only allow one<br />valid (Sub a b) = valid a && valid b && reduce a - reduce b >= 0 -- subsolutions should be positive<br />valid (Mul a b) = valid a && valid b && reduce a > reduce b<br />valid (Div a b) = valid a && valid b && reduce b > 0 && reduce a `mod` reduce b == 0<br /></pre>And finally we have a function that receives a list of numbers and the target number as input and that returns all the possible expressions: <br /><pre class="brush:haskell">findVal :: [Int] -> Int -> [Exp]<br />findVal n res = filter (\e -> valid e && reduce e == res) (pos n)<br /></pre><br />And that's the solution to the problem! If you run this application, you will see that contrary to what you may expect, very little memory is used. This is because Haskell does <i>lazy evaluation</i>, so the lists are actually not computed beforehand but each element is evaluated one at a time.<br /><br />There are some optimzations, which I leave as an exercise for the reader: for example, you can reject wrong expressions much earlier. If you generate a binary operator with two numbers, say <i>Plus (Num 2) (Num 4)</i>, you can reject it immediately (because we only allow 4 + 2 and not 2 + 4).<br /><br />And that's it for today. I hope you've learned something new and interesting :) </div><img src="" height="1" width="1" alt=""/>Ben gnuplot plots look like Mathematica plotsFor an article I am writing I wanted to plot the following function: $$ \theta \left(x > \frac{1}{2} \right) \left(\sin(4 \pi x) + \sin(4 \pi y) +2 \right) $$<br />Wolfram Alpha gives the following pretty;">Plot from Wolfram Alpha</td></tr></tbody></table>However, since you need to pay now to export this picture in a more usable format (like svg, eps or pdf) I decided to recreate the picture in gnuplot. Friendly advice for you others writing articles: <b>always</b> use vector formats where possible, otherwise your graphics will look horrible on higher resolutions!<br /><br />To plot the function in gnuplot we first have to do a little trick, because the step function is not included in gnuplot. It does have the sign function, however. So we can do the following: $$ \theta(x > \frac{1}{2}) = \frac{1 + \text{sgn}(x-\frac{1}{2})}{2} $$<br />A first attempt, with default settings is:<br /><br /><pre class="brush:bash">set terminal postscript eps<br />set pm3d at s hidden3d<br />unset hidden3d<br />unset surface<br />set xrange [0:1]<br />set yrange [0:1]<br />set samples 20,20<br /><br />splot (1+sgn(x-0.5))*(sin(4*pi*x) + sin(4*pi*y)+2)/2 title ''<br /></pre><br />This gives <br /><br /><br /><div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="160" src="" width="320" /></a></div><br />This doesn't really look too good. First thing that has to be changed is the color palette and the color of the grid. The color palette can be changed like this: <br /><br /><pre class="brush:bash">set terminal postscript eps<br />set palette defined ( 0 "#bd2c29", 2 "#ffd35a", 6 "white")<br /></pre><br />The numbers in front of the color codes are the values of the function that the color should correspond to. Thankfully, gnuplot automatically interpolates the colors.<br /><br />Next up is the grid color. The color can be set to a given line style by adding the style number at the end of the pm3d options: <br /><pre class="brush:bash">set pm3d implicit at s hidden3d 100<br />set style line 100 lc rgb '#000000' lt 1 lw 0.6</pre><br />Here I have defined the grid style to be a thin black line. I have chosen index 100 to make sure it doesn't clash with other settings.<br /><br />After removing the color bar and shifting the image down with ticslevel, we get the final image: <br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="206" src="" width="320" /></a></div>This looks a lot better! The only thing missing is the shadowing of surfaces angled away from the camera. I am not aware of a way to produce these in gnuplot. If anyone has additional advice to improve the plot, please let me know!<br /><br />The final version of the code: <br /><br /><pre class="brush:bash">set terminal postscript eps<br />set output '| epstopdf --filter --outfile=plot.pdf'<br />set palette defined ( 0 "#bd2c29", 2 "#ffd35a", 6 "white")<br />set pm3d implicit at s hidden3d 100<br />set style line 100 lc rgb '#000000' lt 1 lw 0.6<br />unset hidden3d<br />unset surface<br />set border 4095 front linetype -1 linewidth 0.8<br />set ticslevel 0<br />set xrange [0:1]<br />set yrange [0:1]<br />set ztics 1<br />set isosamples 40,40<br />set samples 20,20<br />unset colorbox<br /><br />splot (1+sgn(x-0.5))*(sin(4*pi*x) + sin(4*pi*y)+2)/2 title ''<br /></pre><img src="" height="1" width="1" alt=""/>Ben is the Higgs boson?Today the Higgs boson has been found at CERN, a great accomplishment in the field of theoretical particle physics. This discovery means that the model we are currently using is completed: the final ingredient has been found. This model, called the Standard Model, yields very good predictions of what is happening in nature.<br /><br />But what is this Higgs boson, what does it do and why didn't we see it before?<br /><br /><h2> The mystery of the massive particles</h2><div.</div><div><br /></div><div><span style="background-color: white;">Using some more advaced symmetry groups all of our beloved standard particles can be found:</span></div><div><br /></div><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="" width="297" /></a></div><div class="separator" style="clear: both; text-align: center;">The standard model (without Higgs)</div><div><br />The group in red are called gauge bosons. They are resultants of a very special symmetry and they can be interpreted as <i>forces </i>working on all the other particles. In fact, every elementary force has a matching gague boson. The photon (symbolised with a gamma), or "light", transfers electromagnetic forces, the gluon the strong force and Z and W the weak force.</div><div><br /></div><div>But there is a problem. The theory requires the W and Z boson to be <i>massless</i> in order for the theory to work. This is obviously not the case, because these particles have been found to have mass. In fact, they are pretty heavy!</div><div><br /></div><h2> The Higgs mechanism</h2><div>When physicist discovered that the theory was in trouble, they started searching for solutions. The symmetry of nature that can be used to find the gauge bosons worked far too good to just abandon it. Then, a new idea rose: we keep the symmetry, but we say nature <i>broke</i> it spontaneously. Wait, what? </div><div><br /></div><div). </div><div><br /></div><div.</div><div><br /></div>: center;">Spontaneous symmetry breaking</div><div><br /></div><div>A similar scenario this of a toy car that is sitting on a small mountain, but it has some energy which makes the car shift a little. Given enough time, the car will roll off the mountain into a valley, where it will;">Imagine a toy car in this figure</td></tr></tbody></table><div><br /></div><div><br /></div><div>Now, it turns out that breaking this symmetry can be done by introducing a particle: the Higgs particle. When analysing the properties of this particle, it turns out that this particle interacts with all the other particles, including itself! Due to these interactions, the particles gain mass.</div><div><br /></div><h2> Why did this take so long to find?</h2><div).</div><div><span style="background-color: white;"><br /></span></div><div><span style="background-color: white;".</span></div><div><span style="background-color: white;"><br /></span></div><div><span style="background-color: white;".</span></div><div><span style="background-color: white;"><br /></span></div><div><span style="background-color: white;">We aren't quite there yet, but a theory of everything is coming!</span></div><div><span id="goog_369349579"></span><span id="goog_369349580"></span></div><img src="" height="1" width="1" alt=""/>Ben transformations and their inverseWhen you're programming games or other 3d applications using OpenGL or DirectX, it is often required to use affine transformation matrices to describe transformations in space (4x4 matrices and the like). There is not a lot of documentation about this online, and most implementations I've seen, have some sort of hack. In this tutorial, I'll describe what affine transformations are, and more importantly, how to invert them correctly and efficiently. It is assumed that the reader knows what a matrices are and how to multiply them.<br /><br /><b>The affine transformation</b><br />Imagine you have a ball lying at (1,0) in your coordinate system. You want to move this ball to (0,2) by first rotating the ball 90 degrees to (0,1) and then moving it upwards with 1. This transformation is described by a rotation and translation. The rotation is: $$ \left[\begin{array}{cc} 0 & -1\\ 1 & 0\\ \end{array}\right] $$ and the translation is (0,1). To apply this transformation to a vector $\vec{x}$, we do: $$\vec{x}^\prime = R \vec{x} + \vec{T}$$ where R is a rotation matrix, and T is a translation vector. This is called an <i>affine transformation</i>.<br /><br />If you're in 2d space, there is no 2x2 matrix that will do this transformation for all points. However, if we go one dimension higher, to a 3x3 matrix, you can! That's why OpenGL uses 4x4 matrices to describe 3d transformations, as we'll see later. <br /><br /><b>The matrix representation</b><br />The best way to explain how to make this matrix, is to give the matrix for the example above.<br /><br />$$ \left[\begin{array}{ccc} 0 & -1 & 0 \\ 1 & 0 & 1 \\ 0 & 0 & 1 \\ \end{array}\right] $$<br /><br />As you can see, the left upper block is the rotation matrix, and to the right going downwards we have our translation. Because it's a 3x3 matrix now, we have to apply it to a 3d vector. We take the vector we had, $(1,0)$, and set the third component to 1. See what happens:<br /><br />$$ \left[\begin{array}{ccc} 0 & -1 & 0 \\ 1 & 0 & 1 \\ 0 & 0 & 1 \\ \end{array}\right] \begin{pmatrix} 1\\0\\1 \end{pmatrix} = \begin{pmatrix} 0\\2\\1 \end{pmatrix} $$<br /><br />This gives the result we wanted! If you look closer to the matrix multiplication, we see why this works. The trick is to set the last component of the vector to 1, so that the translation just gets added. In a short-hand notation the matrix and vector look like this:<br /><br />$$ \left[\begin{array}{c|c} R & T \\ \hline 0 & 1 \\ \end{array}\right] \begin{pmatrix} x\\ \hline 1 \end{pmatrix}=\begin{pmatrix} x^\prime\\ \hline 1 \end{pmatrix}$$<br /><br /><b>Inverting an affine transformation matrix</b><br />Sometimes it is very imporant to invert an affine transformation, for example to transform back from world space to object space. A naive approach is to just write a function that inverts 3x3 or 4x4 matrices. This is very inefficient, because there are some nice properties we can use.<br /><br /><br />If we think about what happens when we apply the affine transformation matrix, we rotate first over an angle $\alpha$, and then translate over $(T_x, T_y)$. So the inverse should translate first with $(-T_x, -T_y)$, and then rotate over $-\alpha$. Unfortunately, that's not what happens. What does happen is that the rotation is always applied first. So we have to correct for that by modifying our translation. A derivation:<br /><br />$$<br />\begin{array}<br />\vec{x}^\prime = R\vec{x} + T \\<br />\vec{x}^\prime - T = R\vec{x} \\<br />R^{-1}(\vec{x}^\prime - T) = \vec{x}\\<br />\end{array}<br />$$<br /><br />So to get back the original vector $\vec{x}$, we have a new affine transformation:<br /><br />$$ \vec{x} = R^{-1}\vec{x}^\prime - (R^{-1}T) $$<br /><br />What we have to do now is calculate the inverse of a rotation matrix and using that result, calculate our new translation.<br /><br /><br />Let's recall how a general rotation matrix in 2d looks like:<br /><br />$$ \left[\begin{array}{cc} \cos(\alpha) & - \sin(\alpha) \\ \sin(\alpha) & \cos(\alpha) \\ \end{array}\right] $$<br /><br />Because a rotation matrix is unitary, the inverse of a rotation matrix is equal to its transpose, so inverting can be done very quickly:<br /><br />$$ \left[\begin{array}{cc} \cos(\alpha) & \sin(\alpha) \\ -\sin(\alpha) & \cos(\alpha) \\ \end{array}\right] $$<br /><br />Now all we have to do is apply this to T, to get all the components for our inverse matrix:<br /><br />$$ \left[\begin{array}{c|c} R^{-1} & R^{-1}T \\ \hline 0 & 1 \\ \end{array}\right] \begin{pmatrix} x^\prime\\ \hline 1 \end{pmatrix}$$<br /><br /><b>Putting it together</b><br /><br />As we've seen, general 2d affine transformation matrices look like<br /><br />$$ \left[\begin{array}{ccc} \cos(\alpha) & - \sin(\alpha) & T_x \\ \sin(\alpha) & \cos(\alpha) & T_y \\ 0 & 0 & 1 \\ \end{array}\right] $$<br /><br />Applying the strategy we've derived above, the inverse is:<br /><br />$$ \left[\begin{array}{ccc} \cos(\alpha) & \sin(\alpha) & -T_x \cos(\alpha) - T_y \sin(\alpha) \\ -\sin(\alpha) & \cos(\alpha) & -T_y \cos(\alpha) + T_x \sin(\alpha) \\ 0 & 0 & 1 \\ \end{array}\right] $$<br /><br /><br />Expanding to 3d is trivial, since the same rules hold. For example, let's pick the rotation of $\theta$ over the axis $(0,1,0)$ and a translation $(1,2,3)$.<br /><br />The matrix becomes:<br />$$ \left[\begin{array}{cccc} \cos(\theta) & 0 & \sin(\theta) &1 \\ 0 & 1 & 0 & 2\\ -\sin(\theta) & 0 & \cos(\theta) & 3 \\ 0 & 0 & 0 & 1 \\ \end{array}\right] $$<br /><br />And the inverse is:<br />$$<br />\left[<br /><br /><br />\begin{array}{cccc}<br /> \cos (\theta ) & 0 & -\sin (\theta ) & 3 \sin (\theta )-\cos (\theta ) \\<br /> 0 & 1 & 0 & -2 \\<br /> \sin (\theta ) & 0 & \cos (\theta ) & -3 \cos (\theta )-\sin (\theta ) \\<br /> 0 & 0 & 0 & 1<br />\end{array}<br /><br />\right]<br /><br />$$<br /><br />These 4x4 matrices are the ones that OpenGL expects in functions like <span class="Apple-style-span" style="font-family: monospace;">glMultMatrixf!</span><br /><br />In order to use this knowledge in your code, you should write a matrix class that can 1) <a href="">create a rotation matrix from an angle and axis</a> 2) transpose a matrix and 3) be applied to a vector.<br /><b><br /></b><br /><b>Conclusion</b><br />Hopefully this tutorial has helped you better grasp the concepts of affine transformations. We've seen the definition of these transformations and how to use those to find a shortcut for a quick inversion algorithm. If you have any questions, please let me know!<img src="" height="1" width="1" alt=""/>Ben blacklisted me...For a website I am building I want to have facebook authentication, which means that users don't have to make an account. In order to use their API, facebook <b>forces</b> you to make an actual profile on their website. With great reluctance, I made my profile page, getting flooded with requests and other messages instantly. Well, I thought, this is what I have to do to get my key. So then I went to the app registration page and I got the following message: <br /><blockquote><span class="Apple-style-span" style="color: red;":.</span></blockquote>Seriously, WTF. After all that trouble I went through, their "systems" say my account is not authentic. What does that even mean, their systems? This completely baffles me, since I have dumped all sorts of personal stuff on there and I went through an SMS authentication. Nonetheless, their "systems" think I am lying.<br /><br /> I am pretty pissed off right now. The API key proved to be one big carrot on a stick to lure me in. Now I have to scan government papers to actually prove I am who I am. If their oh so intelligent system doesn't think my passport is a fake, that is...<br /><br /><b>update</b>: I have sent a heavily censored copy of my driver's license to facebook. I am un-blacklisted now.<img src="" height="1" width="1" alt=""/>Ben every programmer should have #1: Dynamic programmingDuring this course I'll try and describe several techniques and skills that every programming should have. Many of these subjects involve concepts that save a lot of time and provide easier solutions to problems than ad-hoc ones. If you have any suggestions, please let me know! <br /><br /><h3> Dynamic programming</h3>Dynamic programming is the first skill that every programmer should have. It can be used when you have a problem that can be split up into sub-problems that you've already calculated and cached. I have used it in numerous situations, including optimal control theory problems and <a href="">Project Euler</a> problems. An example:<br /><br />Imagine you want to write an application that prints the factorial for every number up to N, so:<br /><br /><pre>0! 1! 2! 3! ... N!<br /></pre><br />A naive solution would be <br /><pre class="brush:java">public class Main {<br /> public static long fac(int n) {<br /> if (n <= 1) {<br /> return 1;<br /> }<br /><br /> return n * fac(n - 1);<br /> }<br /><br /> public static void main(String[] args) {<br /> for (int i = 0; i < 10; i++) {<br /> System.out.println(fac(i));<br /> }<br /> }<br />}<br /></pre>This becomes very slow if N is large (in this example you can't make N too large, because the long overflows very quickly. Use BigInteger instead). However, if we look at the factorial function, we see that if we calculate 10!, we're recalculating 9!. We see that 10! = 10 * 9!. In general: <br /><pre>N! = N * (N-1)!<br /></pre><pre></pre>If we were to cache n! in a map, we'd be able to significantly reduce computation time. An improved solution: <br /><pre class="brush:java">public class Main {<br /> static Map<Integer, Long> facs = new HashMap<Integer, Long>();<br /><br /> public static long fac(int n) {<br /> if (facs.containsKey(n)) {<br /> return facs.get(n);<br /> }<br /> <br /> if (n <= 1) {<br /> return 1;<br /> }<br /><br /> long result = n * fac(n - 1);<br /> /* Add factorial to map. */<br /> facs.put(n, result);<br /> <br /> return result;<br /> }<br /><br /> public static void main(String[] args) {<br /><br /> for (int i = 1; i < 10; i++) {<br /> System.out.println(fac(i));<br /> }<br /> }<br />}<br /></pre>This is what's called <b>dynamic programming</b> and it is very useful to make seemingly infeasable solutions possible in exchange for memory. Let's look at a realistic example. <br /><br /><h3> Best path in a triangle</h3>Imagine you have a triangle like this: <br /><pre> 3<br /> 7 4<br /> 2 4 6<br />8 5 9 3<br /></pre>and you're aked to calculate the path with the optimal score. The score is calculated by adding all the numbers you go through. In this case the optimal score is 3 + 7 + 4 + 9 = 23. Note that this is <a href="">problem 67</a> of the Euler Project, so if you want to try it for yourself first, you should stop reading here!<br /><br /> This problem is easy to solve for small triangles, but for big triangles it becomes infeasable to calculate all the routes. We're now going to look at a triangle with a depth of 100. This means that there are 2^99 routes! Looking at the triangle above, we see that the value at the top is 3 + [the maximum of the subtree 7 and subtree 4].<br /><br />This looks like a division into subproblems! If we were to cache the values of the tree at 7 and 4, we'd know the value at the top incredibly fast. The dynamic programming solution is thus as follows: <br /><br /><pre class="brush: java">public class Main {<br /> /* Values at every point in the tree. */<br /> public static Map<Point, Integer> values;<br /> public static List<List<Integer>> tree;<br /> <br /> public static Integer getValue(Point p) {<br /> /* Check cache first. */<br /> if (values.containsKey(p)) {<br /> return values.get(p);<br /> }<br /> <br /> /* Boundary conditions. */<br /> if (p.y == tree.size() - 1) {<br /> return tree.get(p.y).get(p.x);<br /> }<br /> <br /> /* Get the values of the two subtrees. */<br /> Integer left = getValue(new Point(p.x, p.y + 1));<br /> Integer right = getValue(new Point(p.x + 1, p.y + 1));<br /> Integer value = tree.get(p.y).get(p.x) + Math.max(left, right);<br /> <br /> values.put(p, value);<br /> return value; <br /> }<br /><br /> public static void main(String[] args) {<br /> /* TODO: read tree from file. */<br /> <br /> System.out.println(getValue(new Point(0,0)));<br /> }<br /><br />}<br /></pre><br />This solution is a sketch. I leave parsing the tree from a file as an exercise to the reader. Note that if you're serious about perfomance, using Integer and other boxed types is a bad idea. I would strongly recommend using the <a href="">Trove High Performance Collections</a> for the cache.<br /><br /> Until next time!<img src="" height="1" width="1" alt=""/>Ben loading of images in Listview<div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="clear:left; float:left;margin-right:1em; margin-bottom:1em"><img border="0" height="320" width="289" src="" /></a></div> A common scenario is adding images to a Listview. For example, if you´re making a cocktail recipe app, you´d want a picture next to the cocktail name. Sometimes the images should be retrieved from the internet and then be displayed. Unfortunately, this is difficult to do right. If you´ve tried it, you´ve probably noticed performance hits, or some strange glitches. In this tutorial, I´ll show you how to download images and display them. We´ll also discuss some pitfalls, like recycling and concurrency.<br /><br /><br /><b>Setting up the listview</b><br />I assume you already know how to define a row layout for a Listview and know about adapters. <br /><br /.<br /><br /><pre class="brush: java">public class ListAdapter extends ArrayAdapter<Article> {<br /> private List<Article> articles;<br /> private Context context;<br /> private final LayoutInflater inflator;<br /><br /> private static final String[] URLS = { /> private static class ViewHolder {<br /> public ImageView iconView;<br /> public TextView nameTextView;<br /> public TextView bottomText;<br /> }<br /><br /> public ListAdapter(Context context, int textViewResourceId,<br /> List<Article> articles) {<br /> super(context, textViewResourceId, articles);<br /> this.articles = articles;<br /> this.context = context;<br /> inflator = (LayoutInflater) context<br /> .getSystemService(Context.LAYOUT_INFLATER_SERVICE);<br /><br /> BitmapManager.INSTANCE.setPlaceholder(BitmapFactory.decodeResource(<br /> context.getResources(), R.drawable.icon));<br /> }<br /><br /> @Override<br /> public View getView(int position, View convertView, ViewGroup parent) {<br /> ViewHolder holder;<br /><br /> if (convertView == null) {<br /> convertView = inflator.inflate(R.layout.article_row, null);<br /><br /> TextView nameTextView = (TextView) convertView<br /> .findViewById(R.id.title);<br /> TextView bottomText = (TextView) convertView<br /> .findViewById(R.id.bottomtext);<br /> ImageView iconView = (ImageView) convertView<br /> .findViewById(R.id.article_icon);<br /> holder = new ViewHolder();<br /> holder.nameTextView = nameTextView;<br /> holder.bottomText = bottomText;<br /> holder.iconView = iconView;<br /> convertView.setTag(holder);<br /> } else {<br /> holder = (ViewHolder) convertView.getTag();<br /> }<br /><br /> Article article = articles.get(position);<br /> holder.nameTextView.setText(article.getTitle());<br /> holder.bottomText.setText(article.getAuthor() + " | "<br /> + article.getPubDate());<br /><br /> holder.iconView.setTag(URLS[position]);<br /> BitmapManager.INSTANCE.loadBitmap(URLS[position], holder.iconView, 32,<br /> 32);<br /><br /> return convertView;<br /> }<br />}<br /><br /></pre><br />As you can see, I am recycling the view, because I only inflate from XML when convertView == null. I also store references to all the children views in a tag. Recycling and tagging greatly improves performance, as can be seen in this <a href="">Google Conference video</a>.<br /><br /><b>Downloading the bitmaps</b><br />A naive way to download a bitmap is to just make a http connection in the getView and set the bitmap using <i>iconView.setImageBitmap()</i>. This would cause severe lag, because the UI thread would have to wait until the image is downloaded. What we want is to download in a separate thread. We also want some kind of cache to store downloaded bitmaps. <br /><br />All this can be done in a singleton BitmapManager. Here is the download function:<br /><br /><pre class="brush: java" /></pre>I don't know if this is the optimal way to download a file, so if you know a better way, please leave a message. As you can see, the bitmap is stored in cache, which is defined as <i>Map<String, SoftReference<Bitmap>> cache;</i>. We are using a SoftReference, because we want the bitmap to be garbage collected if the VM is low on memory.<br /><br /><b>The recycle trap</b><br /.<br /><br /><pre>Row 1 visible: start download of image 1<br />Scrolling<br />Row 3 visible (recycled view of row 1): start download of image 3<br />Download of image 3 done: row 3 image set to image 3<br />Download of image 1 done: row 3 image set to image 1<br /></pre><br /: <i>Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());</i>.<br /><br /><b>Retrieving the bitmap</b><br /><pre class="brush: java"> /></pre>The first thing we do when we load the bitmap, is associating the URL with the ImageView. Then we see if the bitmap is in the cache. If so, we load it from cache, or else we queue the download.<br />It should be noted that the loadBitmap function is called in the UI thread, which means that we don't have to check if the imageView is recycled and we can call functions like setImageBitmap directly.<br /><br /><b>The working thread</b><br / <a href="">ExecutorService</a> class from the Java Concurrency framework. We create a fixed thread pool (<a href="">newFixedThreadPool</a>) with 5 items (this number is arbitrary, I haven't tested which amount is optimal), which means that there will be up to five images that are downloaded at the same time. All the other downloads are stored in an unbounded queue.<br /><br /><pre class="brush: java" /></pre.<br /><br />In handleMessage the bitmap is retrieved from msg.obj. The bitmap is only set if the current URL is the last one to be associated with the ImageView. If the download failed for some reason, a placeholder is used.<br /><br /><b>Conclusion</b><br / :)<br /><br /><br /><b>Full code</b><br /><pre class="brush: java">public enum BitmapManager {<br /> INSTANCE;<br /><br /> private final Map<String, SoftReference<Bitmap>> cache;<br /> private final ExecutorService pool;<br /> private Map<ImageView, String> imageViews = Collections<br /> .synchronizedMap(new WeakHashMap<ImageView, String>());<br /> private Bitmap placeholder;<br /><br /> BitmapManager() {<br /> cache = new HashMap<String, SoftReference<Bitmap>>();<br /> pool = Executors.newFixedThreadPool(5);<br /> }<br /><br /> public void setPlaceholder(Bitmap bmp) {<br /> placeholder = bmp;<br /> }<br /><br /> public Bitmap getBitmapFromCache(String url) {<br /> if (cache.containsKey(url)) {<br /> return cache.get(url).get();<br /> }<br /><br /> return null;<br /> }<br /><br /> /><br /> /><br /> />}<br /><br /></pre><br />In case you're wondering, an enum is the preferred way to create a singleton class.<br /><br /><img src="" height="1" width="1" alt=""/>Ben cutscene framework for Android - part 3We've reached the third and final part of the tutorial on how to make cutscenes. Now that we've already defined Actors and Animations, we just have to define the Cutscene. The cutscene should consist of a list of actors, the current frame and the frame at which the cutscene ends. Animations don't have to be included explicitly, because they are part of the <i>Actor</i> class.<br /><br />You may ask why we need to explicitly define an end frame. We could also look at the frame at which all the animations of each actor have finished. If we set that frame as the end frame, the cutscene is cut off immediately after the last transition. This leaves no time to actually see what's going on. That's why we use an end frame.<br /><br /><pre class="brush:java">public class Cutscene {<br /> private Set<Actor> actors;<br /> private int endFrame;<br /> private int currentFrame;<br /> <br /> public Cutscene(Context context, int cutsceneResource) {<br /> load(context, cutsceneResource);<br /> currentFrame = 0;<br /> }<br /> <br /> public boolean isActive() {<br /> return currentFrame <= endFrame;<br /> }<br /> <br /> public Set<Actor> getActors() {<br /> return actors;<br /> }<br /> <br /> public void update() {<br /> if (!isActive()) {<br /> return;<br /> }<br /> <br /> for (Actor actor : actors) {<br /> actor.update();<br /> }<br /> <br /> currentFrame++;<br /> }<br /> <br /> public void draw(Canvas canvas) {<br /> for (Actor actor : actors) {<br /> actor.draw(canvas);<br /> }<br /> }<br />} <br /></pre><br />As you can see, the Cutscene class is pretty straightforward. Using the framework so far, we can construct a cutscene from source code, with relative ease. It would be even better if we could just read it in from an XML file. For example, look at the following structure:<br /><br /><pre class="brush:xml"><?xml version="1.0" encoding="UTF-8"?><br /><cutscenes><br /> <cutscene end="140"><br /> <actor type="text" name="Intro" x="10.0" y="40.0"<br /><br /> <animation type="text" start="50" text="@string/anim_text" /><br /> </actor><br /> <actor type="bitmap" name="Player" visible="true" x="0.0" y="50.0" bitmap="@drawable/player"><br /> <animation type="translate" start="4" end="60" from_x="0.0" from_y="50.0" to_x="100.0" to_y="50.0" /><br /> </actor><br /> </cutscene><br /></cutscenes><br /></pre><br />All the elements of a simple scene are there: there is a text actor that displays two lines of text and a player bitmap that is moved across the screen. I've added two different ways to add text: you either hardcode it, or you give a reference to a string. The latter is recommended to support internationalisation.<br /><br />I've given each actor a name, so that you can easily add additional information from source code. For example, in my project the player bitmap is a subrectangle of the resource <i>@drawable/player</i>. When this cutscene is parsed, I look for the actor with the name <i>Player</i>, and I substitute the bitmap. If you want to have a custom bitmap, you should use <i>public void load(Context context, int id) {<br /> actors = new HashSet<Actor>();<br /> <br /> XmlResourceParser parser = context.getResources().getXml(id);<br /> try {<br /> int eventType = parser.getEventType();<br /> <br /> Actor currentActor = null;<br /> <br /> while (eventType != XmlPullParser.END_DOCUMENT) {<br /> if (eventType == XmlPullParser.START_TAG) {<br /> if (parser.getName().equals("cutscene")) {<br /> endFrame = parser.getAttributeIntValue(null, "end", 0);<br /> }<br /> <br /> if (parser.getName().equals("actor")) {<br /> String type = parser.getAttributeValue(null, "type");<br /> String name = parser.getAttributeValue(null, "name");<br /> float x = parser.getAttributeFloatValue(null, "x", 0);<br /> float y = parser.getAttributeFloatValue(null, "y", 0);<br /> boolean visible = parser.getAttributeBooleanValue(null,<br /> "visible", false);<br /> <br /> /* Read type specifics. */<br /> if (type.equals("text")) {<br /> String text = parser<br /> .getAttributeValue(null, "text");<br /> int res = parser.getAttributeResourceValue(null,<br /> "text", -1);<br /> if (res != -1) {<br /> text = context.getResources().getString(res);<br /> }<br /> <br /> // TODO: do something for paint. */<br /> Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);<br /> paint.setColor(Color.WHITE);<br /> currentActor = new TextActor(name, text,<br /> new Vector2f(x, y), paint);<br /> currentActor.setVisible(visible);<br /> }<br /> <br /> if (type.equals("bitmap")) {<br /> Bitmap bitmap = null;<br /> if (!parser.getAttributeValue(null, "bitmap")<br /> .equals("custom")) {<br /> int bitmapID = parser<br /> .getAttributeResourceValue(null,<br /> "bitmap", -1);<br /> bitmap = BitmapFactory.decodeResource(<br /> context.getResources(), bitmapID);<br /> }<br /> <br /> currentActor = new BitmapActor(name, bitmap,<br /> new Paint());<br /> currentActor.setVisible(visible);<br /> currentActor.getTransform().setTranslate(x, y);<br /> }<br /> <br /> if (currentActor != null) {<br /> actors.add(currentActor);<br /> }<br /> }<br /> <br /> if (parser.getName().equals("animation")) {<br /> String type = parser.getAttributeValue(null, "type");<br /> int start = parser.getAttributeIntValue(null, "start",<br /> 0);<br /> int end = parser.getAttributeIntValue(null, "end",<br /> start);<br /> <br /> if (type.equals("text")) {<br /> String text = parser<br /> .getAttributeValue(null, "text");<br /> currentActor.addAnimation(new TextAnimation(text,<br /> start));<br /> }<br /> <br /> if (type.equals("translate")) {<br /> float from_x = parser.getAttributeFloatValue(null,<br /> "from_x", 0);<br /> float from_y = parser.getAttributeFloatValue(null,<br /> "from_y", 0);<br /> float to_x = parser.getAttributeFloatValue(null,<br /> "to_x", 0);<br /> float to_y = parser.getAttributeFloatValue(null,<br /> "to_y", 0);<br /> currentActor.addAnimation(new TranslationAnimation(<br /> new Vector2f(from_x, from_y), new Vector2f(<br /> to_x, to_y), start, end));<br /> }<br /> }<br /> }<br /> <br /> eventType = parser.next();<br /> }<br /> } catch (XmlPullParserException e) {<br /> e.printStackTrace();<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br />}<br /></pre><br />This function reads the XML and creates a cutscene. I have left some things out, like defining a <a href="">Paint</a> in the XML, because I haven't implemented those myself. If you want to do such a thing, I would recommend creating another XML structure just for Paints. Then you can add a reference to the resource in the cutscene structure. As you can see, this framework is easily extendable.<br /><br />And there you have it. In this tutorial you've seen how to build a framework for cutscenes. We've started with simple building blocks like animations and actors and finally we've seen how to put them together to make cutscenes and read these from XML files. I hope you liked it!<br /><br /><img src="" height="1" width="1" alt=""/>Ben dictionaries to Android keyboardI recently installed CyanogenMod-7.1.0-RC1 for my Wildfire, and I noticed that some dictionaries are missing from the default Gingerbread keyboard. What this means is that although you can select for example Dutch as input language, there will be no word suggestions. In this post I'll show you how to add those missing dictionaries.<br /><br /><b>Acquiring dictionaries</b><br />The keyboard application is stored in the file <i>/system/app/LatinIME.apk</i>. Online, you can find different LatinIME's that have more dictionaries. I have compiled a list of dictionaries available to two custom roms:<br /><br />CyanogenMod: da, de, en, es, fr, it, iw, ka, pt, ru, sv<br />GingerVillain: da, de, en, es, it, nb, nl, sv<br /><br />There are more custom roms available that may have different languages and you could also try official roms from HTC or any other company that publishes Android phones. When you've found and downloaded a good rom, store the file system/app/LatinIME.apk found in the zip.<br /><br />Now there are two options. The first is replacing LatinIME.apk and the second is modifying the original to support extra dictionaries. In my case, the two keyboards I wanted are English and Dutch, so for me replacing the CyanogenMod's LatinIME.apk with the one from GingerVillain was good enough. You can see below how to copy the file.<br /><br /><b>Adding a dictionary</b><br />To add something to an apk, we first need to extract the apk. This is done using <a href="">apktool</a>. Download and extract both apktool and the helper scripts (depending on your OS) to the same folder.<br /><br />Also make sure that you have adb, the android debugger and that you've set your phone to USB debugging mode (look <a href="">here</a> if you don't know how to do that). To get adb you need to install the SDK platform tools (see <a href="">here</a>).<br /><br />Put the LatinIME.apk with the dictionary you want in the folder where you've stored apktool and rename it to LatinIME_new.apk. When you've done that open a console (cmd.exe in Windows) and navigate to the folder where you've stored apktool.<br /><br /><pre class="bash" name="code">adb pull /system/app/LatinIME.apk LatinIME_old.apk <br />apktool d LatinIME_old.apk old <br />apktool d LatinIME_new.apk new <br /></pre><br />Now that you've done that, you have two new folder: old and new. The old one contains the contents of the original LatinIME.apk and the new folder contains the dictionary you want. Go to the new directory and find res/raw-YOURLANG, where YOURLANG is the two letter abbreviation of your language. Now copy this directory to res folder in the old directory.<br /><br />Now that you've added the file to the extracted apk, it's time to repackage it.<br /><br /><pre class="bash" name="code">apktool b old LatinIME.apk <br /></pre><br />The newly generated LatinIME.apk contains your dictionary, along with all the old ones. Now we have to upload this file to your phone.<br /><br /><b>Updating the LatinIME.apk file</b><br />When you've got the LatinIME.apk you want, we can overwrite the file in your /system/app directory on your phone. Unfortunately, the /system folder is mounted read-only, so we have to remount it first. For the following steps, we make use of the <i>adb</i> again.<br /><br /><pre class="bash" name="code">adb pull /system/app/LatinIME.apk LatinIME_backup.apk <br />adb remount <br />adb push LatinIME.apk /system/app/LatinIME.apk <br /></pre>The first line makes a backup. You can leave that out if you've already done so.<br /><br /><b>Conclusion</b><br />Now that you've updated your LatinIME.apk, you'll need the reboot your phone. After that, you're all set to use your new, fancy dictionary!<br /><img src="" height="1" width="1" alt=""/>Ben cutscene framework for Android - part 2In the last tutorial we've made a framework for basic animations, like translation and text changes. Now it's time to put them together to transform an actor.<br /><br /><b>The actor</b><br />An abstract actor is an object that has variables that can be transformed. In most cases, an actor can be drawn to the screen. For this tutorial, we'll assume that they all do. The actor class should at least contain a set of animations and a transformation matrix that defines how the model is drawn on the screen.<br /><br />The actor also contains the elements that will be transformed by the animations, and therefore it should also be an <i>AnimationChangedListener</i>.<br /><br /><pre class="brush:java">public abstract class Actor implements AnimationChangedListener {<br/> private final String name;<br/> private boolean visible;<br/> private Matrix transform;<br/> private Set<Animation> animations;<br/><br/> public Actor(String name) {<br/> this.name = name;<br/> visible = false;<br/> animations = new HashSet<Animation>();<br/> transform = new Matrix();<br/> }<br/><br/> public String getName() {<br/> return name;<br/> }<br/><br/> public Matrix getTransform() {<br/> return transform;<br/> }<br/><br/> public boolean isVisible() {<br/> return visible;<br/> }<br/><br/> public void setVisible(boolean visible) {<br/> this.visible = visible;<br/> }<br/><br/> /**<br/> * Adds an animation and links the actor as a listener.<br/> * <br/> * @param animation<br/> * Animation<br/> */<br/> public void addAnimation(Animation animation) {<br/> animations.add(animation);<br/> animation.addListener(this);<br/> }<br/><br/> public void update() {<br/> for (Animation animation : animations) {<br/> animation.doTimeStep();<br/> }<br/> }<br/> <br/> public boolean isIdle() {<br/> for (Animation animation : animations) {<br/> if (!animation.isDone()) {<br/> return false;<br/> }<br/> }<br/> <br/> return true;<br/> }<br/><br/> @Override<br/> public void valueChanged(Animation animation) {<br/> float[] old = new float[9];<br/> transform.getValues(old);<br/><br/> switch (animation.getType()) {<br/> case POSITION:<br/> Vector2f trans = (Vector2f) animation.getCurrentValue();<br/> Vector2f diff = trans.sub(new Vector2f(old[Matrix.MTRANS_X],<br/> old[Matrix.MTRANS_Y]));<br/> transform.postTranslate(diff.getX(), diff.getY());<br/> break;<br/> case VISIBILITY:<br/> visible = (Boolean) animation.getCurrentValue();<br/> break;<br/> }<br/> }<br/><br/> public final Vector2f getPosition() {<br/> float[] old = new float[9];<br/> transform.getValues(old);<br/> return new Vector2f(old[Matrix.MTRANS_X], old[Matrix.MTRANS_Y]);<br/> }<br/><br/> public abstract void draw(Canvas canvas);<br/><br/>}<br/></pre><br />The base class Actor listens to two animations: a visibility animation and a translation animation. The exact implementation of the visibility animation is something I leave up to the reader, but it's just a simple switch at a certain frame. At this time, I use the <a href="">Matrix class</a> from Android to store the rotations, scaling and translations, but due to the lack of getters like getPosition or getRotation, I may replace this code with my own Matrix class. Alternatively, I could store the rotation, translation and scale in three different variables.<br /><br />I have given the actor a name, so it can be identified at a later point, for debugging or for setting specifics in the source code (instead of the XML, we'll get to that).<br /><br />The actor is abstract, because the <i>draw</i> method is not implemented. We'll look at two very useful derived classes now.<br /><br /><b>The text actor</b><br />The text actor is an actor that displays a piece of text on the screen. We'll use the <a href="(java.lang.String, float, float, android.graphics.Paint)">drawText</a> function of the Canvas for that. The class should also be an <i>AnimationChangedListener</i>, because it has to receive a notification when a <i>TextAnimation</i> changes the text.<br /><br /><pre class="brush:java">public class TextActor extends Actor implements AnimationChangedListener {<br/> private String text;<br/> private final Paint paint;<br/><br/> public TextActor(String name, String text, Vector2f pos, Paint paint) {<br/> super(name);<br/> this.text = text;<br/> this.paint = paint;<br/><br/> getTransform().setTranslate(pos.getX(), pos.getY());<br/> }<br/> <br/> public Paint getPaint() {<br/> return paint;<br/> }<br/><br/> @Override<br/> public void valueChanged(Animation animation) {<br/> if (animation.getType() == AnimationType.TEXT) {<br/> text = (String) animation.getCurrentValue();<br/> }<br/><br/> super.valueChanged(animation);<br/> }<br/><br/> @Override<br/> public void draw(Canvas canvas) {<br/> Vector2f pos = getPosition();<br/> canvas.drawText(text, pos.getX(), pos.getY(), paint);<br/> }<br/><br/>}<br /></pre><br />The class also requires a <a href="">Paint</a> instance to draw the text correctly.<br /><br /><b>The bitmap actor</b><br />Probably the most important actor is the bitmap actor: this class draws a bitmap to the screen using a certain transformation (defined in the base class). The implementation is very simple:<br /><br /><pre class="brush:java"><br/>public class BitmapActor extends Actor {<br/> private Bitmap bitmap;<br/> private final Paint paint;<br/><br/> public BitmapActor(String name, Bitmap bitmap, Paint paint) {<br/> super(name);<br/> this.bitmap = bitmap;<br/> this.paint = paint;<br/> setVisible(false);<br/> }<br/> <br/> public void setBitmap(Bitmap bitmap) {<br/> this.bitmap = bitmap;<br/> }<br/><br/> public void draw(Canvas canvas) {<br/> if (bitmap != null && isVisible()) {<br/> canvas.drawBitmap(bitmap, getTransform(), paint);<br/> }<br/> }<br/>}<br /></pre><br />Now that we've seen how to make actors, what's left is to put them together in a cutscene. Additionally, we'll learn how to define these cutscenes in simple XML. See you next time!<br /><br /><img src="" height="1" width="1" alt=""/>Ben cutscene framework for Android - part 1Not many Android games I have played have cutscenes or lots of animations. Perhaps because it is hard to make. A cutscene requires higher quality sprites or meshes which the developers may not have. Secondly, and more importantly, coding all the animations is tedious. However, cutscenes contribute to the immersion of the player, much more than a static wall of text! In this tutorial series I will show you how to create a framework to create animations for multiple objects with relative ease. Over the course of this tutorial we'll look at the building blocks for cutscenes, like animations, actors and finally we'll learn to use an XML-format to quickly describe them all.<br /><br />The code is not Android-specific and could be used for other platforms as well.<br /><br /><b>Defining what we want</b><br />Before we start coding, we have to get a better sense of what we want to achieve. For a cutscene we want a scene with multiple objects. These objects could be anything, like a bitmap (sprite) or a piece of text. We will call these objects <b>actors</b>. Each actor can be modified while playing the cutscene by an <b>animation</b>. This could be anything as well, for example: a translation, a rotation, a change of text or a visibility toggle. An animation basically mutates a property of the actor. In this part, we'll look at how to define these animations.<br /><br /><b>Gathering some tools</b><br />First we'll check if Android has some handy tools for us. It seems that from Android 3.0 on, the <a href="">Property Animation</a> is very useful and may do about the same as the framework we're going to build. However, Android 3.0 is too much of a restriction for me. I want my games to run on Android phones from 2.1 on. Their second library called <a href="">View animations</a> is only applicable to views, so that's not useful for sprites rendered in OpenGL or bitmap rendered on a canvas.<br /><br />So it seems we have to do some things ourselves. That's ok, it's not a lot of work. First we start with some tools, a class that describes a 2d vector with float values: Vector2f.<br /><br /><pre class="brush:java">import android.os.Parcel;<br />import android.os.Parcelable;<br /><br />public class Vector2f implements Parcelable {<br /> private final float x, y;<br /><br /> public Vector2f(float x, float y) {<br /> super();<br /> this.x = x;<br /> this.y = y;<br /> }<br /><br /> public Vector2f(Vector2f vec) {<br /> super();<br /> this.x = vec.x;<br /> this.y = vec.y;<br /> }<br /><br /> public Vector2f(Vector2d vec) {<br /> super();<br /> this.x = vec.getX();<br /> this.y = vec.getY();<br /> }<br /><br /> public float getX() {<br /> return x;<br /> }<br /><br /> public float getY() {<br /> return y;<br /> }<br /><br /> public Vector2f add(Vector2f vec) {<br /> return new Vector2f(x + vec.x, y + vec.y);<br /> }<br /><br /> public Vector2f sub(Vector2f vec) {<br /> return new Vector2f(x - vec.x, y - vec.y);<br /> }<br /><br /> public Vector2f scale(float f) {<br /> return new Vector2f(x * f, y * f);<br /> }<br /><br /> public float lengthSquared() {<br /> return x * x + y * y;<br /> }<br /><br /> @Override<br /> public String toString() {<br /> return "(" + x + ", " + y + ")";<br /> }<br /><br /> @Override<br /> public int hashCode() {<br /> final int prime = 31;<br /> int result = 1;<br /> result = prime * result + Float.floatToIntBits(x);<br /> result = prime * result + Float.floatToIntBits(y);<br /> return result;<br /> }<br /><br /> @Override<br /> public boolean equals(Object obj) {<br /> if (this == obj)<br /> return true;<br /> if (obj == null)<br /> return false;<br /> if (getClass() != obj.getClass())<br /> return false;<br /> Vector2f other = (Vector2f) obj;<br /> if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x))<br /> return false;<br /> if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y))<br /> return false;<br /> return true;<br /> }<br /><br /> public Vector2f(Parcel in) {<br /> x = in.readInt();<br /> y = in.readInt();<br /> }<br /><br /> @Override<br /> public int describeContents() {<br /> return 0;<br /> }<br /><br /> public static final Parcelable.Creator<Vector2f> CREATOR = new Parcelable.Creator<Vector2f>() {<br /> @Override<br /> public Vector2f createFromParcel(Parcel in) {<br /> return new Vector2f(in);<br /> }<br /><br /> @Override<br /> public Vector2f[] newArray(int size) {<br /> return new Vector2f[size];<br /> }<br /> };<br /><br /> @Override<br /> public void writeToParcel(Parcel dest, int flags) {<br /> dest.writeFloat(x);<br /> dest.writeFloat(y);<br /><br /> }<br /><br />}</pre><br />This is a thread-safe 2d vector implementation that's parcelable (useful if you want to store a vector using <a href="">onSaveInstanceState</a>). You can also see that a class Vector2d is mentioned, which is the same class only with ints instead of floats. I use Vector2d for positions in a grid.<br /><br />Next in line is defining an Animation. This will be the abstract framework on top of which all the possible animations are built. It should certainly have the start frame, the end frame and the current frame. The framerate itself is determined by the main loop of the application (a nice tutorial can be found <a href="">here</a>). The Animation classes will all transform a single variable (this can be expanded) between those two keyframes. To identify which type of variable is transformed, I use an Enum. You could also use <i>instanceof. </i><br /><br /><pre class="brush:java">public abstract class Animation {<br /> private final int startFrame;<br /> private final int endFrame;<br /> private int currentFrame;<br /> private AnimationType type;<br /> private List<AnimationChangedListener> listeners;<br /><br /> public Animation(int startFrame, int endFrame, AnimationType type) {<br /> super();<br /> this.startFrame = startFrame;<br /> this.endFrame = endFrame;<br /> this.type = type;<br /><br /> currentFrame = 0;<br /> listeners = new ArrayList<AnimationChangedListener>();<br /> }<br /><br /> public AnimationType getType() {<br /> return type;<br /> }<br /><br /> public boolean isActive() {<br /> return currentFrame >= startFrame && currentFrame <= endFrame;<br /> }<br /><br /> public void addListener(AnimationChangedListener listener) {<br /> listeners.add(listener);<br /> }<br /><br /> protected void dispatchValueChangedEvent() {<br /> for (AnimationChangedListener listener : listeners) {<br /> listener.valueChanged(this);<br /> }<br /> }<br /><br /> /**<br /> * Can be overridden. This function should be called at the end.<br /> */<br /> public void doTimeStep() {<br /> if (currentFrame <= endFrame) {<br /> currentFrame++;<br /> }<br /> }<br /><br /> public abstract Object getCurrentValue();<br />}<br /><br /></pre><br />As you can see, I use an observer pattern to notify all listeners that a variable has changed. Because the abstract base class cannot see when a variable is changed, it is up to the derived classes to call <i>dispatchValueChangedEvent()</i>. <i>AnimationChangedListener</i> is a simple interface:<br /><br /><pre class="brush:java">public interface AnimationChangedListener {<br /> void valueChanged(Animation animation);<br />}<br /></pre><br />Each time a frame is being updated, <i>doTimeStep</i> is called. Classes that extend <i>Animation</i> should do their logic there. Let's write a simple animation to see how this works in practice.<br /><br /><b>The translation animation</b><br />Image we want to translate a sprite on the screen between frames 10 and 20. The starting position is (0,0) and the final position is (100,100). This means that the velocity has to be:<br /><br /><pre class="java" name="code">dir = end.sub(start).scale(1.f / (float) (endFrame - startFrame));</pre>This is simply the distance divided by the time in frames. What's left now is to add <i>dir</i> to the variable that tracks the position if the current frame is between the start frame and end frame, or in other words: when the animation is active.<br /><br /><pre class="brush:java">public class TranslationAnimation extends Animation {<br /> private final Vector2f dir;<br /> private Vector2f current;<br /><br /> public TranslationAnimation(Vector2f start, Vector2f end, int startFrame,<br /> int endFrame) {<br /> super(startFrame, endFrame, AnimationType.POSITION);<br /><br /> current = start;<br /> dir = end.sub(start).scale(1.f / (float) (endFrame - startFrame));<br /> }<br /><br /> @Override<br /> public void doTimeStep() {<br /> if (isActive()) {<br /> current = current.add(dir);<br /> dispatchValueChangedEvent();<br /> }<br /><br /> super.doTimeStep();<br /> }<br /><br /> @Override<br /> public Object getCurrentValue() {<br /> return current;<br /> }<br />}<br /></pre><br />And there we have it. The animated variable can be retrieved by calling <i>getCurrentValue()</i>. As we can see, that function returns an <i>Object</i> and not a Vector2f. By querying the type with <i>getType()</i> we know that the variable is a Vector2f. <br /><br />Instead of polling getCurrentValue all the time, it's better to use the callback from <i>dispatchValueChangedEvent()</i>.<br /><br /><b>The text changer</b><br />A second example of a useful animation in cutscenes is one that changes text. This is easily built:<br /><br /><pre class="brush:java"><br/>public class TextAnimation extends Animation {<br/> private String text;<br/> private String newText;<br/><br/> public TextAnimation(String newText, int startFrame) {<br/> super(startFrame, startFrame, AnimationType.TEXT);<br/> this.newText = newText;<br/> text = null;<br/> }<br/><br/> @Override<br/> public void doTimeStep() {<br/> if (isActive()) {<br/> text = newText;<br/> dispatchValueChangedEvent();<br/> }<br/><br/> super.doTimeStep();<br/> }<br/><br/> @Override<br/> public Object getCurrentValue() {<br/> return text;<br/> }<br/><br/>}<br /></pre><br />This class doesn't store the original text, because that would complicate the constructor. It's no problem, because the listeners are only called when a real value is set.<br /><br /><br />We've reached the end of tutorial one. Part 2 will come soon!<img src="" height="1" width="1" alt=""/>Ben
http://feeds.feedburner.com/blogspot/ZyUsr
CC-MAIN-2017-43
refinedweb
10,593
55.34
Last week you saw Ivana talk about language processing. Most of her work focuses on the high level. Next week Peter will talk to you about complex neuron models. Today, I'm going to talk about my work at the top. We know how to: We used these components to: Now, let's try: Given a verb-noun pair from a limited vocabulary, execute the appropriate action. verbis SAYor WRITE nounis HELLOor GOODBYE NONEto indicate execute action vis_sequence = 'SAY HELLO NONE WRITE GOODBYE NONE GOODBYE SAY NONE'.split() def input_vision(t): index = init(t / 0.5) % len(sequence) return sequence[index] import nengo import nengo.spa as spa D = 64 model = spa.SPA() # See "Large-scale cognitive model design using the Nengo neural simulator" by Sughanda et al. for code # IPythonViz(model, "configs/verb_noun_follow.py.cfg") It gets more complicated with increasingly complicated behaviour. For example, the task of counting that Spaun does requires a LOT of lines of code. This also covers other models like: If you want to integrate multiple complex behaviours, which Spaun actually does, you get an unmanageable amounts of code. "If someone wants to implement a new task into Spaun requiring a new module, they're better off reimplementing Spaun entirely than trying to edit the code." - Xuan Choo, creator of Spaun That seems bad. How can fix this? Humans get better at a task if it's repeated. How can we include this in our networks? This only works for basic input-output mapping. Further research needed for motor sequence chunking and other complex tasks. You have to use approximations: Does a Voja-based associative memory match MEG and fMRI data? No. What does? I'm working on it. Ideas for projects requiring refining and discussion: StackOverflow for cognitive modelling, psychology and neuroscience, good for getting summary of literature:
https://nbviewer.jupyter.org/github/Seanny123/guest_syde556_lec/blob/master/Scaling%20SPA%20for%20complex%20behaviour.ipynb
CC-MAIN-2018-51
refinedweb
305
59.5
I have the following Table in a Vertica Database +---------+-------+ | ReadOut | Event | +---------+-------+ | 1 | A | | 1 | A | | 1 | B | | 1 | B | | 2 | A | | 2 | B | | 2 | B | +---------+-------+ +-----------+---------+---------+--+ | Frequency | Event_A | Event_B | | +-----------+---------+---------+--+ | 1 | 1 | 0 | | | 2 | 1 | 2 | | | 3 | 0 | 0 | | | 4 | 0 | 0 | | | . | 0 | 0 | | | . | 0 | 0 | | | . | 0 | 0 | | +-----------+---------+---------+--+ # get all the available event names Eventlist=SELECT DISTINCT Event FROM table # loop over each event to get the frequency for ii in Eventlist: SELECT count(Readout) FROM table WHERE Event = ii group by Readout Vertica does not have the ability to pivot. You'll need to generate the sql to pivot or just pivot in python. I would just do it in python, keep your query simple. As for getting counts per event, you can do it all at one time: with f as ( SELECT readout, event, COUNT(*) frequency FROM mytable GROUP BY 1, 2 ) select frequency, event, count(*) cnt from f group by 1, 2 order by 1, 2 Then use python to pivot and fill in the frequency gaps if you need to. (If you use pandas, pivoting is probably dead simple). Here is an example pivoting to a dict (depends on which lib you are using and settings for your connection, so you'll probably need to change it): from collections import defaultdict myresult = defaultdict(dict) for row in rows: myresult[row['frequency'][row['event']] = row['cnt'] I'm sure there is some more clever way to do it with dict comprehension but this seems straightforward. Hope it helps.
https://codedump.io/share/NPwM4BnCgiMF/1/sql-get-frequency-counter-similar-to-pivot-table
CC-MAIN-2017-43
refinedweb
249
58.15
When working with arrays, we typically use the subscript operator ([]) to index specific elements of an array: However, consider the following IntList class, which has a member variable that is an array: Because the m_list member variable is private, we can not access it directly from variable list. This means we have no way to directly get or set values in the m_list array. So how do we get or put elements into our list? Without operator overloading, the typical method would be to create access functions: While this works, it’s not particularly user friendly. Consider the following example: Are we setting element 2 to the value 3, or element 3 to the value 2? Without seeing the definition of setItem(), it’s simply not clear. You could also just return the entire list and use operator[] to access the element: While this also works, it’s syntactically odd: Overloading operator[] However, a better solution in this case is to overload the subscript operator ([]) to allow access to the elements of m_list. The subscript operator is one of the operators that must be overloaded as a member function. An overloaded operator[] function will always take one parameter: the subscript that the user places between the hard braces. In our IntList case, we expect the user to pass in an integer index, and we’ll return an integer value back as a result. Now, whenever we use the subscript operator ([]) on an object of our class, the compiler will return the corresponding element from the m_list member variable! This allows us to both get and set values of m_anList directly: This is both easy syntactically and from a comprehension standpoint. When list[2] evaluates, the compiler first checks to see if there’s an overloaded operator[] function. If so, it passes the value inside the hard braces (in this case, 2) an argument to the function. list[2] Note that although you can provide a default value for the function parameter, actually using operator[] without a subscript inside is not considered a valid syntax, so there’s no point. Why operator[] returns a reference Let’s take a closer look at how list[2] = 3 evaluates. Because the subscript operator has a higher precedence than the assignment operator, list[2] evaluates first. list[2] calls operator[], which we’ve defined to return a reference to list.m_list[2]. Because operator[] is returning a reference, it returns the actual list.m_list[2] array element. Our partially evaluated expression becomes list.m_list[2] = 3, which is a straightforward integer assignment. list[2] = 3 list.m_list[2] list.m_list[2] = 3 In the lesson a first look at variables, you learned that any value on the left hand side of an assignment statement must be an l-value (which is a variable that has an actual memory address). Because the result of operator[] can be used on the left hand side of an assignment (e.g. list[2] = 3), the return value of operator[] must be an l-value. As it turns out, references are always l-values, because you can only take a reference of variables that have memory addresses. So by returning a reference, the compiler is satisfied that we are returning an l-value. Consider what would happen if operator[] returned an integer by value instead of by reference. list[2] would call operator[], which would return the value of list.m_list[2]. For example, if m_list[2] had the value of 6, operator[] would return the value 6. list[2] = 3 would partially evaluate to 6 = 3, which makes no sense! If you try to do this, the C++ compiler will complain: 6 = 3 C:VCProjectsTest.cpp(386) : error C2106: '=' : left operand must be l-value Dealing with const objects In the above IntList example, operator[] is non-const, and we can use it as an l-value to change the state of non-const objects. However, what if our IntList object was const? In this case, we wouldn’t be able to call the non-const version of operator[] because that would allow us to potentially change the state of a const object. The good news is that we can define a non-const and a const version of operator[] separately. The non-const version will be used with non-const objects, and the const version with const-objects. If we comment out the line clist[2] = 3, the above program compiles and executes as expected. clist[2] = 3 Error checking One other advantage of overloading the subscript operator is that we can make it safer than accessing arrays directly. Normally, when accessing arrays, the subscript operator does not check whether the index is valid. For example, the compiler will not complain about the following code: However, if we know the size of our array, we can make our overloaded subscript operator check to ensure the index is within bounds: In the above example, we have used the assert() function (included in the cassert header) to make sure our index is valid. If the expression inside the assert evaluates to false (which means the user passed in an invalid index), the program will terminate with an error message, which is much better than the alternative (corrupting memory). This is probably the most common method of doing error checking of this sort. Pointers to objects and overloaded operator[] don’t mix If you try to call operator[] on a pointer to an object, C++ will assume you’re trying to index an array of objects of that type. Consider the following example: Because we can’t assign an integer to an IntList, this won’t compile. However, if assigning an integer was valid, this would compile and run, with undefined results. Rule: Make sure you’re not trying to call an overloaded operator[] on a pointer to an object. The proper syntax would be to dereference the pointer first (making sure to use parenthesis since operator[] has higher precedence than operator*), then call operator[]: This is ugly and error prone. Better yet, don’t set pointers to your objects if you don’t have to. The function parameter does not need to be an integer As mentioned above, C++ passes what the user types between the hard braces as an argument to the overloaded function. In most cases, this will be an integer value. However, this is not required -- and in fact, you can define that your overloaded operator[] take a value of any type you desire. You could define your overloaded operator[] to take a double, a std::string, or whatever else you like. As a ridiculous example, just so you can see that it works: As you would expect, this prints: Hello, world! Overloading operator[] to take a std::string parameter can be useful when writing certain kinds of classes, such as those that use words as indices. Conclusion The subscript operator is typically overloaded to provide direct access to individual elements from an array (or other similar structure) contained within a class. Because strings are often implemented as arrays of characters, operator[] is often implemented in string classes to allow the user to access a single character of the string. Quiz time 1) A map is a class that stores elements as a key-value pair. The key must be unique, and is used to access the associated pair. In this quiz, we’re going to write an application that lets us assign grades to students by name, using a simple map class. The student’s name will be the key, and the grade (as a char) will be the value. 1a) First, write a struct named StudentGrade that contains the student’s name (as a std::string) and grade (as a char). Show Solution 1b) Add a class named GradeMap that contains a std::vector of StudentGrade named m_map. Add a default constructor that does nothing. 1c) Write an overloaded operator[] for this class. This function should take a std::string parameter, and return a reference to a char. In the body of the function, first iterate through the vector to see if the student’s name already exists (you can use a for-each loop for this). If the student exists, return a reference to the grade and you’re done. Otherwise, use the std::vector::push_back() function to add a StudentGrade for this new student. When you do this, std::vector will add a copy of your StudentGrade to itself (resizing if needed). Finally, we need to return a reference to the grade for the student we just added to the std::vector. We can access the student we just added using the std::vector::back() function. The following program should run: 2) Extra credit #1: The GradeMap class and sample program we wrote is inefficient for many reasons. Describe one way that the GradeMap class could be improved. 3) Extra credit #2: Why doesn’t this program work as expected? Backwards compatibility with C sometimes could be regretting. Subscript operator is such case. In C is meant to be used with C “arrays”, and in turn those are just `pointer+offset*sizeof` syntactic sugar. Long story short, handy `operator[]` is useless when you deal with pointer to an object. Of course there is possibility to use dereference operator, or just call `operator[]` explicitly, but this is no way better than using getters/setters. Such semantical inconsistency could lead to some evil pitfalls. Consider: class Node { private: Node* m_list; public: ... Node* operator[] (const int index) { return m_list[index]; } }; and when usage: Node cMyNode; Node* pMyNode = cMyNode[2]; // ok - operator[] Node* pNoNode = pMyNode[2]; // gotcha! class Node { private: Node* m_list; public: ... Node* operator[] (const int index) { return m_list[index]; } }; Node cMyNode; Node* pMyNode = cMyNode[2]; // ok - operator[] Node* pNoNode = pMyNode[2]; // gotcha! Good point, Sergk. If you use a subscript on a pointer, the compiler will assume that you are trying to access a member of an array that the pointer is pointing to. If you want to use an overloaded subscript operator on the variable that a pointer points to, you have to dereference the pointer first. However, because the array index operator has a higher precedence than the subscript operator, you have to use parenthesis to make sure it resolves correctly: Node *pNode = new Node(); cout << (*pNode)[2]; (dereference first, then use overloaded subscript operator to get second element) what about overloading the subscript operator to… say sort and int of arrays: example: class Whatever { private: int * m_value; public: int &operator[](std::size_t index); }; I am not sure what you are saying, Jarves. You want to overload the subscript operator to do what? oh sorries :S basically what i’m trying to do here is take a dynamic array of ints (int * m_value) and use the overloaded subscript operator to sort the array from smallest integer to highest integer… and it’s kickin my ass. I would highly recommend using a function named Sort instead of overloading the subscript operator to do array sorting. It’s generally not a good idea to overload operators to do things they aren’t normally used for, simply because it’s confusing and non-intuitive. The “Why operator[] returns a reference” part was brilliant. You made a pretty difficult idea (at least to me) to seem obvious. I agree. The concept of references finally clicked when I read that. I agree guys subs script operator overloading in c++ with header file include simple and sweet program dijiye Hi, and thanks for this post. I have another question. I want to do sub-indexing too, something like: MyNewType[a][b]. anybody? 🙂 You can do this if your overloaded operator[] returns a type that can use operator[] (either a class with an overloaded operator[] or a pointer type) If you want to return an element from a two-dimensional array inside your class, you’re better off overloading operator() (covered next lesson). Hi Alex, In a case where we have 2 lists, can we still overload the [] operator? How does the overload function know which list to use when returning the reference? --rob Your operator[] function will do whatever you write in its body -- it’s just a regular member function with a funny name. So you can overload operator[] to return an element from the first list or the second list. You can also do something more complicated like: This will return an element from the first list if the index is 0-9, return an element from the second list if the index is 10-19, or throw an exception otherwise. Great explanation and yes thank you for the “why operator[] returns a reference” portion, it makes it very clear why it must be so when using array[n] as an l-value. However I am still not clear why operator[] returns a reference when used as an r-value! It seems that would be equivalent to: int x = 1; int y = 2; int array[3] = { 0, 0, 0 }; array[0] = x; // okay, per your explanation, we don't mean to write 0 = 1, rather, we mean [element at index 0] = 1 // but then what about: x = array[0]; // why does x end up holding the r-value of "0", instead of the address of the integer array element at index 0? Perhaps I need more coffee, but the reasoning here is escaping me… is it simply a matter of compiler convention that a reference used as an r-value will always be evaluated for its r-value rather than the l-value? While returning a reference isn’t strictly necessary in an r-value situation, it does prevent needless copies from being made. why can’t we overload array subscript operator as friend. why it gives error when I overload [],->,= operator as friend? The languages designers must have had a good reason for not allowing users to overload operator[] as a friend, but I don’t know what that reason is. In the example, when you; IntList cMyList; cMyList[2] = 3; How does C++ know that the 2 is assigned to nIndex? Is just built-in that when overloading `[]` the argument comes from between `[` and `]` ? Yeah, C++ passes what you type between the hard braces as an argument to the function. The code below was to overload the [] operator to accept a list of 2 elements to access an element of a 3×3 matrix. It seems to work when I uses a variable assignment for the argument ie. “Indexer” , but will not work when I try to enter the list in the form of cAmatrix[{1,1}]. Is there a way I have [] operator take either inputs and output the same result? Matrix3x3.h main.cpp Not that I know of -- I don’t think C++ has a way to declare an anonymous array. Instead of overloading operator[] for this purpose, you really should be using an overloaded operator(). It’s much more suited to indexing multidimensional arrays. Would it be possible to exploit return by pointer to a private member of a class? Since we can’t access private members directly, we don’t know what is their address. But by returning a pointer to them, this would no longer hold true. Any problems that might come with that? Yes, definitely. The internal member variable could be reallocated, leaving the address you’re holding as invalid, and you’d have no way to know. For this reason, it’s usually not a good idea to hold on to pointers or references to an internal class’s members if there’s any chance this could happen. I’m surprised no one has pointed out that it is generally best to define two such operators: This ensures that use on the rhs of an expression does not confuse the compiler into thinking that the array may change. Good call. I’ve updated the article to mention that you can define both non-const and const versions of this operator. In this are we not violating the encapsulation rule of private member, because as we are passing the reference to the original private member "m_anList[10]" i.e. in the main() we get "cMyList.m_anList[2] = 3". So we are just setting the value of the private member in the main() directly without using mutator. So this violates the rule. No, there’s no violation of encapsulation in providing direct access to a single integer via an overloaded operator[]. If we changed the underlying implementation (from an array to a tree, for example), we could still pass back an integer reference to wherever element #2 mapped to in that new structure, and the code using this class would still function without modification. Encapsulation would be violated if we provided a method that returned m_anList, because that would expose the underlying data structure. For the example with an array, I noticed you can use return by reference with a function as well, so you can do something like which does not have the clarity problem mentioned above. My question is: what is the need for overloading the [] operator then? Just having a more familiar way to work with your class? Thanks! Yup, mainly for convenience/consistency, especially for array classes. If my class has 2 arrays of some type (as member), how can I overload the subscript operator to access different elements of both arrays: And, isn’t it a good idea (for C++ 11 users, and for int arrays) to initialize the arrays with all elements set to 0 like this: First, there’s a couple ways you could do this: * Overload the [] operator so that 0 = m_array1, and 1 = m_array2. Then you can do this: myObject[0][5]; // get the 5th element of m_array1 * Overload the () operator and use two parameters, the first to select the array and the second to select the element Second, yes, it’s a good idea to initialize the arrays to zero. Yup, I tried the second one and that worked. I was just too quick to ask this question 🙂 Thanks… Can you please include an example for the first method? Thanks in advance Sorry, I’m not following what you’re asking for an example for. Can you be more specific? Can you please include an example for overloading [] with 2 or more member arrays in a class? You have mentioned the method: Overload the [] operator so that 0 = m_array1, and 1 = m_array2. Then you can do this: myObject[0][5]; // get the 5th element of m_array1. I am getting syntax errors while doing it. I think I am missing something which I am not sure, in my code. I’ll add an example when I get around to updating this article. In the meantime, make sure your overloaded operator[] is returning an array (either a pointer to a built-in array, or a reference to an array class such as std::array or std::vector). #include <iostream> #include <cassert> class Digit { private: int digit1[3]{0}; public: int& operator[](const int index); ostream& operator<<(ostream& out); }; int& Digit::operator[](const int index) { return digit1[index]; } std::ostream& Digit::operator<<(std::ostream& out) { int loop; out << "{"; for (loop = 0; loop < 3; loop++) { out << digit1[loop] << " "; } out << "}"; return out; } int main() { Digit n; n[0] = 4; n[1] = 3; n[2] = 4; n << std::cout; return 0; } In the above example, the "ostream does not have a type" error occurs only when the member variable is an array. Whereas when I add namespace it works. Is there any reason that it works only if we add std namespace for member arrays? Using Visual Studio 2015, it doesn’t compile for me either way. ostream should be std::ostream in the prototype for operator<<. Thanks, Alex. I think the line, above the class should solve the issue This link is not accessible from index page Oops, the wrong article got linked. Fixed now, thanks for letting me know. Hey, Alex. I finally have found a problem in your code. 🙂 🙂 🙂 Fixed, thanks! Hey Alex, In the comment below it should be gradeJoe is left dangling? int main() { GradeMap grades; char& gradeJoe = grades["Joe"]; gradeJoe = ‘A’; char& gradeFrank = grades["Frank"]; gradeFrank = ‘B’; std::cout << "Joe has a grade of " << gradeJoe << ‘\n’; std::cout << "Frank has a grade of " << gradeFrank << ‘\n’; return 0; } When Frank is added, the std::vector must grow to hold it. This requires dynamically allocating a new block of memory, copying the elements in the array to that new block, and deleting the old block. When this happens, any references to existing elements in the std::vector are invalidated! In other words, after we push_back(“Frank”), gradeFrank is left as a dangling reference to deleted memory. Yes, gradeJoe is dangling, not gradeFrank. I’ve updated the answer. Hey, i still didn’t get this point… why whene we add a new block the old one is deleted? the vector do not hold both value? Joe and Frank? By the way: thanx a lot for this tutorial, and sorry for my english am from Algeria Each time you overflow the capacity of a vector, it must resize itself to accommodate the new elements being added. As I noted above, this requires dynamically allocating memory, copying the old elements into the new memory, and then deleting the old memory. Because the elements are copied, the final vector will contain both Joe and Frank. Reference gradeJoe is fine when the vector contains just Joe. However, when we add Frank, the vector must allocate new memory, copy the elements, and delete the old memory. gradeJoe is still pointing to the memory that gets deleted when the vector gets resized, so it becomes a dangling reference. Later, when we try to use it, we’re accessing deleted memory, which will cause bad things to happen. Here’s a really important issue!! In this context isn’t the plural of index indices, not indexes? You’ve got to love the English language for inconsistencies both in spelling and grammar -it’s a dyslexic’s nightmare. Including where and when to use those damnable apostrophes. Yep, fixed. I mess up it’s vs its all the time, and drive my pedantic readers absolutely crazy. 🙂 why does this cause a run-time error RAIItypes.h: main.cpp: output: 2 *** Error in `/media/nyap/acb384f6-b8a7-482b-b700-4070bd5c283b/learncpp/Test/bin/Release/Test’: double free or corruption (fasttop): 0x0000000000caac40 *** Aborted I’ve stepped through it and it seems to occur in the delete statements in the destructors This doesn’t even compile for me on Visual Studio 2015. But I think I know what’s happening here. Your operators are all passed by value, not reference, meaning that they make a copy of the arguments. Beyond the performance hit from doing this, this is actually the cause of your error. So first oneeg and twoeg are created, and dynamic memory is allocated for those. These are then passed into operator+, where parameters one and two become copies of oneeg and twoeg accordingly. When operator+ is finished, the parameters are destroyed, which invokes the constructor for one and two, which deletes the memory being pointed to. This leaves oneeg and twoeg as dangling pointers. Change your parameters to const references and you should be able to avoid this. Hello Alex I can’t get over this part of quiz 1c: Why do we have to add a temporary value instead of just m_map.push_back(name).name? After all, when assigning values, grade["Joe"]=’A’, the grade ‘A’ should fill up the space, no? I tried compiling this, but it doesn’t work. For some reason, I can’t see the mechanics behind, or the reason why we have to burden the function twith creating a new, temporary variable everytime a name/grade is entered. Could you shed some light, please? m_map is a std::vector of StudentGrade, so anything we push on the vector must be a StudentGrade. Pushing on name doesn’t work, because name is a std::string, not a StudentGrade. The compiler isn’t smart enough to infer that you don’t care about the grade part in this case. Another solution would be to create StudentGrade as a class, and provide a converting constructor to convert a std::string to a StudentGrade. Then the explicit temporary wouldn’t be necessary, because the compiler could convert the std::string into a temporary StudentGrade as needed -- but the key point here is that a StudentGrade is needed somehow because that’s what the std:vector holds. I see now, thank you for the explanation. Hi Alex, I’m struggling to understand the example in "Pointers to objects and overloaded operator[] don’t mix" wouldn’t this be accessing the 2nd element in an array of IntLists and trying to set it to 3? No, array indexing starts at 0, so index 2 is the 3rd element of the array. I’ve updated the wording in the lesson slightly to make it clearer anyway. Of course, another foolish mistake on my part. Thanks for sorting it out. In the quiz, number 2, extra credit 1 "We could optimize this by keeping our m_map sorted and using a binary search, so we minimize the number of elements we have to look through to find the ones we’re interested in." May I ask what do you mean by binary search ? Found it on "7.x — Chapter 7 comprehensive quiz". Thanks a lot for such tutorials. I cover binary searching in the Chapter 7 quiz. Thanks for the great tutorial… In the quiz, can you please explain why are we doing this? [code] for (auto &ref : m_map) [code] What will this part of the code do? Thanks and Regards This iterates through all elements of m_map and assigns a reference named ref to each of them in turn. This is covered in lesson 6.12a -- For each loops. Is it possible to implement this for-each loop as simple for loop? How can we deal with termination condition and reference part? Thanks! Yes, since m_map is a vector, we could write: In this line of code: Since the function is constant, why should we still get a reference of the return value and not just the value, since int& just lets the return type also be a l_value, which a const variable will never be able to be? We don’t get a reference of the return value -- we get a const reference of the return value. Const variables can be lvalues, they just can’t be modified. For const version of [] operator overloading what’s the point in returning a reference as in your example.? To avoid making a copy (which would happen if we returned by value). Because operator[] is returning a reference, it returns the actual list.m_list[2] array element. Our partially evaluated expression becomes list.m_list[2] = 3, which is a straightforward integer assignment. Isn’t this illegal in main to initialize a private variable directly? No. You can’t access m_list directly (because of the private access control) but you can access it indirectly through a reference or pointer. Access controls are enforced at compile time, whereas references and pointers evaluate at runtime. This means you can use them to “subvert” access controls (intentionally or otherwise). Hi Alex, I hava a question about the user defined dictionary. In Python, we have __setitem__ and __getitem__ to differentiate between setter and getter. They can have different behaviours. For example: When user try to read from the dictionary, if the key is not in the dictionary, we raise an exception. When user try to assign an value to the dictionary, if the key is not in the dictionary, we create a new entry. But how can we do that in C++? Using the code above, if we try to assign a value to a new key, the code will do exactly what we want. However, if we try to read an invalid key, the map object will simply add a new entry and return a default value, which is kind of wired. How can we solve that? Thanks in advance. The problem here is that operator[] doesn’t know what we intend to do with the result it returns, so it can’t really make any assumptions about whether it should or should not create a new name. Probably the best way to resolve this would be to use explicit getGrade(name) and setGrade(name, grade) functions instead of overloading operator[]. The get function would return the grade if it found the name, otherwise it would return an appropriate error response (error value, exception, etc…). The set function would create a new name if one didn’t exist, and set the value. In the quiz section(1C), you wrote: "This class should take a std::string parameter, and return a reference to a char." Did you mean to write "function" instead of "class"? Yep. Fixed. Thanks for noticing. In one of your first code examples on this page, you have the following: Is there any reason you did not make index a reference parameter, rather than having the function copy it in? Would it not be better for performance to always make any constant parameters referenced? Name (required) Website Current ye@r * Leave this field empty
http://www.learncpp.com/cpp-tutorial/98-overloading-the-subscript-operator/
CC-MAIN-2016-44
refinedweb
4,909
61.56
The test application I used was a basic forms and reports program to manage parts of a neighborhood association's Web site. The Web site lets you list, create, and edit member records; and list, create, and edit contractors' information, including members' contractor references. I wrote the program to handle data using Microsoft Access and Microsoft SQL Server, and all database interaction was via SQL statements, specifically SELECT, INSERT, UPDATE, and DELETE. A few places in the program changed SQL statements based on which database the program used. For example, I tested for true values in a SQL Server bit field by testing for a value of 1, and I tested for true values in an Access Yes/No field by testing for a value of -1. I wrote an ASP version of this application using ADO to talk to the database and a Perl version using the Win32::ODBC module to talk to the database. Each version has a subdirectory called private that contains the administrative pages. During my testing, I attempted to create an Administrator account and restrict the private Web pages' rights to permit access to only that user. This task proved to be the most difficult test for the Web hosting services I tested. I wanted to use Windows NT's built-in security capabilities; however, most ISPs don't let you create users and restrict directories, or the ISPs require you to call support staff to make these changes for you. I might have had better luck creating a user database, building the code to manage it, and logging on users myself. (Interland was the exception because it let me create an Administrator account and set permissions easily.) The standard posting process is to FTP data to the site and post the files in a directory. This process was easy using all the services I tested. Next, I created the ODBC Data Source Name (DSN). Some services let me create the ODBC DSN on a Web page, some services required me to call customer service to create the ODBC DSN, and other services allotted me a DSN as part of my contract. To post Access databases to your Web site, FTP the database to the site. Most hosting services provide a special data or databases directory for this purpose, and their DSNs search these directories for file-based databases. You don't want these directories in Web namespace because a clever user might gain unauthorized access to parts of the site. To post SQL Server data, each vendor gave me its SQL Server system's DNS name or IP address and a login to a database on that server (the vendors usually used the same login information as the FTP account information they assigned me). I used SQL Server Enterprise Manager to import data from my local database to their database. However, three of the vendors were running SQL Server 6.5, and my SQL Server 7.0 Enterprise Manager couldn't talk to the vendors' servers. To overcome this problem, I created SQL scripts to create the tables in a database and INSERT the dummy data into the vendors' databases.
http://www.itprotoday.com/networking/test-application-and-posting-process
CC-MAIN-2017-51
refinedweb
526
59.03
As an opt in feature, it does sound quite interesting. If over the course of a few releases, it proves to be reliable and we don't get tons of support requests of it either not working, or causing the opposite problem, we can consider moving it to an opt out feature. This makes it easy for people to "turn on the magic", but keeps the default safer. It would be very easy to write a one line monkeypatch to make it default behaviour. Django is conservative when it comes to changes to default behaviour, and doubly so when the ORM is considered. This will need to have been used widely in the wild before it would be considered safe as a default behaviour for all projects. This whole process would only take a couple of years, which isn't much time in Django release land! I don't mean to undermine the belief of the people who think it's definitely an improvement in most cases, I just want us to be cautious in how we explore that hypothesis. It's also likely to require a significant patch, and need careful analysis before merging. I'd suggest it's a good candidate for a DEP to discuss the motivation for the project, and to find a shepherd from the core team (Josh? Adam?) to help it land. On 16 August 2017 at 13:48, Luke Plant <l.plant...@cantab.net> wrote: > Hi Josh, > > On 16/08/17 02:26, Josh Smeaton wrote: > > I believe we should be optimising for the **common** use case, not > expecting everyone to be experts with the ORM. > > > If I can come up with a single example where it would significantly > decrease performance (either memory usage or speed) compared to the default > (and I'm sure I can), then I would be strongly opposed to it ever being > default behaviour. > > The status quo is already one where thousands of users and sites are doing > the non-optimal thing because we're choosing to be conservative and have > users opt-in to the optimal behaviour. > > > I wouldn't say it is "optimal behaviour". It is behaviour that is an > optimization for some use cases - common ones, I'd agree - but not all. In > fact it is not even the best optimization - it performs less well in many > cases than a manual `select_related`. > > We don't know how many sites would be affected by the opposite default, > because we aren't putting people in that situation. Generating potentially > large queries (i.e. ones that return lots of results) is going to make > someone's life a lot harder, and can even crash processes (out of memory > errors), or cause massive slowdown due to insufficient memory and swapping. > I have had these kind of issues in production systems, and sometimes the > answer is to prefetch *less* - which is why things like `iterator()` exist, > because sometimes you *don't* want to load it all into memory upfront. > > A massive complaint against Django is how easy it is for users to build in > 1+N behaviour. Django is supposed to abstract the database away (so much so > that we avoid SQL related terms in our queryset methods), yet one of the > more fundamental concepts such as joins we expect users to know about and > optimise for. > > > This is far from the only place where we expect users to be conscious of > what has to go on at the database level. For example, we expect users to > use `.count()` and `.exists()` where appropriate, and not use them where > not appropriate - see > optimization/#don-t-overuse-count-and-exists > > This is an example of doing it right. We could have 'intelligently' made > `__len__()` do `count()`, but this introduces queries that the user did not > ask for, and that's hard for developers to predict. That whole section of > the docs on DB optimisation depends on the possibility of understanding > things at a DB level, and understanding how QuerySets behave, and that they > only do the queries that you ask them to do. The more magic we build in, > the harder we make life for people trying to optimize database access. > > If we have an `auto_prefetch` method that has to be called explicitly, > then we are allowing users who know less about databases to get something > that works OK for many situations. But having it on by default makes > optimization harder and adds unwelcome surprises. > > > I'd be more in favour of throwing an error on > non-select-related-foreign-key-access > than what we're currently doing which is a query for each access. > > > I have some sympathy with this, but I doubt it is somewhere we can go from > the current ORM and Django ecosystem as a default - but see below. > > > The only options users currently have of monitoring poor behaviour is: > > 1. Add logging to django.db.models > 2. Add django-debug-toolbar > 3. Investigate page slow downs > > > Here's a bunch of ways that previously tuned queries can "go bad": > > 1. A models `__str__` method is updated to include a related field > 2. A template uses a previously unused related field > 3. A report uses a previously unused related field > 4. A ModelAdmin adds a previously unused related field > > > I completely agree that visibility of this problem is a major issue, and > would really welcome work on improving this, especially in DEBUG mode. One > option might be a method that replaces lazy loads with exceptions. This > would force you to add the required `prefetch_related` or `select_related` > calls. You could have: > > .lazy_load(None) # exception on accessing any non-loaded FK objects > > .lazy_load('my_fk1', 'my_fk2') # exceptions on accessing any unloaded FK > objects apart from the named ones > > .lazy_load('__any__') # cancel the above, restore default behaviour > > This (or something like it) would be a different way to tackle the problem > - just throwing it out. You could have a Meta option to do > `.lazy_load(None)` by default for a Model. I've no idea how practical it > would be to wire this all up so that is works correctly, and with nested > objects etc. > > This would be a bit of a departure from the current ORM, especially if we > wanted to migrate to it being the default behaviour. If we are thinking > long term, we might have to move to something like this if the future is > async. Lazy-loading ORMs are not very friendly to async code, but an ORM > where you must specify a set of queries to execute up-front might be more > of a possibility. > > > I think a better question to ask is: > > - How many people have had their day/site ruined because we think > auto-prefetching is too magical? > - How many people would have their day/site ruined because we think > auto-prefetching is the better default? > > > Answer - we could guess, but we don't know, and we still have problems > both way, of different frequencies and size. In this case, I think > "explicit is better than implicit" is the wisdom to fall back on. We should > also fall back to the experience we've had with this in the past. We did > have more magical performance fixes in the past, such as the `depth` > argument to `select_related`, removed in 1.7. You now have to explicitly > name the things you want to be selected, instead of the 'easy' option which > did the wrong thing in some cases. > > > > If we were introducing a new ORM, I think the above answer would be > obvious given what we know of Django use today. > > What I'd propose: > > 1. (optional) A global setting to disable autoprefetching > > > This would almost surely interact very badly with 3rd party libraries and > apps who will all want you to set it differently. > > 2. An opt out per queryset > 3. (optional) An opt out per Meta? > 4. Logging any autoprefetches - perhaps as a warning? > > > Logging of possible improvements or auto-prefetches could be really > helpful. We should be careful to namespace the logging so that it can be > silenced easily. The biggest issue with logs/warnings is that the unhelpful > reports drown out the helpful ones, and then the whole feature becomes > useless or worse. > > Regards, > > Luke > > > More experienced Django users that do not want this behaviour are going to > know about a global setting and can opt in to the old behaviour rather > easily. Newer users that do not know about select/prefetch_related or these > settings will fall into the new behaviour by default. > > It's unreasonable to expect every user of django learn the ins and outs of > all queryset methods. I'm probably considered a django orm expert, and I > still sometimes write queries that are non-optimal or *become* non-optimal > after changes in unrelated areas. At an absolute minimum we should be > screaming and shouting when this happens. But we can also fix the issue > while complaining, and help guide users into correct behaviour. > > > On Wednesday, 16 August 2017 08:41:31 UTC+10, Anthony King wrote: >> >> Automatically prefetching is something I feel should be avoided. >> >> A common gripe I have with ORMs is they hide what's actually happening >> with the database, resulting in beginners-going-on-intermediates >> building libraries/systems that don't scale well. >> >> We have several views in a dashboard, where a relation may be accessed >> once or twice while iterating over a large python filtered queryset. >> Prefetching this relation based on the original queryset has the >> potential to add around 5 seconds to the response time (probably more, that >> table has doubled in size since I last measured it). >> >> I feel it would be better to optimise for your usecase, as apposed to try >> to prevent uncalled-for behaviour. >> >> >> >> On Aug 15, 2017 23:15, "Luke Plant" <l.pla...@cantab.net> wrote: >> >>> I agree with Marc here that the proposed optimizations are 'magical'. I >>> think when it comes to optimizations like these you simply cannot know in >>> advance whether doing extra queries is going to a be an optimization or a >>> pessimization. If I can come up with a single example where it would >>> significantly decrease performance (either memory usage or speed) compared >>> to the default (and I'm sure I can), then I would be strongly opposed to it >>> ever being default behaviour. >>> >>> Concerning implementing it as an additional QuerySet method like >>> `auto_prefetch()` - I'm not sure what I think, I feel like it could get >>> icky (i.e. increase our technical debt), due to the way it couples things >>> together. I can't imagine ever wanting to use it, though, I would always >>> prefer the manual option. >>> >>> Luke >>> >>> >>> >>> On 15/08/17 21:02, Marc Tamlyn wrote: >>> >>> Hi Gordon, >>> >>> Thanks for the suggestion. >>> >>> I'm not a fan of adding a layer that tries to be this clever. How would >>> possible prefetches be identified? What happens when an initial loop in a >>> view requires one prefetch, but a subsequent loop in a template requires >>> some other prefetch? What about nested loops resulting in nested >>> prefetches? Code like this is almost guaranteed to break unexpectedly in >>> multiple ways. Personally, I would argue that correctly setting up and >>> maintaining appropriate prefetches and selects is a necessary part of >>> working with an ORM. >>> >>> Do you know of any other ORMs which attempt similar magical >>> optimisations? How do they go about identifying the cases where it is >>> necessary? >>> >>> On 15 August 2017 at 10:44, Gordon Wrigley <gordon....@gmail.com> wrote: >>> >>>> I'd like to discuss automatic prefetching in querysets. Specifically >>>> automatically doing prefetch_related where needed without the user having >>>> to request it. >>>> >>>> For context consider these three snippets using the Question & Choice >>>> models from the tutorial >>>> <> >>>> when >>>> there are 100 questions each with 5 choices for a total of 500 choices. >>>> >>>> Default >>>> for choice in Choice.objects.all(): >>>> print(choice.question.question_text, ':', choice.choice_text) >>>> 501 db queries, fetches 500 choice rows and 500 question rows from the >>>> DB >>>> >>>> Prefetch_related >>>> for choice in Choice.objects.prefetch_related('question'): >>>> print(choice.question.question_text, ':', choice.choice_text) >>>> 2 db queries, fetches 500 choice rows and 100 question rows from the DB >>>> >>>> Select_related >>>> for choice in Choice.objects.select_related('question'): >>>> print(choice.question.question_text, ':', choice.choice_text) >>>> 1 db query, fetches 500 choice rows and 500 question rows from the DB >>>> >>>> I've included select_related for completeness, I'm not going to propose >>>> changing anything about it's use. There are places where it is the best >>>> choice and in those places it will still be up to the user to request it. I >>>> will note that anywhere select_related is optimal prefetch_related is still >>>> better than the default and leave it at that. >>>> >>>> The 'Default' example above is a classic example of the N+1 query >>>> problem, a problem that is widespread in Django apps. >>>> This pattern of queries is what new users produce because they don't >>>> know enough about the database and / or ORM to do otherwise. >>>> Experieced users will also often produce this because it's not always >>>> obvious what fields will and won't be used and subsequently what should be >>>> prefetched. >>>> Additionally that list will change over time. A small change to a >>>> template to display an extra field can result in a denial of service on >>>> your DB due to a missing prefetch. >>>> Identifying missing prefetches is fiddly, time consuming and error >>>> prone. Tools like django-perf-rec >>>> <> (which I was involved in >>>> creating) and nplusone <> exist in >>>> part to flag missing prefetches introduced by changed code. >>>> Finally libraries like Django Rest Framework and the Admin will also >>>> produce queries like this because it's very difficult for them to know what >>>> needs prefetching without being explicitly told by an experienced user. >>>> >>>> As hinted at the top I'd like to propose changing Django so the default >>>> code behaves like the prefetch_related code. >>>> Longer term I think this should be the default behaviour but obviously >>>> it needs to be proved first so for now I'd suggest a new queryset function >>>> that enables this behaviour. >>>> >>>> I have a proof of concept of this mechanism that I've used successfully >>>> in production. I'm not posting it yet because I'd like to focus on desired >>>> behavior rather than implementation details. But in summary, what it does >>>> is when accessing a missing field on a model, rather than fetching it just >>>> for that instance, it runs a prefetch_related query to fetch it for all >>>> peer instances that were fetched in the same queryset. So in the example >>>> above it prefetches all Questions in one query. >>>> >>>> This might seem like a risky thing to do but I'd argue that it really >>>> isn't. >>>> The only time this isn't superior to the default case is when you are >>>> post filtering the queryset results in Python. >>>> Even in that case it's only inferior if you started with a large number >>>> of results, filtered basically all of them and the code is structured so >>>> that the filtered ones aren't garbage collected. >>>> To cover this rare case the automatic prefetching can easily be >>>> disabled on a per queryset or per object basis. Leaving us with a rare >>>> downside that can easily be manually resolved in exchange for a significant >>>> general improvement. >>>> >>>> In practice this thing is almost magical to work with. Unless you >>>> already have extensive and tightly maintained prefetches everywhere you get >>>> an immediate boost to virtually everything that touches the database, often >>>> knocking orders of magnitude off page load times. >>>> >>>> If an agreement can be reached on pursuing this then I'm happy to put >>>> in the work to productize the proof of concept. >>>> >>>> -- >>>>/d402bf30-a5af-4072-8b50-85e921f7f9af% >>>> 40googlegroups/CAMwjO1Gaha-K7KkefJkiS3LRdXvaPPwBeuKmh >>> Qv6bJFx3dty3w%40mail.gmail/a5780df6-ce60-05ae-88e3-997e6bc88f/2f0b5932-1a38-4eaf-84aa- > 13960a303141%40googlegroups.com > <> > . >/9d359e4d-59d6-ff81-8ca6-db3bcd36ac.
https://www.mail-archive.com/django-developers@googlegroups.com/msg49324.html
CC-MAIN-2019-26
refinedweb
2,634
60.65
Package org.slf4j.agent Class AgentOptions - java.lang.Object - org.slf4j.agent.AgentOptions public class AgentOptions extends Object All recognized options in the string passed to the java agent. For "java -javaagent:foo.jar=OPTIONS HelloWorld" this would be "OPTIONS". It is considered to be a list of options separated by (currently) ";", on the form "option=value". The interpretation of "value" is specific to each option. Field Detail IGNORE public static final String IGNOREList of class prefixes to ignore when instrumenting. Note: Classes loaded before the agent cannot be instrumented. - See Also: - Constant Field Values LEVEL public static final String LEVELIndicate the SLF4J level that should be used by the logging statements added by the agent. Default is "info". - See Also: - Constant Field Values TIME public static final String TIMEIndicate that the agent should print out "new java.util.Date()" at the time the option was processed and at shutdown time (using the shutdown hook). - See Also: - Constant Field Values VERBOSE public static final String VERBOSEIndicate that the agent should log actions to System.err, like adding logging to methods, etc. - See Also: - Constant Field Values Constructor Detail AgentOptions public AgentOptions()
https://www.slf4j.org/api/org/slf4j/agent/AgentOptions.html
CC-MAIN-2019-39
refinedweb
191
51.04
#include <openvrml/rendering_context.h> The members could be arguments to the node::render method; but there may be many arguments and adding an argument requires changing nearly every file in the core. node::rendershould be cheap. Secondly, while adding a new member to this class is less work than adding a new argument to every node::rendercall, it still requires a recompile of nearly the whole core. That's because pass-by-value needs to know the exact size of what's being passed. Thirdly, you can't subclass this class. It's concrete. If you pass a subclass it will just get truncated. Why do it this way? Because it makes writing the node::render method easier. We don't have to maintain a stack of states, we just use the call stack instead. That means no heap allocation and deallocation, which is very cool. Also, we don't have to pop the stack at the end of the method. Alternatively, I could have used the "initialization is resource acquisition" pattern, but I felt this was cleaner. Constructs an empty render context. An empty context should not be passed to VrmlNode::render. This constructor is useful only for debugging and experimentation. Returns a reference to the modelview matrix. Sets the modelview matrix. A rendering_context retains a pointer to the passed matrix; it does not make a copy. All memory management is up to the caller. In practice, the passed-in array will generally be a local variable in the node::render method. The current modelview matrix. Track the results of intersecting node bounds with the view volume. Setting to bounding_volume::inside means that all the last tested bounding volume was completely inside the view volume, so all the contained bounding volumes must also be inside and we can skip further testing. bounding_volume::partial means that the last test indicated that the bounding volume intersected the view volume, so some of the children may be visible and we must continue testing. bounding_volume::outside means the last test indicated the bounding volume was completely outside the view volume. However, there's normally no reason to call set with bounding_volume::outside, since the render method returns immediately. But who knows; it might be useful some day, so it's an allowed value. Setting the cull flag to bounding_volume::inside in the browser at the top of the traversal has the effect of disabling the culling tests. The behavior is undefined if the flag is not one of the allowed values. openvrml::bounding_volume Draw the bounding volumes or not. If true, then the renderer may draw the bounding volumes for each primitive. Or maybe not, so you shouldn't depend on this behavior. It does look kinda cool though.
http://openvrml.org/doc/classopenvrml_1_1rendering__context.html
CC-MAIN-2017-30
refinedweb
456
66.74
using namespace std;so they wouldn't have to type the fully qualified name for anything included in headers. To prevent naming conflicts, though, some people don't use it and type in an std:: before everything in headers without the .h extension. My question was, is it worth the lack of having to type so much to get the potential naming conflicts? std::copyin your code, they know you're referring to the C++ standard algorithm and not boost::copyor some company::team::project::copy()function you've pulled in from some obscure header file. Granted, it doesn't really promise that: the only certain way is to write ::std::copy, but almost nobody goes that far. using namespace x;. While obnoxious, it is possible to import a specific symbol of your choosing to take precedence over any existing symbol: using namespace x; stdor CORBAwhere many different implementations exist; and these implementations may (in practice often do) .
http://www.cplusplus.com/forum/general/72248/
CC-MAIN-2014-52
refinedweb
158
50.46
We are in the design phase for product. The idea is that the code will read a list of values from Excel into SQL. The requirements are as follows: Workbook may be accessed by multiple users outside of our program Workbook must remain accessible (i.e. not be corrupted) should something bad occur while our program is running Program will be executed when no users are in the file Right now we are considering using pandas in a simple manner as follows: import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile df = pd.read_excel('File.xlsx', sheetname='Sheet1') """Some code to write df in to SQL""" If this code goes offline with the Excel still open, is there ANY possibility that the file will remain locked somewhere in my program or be corrupted? To clarify, we envision something catastrophic like the server crashing or losing power. Searched around but couldn’t find a similar question, please redirect me if necessary. I also read through Pandas read_excel documentation here: With the code you provide, from my reading of the pandas and xlrd code, the given file will only be opened in read mode. That should mean, to the best of my knowledge, that there is no more risk in what you’re doing than in reading the file any other way – and you have to read it to use it, after all. If this doesn’t sufficiently reassure you, you could minimize the time the file is open and, more importantly, not expose your file to external code, by handing pandas a BytesIO object instead of a path: import io import pandas as pd data = io.BytesIO(open('File.xlsx', 'rb').read()) df = pd.read_excel(data, sheetname='Sheet1') # etc This way your file will only be open for the time it takes to read it into memory, and pandas and xlrd will only be working with a copy of the data. Tags: excel, file, pandas, pythonpython
https://exceptionshub.com/python-possibility-of-corruption-reading-excel-files-with-pandas.html
CC-MAIN-2021-10
refinedweb
328
55.58
Windows Subsystem for Linux (WSL) lets you run software designed for Linux. This gives Windows users access to tools and web developers environments closer resembling that of their peers or the webservers hosting their code. Getting Started First make sure Windows is updated, WSL required additional setup steps prior to version 2004. Then run open PowerShell (as Admin) and run wsl --list --online. This will list all the available OS's for WSL. shell PS C:\Users\user> wsl --list --onlineThe following is a list of valid distributions that can be installed.Install using 'wsl --install -d <Distro>'.NAME FRIENDLY NAMEUbuntu UbuntuDebian Debian GNU/Linuxkali-Linux Kali Linux RollingopenSUSE-42 openSUSE Leap 42SLES-12 SUSE Linux Enterprise Server v12Ubuntu-16.04 Ubuntu 16.04 LTSUbuntu-18.04 Ubuntu 18.04 LTSUbuntu-20.04 Ubuntu 20.04 LTS Installing Pick your favorite flavor, mine is Ubuntu or Debian if I think I might need any older tools. Then run wsl --install -d <Distro>. shell PS C:\Users\user> wsl --install -d UbuntuDownloading: Ubuntu After a while you will see this prompt. Enter a user name that you want to use for the Linux environment and password twice. Installing, this may take a few minutes...Please create a default UNIX user account. The username does not need to match your Windows username.For more information visit: new UNIX username: userNew password:Retype new password: If all goes well you should land in a Linux prompt like this. passwd: password updated successfullyInstallation successful!...user@MACHINE_NAME:~$ Setup Run sudo apt update to refresh all your apt-get repos. shell user@MACHINE_NAME:~$ sudo apt update[sudo] password for user:Get:1 focal InRelease [265 kB]...Get:45 focal-backports/multiverse amd64 c-n-f Metadata [116 B]Fetched 22.0 MB in 7s (2985 kB/s)Reading package lists... DoneBuilding dependency treeReading state information... Done243 packages can be upgraded. Run 'apt list --upgradable' to see them. Then all your favorite tools. shell user@MACHINE_NAME:~$ sudo apt install build-essential git cmakeReading package lists... DoneBuilding dependency treeReading state information... DoneThe following additional packages will be installed:...Do you want to continue? [Y/n] Y...user@MACHINE_NAME:~$ Note: If you are looking to get into C or C++ development build-essentialis a good package to remember to get compilers Visual Studio Code Integration You can use your regular Windows installation of Visual Studio Code to interact directly with the Linux environment. Install the Remote Development extension pack or just Remote - WSL. Then you can use the Remote Explorer to browse WSL Targets (WSL OS's you've installed). All the projects and files are in and commands run in the Linux environment. Note: The Remote Developmentextension pack also includes Remote - SSHwhich allows you to interact with remote Linux environments exactly the same way To test it out we can throw a hello.cpp in there. cpp #include <iostream>int main(){std::cout << "Hello World!\n";return 0;}
https://unicorn-utterances.com/posts/windows-subsystem-for-linux
CC-MAIN-2022-33
refinedweb
490
51.65
Writing mocha tests with style - OOP style: import { suite, test, slow, timeout } from "mocha-typescript";@suite class Hello {@test world() {assert.equal(1, 2, "Expected one to equal two.");}} The test UI will register a suite with tests for the @suite and @test decorators. When the tests run, the class will be instantiated once for each @test method and the method will be called. - Summary - Setting Up - IDEs - Test UI API - Extending Test Behavior - Dependency Injection SummarySummary Test UITest UI The test interface provides support for mocha's built-in tdd, bdd: describe/suite, it/test, timeout, slow, it.only and it.skip; as well as TypeScript decorators based test UI for classes. You can mix and match: import { suite, test, slow, timeout } from "mocha-typescript";suite("one", () => {test("test", () => {});});@suite class Two {@test method() {}} Similarly you can use describe/it: import { suite, test, slow, timeout } from "mocha-typescript";describe("one", () => {it("test", () => {});});@suite class Two {@test method() {}} Or even mix the two approaches to get nested suites: import { suite, test, slow, timeout } from "mocha-typescript";describe("suite one", () => {it("test one", () => {});@suite class TestTwo {@test method() {}}}); WatcherWatcher The mocha-typescript comes with a watcher script that runs the TypeScript compiler in watch mode, and upon successful compilations runs the mocha tests, concatenating the output of both. This in combination with the support for "only": @suite class One {@test.only method1() {}@test method2() {}} Allows for rapid development of both new functionality and unit tests. Please note, the built in mocha watcher should work with mocha-typescript UI and the awesome-typescript-loader. Thanks toThanks to - Haringat for the async support in before and after methods. - godart for taking the extra step to support non-default test file paths. Setting UpSetting Up Adding Mocha-TypeScript to Existing ProjectAdding Mocha-TypeScript to Existing Project If you already have an npm package with mocha testing integrated just install mocha-typescript: npm i mocha-typescript --save-dev Then require the mocha-typescript in your test files and you will be good to go: import { suite, test, slow, timeout } from "mocha-typescript";@suite class Two {@test method() {}} Setting up New Project With Custom UISetting up New Project With Custom UI mocha-typescript-seedmocha-typescript-seed Fork the mocha-typescript-seed repo, or clone it: git clone Don't forget to edit the package.json, and check the license. From that point on, you could: npm i npm test npm run watch Manual StepsManual Steps Create a folder, cd in the folder, npm init, npm install: npm init npm install mocha typescript mocha-typescript @types/mocha chai @types/chai source-map-support nyc --save-dev Edit the package.json and set the scripts section to: "scripts": { "pretest": "tsc", "test": "nyc mocha", "watch": "mocha-typescript-watch", "prepare": "tsc" }, You may omit the nyc tool and have "test": "mocha" instead, nyc is the instanbul code coverage reporting tool. Add a tsconfig.json file with settings similar to: { "compilerOptions": { "target": "es6", "module": "commonjs", "sourceMap": true, "experimentalDecorators": true, "lib": [ "es6" ] } } Create test folder and add test/mocha.opts file. --ui mocha-typescript --require source-map-support/register test/test.js - Sets the mocha-typescript as custom ui - Optionally require the source-map-support/register to have typescript stack traces for Errors - Optionally provide test files list, point to specific dist fodler, or skip this to use mocha's defaults Add your first test file test/test.ts: // Reference mocha-typescript's global definitions: /// <reference path="../node_modules/mocha-typescript/globals.d.ts" /> @suite(timeout(3000), slow(1000)) class Hello { @test world() { } } From that point on, you could either: npm test npm run watch To run the tests once manually or run all tests. Keep in mind you can use add .only to run a single test. Setting Up Dev Test WatcherSetting Up Dev Test Watcher There is a watcher script in the package, that runs tsc -w process and watches its output for successful compilation, upon compilation runs a mocha process. You will need a tsconfig.json, and at least test.ts mocha entrypoint. Install mocha, typescript and mocha-typescript as dev dependencies (required): npm install mocha typescript mocha-typescript --save-dev Add the following npm script to package.json: "scripts":, And run the typescript mocha watcher from the terminal using npm run dev-test-watch. You can use the watcher with plain describe, it functions. The decorator based interface is not required for use with the watcher. The mocha-typescript-watch script is designed as a command line tool. You can provide the arguments in the package.json's script. In case you are not using the default test.js file as entrypoint for mocha, you can list the test suite files as arguments to mocha-typescript-watch and they will be passed to mocha. For example: "scripts":, For complete list with check ./node_modules/.bin/mocha-typescript-watch --help: Options: -p, --project Path to tsconfig file or directory containing tsconfig, passed to `tsc -p <value>`. [string] [default: "."] -t, --tsc Path to executable tsc, by default points to typescript installed as dev dependency. Set to 'tsc' for global tsc installation. [string] [default: "./node_modules/typescript/bin/tsc"] -o, --opts Path to mocha.opts file containing additional mocha configuration. [string] [default: "./test/mocha.opts"] -m, --mocha Path to executable mocha, by default points to mocha installed as dev dependency. [string] [default: "./node_modules/mocha/bin/_mocha"] -g, --grep Passed down to mocha: only run tests matching <pattern>[string] -f, --fgrep Passed down to mocha: only run tests containing <string> [string] -h, --help Show help [boolean] IDEsIDEs WebStormWebStorm JetBrain's stellar WebStorm now (since WebStorm 2017.3 EAP) supports the mocha-typescript mocha UI. Featuring: - Test Explorer - Detects tests in the TypeScript using static analysis. - Test Runner - WebStorm has a Mocha test runner that can be configured to also do a TypeScript compilation before test run. - Code Editor Integration - In the TypeScript code editor, tests are prefixed with an icon, that lets you: - Run a specific test or suite - Debug a specific test or suite The mocha-typescript-seed has been preconfigured (see the .idea folder in the repo) with UnitTests task that will run all mocha tests with the mocha-typescript UI. The UnitTests is configured to run mocha, with TypeScript compilation before launch, use the mocha-typescript mocha UI, as well as include tests in the test folder recursively. TrickyTricky The WebStorm has its own way to define tasks so the configuration for the project is duplicated at few places. Here are some side-effects it would be good for you to be aware of. Should running/debugging a single test/unit from the TypeScript code editor fail due missing ts-node, consider installing npm i ts-node --save-dev to your repo. WebStorm is using ts-node to transpile the file you are testing. This may omit proper type checking or using settings in your tsconfg, but that would rarely be an issue. Should running/debugging a single test/unit run the test twice, that's because WebStorm provides the file you are editing to mocha as .ts file, but mocha also reads the test/mocha.opts where additional files may be specified. You can either: - Nevermind running the test twice - Edit the automatically generated single test config from the top tasks menu in WebStorm and change the file extension it points to from .ts to .js, this will use the JavaScript files produced by the TypeScript compilation of your project. But you will have to change the extension by hand each time you debug or run a single test. - Change the test/mocha.opts file so it won't reference any files (e.g. delete the --recursive testfrom it). In that case you may need to fix the package.json build scripts. At few occasions when misxing BDD and the mocha-typescript decorators based UI, trying to run a single BDD test would cause WebStorm to generate a mocha task that would run using BDD ui, instead of mocha-typescript. In these cases the tests may fail as there is no suite or test functions defined in the BDD UI. To fix this you may edit the default Mocha task, and configure it to use mocha-typescript UI explicitly. From that point on, when you try to run a single test, event BDD one, WebStorm will create Mocha tasks that will use the mocha-typescript UI. Test UI APITest UI API Please note that the methods and decorators used below are introduced through importing from the mocha-typescript module: import { suite, test, slow, timeout } from "mocha-typescript"; Or by installing mocha-typescript as custom mocha test UI. Declarative Suites and TestsDeclarative Suites and Tests Declaring suites is done using the @suite decorator and tests within the suite using the @test decorator: @suite class Suite {@test test1() {}} When used without parameters, the names are infered from the class and method name. Complex names can be provided as arguments to the @suite or @test decorator: @suite("A suite")class Suite {@test("can have tests") {}@test "typescript also supports this syntax for method naming"() {}} Test InheritanceTest Inheritance One can declare abstract classes as bases for derived test classes. Tests methods declared in these base classes will be run in the context of the concrete test class, namely the one that has been decorated with the @suite decorator: export abstract class AbstractTestBase {public static before() {// ...}public before() {// ...}@test aTestFromBase() {// ...}@test "another test from base"() {// ...}public after () {// ...}public static after () {// ...}}@suite class ConcreteTest extends AbstractTestBase {public static before() {// AbstractTestBase.before();// ...}public before() {// super.before();// ...}@test aTestFromConcrete() {// ...}public after() {// ...// super.after();}public static after() {// ...// AbstractTestBase.after();}} Note: You can override test methods inherited from a base class and then call super() in order to run the assertions implemented by the super class. Best practice: You must not inherit from other classes that have been decorated with the suite decorator. Doing so will result in an exception. Use abstract base classes instead. Overriding TestsOverriding Tests Sometimes you might want to override tests inherited from a given base class. You can do this by redeclaring the same test method in your sub class, e.g. export abstract class AbstractTestBase {@test 'test that will be overridden by sub classes'() {chai.assert.fail('sub classes must override this');}}export class ConcreteTest extends AbstractTestBase {@test 'test that will be overridden by sub classes'() {chai.assertTrue(somethingTruthy);}} You may now either implement the test or simply just skip it. Given that skip actually marks the test as pending, this might not be what you want for your test reports. In that case, you could just override the test with an empty body. Which, of course, is considered to be a bad practice, yet sometimes it will become a necessity when testing class hierarchies. So the best practice is to actually provide an assertion for that test. Inheritance and Both Synchronous and Asynchronous Before and After ActionsInheritance and Both Synchronous and Asynchronous Before and After Actions As for both static and instance before() and after() actions, one must make sure that the hooks from the parent class are called, see the above example on how. When using asynchronous actions, additional care must be taken, since one cannot simply pass the done callback to the parent classes' hooks and you will have to use something along the line of this in order to make it happen: export abstract class AbstractTestBase {public static before(done) {// ...// done([err]);}public before(done) {// ...// done([err]);}}@suite class ConcreteTest extends AbstractTestBase {public static before(done) {AbstractTestBase.before((err) => {if (err) {done(err);return;}// ...// done([err]);});}public before(done) {super.before((err) => {if (err) {done(err);return;}// ...// done([err]);});}} With after() actions the patterns are similar yet a bit more involved. Note that similar patterns apply when using Promises or async and await. Important: One must not mix chained calls to both asynchronous and synchronous before and after actions. If a base class defines either action to be asynchronous then you will have to make your action asynchronous as well. See Before and After Actions and Async Tests, Before and After Actions for more information. Generated Suites and TestsGenerated Suites and Tests Mocha's simple interface is very flexible when tests have to be dynamically generated. If tests for classes have to be generated dynamically here is an example: [{ title: 'google', url: '' },{ title: 'github', url: '' }].forEach(({title, url}) => {@suite(`Http ${title}`) class GeneratedTestClass {@test login() {}@test logout() {}}}); Before and After ActionsBefore and After Actions By default, before and after test actions are implemented with instance and static before and after methods. The static before and after methods are invoked before the suite and after the suite, the instance before and after methods are invoked before and after each test method. @suite class Suite {static before() { /* 1 */ }before() { /* 2, 5 */ }@test one() { /* 3 */ }@test one() { /* 6 */ }after() { /* 4, 7 */ }static after() { /* 8 */ }} Async Tests, Before and After ActionsAsync Tests, Before and After Actions The methods that accept a done callback or return a Promise are considered async similar and their execution is similar to the one in mocha. - For done, calling it without params marks the test as passed, calling it with arguments fails the test. - For returned Promise, the test passes is the promise is resolved, the test fails if the promise is rejected. @suite class Suite {@test async1(done) {setTimeout(done, 1000);}@test async2() {return new Promise((resolve, reject) => setTimeout(resolve, 1000));}@test async async3() {// async/await FTW!await something();}} Skipped and Only Suite and TestsSkipped and Only Suite and Tests Marking a test as pending or marking it as the only one to execute declaratively is done using @suite.skip, @suite.only, @test.skip or @test.only similar to the mocha interfaces: @suite.only class SuiteOne {@test thisWillRun() {}@test.skip thisWillNotRun() {}}@suite class SuiteTwo {@test thisWillNotRun() {}} The signatures for the skip and only are the same as the suite and test counterpart so you can switch between @suite.only(args) and @suite(args) with ease. If running in watch mode it may be common to focus a particular test file in your favourite IDE (VSCode, vim, whatever), and mark the suite or the tests you are currently developing with only so that the mocha-typescript watcher would trigger just the tests you are focused on. When you are ready, remove the only to have the watcher execute all tests again. Timing - Timeout, SlowTiming - Timeout, Slow Controlling the time limits, similar to the it("test", function() { this.slow(ms); /* ... */ }); is done using suite or test traits, these are modifiers passed as arguments to the @suite() and @test() decorators: @suite(slow(1000), timeout(2000))class Suite {@test first() {}@test(slow(2000), timeout(4000)) second() {}} The slow and timeout traits were initially working as decorators (e.g. @suite @timeout(200) class Test {}), but this behavior may be dropped in future major versions as it generates too much decorators that clutter the syntax. They are still useful though for setting timeouts on before and after methods (e.g. @suite class Test { @timeout(100) before() { /* ... */ }}). RetriesRetries I would not recommend retrying failed tests multiple times to ensure green light but I also wouldn't judge, here it goes mocha-typescript retries: @suite(retries(2))class Suite {static tries1 = 0;static tries2 = 0;@test first() {assert.isAbove(Suite.tries1++, 2);}@test(retries(5)) second() {assert.isAbove(Suite.tries1++, 3);}} The retries can also be used as a decorator similar to timeout and slow - @test @retries(3) testMethod() {}. Extending Test BehaviorExtending Test Behavior Accessing the Mocha Context Within Class MethodsAccessing the Mocha Context Within Class Methods There are various aspects of the suites and tests that can be altered via the mocha context. Within the default mocha 'BDD' style this is done through the callback's this object. That object is exposed to the TypeScript decorators based UI through a field decorated with the @context decorator: @suite class MyClass {@context mocha; // Set for instenace methods such as tests and before/afterstatic @context mocha; // Set for static methods such as static before/after (mocha bdd beforeEach/afterEach)after() {this.mocha.currentTest.state;}} Skipping Tests In Suite After First Failure - skipOnErrorSkipping Tests In Suite After First Failure - skipOnError In functional testing it is sometimes fine to skip the rest of the suite when one of the tests fail. Consider the case of a web site tests where the login test fail and subsequent tests that depend on the login will hardly pass. This can be done with the skipOnError suite trait: @suite(skipOnError)class StockSequence {@test step1() {}@test step2() { throw new Error("Failed"); }@test step3() { /* will be skipped */ }@test step4() { /* will be skipped */ }} Dependency InjectionDependency Injection Custom dependency injection systems can be provided using registerDI. typeditypedi To use the built-in support: - Set your tsconfig.jsonto emitDecoratorMetadata. - Import mocha-typescript/di/typedi. This will let test instances to be instantiated using typedi, for example: import { assert } from "chai";import { Service } from "typedi";import "../../di/typedi";import { register, suite, test } from "../../index";@Service()class Add {public do(a: number, b: number) {return a + b;}}@suite class TypeDITest {// typedi will resolve `add` here to an instance of the `Add` service.constructor(public add: Add) { }@test public "test linear function"() {assert.equal(this.add.do(1, 2), 3);}}
https://www.npmjs.com/package/mocha-typescript
CC-MAIN-2022-21
refinedweb
2,867
61.06
Overview - Intro - What is AIML? - Create Standard Startup File - Creating an AIML File - Random Responses - Use Existing AIML Files - Install Python AIML Module - Simplest Python Program - Speeding up Brain Load - Reloading AIML While Running - Adding Python Commands - Sessions and Predicates - Additional References UPDATE: There is now a DevDungeon chat bot project for Discord built with Python 3 and AIML. Check out the Chatty Cathy project page for more information, screenshots and source code or jump straight on to the DevDungeon Discord to chat with Chatty Cathy. Also available on GitHub at Intro Artificial intelligence chat bots are easy to write in Python with the AIML package. AIML stands for Artificial Intelligence Markup Language, but it is just simple XML. These code examples will walk you through how to create your own artificial intelligence chat bot using Python. What is AIML? AIML was developed by Richard Wallace. He made a bot called A.L.I.C.E. (Artificial Linguistics Internet Computer Entity) which won several artificial intelligence awards. Interestingly, one of the Turing tests to look for artificial intelligence is to have a human chat with a bot through a text interface for several minutes and see if they thought it was a human. AIML is a form of XML that defines rules for matching patterns and determining responses. For a full AIML primer, check out Alice Bot's AIML Primer. You can also learn more about AIML and what it is capable of on the AIML Wikipedia page. We will create the AIML files first and then use Python to give it some life. Create Standard Startup File It is standard to create a startup file called std-startup.xml as the main entry point for loading AIML files. In this case we will create a basic file that matches one pattern and takes one action. We want to match the pattern load aiml b, and have it load our aiml brain in response. We will create the basic_chat.aiml file in a minute. <aiml version="1.0.1" encoding="UTF-8"> <!-- std-startup.xml --> <!-- Category is an atomic AIML unit --> <category> <!-- Pattern to match in user input --> <!-- If user enters "LOAD AIML B" --> <pattern>LOAD AIML B</pattern> <!-- Template is the response to the pattern --> <!-- This learn an aiml file --> <template> <learn>basic_chat.aiml</learn> <!-- You can add more aiml files here --> <!--<learn>more_aiml.aiml</learn>--> </template> </category> </aiml> Creating an AIML File Above we created the AIML file that only handles one pattern, load aiml b. When we enter that command to the bot, it will try to load basic_chat.aiml. It won't work unless we actually create it. Here is what you can put inside basic_chat.aiml. We will match two basic patterns and respond. <aiml version="1.0.1" encoding="UTF-8"> <!-- basic_chat.aiml --> <category> <pattern>HELLO</pattern> <template> Well, hello! </template> </category> <category> <pattern>WHAT ARE YOU</pattern> <template> I'm a bot, silly! </template> </category> </aiml> Random Responses You can also add random responses like this. This one will respond randomly when it receives a message that starts with "One time I ". The * is a wildcard that matches anything. <category> <pattern>ONE TIME I *</pattern> <template> <random> <li>Go on.</li> <li>How old are you?</li> <li>Be more specific.</li> <li>I did not know that.</li> <li>Are you telling the truth?</li> <li>I don't know what that means.</li> <li>Try to tell me that another way.</li> <li>Are you talking about an animal, vegetable or mineral?</li> <li>What is it?</li> </random> </template> </category> Use Existing AIML Files It can be fun to write your own AIML files, but it can be a lot of work. I think it needs around 10,000 patterns before it starts to feel realistic. Fortunately, the ALICE foundation provides a number of AIML files for free. Browse the AIML files on the Alice Bot website. There was one floating around before called std-65-percent.xml that contained the most common 65% of phrases. There is also one that lets you play BlackJack with the bot. Install Python AIML Module So far, everything has been AIML XML files. All of that is important and will make up the brain of the bot, but it's just information right now. The bot needs to come to life. You could use any language to implement the AIML specification, but some nice person has already done that in Python. Python 2 Install the aiml package first with pip or download from. pip install aiml Python 3 For Python 3, the source code remains exactly the same. You still import the package as aiml but when installing it with pip you use the name python-aiml. The source code is available at. bot recognizes. The patterns recognized depend on what AIML files you loaded. We create the startup file as a separate entity so that we can add more aiml files to the bot later without having to modify any of the programs source code. We can just add more files to learn in the startup xml file. import aiml # Create the kernel and learn AIML files kernel = aiml.Kernel() kernel.learn("std-startup.xml") kernel.respond("load aiml b") # Press CTRL-C to break this loop while True: print kernel.respond(raw_input("Enter your message >> ")) Speeding up Brain Load When you start to have a lot of AIML files, it can take a long time to learn. This is where brain files come in. After the bot learns all the AIML files it can save its brain directly to a file which will drastically speed up load times on subsequent runs. import aiml import os kernel = aiml.Kernel() if os.path.isfile("bot_brain.brn"): kernel.bootstrap(brainFile = "bot_brain.brn") else: kernel.bootstrap(learnFiles = "std-startup.xml", commands = "load aiml b") kernel.saveBrain("bot_brain.brn") # kernel now ready for use while True: print kernel.respond(raw_input("Enter your message >> ")) Reloading AIML While Running You can send the load message to the bot while it is running and it will reload the AIML files. Keep in mind that if you are using the brain method as it is written above, reloading it on the fly will not save the new changes to the brain. You will either need to delete the brain file so it rebuilds on the next startup, or you will need to modify the code so that it saves the brain at some point after reloading. See the next section on creating Python commands for the bot to do that. load aiml b Adding Python Commands If you want to give your bot some special commands that run Python functions, then you should capture the input message to the bot and process it before sending it to kernel.respond(). In the example above we are getting user input from raw_input. We could get our input from anywhere though. Perhaps a TCP socket, or a voice-to-text source. Process the message before it goes through AIML. You may want to skip the AIML processing on certain messages. while True: message = raw_input("Enter your message to the bot: ") if message == "quit": exit() elif message == "save": kernel.saveBrain("bot_brain.brn") else: bot_response = kernel.respond(message) # Do something with bot_response Sessions and Predicates By specifying a session, the AIML can tailor different conversations to different people. For example, if one person tells the bot their name is Alice, and the other person tells the bot their name is Bob, the bot can differentiate the people. To specify which session you are using you pass it as a second parameter to respond(). sessionId = 12345 kernel.respond(raw_input(">>>"), sessionId) This is good for having personalized conversations with each client. You will have to generate your own session Id some how and track them. Note that saving the brain file does not save all the session values. sessionId = 12345 # Get session info as dictionary. Contains the input # and output history as well as any predicates known sessionData = kernel.getSessionData(sessionId) # Each session ID needs to be a unique value # The predicate name is the name of something/someone # that the bot knows about in your session with the bot # The bot might know you as "Billy" and that your "dog" is named "Brandy" kernel.setPredicate("dog", "Brandy", sessionId) clients_dogs_name = kernel.getPredicate("dog", sessionId) kernel.setBotPredicate("hometown", "127.0.0.1") bot_hometown = kernel.getBotPredicate("hometown") In the AIML we can set predicates using the set response in template. <aiml version="1.0.1" encoding="UTF-8"> <category> <pattern>MY DOGS NAME IS *</pattern> <template> That is interesting that you have a dog named <set name="dog"><star/></set> </template> </category> <category> <pattern>WHAT IS MY DOGS NAME</pattern> <template> Your dog's name is <get name="dog"/>. </template> </category> </aiml> With the AIML above you could tell the bot: My dogs name is Max And the bot will respond with That is interesting that you have a dog named Max And if you ask the bot: What is my dogs name? The bot will respond: Your dog's name is Max.
https://www.devdungeon.com/content/ai-chat-bot-python-aiml
CC-MAIN-2021-04
refinedweb
1,524
66.23
I've been doing more and more web development with Tornado recently. It's got an awesome class for running client HTTP calls in your integration tests. To run a normal GET it looks something like this: from tornado.testing import AsyncHTTPTestCase class ApplicationTestCase(AsyncHTTPTestCase): def get_app(self): return app.Application(database_name='test', xsrf_cookies=False) def test_homepage(self): url = '/' self.http_client.fetch(self.get_url(url), self.stop) response = self.wait() self.assertTrue('Click here to login' in response.body) Now, to run a POST request you can use the same client. It looks something like this: def test_post_entry(self): url = '/entries' data = dict(comment='Test comment') from urllib import urlencode self.http_client.fetch(self.get_url(url), self.stop, method="POST", data=urlencode(data)) response = self.wait() self.assertEqual(response.code, 302) That's fine but it gets a bit verbose after a while. So instead I've added this little cute mixin class: from urllib import urlencode class HTTPClientMixin(object): def get(self, url, data=None, headers=None): if data is not None: if isinstance(data, dict): data = urlencode(data) if '?' in url: url += '&%s' % data else: url += '?%s' % data return self._fetch(url, 'GET', headers=headers) def post(self, url, data, headers=None): if data is not None: if isinstance(data, dict): data = urlencode(data) return self._fetch(url, 'POST', data, headers) def _fetch(self, url, method, data=None, headers=None): self.http_client.fetch(self.get_url(url), self.stop, method=method, body=data, headers=headers) return self.wait() Now you can easily write some brief and neat tests: class ApplicationTestCase(AsyncHTTPTestCase, HTTPClientMixin): def get_app(self): return app.Application(database_name='test', xsrf_cookies=False) def test_homepage(self): response = self.get('/') self.assertTrue('Click here to login' in response.body) def test_post_entry(self): # rendering the homepage creates a user and sets a cookie response = self.get('/') user_id_cookie = re.findall('user_id=([\w\|]+);', response.headers['Set-Cookie'])[0] cookie = 'user_id=%s;' % user_id_cookie import base64 guid = base64.b64decode(user_id_cookie.split('|')[0]) self.assertEqual(db.users.User.find( {'_id':ObjectId(user_id_cookie)}).count(), 1) data = dict(comment='Test comment') response = self.post('/entries', data, headers={'Cookie': cookie}) self.assertEqual(response.code, 302) self.assertTrue('/thanks' in response.headers['Location']) So far it's just a neat wrapper to save me some typing and it makes the actual tests look a lot neater. I haven't tested this in anger yet and there might be several interesting corner cases surrounding headers and POST data and what not. Hopefully people can chip in and share ideas on this snippet and perhaps I can fork this into Tornado's core Follow @peterbe on Twitter Ey! Thank you very much for this post! It helped me. But I found a bug and an improvement :D The bug: In the method "test_post_entry" you say "data=urlencode(data)", but it should be "body=urlencode(data)". That is exactly what I was looking for and I realize thanks to the other examples. And the improvement: I do not know if it is a new feature, but you have a "fetch" method in your AsyncHTTPTestCase class, so you can simplify your classes if: 1.- Your HTTPClientMixin inherits from AsyncHTTPTestCase. Maybe the name of your class has no sense any more if you do this :D 2.- from your methods "get" and "post" you call directly to the fetch method: "self.fetch(url, method='POST', body=data, headers=headers)". Indeed, maybe it is not necessary your HTTPClientMixin class any more (or can be simplified even more). Maybe you finally forked the Tornado's core?
https://api.minimalcss.app/plog/tricks-asynchttpclient-tornado
CC-MAIN-2019-43
refinedweb
588
51.55
On Tue, 05 Nov 2013, Wouter Verhelst wrote: > Well, I did ask for the creation of port-specific tags back at > debconf8 (if I'm not mistaken), but you told me to go for usertags > instead ;-) Sounds familiar. Usertags have the advantage of not requiring me to do any work. But presumably at the time I hadn't thought of the difficulties of coordinating all of the different usertags between porters. > Yes, I think that's a good idea; it would avoid issues where > maintainers are waiting on porters and vice versa, since the > reassigning of a bug to a port pseudopackage would make it clear who's > waiting for whom. Additionally, it would allow porters to have a todo > list of things that need to be done for their port but aren't specific > to any one package (or of which the root cause hasn't been found yet, > e.g., "recently compiled binaries segfault, but we don't know why > yet") > > If you're going down this road, I would appreciate it if ports listed on > debian-ports.org would also be getting pseudopackages. Since they would all be under the same ports.debian.org (or similar) namespace, I wouldn't have a problem with it. [My main concern about pseudopackages is polluting the package namespace; since I can't imagine anyone ever wanting to create a package called someport.ports.debian.org for a sane reason, that shouldn't be a big deal.] It would also be possible (in the meantime) for bugs to be assigned to both the port-specific pseudopackage, and the original package which spawned the bug. In any event, if a few active porters wouldn't mind creating a wishlist bug against bugs.debian.org for this with a suggested course of action, I'd appreciate it. Assuming there is no significant disagreement about that course of action, I'd like to implement it within a week or so. -- Don Armstrong PowerPoint is symptomatic of a certain type of bureaucratic environment: one typified by interminable presentations with lots of fussy little bullet-points and flashy dissolves and soundtracks masked into the background, to try to convince the audience that the goon behind the computer has something significant to say. -- Charles Stross _The Jennifer Morgue_ p33
https://lists.debian.org/debian-hppa/2013/11/msg00023.html
CC-MAIN-2019-43
refinedweb
382
58.72
This tutorial was done on a Mac running macOS Mojave 10.14.5. Source code for this tutorial can be found at: Source code for this tutorial can be found at: Support for dependency injection in Azure Functions was announced at Build 2019. This opens up new opportunities for building better architected C# applications with Serverless Azure Functions. In this tutorial I will demonstrate how to build a Web API application using Azure Functions. The application we will build together will use Entity Framework Core Migrations and Dependency Injection. We will use the light-weight VS Code editor for Mac. You need to install the Azure Functions extension for Visual Studio Code before proceeding with this tutorial. Once the extension is installed, you will find it among your extensions. Also, install Azure Functions Core Tools with the following npm command: sudo npm i -g azure-functions-core-tools --unsafe-perm true Create a folder on your hard drive for the location where your project will reside. Under the Functions tab, select your Azure subscription. You will then be able to create a new Azure Functions project. Choose the location on your hard drive that you had previously designated as yourworkspace folder for this project. You will next be asked to select a programming language. Choose C#. You will be asked to choose a template for your project's first function. Note that you can have more than one function in your project. Choose HttpTrigger. Hit Enter after you give your function a name. Give your class a namespace. The namespace I used is Snoopy.Function. I then hit Enter. Choose Anonymous for AccessRights then hit Enter. If a popup window appears asking if you wish to restore unresolved dependencies, click the Restore button. Let us see what the app does. Hit CTRL F5 on the keyboard. The built-in VS Code terminal window will eventually display a URL that uses port number 7071: Copy and paste the URL into a browser or hit Command Click on the URL. You will see the following output in your in the root directory of your application: dotnet add package Microsoft.Azure.Functions.Extensions dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.Design dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools dotnet add package Microsoft.Extensions.Http Let us make a few minor enhancements to our application. 1) Add a simple Student.cs class file to your project with the following content: namespace Snoopy.Function { public class Student { public string StudentId { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] public string School { get; set; } } } 2) Change the signature of the HttpWebAPI class so that it does not have the static keywor. Therefore, the signature of the class will look like this: public class HttpWebAPI 3) Add an Entity Framework DbContext class. In our case, we will add a class file named SchoolDbContext.cs with the following content: namespace Snoopy.Function {" } ); } } } 4) To register a service like SchoolDbContext, create a class file named Startup.cs that implements FunctionStartup. This class will look like this: [assembly: FunctionsStartup(typeof(Snoopy.Function.Startup))] namespace Snoopy.Function { public class Startup : FunctionsStartup { public override void Configure(IFunctionsHostBuilder builder) { var connStr = Environment.GetEnvironmentVariable("CSTRING"); builder.Services.AddDbContext<SchoolDbContext>( option => option.UseSqlServer(connStr)); builder.Services.AddHttpClient(); } } } 5) Inject the objects that are needed by your function class. Open HttpWebAPI.cs in the editor and add the following instance variables and constructor at the top of the class: private readonly HttpClient _client; private readonly SchoolDbContext _context; public HttpWebApi(IHttpClientFactory httpClientFactory, SchoolDbContext context) { _client = httpClientFactory.CreateClient(); _context = context; } 6) We want to use the design-time DbContext creation. Since we are not using ASP.NET directly here, but implementing the Azure Functions Configure() method, Entity Framework will not automatically discover the desired DbContext. Therefore, we need to implement an IDesignTimeDbContextFactory to drive the tooling. Create a C# class file named SchoolContextFactory.cs and add to it the following content: namespace Snoopy.Function {); } } } 7)="cp "$(TargetDir)bin\$(ProjectName).dll" "$(TargetDir)$(ProjectName).dll"" /></Target> 8) The EF utility used by .NET Core 3.x had changed. We want to make sure that we are using .NET Core 2.2. Therefore, add the following global.json file in the root of your application so that we specify the SDK version: { "sdk": { "version": "2.2.300" } } "sdk": { "version": "2.2.300" } } 9) Go ahead and create a SQL Database Server in Azure. Copy the connection string into a plain text editor (like TextEdit) so that you can later use it to set an environment variable in your Mac's environment: export CSTRING="Server=tcp:XXXX.database.windows.net,1433;Initial Catalog=SchoolDB;Persist Security Info=False;User ID=YYYY;Password=ZZZZ;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Where: XXXX is the name of your SQL Azure database server YYYY is your database username ZZZZ is your database password Note: I called the database StudentsDB. You can call it whatever you like. 10) The next step is to apply Entity Framework migrations. Open a terminal window in the root of your application. Paste the environment variable setting that you saved in a text editor in the previous step into the terminal window. Thereafter, execute the following command inside the same terminal window: dotnet build dotnet ef migrations add m1 This produces a Migrations folder in your project. using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations; namespace FunctionsWeb[,] { { "4ceab280-96ba-4c2a-911b-5af687a641a4", "Jane", "Smith", "Medicine" }, { "8ebb5891-b7ca-48f8-bd74-88de7513c6d0", "John", "Fisher", "Engineering" }, { "4f00688f-1c03-4255-bcb0-025b9221c0d7", "Pamela", "Baker", "Food Science" }, { "e5dd769d-55d1-49a0-9f79-d8ae3cf9c474", "Peter", "Taylor", "Mining" } }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Students"); } } } 11) The next step is to create the database and tables. Execute the following command in the same terminal window as above: dotnet ef database update If all goes well, you will receive a message that looks like this: Applying migration '20190626012048_m1'. Done. 12) Let us now create an endpoint in our Azure function that returns all the students as an API. Add the following method to the Azure functions file named HttpWebApi. Before we can run the application, we need to set the CSTRING environment variable in the application's local environment. This is done by adding the CSTRING environment variable to the local.settings.json file as shown below: { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "CSTRING": "Server=tcp:XXXX.database.windows.net,1433;Initial Catalog=SchoolDB;Persist Security Info=False;User ID=YYYY;Password=ZZZZ;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" } } Run the application by hitting CTRL F5 on the keyboard. You will see the following output in a VS Code terminal window: Copy the students URL (I.E.) and paste it into a browser. Alternatively, you can simply hit Command Click on the link. The result will look like this: Conclusion It is easy to create Azure Functions with the very flexible VS Code editor. Also, creating an API with Azure Functions is much more cheaper than doing it with an ASP.NET Core Web application because you pay a fraction of a cent for every request and the app does not need to be constantly running.
http://blog.medhat.ca/2019/06/
CC-MAIN-2020-10
refinedweb
1,210
50.02
<xsl:strip/preserve-space> - Functionality - Identifying strippable whitespace nodes - Determining which nodes to strip - Stripping nodes - Filtering whitespace nodes Functionality The Both elements take one attribute "elements" which contains a whitespace separated list of named nodes which should be or preserved stripped from the source document. These names can be on one of these three formats (NameTest format): - All whitespace nodes: elements="*" - All whitespace nodes with a namespace: elements="<namespace>:*" - Specific whitespace nodes: elements="<qname>" Identifying strippable whitespace nodes. Determining which nodes to strip: - the element name of the parent of the text node is in the set of elements listed in <xsl:preserve-space> - the text node contains at least one non-whitespace character - an ancenstor of the whitespace text node has an attribute of xsl:space="preserve", and no close ancestor has and attribute of: - stylesheet A imports stylesheets B and C in that order; - stylesheet B imports stylesheet D; - stylesheet C imports stylesheet E. Then the order of import precedence (lowest first) is D, B, E, C, A. Our next consideration is the priority of NameTests (XPath spec): elements="<qname>"has priority 0 elements="<namespace>:*"has priority -0.25 elements="*"has priority -0.5 Stripping nodes: - The translet can, prior to starting to traverse the DOM, send a reference to the tables containing information on which nodes we want stripped to the DOM interface. The DOM interface is then responsible for hiding all stripped whitespace nodes from the iterators and the translet. A problem with this approach is that we want to omit the DOM interface layer if the translet is only accessing a single DOM. The DOM interface layer will only be instanciated by the translet if the stylesheet contained a call to the document()function. - The translet can provide its iterators with information on which nodes it does not want to see. The translet is still shielded from unwanted whitespace nodes, but it has the hassle of passing extra information over to most iterators it ever instanciates. Note that all iterators do not need be aware of whitepspace nodes in this case. If you have a look at the figure again you will see that only the first level iterator (that is the one closest to the DOM or DOM interface) will have to strip off whitespace nodes. But, there may be several iterators that operate directly on the DOM ( invoked by code handling XSL functions such as count()) and every single one of those will need to be told which whitespace nodes the translet does not want to see. - The third approach will take advantage of the fact that not all translets will want to strip whitespace nodes. The most effective way of removing unwanted whitespace nodes is to do it once and for all, before the actual traversal of the DOM starts. This can be done by making a clone of the DOM with exlusive-access rights for this translet only. We still gain performance from the cache because we do not have to pay the cost of the delay caused by downloading and parsing the XML source file. The cost we have to pay is the time needed for the actual cloning and the extra memory we use. Normally one would imagine the translet (or the wrapper class that invokes the translet) calls the DOM cache with just an URL and receives a reference to an instanciated DOM. The cache will either have built this DOM on-demand or just passed back a reference to an existing tree. In this case the DOM would need an extra call that a translet would use to clone a DOM, passing the existing DOM reference to the cache and recieving a new reference to the cloned DOM. The translet can then do whatever it wants with this DOM (the cache need not even keep a reference to this tree).. Filtering whitespace nodes: - the namespace (can be the default namespace) - the element name or " *" - the type of rule; NS:EL, NS: *or * - the priority of the rule (based on import precedence and type) - the action; either strip or preserver.
http://xalan.apache.org/xalan-j/xsltc/xsl_whitespace_design.html
CC-MAIN-2018-34
refinedweb
683
53.04
There seems to be a Name Resolution issue. Datanode denied communication with namenode: DatanodeRegistration(0.0.0.0, storageID=DS-30209445-192.168.2.41-50010-1371109358645, infoPort=50075, ipcPort=50020, Here DataNode is identifying itself as 0.0.0.0. Looks like dfs.hosts enforcement. Can you recheck on your NameNode's hdfs-site.xml configs that you are surely not using a dfs.hosts file? This error may arise if the datanode that is trying to connect to the namenode is either listed in the file defined by dfs.hosts.exclude or that dfs.hosts is used and that datanode is not listed within that file. Make sure the datanode is not listed in excludes, and if you are using dfs.hosts, add it to the includes. Restart hadoop after that and run hadoop dfsadmin -refreshNodes. HTH It really comes down to a personal preference. The product level is the ultimate final artifact most of the time. As you discovered, it has much better tooling integration. When the product is assembled by Tycho or PDE Build you'll know exactly what's in it and what needs to be started for it in order to work properly. However, sometimes it doesn't feel right to go down to the bundle granularity level in product definitions especially when it's composed of features only. But defining start properties at the feature level or even at the bundle level can be tricky, though. For example, when someone consumes your features/bundles in another product they might have different auto-start/start-level requirements. FWIW, the p2.inf file isn't outdated at all. It's the raw bare metal to modify/op There is indeed something strange going on with the setting of auto-complete-mode. (I'm using the ELPA version in a GNU Emacs 24.3.1) This is set up by customize-group RET auto-complete : '(ac-auto-show-menu t) '(ac-auto-start t) At this point if you M-x auto-complete-mode you get a [no match] right in the minibuffer. Only after you try to M-x auto-complete, yelding a "auto-complete-mode is not enabled" weird error, will you be able to M-x auto-complete-mode (but without command completion... Hm) and then be in the mode. If you put this in your init file (.emacs) (require 'auto-complete) (auto-complete-mode t) It will be effective only if you re-eval it after startup (?!?). The same with something like (if (auto-complete) (auto-complete-mode t)) The only way that I found You could create a chatlog directive and add it to your markup like this: <div chatlog Then in the linking function of your directive you can do something like: link: function(scope, element, attrs) { if (scope.$last) { // this will run each time the channel.msgLog array changes // more precisely, every time the last element is linked } } I don't believe you can log the activities to the event log, but what you can do is use the -xml parameter to output the changes in XML format. You could then use this to log to the event log via a Powershell script, for example. Safe_mode is a PHP feature that has been depreciated in 5.3 and ultimately removed in 5.4. It is pointless and potentially dangerous and should not be used. To turn it off go to your php.ini file and change safe_mode = on to safe_mode = off Restart apache and you should be good to"> < Ok, i just had a similar problem. Ninject didn't register when I ran the application on my local IIS (7.5), in IIS Express however, it worked fine. The problem was that I had batch="false" in my compilation node in web.config. Setting batch to true (which is the default) solved the problem. My suggestion will be to use the method onPause of the activity in application A and set a flag there "application B was called". Then if this flag is set do not call application B in onCreate of the activity in Application A and unset the flag. If application B is too long in the foreground application A might be suspended by the system and the flag will be reset. In such case maybe it is good idea to have the flag stored in some persistent storage (e.g. SharedPreferences). EDIT One more thing: the flag should be set in onPause only if the activity is being paused, because the other application will be shown (this will be easily determinable, because everything happens in the same class). There is no priority in AppFabric Auto Start feature. You can't assume that one service will always be started before the others. Also, you can't assume they will start all at the same time. For the specific scenario, it's recommanded to use WCF 4.0 Discovery and Announcement. Announcement feature enables service to announce their availability (by sending Hello and Bye announcements) whereas Discovery feature allow clients to discover service address at runtime. All your services are on the same server ? could be pertinent to use a namedPipeBinding. () i have struggled a lot in this issue. I did everything i could to keep my services alive in IIS but eventually got tired and had to take different approach. I created a windows service just to keep those app pool alive. One approach you can try is go to IIS config file and verify that you can see the configuration you made is reflected in that config file. Refer to the link on top. But your configuration will be reset on app pool restart whatever time you set it to go to sleep. You might need to comeup with some approach. Try to give your Carousel an id and try this $('#myCarousel').carousel({ // For Carousel Image Slider interval: 6000, cycle: true, }).trigger('slid'); myCarousel = id of carousel To start your service on BOOT_COMPLETED event and to receive SMS intent continuously. AndroidManifest.xml: <receiver android: <intent-filter> <action android: </intent-filter> </receiver> BootReceiver.java: public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent service = new Intent(context, SMSService.class); context.startService(service); } } SMSService.java: public class SMSService extends IntentService { @Override protected void onHandleIntent(Intent intent) { String action = intent.getAction(); if (Intent.BOOT_COMPLETED.equals(action)) { The simplest way is to add java -jar YourJarFile.jar in /etc/rc.d/rc.local Note: Commands in the above file are run at startup (as root). Note that if you do this, your command will NOT respond to the usual service start/ stop commands. In the application server Run/Debug configuration open the Logs tab and specify the full log file path there. You can just search your disk for algo_js.log file and specify its location. I was having a similar problem using normal QT4.x on linux. The issue was that something was connected to the clicked signal. I think it was stealing/changing the focus of the mouse. I just changed that item to connect to the the released signal. That doesn't mean you can't connect to clicked, but just be sure that there are no focus stealing side-effects. I think you are taking the hard way out there is a much easier way of implementing what you are trying to do in ASP.net. First it would require the use of jQuery UI (date-picker). I came up with a pure JavaScript and HTML5 solution to your problem. I think you are going a bit over board with the post back of the data just so you can get the date out of it. Note: I am not doing any validation nor have I made this specific towards your application. Here is my solution: CSS style, just to make things okay looking ;) <!-- link to the jQuery UI CSS --> <link href="" /> <style> #employee_form { width: 350px; background: #f0e68c; padding: .2em; } li { list-style: no'm guessing this is on a debian server? If not, this may not be the solution... but we ran into this on our Ubuntu based installations. This is happening because of the combination of the installed PHP package and the cron scripts that are running to take care of the session cleanup. (for whatever reason... not sure why they're doing that...) We were successful by doing the following things: - removing the cron job to clear out the PHP session stuff (trust me, its there - its annoying) - chmod www-data:www-data /var/lib/php5 (or equivalent info) - session.gc_probability = 1 in your php.ini file May not be the best solution, but it took care of it for me. solved it with the help of this question: jQuery - Dialog auto-resize on dynamic content and maintain center position ajaxStop is called whenever ajax finishes loading, so I'm resizing the dialog when ajaxStop is called and it's works perfectly! $(document).ajaxStop(function(){ $(".dialog").dialog({height:"auto",width:"auto"}); }); Yes. The same reason if you only ever read an argument you make the parameter const&. T // I'm copying this T& // I'm modifying this const T& // I'm reading this Those are your "defaults". When T is a fundamental type (built-in), though, you generally just revert to const T (no reference) for reading, because a copy is cheaper than aliasing. I have a program that I'm developing in which I'm considering making this change throughout, since efficiency is critical in it Don't make blind sweeping changes. A working program is better than a fast but broken program. How you iterate through your loops probably won't make much of a difference; you're looping for a reason, aren't you? The body of your loop will much more likely be the culprit. If efficiency is Does it need to change when content is visible? If not try this: you could do an update in the viewWillAppear method. For each label, call [firstLabel setNumberOfLines:0]; [firstLabel setText:newProductTitleText]; [firstLabel sizeToFit]; Setting number of lines to 0 lets the label dynamically use an many lines as it needs. If this is an empty label that should actually become 0 lines. This will update the frames and autolayout should take care of the rest. From your question, it seems your using multiple markers and you want to set zoom level. If so my suggestion is to take a look at fitBounds(). fitBounds() method adjusts the map's viewport in order to view the passed LatLngBounds in full at the centre of the map. auto is used to deduce one type from an expression. Using your suggested syntax would not help because exactly one type can be stored in a container. If you need a way to store any type in the container, take a loop at boost::any, so you can use std::array<boost::any, 5> myArray; This example forces both horizontal and vertical alignment of an image inside a box; in this specific case, constrained to 130x130px. Change the width and height defined as 130px in 2 separate places each in the css to change the constrained size. [edit: added simplified example showing minimum required setup] Simplified example: html: <div class="pic"> <img src="/path/to/pic.jpg"/> </div> css: .pic { display: inline-block; width: 130px; height: 130px; outline: solid 1px #cccce3; font-size: 0; text-align: center; } .pic:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; } .pic img { max-width: 130px; max-height: 130px; display: inline-block; vertical-align: middle; } Compl If what you are looking for is a service that indexes your raw data into autocomplete then you could make use of hosted ElasticSearch services like qbox.io, searchify.com, Found.no and more You need to index your data first into the elastic search and then query for auto-completion. A detailed explanation on how to achieve that is explained in this rackspace blog and searchify. Excerpt from the rackspace developer blog: Auto-complete (e.g. the slick functionality you see when you begin typing in the search box at the top of your Facebook feed) is an extremely popular feature in applications these days. While a wildcard query in a typical data store like MySQL or MongoDB performs adequately with thousands of records, producing near-instant response times with millions or ev This sounds like something you'll have to script. If you save as much as I do (a lot), then you'll end up with a lot of commits. Unless you're careful about when you save, you'll probably end up with a messy history, unless you squash things later. Are you sure that you want to commit and push automatically every time you save? It also matters whether or not you're pushing to your own private branch or repo. You could do something like this: namespace autohide { public partial class Form1 : Form { public int pin = 0; public Form1() { InitializeComponent(); panel1.Visible = false; } void ChangeIconPin() { switch (pin) { case 0: //Changes the pin-icon to display a unpinned frame. this.button_Pin.BackgroundImage = autohidefixv2.Properties.Resources._55_roto; break; case 1: //Changes the pin-icon to display a pinned frame. this.button_Pin.BackgroundImage = autohidefixv2.Properties.Resources._55_2; break; default: You can use gq operator for autoformatting, but I cannot say how good the result will be: this function is used mainly for formatting text: in Behavior can be adjusted using 'formatexpr' or 'formatprg', you can use the latter if you know good formatter program. The socket is the "file" that nginx and unicorn use as a channel for all communication between them. Where have you defined it? In our unicorn configs, we usually have a line like this: listen APP_PATH + "/tmp/pid/.unicorn.sock Then, in your nginx.conf, you need to tell nginx about this socket, e.g.: upstream unicorn { server unix:/var/www/demo/tmp/pid/.unicorn.sock fail_timeout=0; } location / { root /var/www/demo/current/public ; try_files $uri @unicorns; } location @unicorns { proxy_pass; } In this config file, the first section defines how nginx can reach unicorn. The second one actually routes requests to an abstract location "@unicorns" which, in turn, is defined in the last section. This way you can reuse the @unicorns shorthand if your have more compl I think my topic will provide a response to you, even if not perfect. You may also check FelixDroid which is using a different approach seen on other projects. However, I long for a better solution. Going to see if I can find or write a ContextWrapper that will fill the bill. Full Android support for OSGi bundles (Knopflerfish) When working with mouse primitives, there is no way to know if a mouse-down is part of a click, a double-click, or a drag until a subsequent event is fired. A mouse-down followed by a mouse-move is a drag (if the move is greater than some threshold, to allow for human motion while clicking) A mouse-down followed by a mouse-up is a click if the time span is too great to be a double-click. A mouse-down is a double-click if the down/up/down/up falls withing the double-click threshold. The difference between a drag and a rect-select is based (usually) on whether or not an object is present under the mouse position when the down is fired. How to read parameters in a batch file: caller batch start "" "%dirofbatch%data1.exe" "%downloc%" "%dirofbatch%" "%lver%" "%lget%" called batch set "parm1=%~1" set "parm2=%~2" set "parm3=%~3" set "parm4=%~4" echo %parm1% %parm2% %parm3% %parm4% You can call refresh and all bundles will be restarted that had package wirings to the old API bundle. You can call refresh on the console or programmatically FrameworkWiring.refreshBundles(...) For more information you can check the javadoc of the mentioned function. You can replace your textview by a Chronometer view, set his format using setFormat("HH:MM) and call to start() function when the activity is brought to front. Reference <!DOCTYPE html> <html> <body bgcolor="#2E9AFE"> <marquee style="background-color: #2E9AFE; bottom: 0; color: #ffffff; height: 100%; position: absolute; text-align: center;" scrollamount="2" direction="up" loop="true"> <strong>I AM HERE<br/>Vx.0<br/><br/>DEVELOPER<br/>xxxxxx<br/><br/><br/>CONTACT US<br/>xxxxxx</strong> </marquee> </body> </html> Please note, to my knowledge this is not valid HTML. To validate, check out. Also, there were two body tags (instead of one) and some other HTML that wasn't properly formatted, most of which I tried to address. If you're not yet familiar with CSS, just know that it's your friend. (In other words, you'd probably be You can use shortcut when call the chrome.exe instead using full path location. Module Module1 Sub Main() System.Diagnostics.Process.Start("chrome.exe", "--incognito") End Sub End Module More: start-google-chrome-from-run-windows-key-r UPDATE I found what is your problem in your code. Your code using –-incognito in the parameter, but it should be --incognito. See the first character in that parameter. Should be - instead –. Module Module1 Sub Main() System.Diagnostics.Process.Start("C:Program Files (x86)GoogleChromeApplicationchrome.exe", "--incognito") End Sub End Module Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles fb_button.Click Dim fb_button As String = Nothing For Each element As HtmlElement In WebBrowser1.Document.All If InStr(element.Id, "u_0_b") Then fb_button = element.Id End If WebBrowser1.Document.GetElementById("email").SetAttribute("value", TextBox1.Text) WebBrowser1.Document.GetElementById("pass").SetAttribute("value", TextBox2.Text) WebBrowser1.Document.GetElementById(fb_button).InvokeMember("click") End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load WebBrowser1.Navigate("") End Sub In the intent your are sending to TabExercise, you can send the tabindex you want to load, and then call setCurrentTab (int index). Did you try something like this?
http://www.w3hello.com/questions/Any-logs-for-AWS-RDS-auto-start-
CC-MAIN-2018-17
refinedweb
2,997
64.91
). The included scaffolds are these: starter - URL mapping via URL dispatch and no persistence mechanism. zodb - URL mapping via traversal and persistence via ZODB. Note that, as of this writing, this scaffold will not run under Python 3, only under Python 2. alchemy - URL mapping via URL dispatch and persistence via SQLAlchemy Creating the Project¶ In Installing Pyramid, you created a virtual Python environment via the virtualenv command. To start a Pyramid project, use the pcreate command installed within the virtualenv. We’ll choose the starter scaffold for this purpose. When we invoke pcreate, it will create a directory that represents our project. In Installing Pyramid we called the virtualenv directory env; the following commands assume that our current working directory is the env directory. On UNIX: $ bin/pcreate -s starter MyProject Or on Windows: > Scripts\pcreate -s starter MyProject The above command uses the pcreate command to create a project with the starter scaffold. To use a different scaffold, such as alchemy, you’d just change the -s argument value. For example, on UNIX: $ bin/pcreate -s alchemy MyProject Or on Windows: > Scripts\pcreate -s alchemy MyProject Here’s sample output from a run of pcreate on UNIX for a project we name MyProject: $ bin/pcreate -s starter MyProject Creating template pyramid Creating directory ./MyProject # ... more output ... Running /Users/chrism/projects/pyramid/bin/python setup.py egg_info As a result of invoking the pcreate command, a directory named MyProject is created. That directory is a package which holds very simple: $ cd MyProject $ ../bin/python setup.py develop Or on Windows: > cd MyProject > ..\Scripts\python.exe setup.py develop Elided output from a run of this command on UNIX is shown below: $ cd MyProject $ ../bin/python setup.py develop ... Finished processing dependencies for MyProject==0.0 This will install a distribution representing your project into the interpreter’s library set so it can be found by import statements and by other console scripts such as pserve, pshell, proutes and pviews. Running The Tests For Your Application¶ To run unit tests for your application, you should invoke them using the Python interpreter from the virtualenv you created during Installing Pyramid (the python command that lives in the bin directory of your virtualenv). On UNIX: $ ../bin/python setup.py test -q Or on Windows: > ..\Scripts\python.exe setup.py test -q Here’s sample output from a test run on UNIX: $ ... Running The Project Application¶ Once a project is installed for development, you can run the application it represents using the pserve command against the generated configuration file. In our case, this file is named development.ini. On UNIX: $ ../bin/pserve development.ini On Windows: > ..\Scripts\pserve development.ini Here’s sample output from a run of pserve on UNIX: $ ../bin/pserve development.ini Starting server in PID 16601. serving on 0.0.0.0:6543 view at By default, Pyramid applications generated from a scaffold will listen on TCP port 6543. You can shut down a server started this way by pressing Ctrl-C. The default server used to run your Pyramid application when a project is created from a scaffold is named Startup. For more information about environment variables and configuration file settings that influence startup and runtime behavior, see Environment Variables and .ini File Settings. Reloading Code¶ Pyramid application is not put into effect until the server restarts. For example, on UNIX: $ ../bin/pserve development.ini --reload Starting subprocess with file monitor Starting server in PID 16601. serving on Now if you make a change to any of your project’s .py files or .ini files, you’ll see the server restart automatically:. Viewing the Application¶ Once your application is running via pserve, you may visit in your browser. You will see something in your browser like what is displayed in the following image: This is the page shown by default when you visit an unmodified pcreate generated starter application in a browser. The Debug Toolbar¶ If you click on the image shown at the right hand top of the page (“^DT”), you’ll be presented with a debug toolbar that provides various niceties while you’re developing. This image will float above every HTML page served by Pyramid while you develop an application, and allows you show the toolbar as necessary. Click on Hide to hide the toolbar and show the image again. : the hash mark anywhere except the first column instead, for example like this: When you attempt to restart the application with a section like the abvoe you’ll receive an error that ends something like this, and the application will not start: ImportError: No module named #pyramid_debugtoolbar The Project Structure¶ The starter scaffold generated a project (named MyProject), which contains a Python package. The package is also named myproject, but it’s lowercased; the scaffold generates a project which contains a package that shares its name except for case. All Pyramid pcreate -generated projects share a similar structure. The MyProject project we’ve generated has the following directory structure: MyProject/ |-- CHANGES.txt |-- development.ini |-- MANIFEST.in |-- myproject | |-- __init__serve,. Note, Chameleon and Mako will be shown on the right hand side). This means that any remote system which has TCP access to your system can see your Pyramid application. The sections that live between the markers # Begin logging configuration and # End logging configuration represent Python’s standard library logging module configuration for your application. The sections between these two markers. and The Hitchhiker’s Guide to Packaging., when adding Python package dependencies, install and use your application. entry point for commands such as pserve, pshell, pviews, and others. -. Lines 3-10 define a function named mainthat returns a Pyramid WSGI application. This function is meant to be called by the PasteDeploy framework as a result of running pserve. Within this function, application configuration is performed. Line 6 creates an instance of a Configurator. Line 7 registers a static view, which will serve up the files from the myproject:staticasset specification (the staticdirectory of the myprojectpackage). Line 8 adds a route to the configuration. This route is later used by a view in the viewsmodule. Line 9 calls config.scan(), which picks up view registrations declared elsewhere in the package (in this case, in the views.pymodule). Line 10 3 a asset specification that specifies the mytemplate.pt file within the templates directory of the myproject package. The asset specification could have also been specified as myproject:templates/mytemplate.pt; the leading package name and colon is optional. The template file it actually points to is a Chameleon ZPT template file. ( templates/my_template.pt). See Writing View Callables Which Use a Renderer for more information about how views, renderers, and templates relate and cooperate. Note Because our development.ini has a pyramid pyramid.reload_templates to false to increase the speed at which templates may be rendered. static¶ This directory contains static assets which support the mytemplate.pt template. It includes CSS and images. templates/mytemplate.pt¶ The single Chameleon template that exists in the project. Its contents are too long to show here, but it displays a default page when rendered. It is referenced by the call to @view_config as the renderer of the my_view view callable in the views.pyproject. You can then continue to add view callable functions to the blog.py module, but you can also add other .py files which contain view callable functions to the views directory. As long as you use the @view_config directive to register views in conjuction an Pyramid scaffold scaffolding. But we strongly recommend using while developing your application, because many other convenience introspection commands (such as pviews, prequest, proutes and others) are also implemented in terms of configuration availaibility of this .ini file format. It also configures Pyramid logging and provides the --reload switch for convenient restarting of the server when code changes. Using an Alternate WSGI Server¶ Pyramid scaffolds.
https://docs.pylonsproject.org/projects/pyramid/en/1.3-branch/narr/project.html
CC-MAIN-2018-47
refinedweb
1,313
56.86