Review Questions Ljq

1. This term refers to an individual item in a list. 2. This is a number that identifies a character in a string, or an item in a list. 3. This is the first index in a string or a list. d. The size of the list minus one 4. This is the last index in a string or a list. d. The size of the string or list minus one 5. This will happen if you try to use an index that is out of range for a list. a. a ValueError exception will occur b. an IndexError exception will occur c. The string or list will be...

How do I create a popup menu

Menus don't just pull down from menu bars at the top of your frame. They can also pop up from anywhere in the frame. Most of the time, a pop-up menu is used to provide actions that are context-sensitive, and that relate to the object at the location where the user clicks. Figure 10.6 displays an example of pop-up menus in action. Pop-up menus are created very similarly to standard menus, however, they are not attached to the menu bar. Listing 10.9 displays the code for a sample popup menu....

Ellipsis Object

The Ellipsis object is used to indicate the presence of an ellipsis in an index lookup .There is a single object of this type, accessed through the built-in name Ellipsis. It has no attributes and evaluates as True. None of Python's built-in types make use of Ellipsis, but it may be useful if you are trying to build advanced functionality into the indexing operator on your own objects.The following code shows how an Ellipsis gets created and passed into the indexing operator e 3, , 4 Calls...

How can I perform a print preview

One of the advantages of the device contexts as they are implemented in wxPy-thon is that it makes it easy to manage print preview, since most of the functionality comes from just replacing the printer device context with a screen device context. However, the print preview API is a bit different than for regular printing. For one thing, since print preview takes place on screen in a window, wxPy-thon provides a frame class for previewing. The next three sections describe the print preview...

Cropping and resizing images

The crop left, top, right, bottom method returns a rectangle portion of an image. resize w, h , filter returns a resized copy of an image. The filter argument controls what sort of sampling is used against the original image, and can be one of BILINEAR, BICUBIC, or NEAREST the default . One other useful method is thumbnail w, h , which resizes the object in place while maintaining the original aspect width-to-height ratio. Because of this, it may not use the exact size you pass in.

Web Services

In Chapter 5, we defined the data access layer and the entities our application would manipulate. In this chapter, we will explain how we can articulate our photoblog application by using web services as an API to access and operate the entities we have defined. We will introduce the concept of web services based on the REST principles as well as the Atom Publishing Protocol and explain how we can implement them using CherryPy. By the end of this chapter, you should understand how web services...

Say Hello

Here, as an example, we create a simple web app that displays the message Hello from MyApp to the user. We will call this application myapp. We will also add a counter that counts how many times the same user visits the page. You can create a new application simply by typing its name in the form on the top right of the site page in admin. After you press submit , the application is created as a copy of the built-in welcome application. Now you have a copy of the welcome application. To edit an...

Handling File Actions

The File menu is probably the most widely implemented menu in main-window-style applications, and in most cases it offers, at the least, new, save, and quit or exit options. dialog newimagedlg.NewImageDlg self if dialog.exec_ self.addRecentFile self.filename self.image QImage for action, check in self.resetableActions action.setChecked check self.image dialog.image self.filename None self.dirty True self.showImage self.sizeLabel.setText d x d self.image.width , self.image.height...

Using and bytearray Objects

So far we've focused on str and bytes, since they subsume Python 2's unicode and str. Python 3.0 has a third string type, though bytearray, a mutable sequence of integers in the range 0 through 255, is essentially a mutable variant of bytes. As such, it supports the same string methods and sequence operations as bytes, as well as many of the mutable in-place-change operations supported by lists. The bytearray type is also available in Python 2.6 as a back-port from 3.0, but it does not enforce...

The Tkinter Module

Tkinter is Python's de facto standard GUI toolkit. It's the most cross-platform GUI. Many applications are written using Tkinter because it is a very powerful and flexible tool. Maybe the most notable features are its geometry management, which is much better than standard windows, and its efficient Text and Canvas widgets. Many toolkits support as good as or better geometry management some of them are listed in this chapter . Tkinter, which stands for Tk interface, is the standard Python...

