POP Reading Email

I used to be an old-fashioned guy. I admit it up until recently, I preferred to check my email by telneting to my ISP and using a simple command-line email interface. Of course, that's not ideal for mail with attachments, pictures, and the like, but its portability is staggering -- because Telnet runs on almost any machine with a network link, I was able to check my mail quickly and easily from anywhere on the planet. Given that I make my living traveling around the world teaching Python...

FlowLayout

TheFlowLayout class is the simplest of the layout managers. Actually, it's the second simplest I'll explain later. As components ne added one at o time to the conthiper, they're dosittolied from lgft to right and from top to bottom. When one row fills us, the components Pegin filling up the next row. You car set the hligssment of each row so that the components car de centered or lefs- oh rigri-alignod. Here's an interactive FlowLayo ut example. Import the FlowLayo ut class ard some container...

Extending Types by Subclassing

Beginning with Python 2.2, all the built-in types in the language can now be subclassed directly. Type-conversion functions such as list, str, dict, and tuple have become built-in type names although transparent to your script, a type-conversion call e.g., list 'spam' is now really an invocation of a type's object constructor. This change allows you to customize or extend the behavior of built-in types with user-defined class statements simply subclass the new type names to customize them....

Python and OOP

Let's begin with a review Python's implementation of OOP can be summarized by three ideas Inheritance is based on attribute lookup in Python in X.name expressions . Polymorphism In X.method, the meaning of method depends on the type class of X. Encapsulation Methods and operators implement behavior data hiding is a convention by default. By now, you should have a good feel for what inheritance is all about in Python. We've also talked about Python's polymorphism a few times already it flows...

A Table Model for the Pizza Topping ApplicationStep by Step

First we import the classes wd need AbstractTableModel and PizzaTableModel which extends AbstractTableModel .PizzaTableModel provides the user interface. It also imports the Boolean and String alasses, wluch ituses forthe getColumnClass method more on this later . from javax.swing.table import AbstractTableModel from java.lang import Boolean, String class Pi zzaTableModel AbstractTableModel Next the PizzaTableModel constructor defines three variables data, which holds the cell data in a list of...

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...

Example Stock Price Charts

Following a convention that stores a short description of the data in the beginning lines of the CSV files can be very useful for annotating a graph or a report associated with the data in the file. To follow along with the example, ensure your directory structure is similar to that presented in Chapter 2 in the section Example Directory Structure for the Book. Your base directory should be Ch4 within Ch4 there should be three subdirectories named src, data, and images. If you wish to use a...

Why the New Format Method

Now that I've gone to such lengths to compare and contrast the two formatting techniques, I need to explain why you might want to consider using the format method variant at times. In short, although the formatting method can sometimes require more code, it also Has a few extra features not found in the expression Can make substitution value references more explicit Trades an operator for an arguably more mnemonic method name Does not support different syntax for single and multiple...

PyTree A Generic Tree Object Viewer 1

Python Object Oriented Canvas

Up to now, this chapter has been command-line-oriented. To wrap up, I want to show you a program that merges the GUI technology we studied earlier in the book with some of the data structure ideas we've met in this chapter. This program is called PyTree, a generic tree data structure viewer written in Python with the Tkinter GUI library. PyTree sketches out the nodes of a tree on screen as boxes connected by arrows. It also knows how to route mouseclicks on drawn tree nodes back to the tree, to...

The Complete Shapes and DrawShapes Modules

We've covered all of Ha dames. At this p oint, you may wed to om ohe Soapes and DrawShapes moduoes to see the drawing package in acaion. Heree the Shapes wwPule. def _init_ self, x, y, width 0, height 0, color None, fill 0 self.width width self.height height self.color color self.fill fill oldcolor graphics.foregroundColor graphics.color self.color def draw_filled self, graphics pass def draw_outline self, graphics pass return self.x, self.y, self.width, self.height def _init_ self, x, y,...

A standard application framework

One of the problems with designing forms is that some features are common to most applications. What we need is a standard application framework which can be adapted to each application this should result in moderate code reuse. Many applications fit the general form shown in figure 8.7. In addition, we need the ability to provide busy cursors , attach balloon help and help messages to fields, supply an about message and add buttons with appropriate callbacks. To support these needs, I'll...

