Archive for May, 2008

226 CHAPTER 10 BATTERIES INCLUDED (Jetty web server) The reason

Saturday, May 31st, 2008

226 CHAPTER 10 BATTERIES INCLUDED The reason for the usefulness of the deque is that it allows appending and popping efficiently at the beginning (to the left), as opposed to lists. As a nice side effect, you can also rotate the elements (that is, shift them to the right or left, wrapping around the ends) efficiently. Deque objects also have extendand extendleft methods, with extend working like the corresponding list method, and extendleft working analogously to appendleft. Note that the elements in the iterable used in extendleft will appear in the deque in reverse order. time The time module contains functions for, among other things, getting the current time, manipulating times and dates, and reading dates from strings and formatting dates as strings. Dates can be represented as either a real number (the seconds since 0 hours, January 1 in the epoch, a platform-dependent year; for UNIX, it s 1970), or a tuple containing nine integers. These integers are explained in Table 10-5. For example, the tuple (2002, 1, 21, 12, 2, 56, 0, 21, 0) represents January 21, 2002, at 12:02:56, which is a Monday, and the 21st day of the year. (No daylight savings.) Table 10-5. The Fields of Python Date Tuples Index Field Value 0 Year For example, 2000, 2001, and so on 1 Month In the range 1 12 2 Day In the range 1 31 3 Hour In the range 0 23 4 Minute In the range 0 59 5 Second In the range 0 61 6 Weekday In the range 0 6, where Monday is 0 7 Julian day In the range 1 366 8 Daylight Savings 0, 1, or 1 Some of these values need some explaining: The range for seconds is 0 61 to account for leap seconds and double leap seconds. The Daylight Savings number is a Boolean value (true or false), but if you use 1, mktime (a function that converts such a tuple to a timestamp measured in seconds since the epoch) will probably get it right. Some of the most important functions in the timemodule are described in Table 10-6.
Check Tomcat Web Hosting services for best quality webspace to host your web application.

CHAPTER 10 (Cool web site) BATTERIES INCLUDED 225 The heapreplace

Friday, May 30th, 2008

CHAPTER 10 BATTERIES INCLUDED 225 The heapreplace function is not quite as commonly used as the others. It pops the smallest element off the heap and then pushes a new element onto it. This is more efficient than a heappop followed by a heappush: >>> heapreplace(heap, 0.5) 0 >>> heap [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6] >>> heapreplace(heap, 10) 0.5 >>> heap [1, 2, 5, 3, 6, 7, 9, 8, 4, 10] The remaining two functions of the heapq module, nlargest(n, iter) and nsmallest(n, iter), are used to find the n largest or smallest elements, respectively, of any iterable object iter. You could do this by using sorting (for example, using the sorted function) and slicing, but the heap algorithm is faster and more memory-efficient (and, not to mention, easier to use). Deques (and Other Collections) Double-ended queues, or deques, can be useful when you need to remove elements in the order in which they were added. In Python 2.4, the collections module was added, which contains the deque type. Note As of Python 2.4, the collections module only contains the deque type. Possible future additions are B-trees and Fibonacci heaps. A deque is created from an iterable object (just like sets) and has several useful methods: >>> from collections import deque >>> q = deque(range(5)) >>> q.append(5) >>> q.appendleft(6) >>> q deque([6, 0, 1, 2, 3, 4, 5]) >>> q.pop() 5 >>> q.popleft() 6 >>> q.rotate(3) >>> q deque([2, 3, 4, 0, 1]) >>> q.rotate(-1) >>> q deque([3, 4, 0, 1, 2])
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

Com web hosting - 224 CHAPTER 10 BATTERIES INCLUDED >>> from

Thursday, May 29th, 2008

224 CHAPTER 10 BATTERIES INCLUDED >>> from heapq import * >>> from random import shuffle >>> data = range(10) >>> shuffle(data) >>> heap = [] >>> for n in data: … heappush(heap, n) >>> heap [0, 1, 3, 6, 2, 8, 4, 7, 9, 5] >>> heappush(heap, 0.5) >>> heap [0, 0.5, 3, 6, 1, 8, 4, 7, 9, 5, 2] Note The order of the elements isn t as arbitrary as it seems. They aren t in strictly sorted order, but there is one guarantee made: the element at position i is always greater than the one in position i // 2 (or, conversely, it s smaller than the elements at positions 2*iand 2*i + 1). This is the basis for the underlying heap algorithm. This is called the heap property. The heappop function pops off the smallest element, which is always found at index 0, and makes sure that the smallest of the remaining element takes over this position (while preserving the heap property mentioned in the previous note). Even though popping the first element of a list isn t efficient in general, it s not a problem here, because heappop does some nifty shuffling behind the scenes: >>> heappop(heap) 0 >>> heappop(heap) 0.5 >>> heappop(heap) 1 >>> heap [2, 5, 3, 6, 9, 8, 4, 7] The heapify function takes an arbitrary list and makes it a legal heap (that is, it imposes the heap property mentioned in the previous note) through the least possible amount of shuffling. If you don t build your heap from scratch with heappush, this is the function to use before starting to use heappush and heappop: >>> heap = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2] >>> heapify(heap) >>> heap [0, 1, 5, 3, 2, 7, 9, 8, 4, 6]
Visit our web design programs services for an affordable and reliable webhost to suit all your needs.