The Team Repository View

The team repository view supplants most of the Subversion status operations we looked at earlier in the chapter. It shows how the repository is different from your working copy, and how your working copy is different from the repository. It can combine those views showing all changes, or it can show only files with conflicts. It can show the aggregate changes, or it can break the differences down by revision. Open the repository view by choosing the menu item Window gt Open View gt Other. This...

Options specific to Canvas

closeenough Specifies a floating-point value indicating how float 0.5 close the mouse cursor must be to an item before it is considered to be inside the item. Defaults to 1.0. confine Specifies a boolean value that indicates whether or not it should be allowable to set the canvas's view outside the region defined by the scrollre-gion argument. Defaults to true, which means that the view will be constrained within the scroll region. Specifies the color to use as background in the color 'yel-...

Distributing Unix applications

Supporting your application is usually a simple task once you have access to a built Python and Tcl Tk. In general, UNIX end users are capable of building and installing both of these so you may be able to simply require your end users to take care of them. Then your application installation may be as simple as extracting files from a tar file and editing the users' environments appropriately. For the moment, let's assume that this is the case, so we will concentrate on getting your application...

Figure The flat plane becomes a full rotating cube

Pyopengl Glrotatef Spin

Let's say you wanted to speed up and twist your rotating cube around a bit more. It's easy to fiddle with MatrixMode, especially since you've thought ahead and included a number of variables with which to do it x,y, and z rots are the rotations on each axis xrot yrot zrot 0.0 These variables, xrot, yrot, and zrot, can be used to rotate the cube in a new way on the x-, y-, and x-axes. Do so by adding a few lines to the top of drawgraphics glLoadidentity glTranslatef 0.0, 0.0, -5.0 global rquad...

The String Data Type

A string is a sequence of characters. In Chapter 2 you learned that a string literal is a sequence of characters in quotations. Python also allows strings to be delimited by single quotes apostrophes . There's no difference just be sure to use a matching set. Strings can be stored in variables, just like numbers. Here are some examples illustrating these two forms of string literals. gt gt gt strl Hello gt gt gt str2 'spam' gt gt gt print strl, str2 Hello spam gt gt gt type strl lt type...

The Address Book as ClientServer

Back in the files topic we built a version of our address book using a dictionary. Let's reuse that example but this time we will build a client server version. Notice that the original code broke one of the good practice rules we discussed earlier I included User Interface code in my helper functions. If we were to try to use this code we would get messages from the child process mixed up with messages from the parent. We need to tweak the code slightly so that we can turn it into a reusable...

Firststep changes

In order to use the compatibility layer there are still a few changes that need to be made to your code. Many of these changes can be made by running the alter_codel module with your code as input. 1. Importing the alter_codel module handles all these changes a import Numeric - gt import numpy.oldnumeric as Numeric b import Numeric as XX - gt import numpy.oldnumeric as XX c from Numeric import lt name1 gt , lt nameN gt - gt from numpy.oldnumeric import lt name1 gt , , lt nameN gt d from Numeric...

Example AppleScript interface running on Mac

ALLOWED_SCRIPTS edit ser serial.Serial ' dev tty.pybook' print Waiting for message while True msg serial.readline .strip if msg exit print gt gt serial, bye break print Running script msg os.system osascript s.script msg print gt gt serial, Script ok The idea is that the phone client is used to choose one of the scripts to execute on the PC side. Once again, we can use Example 59 as the phone client. Again, echoing should be disabled by setting ECHO False in the client. In Python, the os.system...

generateusernamespy

Imagine we are setting up a new computer system and need to generate user-names for all of our organization's staff. We have a plain text data file UTF-8 encoding where each line represents a record and fields are colon-delimited. Each record concerns one member of the staff and the fields are their unique staff ID, forename, middle name which may be an empty field , surname, and department name. Here is an extract of a few lines from an example data users.txt data file 1601 Albert Lukas...

Indexing Lists Versus Dictionaries