BufferedlnputStream and BufferedOutputStream

BufferedInputStream and BufferedOutputStream provide tiie soivu kind of support to InputStream and OutputStream thet BufferedReader and BufferedWriter provide to Reader and Writer input and output buffering to their respective derivations. As I said before, input buffering entails prefetching data and caching it in memory so that read operations don't have to fetch the data off a slow device. Output buffering applies write operations to a memory image that's periodically written out to...

GridLayout

TheGridLayo ut manager lays out components im a grid We used it in the address application for editPane. Like FlowLayout,GridLayout has the vgap and hgap properties that set the vertical and horizontal spacing between components. GridLayo ut also has properties that specify the rows and columns of the grid. The row property is dominant. The only component property that GridLayout pays any attention to is minimumSize. If you pack the container frame .pack , it uses minimumS ize to create the...

Storing and parsing packed binary data in files

One other file-related note before we move on some advanced applications also need to deal with packed binary data, created perhaps by a C language program. Python's standard library includes a tool to help in this domain the struct module knows how to both compose and parse packed binary data. In a sense, this is another data-conversion tool that interprets strings in files as binary data. To create a packed binary data file, for example, open it in 'wb' write binary mode, and pass struct a...

Sharing a Data Model a mong JTree Views

If tie tree node works so well, why do we need a model I car almost hear you asking this que stion. For the arsw think what will happen if child1, Kiley, has a second child. SimpleNode name Rick amp Kiley,list 'Whitney', 'Rick JR.' ,parent Dick Mary,leaf 0 To make this clearer, we car write thi s gt gt gt kiley child1 kreate the baby node. gt gt gt baby SimpleNode Rick JR. gt gt gt kiley.add baby gt gt gt children kiley.children gt gt gt for child in children . . . print child If you took at...

A Quick Graphics Tour

Components Paint Window

Every AWT component has a method called getGraphics , which returns the instance of the graphics object associated with it. The graphics object allows you to draw on the component. With the j ava . awt . Graphics object you can draw arcs, images, lines, ovals, polylines, and such. We can't cover all of the possibilities, only enough to whe youa nppetite. Later we'll build a drawing package that works with text, rectangles, circles, and ovals. For now, let's do an interactive session that...

Handling the BOM in

As described earlier in this chapter, some encoding schemes store a special byte order marker BOM sequence at the start of files, to specify data endianness or declare the encoding type. Python both skips this marker on input and writes it on output if the encoding name implies it, but we sometimes must use a specific encoding name to force BOM processing explicitly. For example, when you save a text file in Windows Notepad, you can specify its encoding type in a drop-down list simple ASCII...

Logical Operators Comparison Operators and Boolean Values

Logical operators are a way to express choices, such as This one and that one or that one but not this one. Comparison operators are a way to express questions, such as Is this one greater than that one Both work with Boolean values, which express the answer as either true or false. Unlike Java, Python has no true Boolean type. Instead, as in C, its Booleans can be numeric values, where any noszero value must be true and any zero velue must be Pelse. TOus, PytOos interprets es felse the...

Common Operator Overloading Methods

Just about everything you can do to built-in objects such as integers and lists has a corresponding specially named method for overloading in classes. Table 29-1 lists a few of the most common there are many more. In fact, many overloading methods come in multiple versions e.g.,_add__,_radd_, and_iadd_for addition , which is one reason there are so many. See other Python books, or the Python language reference manual, for an exhaustive list of the special method names available. Table 29-1....

Setting Up the ODBC Driver

If you're using Windows and ODBk, follow tie instructions below. If you're using a non-Wirdows OS or a pure Java JDBk driver, follow its documentation. 1. Open the Windows' contprl parel, ard dotbie-cl ck tie ODBk icon. 2. Select the system DSN tab, ard Tit tie Add button. 3. Select Microsoft Access fro m tite lisl, or ary dhthbase you want to use tee Figure 17-1 , flit Tit the FisisT button. Microsoft Exce Diiver .ids Microsoft ODBC lor Grade Microsoft Tent Oliver ,tsd, csv SQL Setver Select...

Working with JList