CHAPTER 10 BATTERIES (Starting a web site) INCLUDED 223 There are

Wednesday, May 28th, 2008

CHAPTER 10 BATTERIES INCLUDED 223 There are various in-place operations as well, with corresponding methods, as well as the basic methods addand remove. For more information, see the Python Library Reference, in the section about set types (http://python.org/doc/lib/types-set.html). Tip If you need a function for finding, say, the union of two sets, you can simply use the unbound version of the union method, from the set type. This could be useful, for example, in concert with reduce: >>> mySets = [] >>> for i in range(10): … mySets.append(set(range(i,i+5))) … >>> reduce(set.union, mySets) set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) Sets are mutable, and may therefore not be used, for example, as keys in dictionaries. Another problem is that sets themselves may only contain immutable (hashable) values, and thus may not contain other sets. Because sets of sets often occur in practice, this is something of a problem . . . Luckily, there is the frozenset type, which represents immutable (and, therefore, hashable) sets: >>> a = set() >>> b = set() >>> a.add(b) Traceback (most recent call last): File ““, line 1, in ? TypeError: set objects are unhashable >>> a.add(frozenset(b)) The frozenset constructor creates a copy of the given set, and is useful whenever you want to use a set either as a member of another set or as the key to a dictionary. Heaps Another well-known data structure is the heap, a kind of priority queue. A priority queue lets you add objects in an arbitrary order and at any time (possibly in-between the adding) find (and possibly remove) the smallest element. It does so much more efficiently than, say, using min on a list. In fact, there is no separate heap type in Python only a module with some heap- manipulating functions. The module is called heapq (with the q standing for queue), and it contains six functions, the first four of which are directly related to heap manipulation. You must use a list as the heap object itself. The heappushfunction is used to add an item to a heap. Note that you shouldn t use it on any old list only one that has been built through the use of the various heap functions. The reason for this is that the order of the elements is important (even though it may look a bit haphazard; the elements aren t exactly sorted).
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.

222 CHAPTER (Web hosting services) 10 BATTERIES INCLUDED Just as

Tuesday, May 27th, 2008

222 CHAPTER 10 BATTERIES INCLUDED Just as with dictionaries, the ordering of set elements is quite arbitrary, and shouldn t be relied on: >>> set([’fee’, ‘fie’, ‘foe’]) set([’foe’, ‘fee’, ‘fie’]) In addition to checking for membership, you can perform various standard set operations (which you may know from mathematics) such as union and intersection, either by using methods or by using the same operations as you would for bit operations on integers (see Appendix B). For example, you can find the union of two sets using either the union method of one of them or the bitwise OR operator, |: >>> a = set([1, 2, 3]) >>> b = set([2, 3, 4]) >>> a.union(b) set([1, 2, 3, 4]) >>> a | b set([1, 2, 3, 4]) Here are some other methods and their corresponding operators; the names should make it clear what they mean: >>> c = a & b >>> c.issubset(a) True >>> c <= a True >>> c.issuperset(a) False >>> c >= a False >>> a.intersection(b) set([2, 3]) >>> a & b set([2, 3]) >>> a.difference(b) set([1]) >>> a - b set([1]) >>> a.symmetric_difference(b) set([1, 4]) >>> a ^ b set([1, 4]) >>> a.copy() set([1, 2, 3]) >>> a.copy() is a False
Note: In case you are looking for affordable and reliable webhost to host and run your j2ee application check Vision J2ee Web Hosting services.

CHAPTER 10 BATTERIES INCLUDED 221 Listing 10-7. (Ftp web hosting)

Monday, May 26th, 2008

CHAPTER 10 BATTERIES INCLUDED 221 Listing 10-7. The Line Numbering Program with Line Numbers Added # numberlines.py # 1 # 2 import fileinput # 3 # 4 for line in fileinput.input(inplace=1): # 5 line = line.rstrip() # 6 num = fileinput.lineno() # 7 print ‘%-40s # %2i’ % (line, num) # 8 Caution Be careful about using the inplace parameter it s an easy way to ruin a file. You should test your program carefully without setting inplace (this will simply print out the result), making sure the program works before you let it modify your files. For another example using fileinput, see the section about the random module, later in this chapter. Sets, Heaps, and Deques There are many useful data structures around, and Python supports some of the more common ones. Some of these, such as dictionaries (or hash tables) and lists (or dynamic arrays), are integral to the language. Others, although somewhat more peripheral, can still come in handy sometimes. Sets Sets were introduced in Python 2.3, through the Set class in the sets module. Although you may come upon Set instances in existing code, there is really very little reason to use them yourself unless you want to be backward compatible; in Python 2.3 sets were made part of the language, through the set type. So, there s no longer any need to import the sets module you can just create sets directly: >>> set(range(10)) set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) Sets are constructed from a sequence (or some other iterable object). Their main use lies in checking membership, and thus duplicates are ignored: >>> set([0, 1, 2, 3, 0, 1, 2, 3, 4, 5]) set([0, 1, 2, 3, 4, 5])
From our experience, we are can tell you that you can find a reliable and cheap webhost service at Java Web Hosting services.

220 CHAPTER 10 (Web host) BATTERIES INCLUDED The function

Sunday, May 25th, 2008

220 CHAPTER 10 BATTERIES INCLUDED The function fileinput.filelinenoreturns the number of the current line within the current file. Each time you are finished with one file and begin processing the next, the file line number is reset, and restarts at 1. The function fileinput.isfirstline returns a true value if the current line is the first line of the current file and a false value otherwise. The function fileinput.isstdin returns a true value if the current file is sys.stdin and false otherwise. The function fileinput.nextfile closes the current file and skips to the next one. The lines you skip do not count against the line count. This can be useful if you know that you are finished with the current file for example, if each file contains words in sorted order, and you are looking for a specific word. If you have passed the word s position in the sorted order, you can safely skip to the next file. The function fileinput.close closes the entire chain of files and finishes the iteration. Example Numbering the lines of a Python script. Let s say you have written a Python script and you want to number the lines. Because you want the program to keep working after you ve done this, you have to add the line numbers in comments to the right of each line. To line them up, you can use string formatting. Let s allow each program line to get 40 characters maximum and add the comment after that. The program in Listing 10-6 shows a simple way of doing this with fileinput and the inplace parameter. Listing 10-6. Adding Line Numbers to a Python Script # numberlines.py import fileinput for line in fileinput.input(inplace=True): line = line.rstrip() num = fileinput.lineno() print ‘%-40s # %2i’ % (line, num) If you run this program on itself, like this: $ python numberlines.py numberlines.py you end up with the program in Listing 10-7. Note that the program itself has been modified, and that if you run it like this several times, you end up with multiple numbers on each line. Recall that rstrip is a string method that returns a copy of a string, where all the whitespace on the right has been removed (see the section String Methods in Chapter 3 and Table B-6 in Appendix B).
We would like to recommend you tested and proved virtual web hosting services, which you will surely find to be of great quality.

CHAPTER 10 BATTERIES INCLUDED 219 fileinput You (Web host server)

Saturday, May 24th, 2008

CHAPTER 10 BATTERIES INCLUDED 219 fileinput You learn a lot about reading from and writing to files in Chapter 11, but here is a sneak preview. The fileinput module enables you to easily iterate over all the lines in a series of text files. If you call your script like this (assuming a UNIX command line): $ python some_script.py file1.txt file2.txt file3.txt you will be able to iterate over the lines of file1.txt through file3.txt in turn. You can also iterate over lines supplied to standard input (sys.stdin, remember?), for example, in a UNIX pipe (using the standard UNIX command cat): $ cat file.txt | python some_script.py If you use fileinput, this way of calling your script (with cat in a UNIX pipe) works just as well as the previous one (supplying the file names as command-line arguments to your script). The most important functions of the fileinput module are described in Table 10-4. Table 10-4. Some Important Functions in the fileinput Module Function Description input([files[, inplace[, backup]]) Facilitates iteration over lines in multiple input streams filename() Returns name of current file lineno() Returns current (cumulative) line number filelineno() Returns line number within current file isfirstline() Checks whether current line is first in file isstdin() Checks whether last line was from sys.stdin nextfile() Closes current file and moves to the next close() Closes the sequence The function fileinput.input is the most important of the functions. It returns an object that you can iterate over in a for loop. If you don t want the default behavior (in which fileinput finds out which files to iterate over), you can supply one or more file names to this function (as a sequence). You can also set the inplace parameter to a true value (inplace=True) to enable in-place processing. For each line you access, you ll have to print out a replacement, which will be put back into the current input file. The optional backup argument gives a file name extension to a backup file created from the original file when you do in-place processing. The function fileinput.filename returns the file name of the file you are currently in (that is, the file that contains the line you are currently processing). The function fileinput.lineno returns the number of the current line. This count is cumulative so that when you are finished with one file and begin processing the next, the line number is not reset but starts at one more than the last line number in the previous file.
If you are looking for cheap and quality webhost to host and run your website check Jboss Web Hosting services.

218 CHAPTER 10 BATTERIES INCLUDED Example Starting

Thursday, May 22nd, 2008

218 CHAPTER 10 BATTERIES INCLUDED Example Starting a Web browser. The system command can be used to execute any external program, which is very useful in environments such as UNIX where you can execute programs (or commands) from the command line to list the contents of a directory, send e-mail, and so on. But it can be useful for starting programs with graphical user interfaces, too such as a Web browser. In UNIX, you can do the following (provided that you have a browser at /usr/ bin/firefox): os.system(’/usr/bin/firefox’) A Windows version would be (again use the path of a browser you have installed) os.system(r’c:”Program Files”"Mozilla Firefox”firefox.exe’) Note that I ve been careful about enclosing Program Files and Mozilla Firefox in quotes; otherwise DOS (which handles the command) balks at the whitespace. (This may be important for directories in your PYTHONPATH as well.) Note also that you have to use backslashes here because DOS gets confused by forward slashes. If you run this, you will notice that the browser tries to open a Web site named Files”Mozilla… the part of the command after the whitespace. Also, if you try to run this from IDLE, a DOS window appears, but the browser doesn t start until you close that DOS window. All in all, not exactly ideal behavior. Another function that suits the job better is the Windows-specific function os.startfile: os.startfile(r’ c:Program FilesMozilla Firefoxfirefox.exe’) As you can see, os.startfile accepts a plain path, even if it contains whitespace. (That is, don t enclose Program Files in quotes as in the os.system example.) Note that in Windows, your Python program keeps on running after the external program has been started by os.system (or os.startfile), whereas in UNIX, your Python program waits for the os.system command to finish. A BETTER SOLUTION: WEBBROWSER The os.system function is useful for a lot of things, but for the specific task of launching a Web browser there s an even better solution: the webbrowser module. It contains a function called open that lets you automatically launch a Web browser to open the given URL. For example, if you want your program to open the Python Web site in a Web browser (either starting a new browser or using one that is already running), you simply use import webbrowser webbrowser.open(’http://www.python.org’) and the page should pop up. Pretty nifty, huh?
You want to have a cheap webhost for your apache application, then check apache web hosting services.

CHAPTER 10 BATTERIES INCLUDED 217 Table 10-3. (Ecommerce web host)

Wednesday, May 21st, 2008

CHAPTER 10 BATTERIES INCLUDED 217 Table 10-3. Some Important Functions and Variables in the os Module Function/Variable Description environ Mapping with environment variables system(command) Executes an OS command in a subshell sep Separator used in paths pathsep Separator to separate paths linesep Line separator (’n', ‘r’, or ‘rn’) urandom(n) Returns n bytes of cryptographically strong random data Tip A useful function for traversing directories is os.walk. Check it out in the Python Library Reference. The mapping os.environ contains environment variables described earlier in this chapter. For example, to access the environment variable PYTHONPATH, you would use the expression os.environ[’PYTHONPATH’]. This mapping can also be used to change environment variables, although not all platforms support this. The function os.system is used to run external programs. There are other functions for executing external programs, including execv, which exits the Python interpreter, yielding control to the executed program, and popen, which creates a file-like connection to the program. For more information about these functions, consult the standard library documentation. Tip The subprocess module is a recent addition to Python, which collects the functionality of the os.system, execv, and popen functions. The module variable os.sepis a separator used in pathnames. The standard separator in UNIX is ‘/’, the standard in Windows is ‘\’ (the Python syntax for a single backslash), and in Mac OS, it is ‘:’. (On some platforms, os.altsep contains an alternate path separator, such as ‘/’ in Windows.) You use os.pathsep when grouping several paths, as in PYTHONPATH. The pathsep is used to separate the pathnames: ‘:’ in UNIX, ‘;’ in Windows, and ‘::’ in Mac OS. The module variable os.linesep is the line separator string used in text files. In UNIX this is a single newline character (’n'), in Mac OS it s a single carriage return character (’r'), and in Windows it s the combination of a carriage return and a newline (’rn’). The urandom function uses a system-dependent source of real (or, at least, cryptographically strong) randomness. If your platform doesn t support it, you ll get a NotImplementedError.
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.