A text, as we have seen, is treated in Python as a list of words. An important property of lists is that we can look up a particular item by giving its index, e.g., textl l00 . Notice how we specify a number and get back a word. We can think of a list as a simple kind of table, as shown in Figure 5-2. Figure 5-2. List lookup We access the contents of a Python list with the help of an integer index. Contrast this situation with frequency distributions Section 1.3 , where we specify a word and...

Examples 1

Hangman server 2 3 Hangman server 3 3 Text to speech MP3 player Blocking MP3 player MIDI player Sound recorder Animal sounds Binding a keycode to a callback function Key events Creating a directory for application data Retrieve the current GSM cell ID GSM location application 56 Send photos to another phone via Bluetooth 60 PySerial script running on PC 61 AppleScript interface running on Mac 72 Set the default access point SMS search using list comprehensions Input sanitization using list...

Understanding the application object lifecycle

The lifecycle of your wxPython application object begins when the application instance is created and ends just after the last application window is closed. This does not necessarily correspond to the beginning and ending of the Python script that surrounds your wxPython application. The script may choose to do some activity before creating the wxPython application, and may do further cleanup after the application MainLoop exits. All wxPython activity, however, must be performed during the life...

escape

escape escapes all nonalphanumeric characters before passing the expression to tee compiler, and returns a string with all metacharacters escaped. Here's an example in wficF the compile function fails because there are unmatched parentykses gt gt gt from re import gt gt gt strVar group gt gt gt cre compile strVar File lt console gt , line 1, in re.error Unmatched parentheses. In this example, tfe non-alphanumeric characters are escaped, so tfe compile function works gt gt gt cre compile escape...

Understanding Environment variables

Environment variables are simply a kind of storage location managed by the operating system. When you open a command prompt, you can see a list of environment variables by typing Set and pressing Enter. Figure 10-6 shows the environment variables on my system. The environment variables or at least their values will differ on your machine, so you should take a look at them. If you want to see the value of a particular environment variable, type Set VariableName such as Set USERNAME and press...

Filtering

One of the reasons to transform a time-domain signal to a frequency-domain signal is for the purpose of filtering. A filter is an operation that changes a signal. Much like filters in your kitchen sink, filters let some frequencies pass water , while stopping other frequencies large food remains . Filters are used in a variety of applications, ranging from audio to radar systems. Filters are categorized by their behavior. A filter that lets through low frequencies and stops high frequencies is...

Defining Your Own Modules

Section 2.1, The Big Picture, on page 17 explained that in order to save code for later use, you can put it in a file with a .py extension. You can then tell Python to run the code in that file, rather than typing commands in at the interactive prompt. What we didn't tell you then is that every Python file can be used as a module. The name of the module is the same as the name of the file, but without the .py extension. For example, the following function is taken from Section 2.6, Function...

Reading Tagged Corpora

Several of the corpora included with NLTK have been tagged for their part-of-speech. Here's an example of what you might see if you opened a file from the Brown Corpus with a text editor The at Fulton np-tl County nn-tl Grand jj-tl Jury nn-tl said vbd Friday nr an at inves-tigation nn of in Atlanta's np recent jj primary nn election nn produced vbd no at evidence nn '' '' that cs any dti irregularities nns took vbd place nn . . Other corpora use a variety of formats for storing part-of-speech...

Formulating Algorithms Case Study CounterControlled Repetition

To illustrate how algorithms are developed, we solve several variations of a class-averaging problem. Consider the following problem statement A class often students took a quiz. The grades integers in the range 0 -100 for this quiz are available. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students. The algorithm for solving this problem requests each of the grades, performs the averaging calculation and prints the...

Not all snakes will squish you

Chances are you were given this book for your birthday. Or possibly for Christmas. Aunty Mildred was going to give you mismatching socks that were two sizes too large and you wouldn't want to wear when you grew into them anyway . Instead, she heard someone talking about this printable book, remembered you had one of those computer-thingamabobs that you tried to show her how to use last Christmas you gave up when she started trying to talk into the mouse , and got them to print another copy....

Decision Structures and Boolean Logic

The XPath Access Mechanism