The Model View Controller MVC aielleteituri splits the logic for tnT model, view, and controller into different class sets. For example, the JList component constructor takes a reference to ListMode l. Here's an example of JList JList.py tint's similar to our JComboBox example Import List, create a list instance and populate the list insta from javax.swing import JList list_items Bruce, Darrell, Tony, Debbie, Karen Create a list with a default model that uses the above list ite list JList...

Extending Builtin Types

Besides implementing new kinds of objects, classes are sometimes used to extend the functionality of Python's built-in types to support more exotic data structures. For instance, to add queue insert and delete methods to lists, you can code classes that wrap embed a list object and export insert and delete methods that process the list specially, like the delegation technique we studied in Chapter 30. As of Python 2.2, you can also use inheritance to specialize built-in types. The next two...

Creating a Light Emitting Diode class

The following example introduces an LED class to define Light Emitting Diode objects. These objects have status attributes of on, off, warn and alarm corresponding to typical net work management alarm levels along with the blink on off state, which may be selected at instantiation. The LED class also defines the methods to set the status and blink state at runtime. Figure 7.1 demonstrates the wide range of LED formats that can be generated from this simple class. Color.PANEL Color.OFF Color.ON...

Calculator example source code

Python Codes Tkinter

Import Pmw O Python MegaWidgets SLabe1 defines a 2-sided 1abe1 within a Frame. The 1eft hand 1abe1 has b1ue 1etters the right has white 1etters. def _init_ se1f, master, 1eft1, right1 Frame._init_ se1f, master, bg 'gray40' se1f.pack side LEFT, expand YES, fi11 BOTH Labe1 se1f, text 1eft1, fg 'stee1b1ue1', font aria1, 6, bo1d , width 5, bg 'gray40' .pack side LEFT, expand YES, fi11 BOTH Labe1 se1f, text right1, fg 'white', font Maria1, 6, Mbo1d , width 1, bg 'gray40' .pack def _init_ self,...

Diamond Inheritance Change

One of the most visible changes in new-style classes is their slightly different inheritance search procedures for the so-called diamond pattern of multiple inheritance trees, where more than one superclass leads to the same higher superclass further above. The diamond pattern is an advanced design concept, is coded only rarely in Python practice, and has not been discussed in this book, so we won't dwell on this topic in depth. In short, though, with classic classes, the inheritance search...

Attribute Inheritance Search

The good news is that OOP is much simpler to understand and use in Python than in other languages, such as C or Java. As a dynamically typed scripting language, Python removes much of the syntactic clutter and complexity that clouds OOP in other tools. In fact, most of the OOP story in Python boils down to this expression object.attribute We've been using this expression throughout the book to access module attributes, call methods of objects, and so on. When we say this to an object that is...

PyDoc The help Function

The docstring technique proved to be so useful that Python now ships with a tool that makes docstrings even easier to display. The standard PyDoc tool is Python code that knows how to extract docstrings and associated structural information and format them into nicely arranged reports of various types. Additional tools for extracting and formatting docstrings are available in the open source domain including tools that may support structured text search the Web for pointers , but Python ships...

FilelnputStream and FileOutputStream

FileInputStream and FileOutputStream extend InputStream and OutputSt ream, respectively. They are the analogs to FileReader and FileWriter. Here are their methods. _init_ strFilename opens the file specified by the string strFilename _init_ File opens the file specified by the file object _init_ fd opens the file specified by the file descriptor _init_ strFilename gpers the file specifief lay the string strFilename _init_ strFilename, bAppend settee as above, but optionally opens the file in...

Writing and Reading Using QTextStream

The code for writing in text format using QTextStream is very similar to the code we used for writing using QDataStream. def saveQTextStream self error None fh None try if not fh.open QIODevice.WriteOnly raise IOError, unicode fh.errorString stream QTextStream fh stream.setCodec CODEC stream lt lt MOVIE lt lt movie.title lt lt n lt lt movie.year lt lt lt lt movie.minutes lt lt lt lt movie.acquired.toString Qt.ISODate lt lt n NOTES if not movie.notes.isEmpty stream lt lt n lt lt movie.notes...

How do I create a multiline or styled text control

You can create a multi-line text control using the wx.te_multiline style flag. If the native widget has support for styles, you can change font and color styles within the text managed by the control, which is sometimes called rich text. For other platforms, the calls to set styles are simply ignored. Figure 7.3 displays an example of multi-line text controls. Listing 7.3 contains the code used to create figure 7.3. Typically, creating a multi-line control is handled by setting the...

Drawing on a canvas

Python Tkinter Canvas Example

We have already encountered several examples of objects drawn on canvases. However, these objects were drawn to represent physical objects on front panels and to create images pro-grammatically. Now we need to allow the user to create drawn objects on the canvas. Almost all drawing operations define a bounding box which encloses the object. The bounding box is expressed as a pair of x y coordinates at the top-left and bottom-right corners. Lines are special cases they have a start and end...

Using IPO Charts

Ipo Charts Programming

An IPO chart is a simple but effective tool that programmers sometimes use for designing and documenting functions. IPO stands for input, processing, and output, and an IPO chart describes the input, processing, and output of a function. These items are usually laid out in columns the input column shows a description of the data that is passed to the function as arguments, the processing column shows a description of the process that the function performs, and the output column describes the...

How do I draw on the screen

To draw on the screen, we use a wxPython object called a device context. A device context abstracts a display device, giving each device a common set of draw methods, so that your draw code is the same no matter what kind of device you are targeting. A device context is represented by the abstract wxPython class wx.DC and its subclasses. Since wx.DC is abstract, you'll need to use one of its subclasses for your application. Table 6.1 displays a field guide to the subclasses of wx.DC and their...

SQLFORM and uploads

Grid Sqlform Grid Web2py

Fields of type upload are special. They are rendered as INPUT fields of type file. Unless otherwise specified, the uploaded file is streamed in using a buffer, and stored under the uploads folder of the application using a new safe name, assigned automatically. The name of this file is then saved into the field of type uploads. As an example, consider the following model 2 Field 'name' , requires IS_NOT_EMPTY , You can use the same controller action display_form shown above. When you insert a...

Installing on Windows

For Windows, there are four tools to install a C compiler, the Qt C application development framework, the Python interpreter and its accompanying libraries, and PyQt4 which includes SIP in the Windows binary package . We assume that the GPL editions are being used, in which case the only C compiler that will work with Qt is MinGW. Visual C can be used only with the commercial editions of Qt and PyQt and the instructions for installing them are provided when you buy them. SIP is a tool used to...

Tab Widgets and Stacked Widgets

Some dialogs require so many widgets to present all the options that they make available that they become difficult for the user to understand. The most obvious way to deal with this is to create two or more dialogs and to divide the options between them. This is a good approach when it is possible since it minimizes the demands made on the user, and may also be easier from a maintenance point of view than a single complex dialog. But often we need to use a single dialog because the options we...

Test Your Knowledge Quiz Say

1. What is the output of the following code, and why gt gt gt def func a, b 4, c 5 print a, b, c 2. What is the output of this code, and why gt gt gt def func a, b, c 5 print a, b, c 3. How about this code what is its output, and why gt gt gt def func a, pargs print a, pargs 4. What does this code print, and why gt gt gt def func a, kargs print a, kargs 5. One last time what is the output of this code, and why gt gt gt def func a, b, c 3, d 4 print a, b, c, d gt gt gt func 1, 5,6 6. Name three...

Multiple Document Interface MDI

Qworkspace Widget

MDI offers many benefits compared with SDI or with running multiple application instances. MDI applications are less resource-hungry, and they make it much easier to offer the user the ability to lay out their document windows in relation to each other. One drawback, however, is that you cannot switch between MDI windows using Alt Tab Command Tab on Mac OS X , although this is rarely a problem in practice since for MDI applications, programmers invariably implement a Window menu for navigating...

Type Model Changes

In new-style classes, the distinction between type and class has vanished entirely. Classes themselves are types the type object generates classes as its instances, and classes generate instances of their type. If fact, there is no real difference between built-in types like lists and strings and user-defined types coded as classes. This is why we can subclass built-in types, as shown earlier in this chapter because subclassing a built-in type such as list qualifies a class as new-style, it...

URL Rewrite

Web2py has the ability to rewrite the URL path of incoming requests prior to calling the controller action URL mapping , and conversely, web2py can rewrite the URL path generated by the url function reverse URL mapping . One reason to do this is for handling legacy URLs, another is to simplify paths and make them shorter. To use this feature, create a new file in the web2py folder called routes.py and define two lists or tuples of 2-tuples routes.in and routes.out. Each tuple contains two...