The XPath part of the solution makes accessing the elements within the XML document much easier than a traditional event-driven or even DOM-based parser. To use the XPath interface is simplicity itself. For example, to get a list of all the subelements, you need to do is access the elements property of the parent element. The each method accepts an XPath definition that in turn returns a list of all the subelements that it finds. For example, you can work through all the items using this...

The ACalculus

In Section 1.3, we pointed out that mathematical set notation was a helpful method of specifying properties P of words that we wanted to select from a document. We illustrated this with 31 , which we glossed as the set of all w such that w is an element of V the vocabulary and w has property P. It turns out to be extremely useful to add something to first-order logic that will achieve the same effect. We do this with the A-operator pronounced lambda . The A counterpart to 31 is 32 . Since we...

The Netbeans Python Debugger

As mentioned previously, the Netbeans IDE also includes a Python debugger that is derived from JeanYves Mengant's jpydbg debugger. This section will discuss how to make use of the Netbeans Python debugger along with some examples using our HockeyRoster code that was written in the previous section. If you have used a debugger in another IDE, or perhaps the Java debugger that is available for Netbeans, this debugger will feel quite familiar. The Python debugger includes many features such as...

Example Plain Text Table of Contents

Though there are many forms of documentation, plain text is perhaps the most common, as it doesn't require any additional software to view. Navigating large chunks of documentation can be difficult, though, because of the lack of links or page numbers for a table of contents. Line numbers could be used instead of page numbers, but a properly formatted table of contents can still be tedious to maintain. Consider a typical table of contents, where the title of a section is left-aligned and the...

Unpacking arguments

There's one more nifty trick involving variable arguments and keyword arguments. We've used it in some of our previous examples, but it's never too late for an explanation. Given a list or dictionary of values, we can pass those values into a function as if they were normal positional or keyword arguments. Have a look at this code def show_args arg1, arg2, arg3 THREE print arg1, arg2, arg3 arg1 ONE, arg2 TWO print Unpacking a sequence , end show_args some_args print Unpacking a dict , end...

Asynchronous IO with select and poll

When a server communicates with a client, the data it receives from the client may come in fits and spurts. If you're using forking and threading, that's not a problem. While one parallel waits for data, other parallels may continue dealing with their own clients. Another way to go, however, is to deal only with the clients that actually have something to say at a given moment. You don't even have to hear them out you just hear or, rather, read a little, and then put it back in line with the...

Deploying a Single JAR

In order to deploy an application to the Java Warehouse, it must be packaged as a single JAR file. We've already discussed packaging Jython applications into a JAR file using the Jython standalone method in Chapter 13. In this section, you will learn how to make use of the One-JAR http one-jar.sourceforge.net product to distribute client-based Jython applications. In order to get started, you will need to grab a copy of One-JAR. There are a few options available on the download site, but for...

A completely different way to set up variables

One of the most common uses for the various setup and teardown functions is to ensure certain class or module variables are available with a known value before each test method is run. py.test offers a completely different way to do this using what are known as funcargs, short for function arguments. Funcargs are basically named variables that are previously set up in a test configuration file. This allows us to separate configuration from execution of tests, and allows the funcargs to be used...

Python DB API

The quest to provide a standard way to interface to database systems drove a group of people to develop Python Database API. The Python DB API is maintained by the Database Special Interest Group DB-SIG . For more information, check out their Web site at http www.python.org sigs db-sig . The following list shows all the database modules that currently implement the Python DB API specification proposed by the DB-SIG. This means that after you understand the API, you will be able to handle, in a...

Implementing the Singleton Design Pattern

Sometimes in your applications you will have objects that by their very nature should exist at most one time and one time only a global application object would be one example. Indeed, Singletons occasionally get a bad rap for being glorified global variables, which developers frown on because it's more of a hassle to ensure that the state of that variable is correct everywhere. In IronPython, we'll store an instance of a class in a variable for reference if that instance variable is null, we...

Basic Concepts

A running program is called a process. Each process has its own system state, which includes memory, lists of open files, a program counter that keeps track of the instruction being executed, and a call stack used to hold the local variables of functions. Normally, a process executes statements one after the other in a single sequence of control flow, which is sometimes called the main thread of the process. At any given time, the program is only doing one thing. A program can create new...

Embedding the Jython Interpreter

By embedding the Jython interpreter in your own Java classes, you can run scripts from within your application, gaining control over the complete environment. That's important because few Java applications run from the command line. You can find the Jython interpreter in the class org.python.util.PythonInterpreter. You can use code like the following to initialize the Jython interpreter Properties props new Properties props.put python.home, pythonHome PythonInterpreter.initialize...

Working with Surface Objects

Loading images into Pygame is done with a simple one-liner pygame.image.load takes the file name of the image you want to load and returns a surface object, which is a container for an image. Surfaces can represent many types of image, but Pygame hides most of these details from us so we can treat them in much the same way. Once you have a surface in memory, you can draw on it, transform it, or copy it to another surface to build up an image. Even the screen is represented as a surface object....

Computing Probabilities

With the mathematical rules from probability theory one may compute the probability that a certain event happens, say the probability that you get one black ball when drawing three balls from a hat with four black balls, six white balls, and three green balls. Unfortunately, theoretical calculations of probabilities may soon become hard or impossible if the problem is slightly changed. There is a simple numerical way of computing probabilities that is generally applicable to problems with...

Event Binding 1

Happily, lambda also gives us a way to parameterize event binding. Instead of self.buttonHandler a event, button name, 1, Good stuff which wouldn't work, because there was no way to include the event argument in the argument list , we can use lambda, this way event binding -- passing the event as an argument self.button1.bind , event, arg1 button name, arg2 1, arg3 Good stuff self.buttonHandler a event, arg1, arg2, arg3 Note that event here is a variable name -- it is not a Python keyword or...

Using the interactive interpreter

When you download IronPython,33 you have two choices. You can download and install the msi installer IronPython 2 only , which includes the Python 2.5 standard library. Alternately, you can download and unpack the binary distribution that comes as a zip file. Whichever route you take, you'll have two executables, ipy.exe and ipyw.exe, which are the equivalents of the Python executables python.exe and pythonw.exe. Both are used to launch Python scripts ipy.exe launches them with a console...

A TextBased UI

In designing PokerApp we have also developed a specification for a generic Pokerlnterface class. Our interface must support the methods for displaying information setMoney, setDice, and showResult. It must also have methods that allow for input from the user wantToPlay, and chooseDice. These methods can be implemented in many different ways, producing programs that look quite different even though the underlying model, PokerApp, remains the same. Usually, graphical interfaces are much more...

The SOAP Response

Here's a possible response you might get from a SOAP server after sending it the sortList request lt xml version 1.1 encoding UTF-8 gt lt SOAP-ENV Envelope encoding lt SOAP-ENV Body lt lt ns1 sortList xmlns ns1 urn SearchSort lt lt tem gt 10 lt item gt lt return lt lt lt ns1 sortList gt lt lt SOAP-ENV Envelope gt Just as with XML-RPC, a SOAP response has the same basic structure as a SOAP request. Where the SOAP request had a list of arguments, the SOAP response has a single return value. This,...

Expressions functions and Python types

The simplest example of this is to use IronPython to evaluate individual expressions. IronPython makes a great calculator 21 So far, whenever we have executed Python code from a string we have passed in the enumeration member SourceCodeKind.Statements. This member has a sister, SourceCodeKind.Expression, that allows us to evaluate an expression and return an object. It is used in this snippet of C to evaluate a simple mathematical expression string code 2 3 5 ScriptSource source 21 You can see...

Human factors

Extensive documents on Human Factor Engineering describe GUI design in scientific terms see the Reference section . In particular, font choice may be based on calculating the arc subtended by a character from a point 20 inches from the character the viewing position . While I have worked on projects where it was necessary to actually measure these angles to confirm compliance with specifications, it is not usually necessary to be so precise. When designing an application that includes a GUI,...