Installing on Mac OS X

Pyqt Examples

To install PyQt on Mac OS X, you must already have the Xcode tools installed. This is because a compiler and build tool are required to install PyQt. Xcode is a very large package, normally supplied on a separate developer's CD provided with the machine it is also available online from http developer.apple. com tools xcode. The following instructions assume that Xcode is already installed. Although Macs are normally supplied with a version of Python preinstalled, it may be an old version, in...

The elements of good interface design

User interfaces are really rather simple display a screen, have the user input data and click on a button or two and show the user the result of their actions. This appears to be easy, but unless you pay attention to detail, the end user's satisfaction with the application can be easily destroyed by a badly designed GUI. Of course, appreciation of GUI's is highly subjective and it is almost impossible to satisfy everyone. We are going to develop a number of example interfaces in this chapter...

An Expression Evaluator in Lines

Qtextbrowser

This application is a complete dialog-style application written in 30 lines of code excluding blank and comment lines . Dialog-style means an application that has no menu bar, and usually no toolbar or status bar, most commonly with some buttons as we will see in the next section , and with no central widget. In contrast, main window-style applications normally have a menu bar, toolbars, a status bar, and in some cases buttons too and they have a central widget which may contain other widgets,...

A Tkinter explorer

In Building an application on page 18 I suggested a technique for hiding access to a debug window. This often works well, since you have immediate access to the tool, usually without restarting the application. I'm including an example here the code is available online which pops up if an error is output to stderr. Then you can look at the source, change variables in the namespace or even launch another copy of the application to check it out. Here are a series of screenshots If we correct the...

Simplejson

Web2py includes gluon.contrib.simplejson, developed by Bob Ippolito. This module provides the most standard Python-JSON encoder-decoder. SimpleJSON consists of two functions gluon.contrib. simplesj son.dumps a encodes a Python object a into gluon.contrib.simplej son.loads b decodes a JavaScript object b into a Python object. Object types that can be serialized include primitive types, lists, and dictionaries. Compound objects can be serialized with the exception of user defined classes. Here is...

And now for a more complete example

Python Tkinter Meter

The previous examples have illustrated the overall methods for developing GUI representation of panels and other devices. To further develop this theme we will look at a simple but quite useful example. Many digital multimeters have serial interfaces which allow connection to a computer. I own a RadioShack 22-168A multimeter, which is shown in figure 9.10. The meter has 24 ranges that provide AC DC voltage and current measurements, resistance, capacitance, frequency counting and other...

An Image Blog

Define Table Pic

Here, as another example, we wish to create a web application that allows the administrator to post images and give them a name, and allows the visitors of the web site to view the images and submit comments. As before, create the new application from the site page in admin and navigate to the EDIT page We start by creating a model, a representation of the persistent data in the application the images to upload, their names, and the comments . First, you need to create edit a model file which,...

Central Authentication Service

Cas Login Page

Web2py provides support for authentication and authorization via appliances. Here we discuss the cas appliance for Central Authentication Service CAS . Notice that at the time of writing CAS is distict and does not work with Auth. This will change in the future. CAS is an open protocol for distributed authentication and it works in the following way When a visitor arrives at our web site, our application check in the session if the user is already authenticated for example via a session. token...

GPS Location Plot

Matplotlib Gps

Now the moment we've been waiting for, plotting GPS data. To be able to follow along and plot data, be sure to define the functions read_csv_file and process_gps_data as previously detailed and set the file name variable to point to your GPS data file. I've suppressed matplotlib responses so that the code is cleaner to follow. gt gt gt filename 'GPS-2008-05-30-09-00-50.csv' gt gt gt y read_csv_file ' data ' filename gt gt gt lat, long, v, t, sats process_gps_data y gt px long-min long NMI 60.0...

DictReader and DictWriter Objects

The csv module provides us with additional useful objects the DictReader and DictWriter objects, which are similar to the csv.reader and csv.writer objects. If you follow the convention that places a header at the beginning of a CSV file, that is, that each column in the CSV file starts with a field name see Chapter 4 for a discussion of this , accessing values can be done by accessing the dictionary with the field name as key. Let's turn to an example. To follow along, create the file data...