From adamg@mailbox.hu Tue Apr 1 03:18:01 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Tue Apr 1 03:18:01 2003 Subject: [Tutor] Re: implementing relationship between objects Message-ID: >My question too: tell us a bit more about what you want to accomplish. And >consider, based on what you've told us so far, using a database to manage >these relationships, as that's what (inter alia) they're good at. My problem is that I'm trying to move from relational data storage to object oriented. Currently I'm trying to use ZODB as persistence, but as I know ZODB does not provide 'relations' or 'referential integrity' and such things. It simply 'stores' my objects. So I have to implement somehow all these 'basic' things. (Or is there any module or package to accomplish this?). This is the background of the question. My current 'basic' problem is how to implement the 'relations' in python cleverly. Let's say I have a car which has some main parts: car[part1] = 1 piece part(chassis) car[part2] = 1 piece part(engine) car[part3] = 4 piece part(wheels) car[part4] = 2 piece part(seat) Thank you, Adam From adamg@mailbox.hu Tue Apr 1 03:33:02 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Tue Apr 1 03:33:02 2003 Subject: [Tutor] how to do a (special) sorted list Message-ID: Dear all, As I wrote in 'implementing relationship between objects' I'm trying to move from relational data storage to object oriented. The second problem is to implement a sorted list with the following options: 1. The items should not be 'unique' as they are with a dict or ZODB.BTree. 2. Items should be accessible with the key (this is really simple) 3. Items should be accessible with a sequence number 4. After <3> is working it's easy to implement a 'first', 'last', 'next', 'prev' method to walk the list Is there maybe any module or package to accomplish this? Thanx, Adam From bkd@graphnet.com Tue Apr 1 03:35:03 2003 From: bkd@graphnet.com (noc) Date: Tue Apr 1 03:35:03 2003 Subject: [Tutor] creating variable names from string slices Message-ID: <021e01c2f828$16876ef0$5102020a@graphnet.com> I have not been able to find the magic combination of keywords that will guide me to the page for a recipe that shows me how to do this. I'm telnetting to a mainframe, and capturing a screendump of data that's neatly column formatted: Betty Blonde Student Veronica Brunette Student Ginger Redhead Castaway Maryann Brunette Castaway What I want to do is define a function that gets passed each line, and returns a dictionary with the first element as the name, and the subsequent elements as the key:value pairs: (since the data is already in a nifty columnar form, I'll just be slicing the elements out of the string) Betty == {'haircolor':'Blonde', 'role':'Student'} Veron == {'haircolor':'Brunett', 'role':'Student'} Ginge == {'haircolor':'Redhea', 'role':'Castawa'} Marya == {'haircolor':'Brunett', 'role':'Castawa'} How do I make this trick work? Bruce From Janssen@rz.uni-frankfurt.de Tue Apr 1 05:16:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Apr 1 05:16:02 2003 Subject: [Tutor] creating variable names from string slices In-Reply-To: <021e01c2f828$16876ef0$5102020a@graphnet.com> Message-ID: On Tue, 1 Apr 2003, noc wrote: > How do i make this trick work? simply forget such tricks! Do not stuff arbitrary data into your global namespace (Or what will you do, when one of those pretties are called "str" or "SystemExit"? ;-) E.g. you can put it into a list (or a dictionary of dictionaries or whatever suits your purpose best): data = [{'name':'Betty', 'haircolor':'Blonde', 'role':'Student'}, {'name': 'Veron', 'haircolor':'Brunett', 'role':'Student'}, {'name': 'Ginge', 'haircolor':'Redhea', 'role':'Castawa'}, {'name': 'Marya', 'haircolor':'Brunett', 'role':'Castawa'}, ] Michael From alan.gauld@bt.com Tue Apr 1 07:23:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 07:23:01 2003 Subject: [Tutor] implementing relationship between objects Message-ID: > How would you implement in python a 'relational' 1:1, 1:N, N:N > relationship between objects? 1:1 A simple reference in each object. Since Python varable names are references there is no need for anything else. 1:N One object holds a list(or dictionary) of references. Potentially each object in the list holds a reference to the "parent" - this is what the widgets in the Tkinter containment tree do. N:N Usually best modelled by an explicit mapping object, either a dictionary of lists or a pair of dictionaries for two way lookup. Perhaps wrapping it in a class with appropriate methods to maintain consistency. This is by far the hardest of the scenarios. > Of course both 'sides' should know about the other and changing one > 'side' of the relation should affect the other side (kind of referetial > integrity). The manipulation would normally be done by the methods of the objects. It depends on exactly how much coupling you need/want. eg. A<->B Change A to refer to C, implies what? That B be set to None? (what if there is a contraint that B always points to something - do we delete B or return failure?) And as part of setting C as the new reference from A we need to set C to refer to A. So we wind up with: A->C C->A B->None (or is deleted?) These are application level decisions. The choices will be reflected in the implementation of the methods. Python is not a relational database and if thats the behaviour you need you would be best using an RDBMS IMHO. The usual rules of OO Design apply - work out what you want the objects to do and implement that. Do not build some generic function and then bend the problem to suit. (Unless of course the generic solution is the problem you are trying to solve, in which case expect a lot of pain - generic solutions are invariably difficult!) Alan G. From alan.gauld@bt.com Tue Apr 1 07:46:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 07:46:01 2003 Subject: [Tutor] If not global, how? Message-ID: > class EntryClass(Pmw.EntryField): > def __init__(self, parent=0): > > def SendCommand(command): > for command in ('\x09','\x06'): > .... > old=outputbox.getvalue() > .... > > def Callback(self): > value=self.getvalue() > if value: SendCommand(value) First of all you show sendCommand as part of the class (by the indentation) but it doesn't have a self parameter. It does have a command parameter so python will think that 'command' is the self value(self is just a naming convention, you can call the first paramerter in a method anything you like!). I don't think that's what you want, rather you want to put sendCommand function outside the class. Second within sendCommand you refer to outputbox - where is this defined? Its not part of the Entry class not in sendCommand itself? I suspect you want to pass outputbox into sendCommamd as an argument. If you move sendCommand out of the class and add the outputbox as a parameter then your Callback should work fine since it will see sendCommand as a global function - although you need to find a way for sendCommand to locate the right outputbox!. Without really knowing what your GUI design is like its kind of hard to know the solution. I'm inclined to go back to first principles and ask what the responsibility of your Entryclass is? Normally an Entry Class stores and retrieves text. Thats it. End of story. Now you are subclassing the Entry to add what capability? What will be different about your EntryClass from the standard one? If you are trying to link the entryClass to sending (or receiving) data along a port then maybe its a PortEntry class and it should have a reference to the port in the class. But if thats the case then it seems likely the outputbox needs to be involved somewhere too? So, is the EntryClass tied to a single specific outputbox? If so add a reference to it in your class and pass it in as an argument to init(). You can then pass it out to sendCommand() from your callback. If OTOH there are multiple output boxes and ports then it gets much more complicated and I think we need to step back and look at the bigger picture of whats required. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Apr 1 07:57:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 07:57:01 2003 Subject: [Tutor] Events in tkinter Message-ID: > How can I create the following event using classes? > > I want to type "control o", for example, and it call this function. It seems to me that classes is kind of irrelevant to the question, why do you think that classes are needed? What you need to do is bind the keypress even of some widget to the open function (but please rename it coz there are already open() functions in Python and that will get very confusing!) As an example of catching ctrl characters from a Tk widget take a look at my Event Driven Programming tutor topic (it also uses classes FWIW). Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Tue Apr 1 08:05:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 08:05:02 2003 Subject: [Tutor] how to do a (special) sorted list Message-ID: > The second problem is to implement a sorted list with the > following options: It looks like a standard Python list with the twist of sorting itself after every addition.(Which could become slow BTW!) You could create a class to do that either subclassing from the standard list or, I think thee is a UserList which is specifically designed for this. Then override the insert/append/assign operations to call the standard variant followed by a sort() call. Alan g From alan.gauld@bt.com Tue Apr 1 08:07:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 08:07:02 2003 Subject: [Tutor] creating variable names from string slices Message-ID: > Betty Blonde Student > Veronica Brunette Student > > What I want to do is define a function that gets passed each line, and > returns a dictionary with the first element as the name, and > the subsequent elements as the key:value pairs: Split the line then assign the firstvelement as the key and the rest as the value. Something like: words = line.split() data[words[0]] = words[1:] > How do I make this trick work? Split the string rather than using slicing. You probably want to strip() any whitespace off the words before inserting them too... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From gyromagnetic@excite.com Tue Apr 1 08:32:01 2003 From: gyromagnetic@excite.com (gyro funch) Date: Tue Apr 1 08:32:01 2003 Subject: [Tutor] Re: how to do a (special) sorted list Message-ID: <20030401133119.D101613408@xmxpita.excite.com> alan.gauld@bt.com wrote: >>The second problem is to implement a sorted list with the >>following options: > > > It looks like a standard Python list with the twist of sorting itself > after every addition.(Which could become slow BTW!) > > You could create a class to do that either subclassing from the standard > list or, I think thee is a UserList which is specifically designed for > this. Then override the insert/append/assign operations to call the > standard variant followed by a sort() call. > > Alan g > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Check out the 'bisect' module. It contains functions that can insert items in a list in such a way as to maintain sorted order. I expect that an initial sort (using Python's very fast sort implementation), followed by inserts using bisect.insort() wouldn't be too shabby. -g _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From Jaco.Smuts@za.didata.com Tue Apr 1 08:39:02 2003 From: Jaco.Smuts@za.didata.com (Jaco Smuts (ZA)) Date: Tue Apr 1 08:39:02 2003 Subject: [Tutor] python accounting package Message-ID: <862D79D0DADB244E8563C6F9277C02FF022C1191@zabrysvcl01ex01.af.didata.local> Hello there I'm playing with the idea of writing my own little accounting app to automate my personal business accounting. (Very simple). Is anyone aware of any Python accounting stuff that I could use (not to re-invent the wheel). I've come across the double talk stuff from the win32 programming book and a python erp project (but the accounting bit boils down to a proposal doc written some time ago). I also plan on using MySQL. Any information will be greatly appreciated. regards jaco ps. please excuse the disclaimer, I have no control over it...... *************************************************************************************** This message contains information intended solely for the addressee, which is confidential or private in nature and subject to legal privilege. If you are not the intended recipient, you may not peruse, use, disseminate, distribute or copy this message or any file attached to this message. Any such unauthorised use is prohibited and may be unlawful. If you have received this message in error, please notify the sender immediately by e-mail, facsimile or telephone and thereafter delete the original message from your machine. Furthermore, the information contained in this message, and any attachments thereto, is for information purposes only and may contain the personal views and opinions of the author, which are not necessarily the views and opinions of Dimension Data (South Africa) (Proprietary) Limited or its subsidiaries and associated companies ("Dimension Data"). Dimension Data therefore does not accept liability for any claims, loss or damages of whatsoever nature, arising as a result of the reliance on such information by anyone. Whilst all reasonable steps are taken to ensure the accuracy and integrity of information transmitted electronically and to preserve the confidentiality thereof, Dimension Data accepts no liability or responsibility whatsoever if information or data is, for whatsoever reason, incorrect, corrupted or does not reach its intended destination. ************************************************************************************* From magnus@thinkware.se Tue Apr 1 09:22:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Apr 1 09:22:01 2003 Subject: OT: spaces WAS: Re: [Tutor] about regular expression In-Reply-To: <20030327170006.26495.24622.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030401161054.02ab3ce8@www.thinkware.se> At Thu, 27 Mar 2003 04:12:58 -0600 Jerry Jorgenson wrote: >Strictly speaking, it depends on the typeface you use. The "two spaces" >were evented because a typewriter has a fixed font and the letters don't >have the same space between them, instead each letter takes up the same >amount of space (an "i" takes the same space as an "m"), so the extra >space was required. I looked in some old books, that are pre D.T.P., i.e. made with traditional lead types. The ones from the 1940's or 1950's are all with the same space between senteces as between words. The ones I found that were older than that (1903 and 1929) had roughly twice the distance between sentences as between words. That can hardly be attributed to typewriters. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From ATrautman@perryjudds.com Tue Apr 1 09:57:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue Apr 1 09:57:02 2003 Subject: OT: spaces WAS: Re: [Tutor] about regular expression Message-ID: <06738462136C054B8F8872D69DA140DB010726@corp-exch-1.perryjudds.com> At Thu, 27 Mar 2003 04:12:58 -0600 Jerry Jorgenson wrote: >Strictly speaking, it depends on the typeface you use. The "two spaces" >were evented because a typewriter has a fixed font and the letters don't >have the same space between them, instead each letter takes up the same >amount of space (an "i" takes the same space as an "m"), so the extra >space was required. I looked in some old books, that are pre D.T.P., i.e. made with traditional lead types. The ones from the 1940's or 1950's are all with the same space between senteces as between words. [Alan] The 45's (post WWII when higher speed film became common) through 60's (70's if you worked at a dinosaur shop) books were probably made using a negative film to positive film transfer technique where a single lead screw controlled the x-axis motion. The amount of rotation was controlled by the key press. The film and silver were very expensive so the amount of spaces before a paragraph were reduced and I believe that would account for the single spaces in books meant for mass manufacture. Large scale romance novels (I assume other low cost paper backs) still have special software for realigning text to get more word per page as long as it reduces page count and give good chapter breaks. This can reduce the printing costs amazingly. [Alan] The ones I found that were older than that (1903 and 1929) had roughly twice the distance between sentences as between words. That can hardly be attributed to typewriters. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From Bruce Dykes" Message-ID: <03ef01c2f85f$652b6700$5102020a@graphnet.com> ----- Original Message ----- From: To: ; Sent: Tuesday, April 01, 2003 08:05 Subject: RE: [Tutor] creating variable names from string slices > > Betty Blonde Student > > Veronica Brunette Student > > > > What I want to do is define a function that gets passed each line, and > > returns a dictionary with the first element as the name, and > > the subsequent elements as the key:value pairs: > > Split the line then assign the firstvelement as the key and the rest as the > value. > Something like: > > words = line.split() > data[words[0]] = words[1:] > > > How do I make this trick work? > > Split the string rather than using slicing. You probably want to strip() > any whitespace off the words before inserting them too... Hrrmm....I've actually decided to follow Michael's advice, as the dictionaries will be bundled up into a list anyway, and it really doesn't matter if the list is [a, b, c] or [{'name':'a'}, {'name':'b'}, {'name':'c'}]. Or does it? But back to your solution, the data is columnar, and some of the fields are empty, so I think I would have to modify your snippet above: words=line.split() dictionaryname[words[0]]={} dictionaryname[haircolor]=line[5:10] dictionaryname[role]=line[15:20] Yes? Bruce From garnaez@yahoo.com Tue Apr 1 10:11:08 2003 From: garnaez@yahoo.com (Gerardo Arnaez) Date: Tue Apr 1 10:11:08 2003 Subject: [Tutor] iterators generators Message-ID: <20030401151044.95165.qmail@web20204.mail.yahoo.com> Hi all, I've been learning a lot, really enjoyed list comprehesions. but cant seem to get my head around iterators and generators, anyone know of any good reading, Ive read the PEP's and just didnt grok it I also read the IBM Charming python and again failed to grok it G __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more http://platinum.yahoo.com From charlie@begeistert.org Tue Apr 1 10:39:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Tue Apr 1 10:39:01 2003 Subject: [Tutor] Getting at object names Message-ID: <20030401174018.4874.21@wonderland.1049185264.fake> Dear list, I've started using dispatching via a dictionary which is really nice but I came across a problem which I couldn't solve easily and would appreciate your help. imagine this: friday = [] saturday = [] sunday = [] days = {'1': friday, '2': saturday, '3': sunday} # the lists are then filled d = days.keys d.sort for day in d: print days[day].__name__, days[day], Now I know the last line doesn't work because __name__ isn't an attriubute of the list. But is it possible to get at the name of the list? Thanx very much Charlie From adamg@mailbox.hu Tue Apr 1 10:50:04 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Tue Apr 1 10:50:04 2003 Subject: [Tutor] Re: how to do a (special) sorted list In-Reply-To: <20030401133119.D101613408@xmxpita.excite.com> Message-ID: What should I do when I have to delete an item? Simply issue list.remove(item) or are there some faster things? Adam -----Original Message----- [snip] >Then override the insert/append/assign operations to call the > standard variant followed by a sort() call. [snip] Check out the 'bisect' module. It contains functions that can insert items in a list in such a way as to maintain sorted order. [snip] From brian@dungeoncrawl.org Tue Apr 1 11:02:01 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Tue Apr 1 11:02:01 2003 Subject: [Tutor] Floats as dictionary keys Message-ID: <5.2.0.9.0.20030401105705.00adecf0@localhost> I've got this code: def getSortedKeys(dictionary): keys = dictionary.keys() keys.sort() return keys def findAverage(dice, sides): # returns a float, details not important diceFirst = {} averagesFirst = {} for dice in range(5)[1:]: for sides in [4, 6, 8, 10, 12]: average = findAverage(dice, sides) diceString = "%dd%2d" % (dice, sides) diceFirst[diceString] = average averagesFirst[average] = diceString for key in getSortedKeys(diceFirst): print key + ": " + str(diceFirst[key]) for key in getSortedKeys(averagesFirst): print str(averagesFirst[key]) + ": " + key The problem I have is that the floats get turned into strings and get sorted wrong. The output I get for the second loop looks like this: 4d10: 10.7147 3d12: 11.1702 4d12: 12.2725 1d 4: 3.3886 1d 6: 4.2657 2d 4: 4.6639 1d 8: 5.0885 3d 4: 5.6046 2d 6: 5.783 1d10: 6.1249 4d 4: 6.2817 3d 6: 6.8376 2d 8: 7.0938 1d12: 7.1222 4d 6: 7.6049 3d 8: 8.2827 2d10: 8.3605 4d 8: 9.1556 3d10: 9.6382 2d12: 9.745 Is there any way to force the dictionary not to stringize my float values? -- "Words are poison." - Nick on love From bgailer@alum.rpi.edu Tue Apr 1 11:48:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue Apr 1 11:48:01 2003 Subject: [Tutor] Getting at object names In-Reply-To: <20030401174018.4874.21@wonderland.1049185264.fake> Message-ID: <5.2.0.9.0.20030401092740.01a12710@66.28.54.253> --=======1A7D2F32======= Content-Type: text/plain; x-avg-checked=avg-ok-F9A4B05; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 05:40 PM 4/1/2003 +0200, Charlie Clark wrote: >friday = [] >saturday = [] >sunday = [] > >days = {'1': friday, '2': saturday, '3': sunday} > ># the lists are then filled > >d = days.keys Should be d = days.keys() >d.sort Should be d.sort() >for day in d: > print days[day].__name__, days[day], Are you wanting the output to look like: friday [1, 2, 3] saturday [6] sunday [4, 5]? That can't be done easily the way you've structured things. The lists don't have names. What's in the dictionary are references to the lists, and the variables friday, sturday and sunday are also references to the lists. You could get at the variable names by searching thru globals() and comparing ids, but that's messy. OOP to the rescue! #subclass list and give it a name attribute: class day(list): def __init__(self, name): self.name = name def set(self, items): self[:] = items # create the list objects and give them names friday = day('friday') saturday = day('saturday') sunday = day('sunday') # fill the lists friday.set([1,2,3]) saturday.set([4,5]) sunday.set([6]) days = {'1': friday, '2': saturday, '3': sunday} d = days.keys() d.sort() for day in d: print days[day].name, days[day], Note there are many other ways to fill the lists besides my set() method. Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======1A7D2F32======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-F9A4B05 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======1A7D2F32=======-- From magnus@thinkware.se Tue Apr 1 12:09:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Apr 1 12:09:02 2003 Subject: [Tutor] Creating a database In-Reply-To: <20030331170006.18810.61682.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030401174333.02ab4038@www.thinkware.se> At Sun, 30 Mar 2003 11:10:44 -0600 Billie wrote: >Well, I'm off on a project, and want to know if Python will do the trick. Certainly. I just made something similar to keep track of our whisky tasting notes. :) http://www.thinkware.se/whisky/whisky.cgi >I'm wanting to create a web page that lists names, addresses and phone >numbers, and I want it to be storable. Since I had access to MySQL at my web site, and know SQL well, I used that, but there are many options. Relational databases like MySQL etc are able to handle several simultaneous users, but that might not be an issue. It depends on your situation. A solution which is rather neat if the list is fairly small, is to use pickle, to turn python objects into something you can store directly in a file. It's explained well in Patrick O'Brien's article at IBM http://www-106.ibm.com/developerworks/library/l-pypers.html , but I'll give you a small example that you can play with. First, we make an initial pickle of a list. >>> f = file('test.pkl', 'w') # Open file for writing >>> import cPickle as pickle >>> l = [] >>> help(pickle.dump) Help on built-in function dump: dump(...) dump(object, file, [binary]) --Write an object in pickle format to the given file If the optional argument, binary, is provided and is true, then the pickle will be written in binary format, which is more space and computationally efficient. >>> pickle.dump(l,f) Lets use the ASCII format for now. Clarity is more important then performance most of the time. The file now looks like this: (lp1 . Not much, but it's just an empty list... Now, lets make a program that adds something to the list, and another that reads it. Naturally, they can be combined if we wish. Reading seems simple, lets start with that... # pickleprint.py import cPickle as pickle f = file('test.pkl', 'r') l = pickle.load(f) for e in l: print e I think it's working. It does seem to print nothing when I run it, and that's what I expect. Let's add something to the pickle, and see if I'm right! # pickleadd.py import cPickle as pickle import sys f = file('test.pkl', 'r') l = pickle.load(f) f.close() l.append(sys.argv[1]) f = file('test.pkl', 'w') pickle.dump(l, f) Let's try it out: H:\python>pickleadd.py "Hello There" H:\python>pickleprint.py Hello There H:\python>pickleadd.py "Add some more?" H:\python>pickleprint.py Hello There Add some more? H:\python>pickleadd.py "This seems to work" H:\python>pickleprint.py Hello There Add some more? This seems to work There! We now have a basic persistence mechanism. So, what does our file look like? H:\python>more test.pkl (lp1 S'Hello There' aS'Add some more?' aS'This seems to work' p2 a. Not too bad, but it's nice that we don't have to care... :) In your case, you would probably want to have a list of tuples, something like this: [('Al', 'Capone', 'Gangster', 'al@chicago.danger.com'), ('Billie', 'Holliday', 'Singer', 'billie@hmv.co.uk')] If you have some kind of well defined key, you would use a dictionary instead. I'd suggest than you put all the functions involved in pickle in a separate file, i.e. module. Let's call it pickletab.py. Give it a generic interface, and you will be able to switch to another storage method (maybe SQL?) later, without changing more than that file. (Modularity is a good thing) With just one simple table, I can imagine an API looking like this: import pickletab as db ... db.add(aTuple) db.remove(aTuple) db.list(sortColumn) This is the minimal version. (Where updating means remove old version followed by add new version.) Of course, I couldn't help myself, but wrote such a module. It just took me 20 minutes or so--it shouldn't be impossible for a beginner, but tell me if you want to "cheat" ;) There's a lot lets before you are done... > Being new, first I'm sure it's >possible, second, is it very difficult (I shouldn't think so, but am still >asking). I remember making sorted lists in BASIC, but I want this where the >user clicks and chooses their preference. For sorting on varying columns, it's most convenient to use the so-called Decorate-Sort-Undecorate method. I think Id use a single integer as parameter, with its absolute value indicating column, and its sign indicating direction. So db.list(2) would mean "sort on the second column, first to last), and db.list(-3) would mean "sort on third column, last to first". But let's leave this for later. >Am I taking on more than I'm ready for? I like challenges, but must have a >bit of reality in check, also. Think modular. Solve one piece at a time. I think you can do this. I'd start with something that works on the command line first, and add web features later. CGI-scripts are a bit tricky to debug, since they are run from the webserver with different settings and permissions than your normal session. (The new cgitb module is very helpful though...) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld@bt.com Tue Apr 1 12:34:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 12:34:01 2003 Subject: [Tutor] creating variable names from string slices Message-ID: > But back to your solution, the data is columnar, and some of > the fields are empty, Ah! You omitted that last little detail earlier! :-) > so I think I would have to modify your snippet above: In that case I'd use slicing to split the row as you suggested. The list of dictionaries approach is Ok but gives a very different solution to what you asked for.... Alan g. From alan.gauld@bt.com Tue Apr 1 12:41:08 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 12:41:08 2003 Subject: [Tutor] Getting at object names Message-ID: > friday = [] > saturday = [] > sunday = [] > > days = {'1': friday, '2': saturday, '3': sunday} > > # the lists are then filled > > d = days.keys > d.sort > > for day in d: > print days[day].__name__, days[day], > > Now I know the last line doesn't work because __name__ isn't > an attriubute of the list. But is it possible to get at the name of the list? No, because its just a symbol in the program (OK you could read the local namespace dictionary but that's messy and not to be encouraged! Why not just associate the dayname with the key? days = {1:('friday',friday),2:('saturday',saturday).....} for day in d print days[day][0],days[day][1] Alan G. From lobow@brturbo.com Tue Apr 1 12:43:01 2003 From: lobow@brturbo.com (Diego Prestes) Date: Tue Apr 1 12:43:01 2003 Subject: [Tutor] Events in tkinter References: Message-ID: <3E89CF21.1030305@brturbo.com> Tks for the help, I already done the event. I said used this in classes because I maked a simple example and it works but in my program because of the classes it was not working. The names its just an example. I translate for english to be easier for people in the list understand, the names in my program are in portuguese. Diego alan.gauld@bt.com wrote: >>How can I create the following event using classes? >> >>I want to type "control o", for example, and it call this function. >> >> > >It seems to me that classes is kind of irrelevant to the question, >why do you think that classes are needed? > >What you need to do is bind the keypress even of some widget to >the open function (but please rename it coz there are already >open() functions in Python and that will get very confusing!) > >As an example of catching ctrl characters from a Tk widget take >a look at my Event Driven Programming tutor topic (it also uses >classes FWIW). > >Alan g. >Author of the Learn to Program website >http://www.freenetpages.co.uk/hp/alan.gauld/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From jlohman@cox.net Tue Apr 1 12:43:18 2003 From: jlohman@cox.net (jlohman@cox.net) Date: Tue Apr 1 12:43:18 2003 Subject: [Tutor] Searching for text while ignoring case Message-ID: <20030401174206.UYL22936.fed1mtao04.cox.net@smtp.west.cox.net> How do I make a command like FIND() search for text strings in a line and can recognize them regardless of case? A word like "puppy" would be "Puppy" sometimes if it started a sentence. However, a search for "puppy" will miss "Puppy". How do I make text search case-insensitive? Surely this is a common task and there should be a command to deal with it...but I cannot find it. -Jeff From dyoo@hkn.eecs.berkeley.edu Tue Apr 1 12:46:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 1 12:46:09 2003 Subject: [Tutor] please help In-Reply-To: <20.df5196c.2bba575e@aol.com> Message-ID: On Mon, 31 Mar 2003 GREENDAY31087@aol.com wrote: > Concerning py2exe: I think I'm doing this right but it still wont work > for me. I have the setup file and the script file. here they are: > > # setup.py > from distutils.core import setup > import py2exe > > setup(name="test", > scripts=["test.py"], > ) > > > #test.py > print "THIS IS A TEST" > > And When I start the setup program, it says: > usage: test.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: test.py --help [cmd1 cmd2 ...] > or: test.py --help-commands > or: test.py cmd --help > error: no commands supplied Hello! Hmmm... One important thing you need to mention is how you're starting up the setup program. According to: http://py2exe.sourceforge.net/ your command should look something like: python setup.py py2exe That third part --- 'py2exe' --- is important. You may have just typed the first two parts: python setup.py because I can duplicate a similar kind of error message if I leave it off: ### [dyoo@tesuque dyoo]$ python setup.py usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: no commands supplied ### ... But if we take a close look at your error message, it's mentioning 'test.py' rather than 'setup.py'! Can you make sure you haven't interchanged the files accidently? 'setup.py' itself should be the only file to contain that distutils import and that call to setup(). > Am I missing something that's completely obvious? I apologize for being > kinda thick but I'm trying to get it to work. Thanks py2exe is a bit specialized, but I think there are enough folks here that have fiddled with it. Please feel free to ask questions about it, and we'll do what we can to help make it less aggrevating. Good luck! From alan.gauld@bt.com Tue Apr 1 12:52:12 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Apr 1 12:52:12 2003 Subject: [Tutor] Floats as dictionary keys Message-ID: > def getSortedKeys(dictionary): > keys = dictionary.keys() > keys.sort() > return keys > ... > for dice in range(5)[1:]: > average = findAverage(dice, sides) > diceString = "%dd%2d" % (dice, sides) > diceFirst[diceString] = average So you make a string and use it as the key. The same key that getSortedKeys() uses to sort. > for key in getSortedKeys(diceFirst): > print key + ": " + str(diceFirst[key]) And here you print out the value converted to a string. > The problem I have is that the floats get turned into strings and get > sorted wrong. The output I get for the second loop looks like this: But you aren't sorting by value you are sorting by keys which you explicitly force to be strings. I don't understand. > Is there any way to force the dictionary not to stringize my > float values? It doesn't appear to be stringizing them, you do that when you print them. I think I'm missing something? Alan g. From jeff@ccvcorp.com Tue Apr 1 13:24:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Apr 1 13:24:01 2003 Subject: [Tutor] creating variable names from string slices References: <021e01c2f828$16876ef0$5102020a@graphnet.com> Message-ID: <3E89D966.6030305@ccvcorp.com> noc wrote: >I'm telnetting to a mainframe, and capturing a screendump of data that's >neatly column formatted: > >[...] >What I want to do is define a function that gets passed each line, and >returns a dictionary with the first element as the name, and the subsequent >elements as the key:value pairs: > Something like this, perhaps? First, we get the imported data into a list of lines: >>> import pprint >>> captured = """Betty Blonde Student ... Veronica Brunette Student ... Ginger Redhead Castaway ... Maryann Brunette Castaway""" >>> lines = captured.split('\n') >>> pprint.pprint(lines) ['Betty Blonde Student', 'Veronica Brunette Student', 'Ginger Redhead Castaway', 'Maryann Brunette Castaway'] >>> Now, we write a function that deals with a single line. Since we know the structure of the line, we can take advantage of that fact. >>> def processline(line): ... fields = ['haircolor', 'role'] ... line = line.split() ... fielddata = zip(fields, line[1:]) ... return line[0], dict(fielddata) ... >>> This function returns a tuple of a name (the first column of input) and a dictionary that's constructed from the second and subsequent columns, along with the column names. (If we wanted to get fancy, we might build the list of fields from the first line of our input, reading column headers, but for now I'm just using a statically defined list of fields.) Now all we have to do is run each line through this function, and store the results. >>> data = {} >>> for line in lines: ... name, info = processline(line) ... data[name] = info ... >>> pprint.pprint(data) {'Betty': {'haircolor': 'Blonde', 'role': 'Student'}, 'Ginger': {'haircolor': 'Redhead', 'role': 'Castaway'}, 'Maryann': {'haircolor': 'Brunette', 'role': 'Castaway'}, 'Veronica': {'haircolor': 'Brunette', 'role': 'Student'}} >>> Looks about right to me! Depending on how you're using this data, it might also be practical to define a class, and make each line into an instance of that class, with attributes named 'haircolor' and 'role'. >>> class Girl: ... def __init__(self, name, haircolor, role): ... self.name = name ... self.haircolor = haircolor ... self.role = role ... >>> def processline(line): ... instance = Girl(*line.split()) ... return instance.name, instance ... >>> Note the use of '*line.split()' to feed arguments to Girl. This has the effect of passing each element of the list returned by line.split() as an individual parameter, rather than as an aggregated list. Now we can process each line, and do whatever with the resulting objects. >>> data = {} >>> for line in lines: ... name, info = processline(line) ... data[name] = info ... >>> pprint.pprint(data) {'Betty': <__main__.Girl instance at 0x01608918>, 'Ginger': <__main__.Girl instance at 0x0162D710>, 'Maryann': <__main__.Girl instance at 0x01622690>, 'Veronica': <__main__.Girl instance at 0x015EF3C8>} >>> for item in data.values(): ... print item.name, item.role ... Veronica Student Betty Student Ginger Castaway Maryann Castaway >>> Jeff Shannon Technician/Programmer Credit International From Janssen@rz.uni-frankfurt.de Tue Apr 1 13:45:06 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Apr 1 13:45:06 2003 Subject: [Tutor] Searching for text while ignoring case In-Reply-To: <20030401174206.UYL22936.fed1mtao04.cox.net@smtp.west.cox.net> Message-ID: On Tue, 1 Apr 2003 jlohman@cox.net wrote: > How do I make a command like FIND() search for text strings in a line > and can recognize them regardless of case? A word like "puppy" would > be "Puppy" sometimes if it started a sentence. However, a search for > "puppy" will miss "Puppy". > > How do I make text search case-insensitive? Surely this is a common > task and there should be a command to deal with it...but I cannot find > it. two opportunities: * lower() both line and searchstring (or upper() - just what you like better) * search() from re-modul with flag re.IGNORECASE: mt = re.search(search_string, line, re.IGNORECASE) if mt: # search string was found mt.group() Michael > > -Jeff > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From emile@fenx.com Tue Apr 1 13:59:02 2003 From: emile@fenx.com (Emile van Sebille) Date: Tue Apr 1 13:59:02 2003 Subject: [Tutor] Re: Searching for text while ignoring case References: <20030401174206.UYL22936.fed1mtao04.cox.net@smtp.west.cox.net> Message-ID: jlohman@cox.net asks, > How do I make a command like FIND() search for text > strings in a line and can recognize them regardless > of case? A word like "puppy" would be "Puppy" sometimes > if it started a sentence. However, a search for "puppy" > will miss "Puppy". > Here's one way: >>> text = "Testing, one, two, three, testing." >>> text.find("testing") 26 >>> text.upper().find("testing".upper()) 0 >>> (Remember that -1 indicates no match with find) -- Emile van Sebille emile@fenx.com --------- From jeff@ccvcorp.com Tue Apr 1 14:04:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Apr 1 14:04:01 2003 Subject: [Tutor] Floats as dictionary keys References: <5.2.0.9.0.20030401105705.00adecf0@localhost> Message-ID: <3E89E2A8.5050701@ccvcorp.com> Brian Christopher Robinson wrote: > Is there any way to force the dictionary not to stringize my float > values? It doesn't -- you're doing that yourself somehow. Cutting and pasting the results you showed into another dictionary gives me this: >>> pprint.pprint(averagesfirst) {3.3885999999999998: '1d 4', 4.2656999999999998: '1d 6', 4.6638999999999999: '2d 4', 5.0884999999999998: '1d 8', 5.6045999999999996: '3d 4', 5.7830000000000004: '2d 6', 6.1249000000000002: '1d10', 6.2816999999999998: '4d 4', 6.8376000000000001: '3d 6', 7.0937999999999999: '2d 8', 7.1222000000000003: '1d12', 7.6048999999999998: '4d 6', 8.2827000000000002: '3d 8', 8.3605: '2d10', 9.1555999999999997: '4d 8', 9.6381999999999994: '3d10', 9.7449999999999992: '2d12', 10.714700000000001: '4d10', 11.170199999999999: '3d12', 12.272500000000001: '4d12'} >>> Now, using essentially the same code as you showed, I get them sorted in proper numeric order: >>> def GetSortedKeys(adict): ... keys = adict.keys() ... keys.sort() ... return keys ... >>> for key in GetSortedKeys(averagesfirst): ... print '%4s : %8.5f' % (averagesfirst[key], key) ... 1d 4 : 3.38860 1d 6 : 4.26570 2d 4 : 4.66390 1d 8 : 5.08850 3d 4 : 5.60460 2d 6 : 5.78300 1d10 : 6.12490 4d 4 : 6.28170 3d 6 : 6.83760 2d 8 : 7.09380 1d12 : 7.12220 4d 6 : 7.60490 3d 8 : 8.28270 2d10 : 8.36050 4d 8 : 9.15560 3d10 : 9.63820 2d12 : 9.74500 4d10 : 10.71470 3d12 : 11.17020 4d12 : 12.27250 >>> I'm not sure why the results you show are different -- perhaps they were generated with a different version of the code than what you posted? In any case, though, unless you're doing more with these dictionaries later, you might be better off generating a single list or dictionary of two-tuples, which might be easier to fiddle with. >>> averages = {} >>> for dice in range(1,5): # note the use of a start param for range ... for sides in [4, 6, 8, 10, 12]: ... avg = findAverage(dice, sides) ... diceString = "%dd%2d" % (dice, sides) ... averages[diceString] = (avg, diceString) ... >>> averageslist = averages.values() >>> averageslist.sort() >>> for avg, dice in averageslist: ... print '%4s : %8.5f' % (dice, avg) ... 1d 4 : 3.38860 1d 6 : 4.26570 2d 4 : 4.66390 1d 8 : 5.08850 3d 4 : 5.60460 2d 6 : 5.78300 1d10 : 6.12490 4d 4 : 6.28170 3d 6 : 6.83760 2d 8 : 7.09380 1d12 : 7.12220 4d 6 : 7.60490 3d 8 : 8.28270 2d10 : 8.36050 4d 8 : 9.15560 3d10 : 9.63820 2d12 : 9.74500 4d10 : 10.71470 3d12 : 11.17020 4d12 : 12.27250 >>> templist = [(value, key) for key, value in averageslist] >>> templist.sort() >>> for dice, avg in templist: ... print '%4s : %8.5f' % (dice, avg) ... 1d 4 : 3.38860 1d 6 : 4.26570 1d 8 : 5.08850 1d10 : 6.12490 1d12 : 7.12220 2d 4 : 4.66390 2d 6 : 5.78300 2d 8 : 7.09380 2d10 : 8.36050 2d12 : 9.74500 3d 4 : 5.60460 3d 6 : 6.83760 3d 8 : 8.28270 3d10 : 9.63820 3d12 : 11.17020 4d 4 : 6.28170 4d 6 : 7.60490 4d 8 : 9.15560 4d10 : 10.71470 4d12 : 12.27250 >>> Putting both results into a single list or dict gives you a little more flexibility in dealing with the data later,. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Apr 1 14:42:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Apr 1 14:42:02 2003 Subject: [Tutor] Getting at object names References: <20030401174018.4874.21@wonderland.1049185264.fake> Message-ID: <3E89E649.5000209@ccvcorp.com> Charlie Clark wrote: >Now I know the last line doesn't work because __name__ isn't an attriubute >of the list. But is it possible to get at the name of the list? > > Just include the name as part of the dictionary, making the dictionary values a tuple of (string, list): days = {'1': ('friday', []), '2': ('saturday', []), '3': ('sunday', [])} d = days.keys() d.sort() for day in d: name, values = days[d] print '%s : %s' % (name, values) Jeff Shannon Technician/Programmer Credit International From tlo@aw.sgi.com Tue Apr 1 18:01:25 2003 From: tlo@aw.sgi.com (Terence Lo) Date: Tue Apr 1 18:01:25 2003 Subject: [Tutor] smtp.sendmail and xml? Message-ID: <022501c2f8a2$bed6be10$ca411dc6@ms.aliaswavefront.com> hi there i have a question: I'm trying to get use smtp.sendmail to send mail. smtp.sendmail(sender, mailinglist, message.getvalue()) Everything appears to work fine if I define strings sender, mailinglist to be: sender = "user1@aol.com" mailinglist = "user2@aol.com" However, when I fetch the values from XML using xml objectify: sender = config.mailer.sender.PCDATA mailinglist = config.mailer.mailinglist.PCDATA As a sanity test, I even print to screen the vars sender and mailinglist and they both return user1@aol.com and user2@aol.com respectively. But strangely enough, when I execute smtp.sendmail(....) I get the following error: File "C:\Python21\lib\smtplib.py", line 494, in sendmail (code,resp) = self.data(msg) File "C:\Python21\lib\smtplib.py", line 384, in data raise SMTPDataError(code,repl) smtplib.SMTPDataError: (503, 'Need RCPT (recipient)') Anyone know what the heck I'm doing wrong? thx in advance. T From Bruce Dykes" <3E89D966.6030305@ccvcorp.com> Message-ID: <038901c2f91c$a14a3230$5102020a@graphnet.com> ----- Original Message ----- From: "Jeff Shannon" To: Cc: "noc" Sent: Tuesday, April 01, 2003 13:24 Subject: Re: [Tutor] creating variable names from string slices > noc wrote: > > >I'm telnetting to a mainframe, and capturing a screendump of data that's > >neatly column formatted: > > > >[...] > >What I want to do is define a function that gets passed each line, and > >returns a dictionary with the first element as the name, and the subsequent > >elements as the key:value pairs: > > > > Something like this, perhaps? > > First, we get the imported data into a list of lines: ayup...I'm using: records=string.split(telnet.readuntil(prompt),'\n') but I'll also need to do read from a file.... > Now, we write a function that deals with a single line. Since we know > the structure of the line, we can take advantage of that fact. > > >>> def processline(line): > ... fields = ['haircolor', 'role'] > ... line = line.split() > ... fielddata = zip(fields, line[1:]) > ... return line[0], dict(fielddata) > ... > >>> As I said, I need to slice data from the string, since it's columnar, but we can get around that simply enough: >>> def processline(line): ... fields = ['haircolor', 'role'] ... name = line.split()[0] ... line = [line[5:10],line[15:20]] ... fielddata = zip(fields, line) ... return name, dict(fielddata) ... >>> yes? > This function returns a tuple of a name (the first column of input) and > a dictionary that's constructed from the second and subsequent columns, > along with the column names. (If we wanted to get fancy, we might build > the list of fields from the first line of our input, reading column > headers, but for now I'm just using a statically defined list of fields.) > > Now all we have to do is run each line through this function, and store > the results. > > >>> data = {} > >>> for line in lines: > ... name, info = processline(line) > ... data[name] = info > ... But we can combine this with above for: >>> def processline(line): ... fields = ['haircolor', 'role'] ... name = line.split()[0] ... line = [line[5:10],line[15:20]] ... fielddata = zip(fields, line) ... record = {} ... record[name] = fielddata ... return record ... >>> And that should return our dictionary: {'Betty': {'haircolor': 'Blond', 'role': 'Stude'}}, yes? > Depending on how you're using this data, it might also be practical to > define a class, and make each line into an instance of that class, with > attributes named 'haircolor' and 'role'. Well, let's not get too crazy here! I don't think I really need anything as elaborate creating a class from it. I'm looking at 9 fields, to which I'll be adding date, time, and an ancillary field, for a few hundred records. Times four. But that's just for the current snapshot of data. The script will be running every 15 minutes, and I'll be keeping and loading a file that holds 90 minutes worth of snapshots, which means 6 datasets. Hmmm. That's rather a lot. I'll be comparing one field of each record in the current snapshot, with the same field in the most recent snapshot, and then performing some action based on if the field changes. The file of stored data So the question is, when do you decide to make a class, and when do you stick with Python's native dictionary tools? > Note the use of '*line.split()' to feed arguments to Girl. This has the > effect of passing each element of the list returned by line.split() as > an individual parameter, rather than as an aggregated list. Now we can > process each line, and do whatever with the resulting objects. > >>> data = {} > >>> for line in lines: > ... name, info = processline(line) > ... data[name] = info > ... > >>> pprint.pprint(data) > {'Betty': <__main__.Girl instance at 0x01608918>, > 'Ginger': <__main__.Girl instance at 0x0162D710>, > 'Maryann': <__main__.Girl instance at 0x01622690>, > 'Veronica': <__main__.Girl instance at 0x015EF3C8>} > >>> for item in data.values(): > ... print item.name, item.role > ... > Veronica Student > Betty Student > Ginger Castaway > Maryann Castaway > >>> And the answer is, when we need the additional abstraction of handling objects and flexible access to attributes is necessary? Bruce From op73418@mail.telepac.pt Wed Apr 2 08:36:09 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Apr 2 08:36:09 2003 Subject: [Tutor] iterators generators References: <20030401151044.95165.qmail@web20204.mail.yahoo.com> Message-ID: <000701c2f91d$c2cb0cd0$a8130dd5@violante> ----- Original Message ----- From: "Gerardo Arnaez" To: Sent: Tuesday, April 01, 2003 4:10 PM Subject: [Tutor] iterators generators > Hi all, I've been learning a lot, > really enjoyed list comprehesions. > but cant seem to get my head around iterators and > generators, anyone know of any good reading, Ive read > the PEP's and just didnt grok it > I also read the IBM Charming python and again failed > to grok it > I'll stand up and try to explain iterators and generators. First a definition: An object is iterable (or is an iterable) if iter() doesn't raise an exception (TypeError to be more exact). Iterables are nice because they allow for loops, e.g. for elem in : Examples: list, tuple, file, etc. >>> print iter([]) >>> Now iter() is a builtin function and when called on an iterable it returns an *iterator* which may or may not be the same thing as the iterable itself. >>> a = [] >>> print id(a), id(iter(a)) 17990976 17999536 As you can see the list iterable is different from the iterator itself. I think (but I'm not sure) that files are scheduled in 2.3 to become their own iterators. Anyway, what the iterator object is supposed to encapsulate is the traversal through the elements of the iterable. It does this by having a method, next(), that gives the next element (whatever that may be) or raises a StopIteration exception if there is nothing left to spew. When Python encounters a for elem in : it basically is the same: get the iterator of iterable and sucessively bind elem to whatever the iterator's next method returns until a StopIteration exception is raised. Note that an iterator is also an iterable. But the iterator of an iterator is the iterator itself (usually - I suppose there is some more exotic code out there where this rule is broken). >>> b = iter(a) >>> print b >>> print b is iter(b) 1 If you want to code your own iterable just define __iter__. If it is an iterator make __iter__ return self (unless you know what you are doing) and provide a next method. Now for generators. Generators are a cross-breeding between a function and an iterable. It is better an example first: >>> def test(n = 0): ... start = n ... while True: ... yield start ... start += 1 ... >>> print test This is a generator because of the presence of the yield keyword in its body. But, as you can see test *is* a function. When called for the first time it gives >>> a = test() >>> print a A generator. Now a generator *is* an iterator. To see that: >>> a.next >>> print id(a), id(iter(a)) 18124192 18124192 But it is a special kind of iterator. It remembers all the state about the "function". Let us go back to our little example to see how it works. When you first call a.next() (either explicitely or implicitely in a for loop) it executes the code in the body until the first yield. When it gets there it "returns" whatever expression is in front of the yield but instead of discarding the function it "suspends" it. This means two things (at least): The state of all the local variables is kept *and* the place where you yielded is also kept. On the next next() call you execute the body of test with your local variables in the state they were in *and* right from the place where you last yielded: In our little examlpe, execution resumes with start += 1 which bumps start to 1. Execution continues until the next yield. Generators are mostly used in coding iterators, but in D. Mertz's Charming Python column you can see other examples for them including exotic microthreading, state machines, etc. And that is basically all there is to it. Hope it helps, with my best regards, G. Rodrigues From a_abdi406@yahoo.com Wed Apr 2 11:23:05 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Apr 2 11:23:05 2003 Subject: [Tutor] about NLTK Message-ID: <20030402162204.30611.qmail@web14503.mail.yahoo.com> --0-696791589-1049300524=:25552 Content-Type: text/plain; charset=us-ascii hi, I have question about the modules, I downloaded NLTK module for win32 and I followed the instruction for installation from the web, having dowloaded I the wizardinstallation guided me to complete the installation and it installed the same directory as Python22, I opened the python interactive window to check whether the installation was successfull I called the module as follows: >>> from nltk.token import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named nltk.token >>> I consulted the FAQ before posting the question, so what is going on ? folder structure is as follows: C:\\Python22\\nltk1.0 thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more --0-696791589-1049300524=:25552 Content-Type: text/html; charset=us-ascii

hi,

I have question about the modules, I downloaded NLTK module for win32 and I followed the instruction for installation from the web, having dowloaded I the wizardinstallation guided me to complete the installation and it installed the same directory as Python22,  I opened the python interactive window to check whether the installation was successfull I called the module as follows:

>>> from nltk.token import *
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ImportError: No module named nltk.token
>>>

I consulted the FAQ before posting the question, so what is going on ?

folder structure is as follows:

C:\\Python22\\nltk1.0

                  

thanks in advance

 



Do you Yahoo!?
Yahoo! Tax Center - File online, calculators, forms, and more --0-696791589-1049300524=:25552-- From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 13:20:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 13:20:02 2003 Subject: [Tutor] please help (fwd) Message-ID: [I'm slightly busy at the moment; sorry! I will forward this to tutor@python.org.] ---------- Forwarded message ---------- Date: Tue, 1 Apr 2003 23:51:15 EST From: GREENDAY31087@aol.com To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] please help I made a mistake. The error message looked more like the one you had. So, do you mean to put the command python setup.py py2exe in the setup program so it looks like: *************************************** # setup.py from distutils.core import setup import py2exe setup(name="test", scripts=["test.py"], ) python setup.py py2exe *************************************** -?? What do you mean? From jeff@ccvcorp.com Wed Apr 2 13:56:11 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 2 13:56:11 2003 Subject: [Tutor] creating variable names from string slices References: <021e01c2f828$16876ef0$5102020a@graphnet.com> <3E89D966.6030305@ccvcorp.com> <038901c2f91c$a14a3230$5102020a@graphnet.com> Message-ID: <3E8B3275.5030000@ccvcorp.com> Bruce Dykes wrote: >>First, we get the imported data into a list of lines: >> >> > >ayup...I'm using: > >records=string.split(telnet.readuntil(prompt),'\n') > >but I'll also need to do read from a file.... > Which is easy enough to do with readlines() / xreadlines(); the important point here being that it doesn't really matter where your data is coming from if you can get it into a consistently-formatted list of lines. >>Now, we write a function that deals with a single line. Since we know >>the structure of the line, we can take advantage of that fact. >>[...] >> >As I said, I need to slice data from the string, since it's columnar, but we >can get around that simply enough: > > >>> def processline(line): > ... fields = ['haircolor', 'role'] > ... name = line.split()[0] > ... line = [line[5:10],line[15:20]] > ... fielddata = zip(fields, line) > ... return name, dict(fielddata) > ... > >>> > >yes? > Okay, having seen later that some 'cells' in the table may be empty, then yes, you'll need to use slicing. You can actually make it a little easier to maintain, though, by making that list of fieldnames into a dictionary of fieldnames and start/end points. >>> fields = { ... 'name': (0,10), ... 'haircolor': (15,25), ... 'role': (30,40) ... } >>> def processline(line): ... item = {} ... for key, val in fields.items(): ... item[key] = line[val[0]:val[1]] ... return item ... >>> Note that I've just made 'name' a field like any other, instead of special-casing it as before. You *could* still special-case it so that it doesn't go in the item dictionary, or you could leave it in the dictionary but also return it separately by changing the function's last line to 'return item["name"], item'. >>Now all we have to do is run each line through this function, and store >>the results. >> >> >>> data = {} >> >>> for line in lines: >>... name, info = processline(line) >>... data[name] = info >>... >> >> > >But we can combine this with above for: > > >>> def processline(line): > ... fields = ['haircolor', 'role'] > ... name = line.split()[0] > ... line = [line[5:10],line[15:20]] > ... fielddata = zip(fields, line) > ... record = {} > ... record[name] = fielddata > ... return record > ... > >>> > >And that should return our dictionary: >{'Betty': {'haircolor': 'Blond', 'role': 'Stude'}}, > >yes? > Well, we *could*, but then we'd have a separate single-entry dictionary for each line, and we'd need another list or dictionary to store all of those dictionaries... I don't see the advantage to that. >>Depending on how you're using this data, it might also be practical to >>define a class, and make each line into an instance of that class, with >>attributes named 'haircolor' and 'role'. >> >> > >Well, let's not get too crazy here! >[...] >So the question is, when do you decide to make a class, and when do you >stick with Python's native dictionary tools? > I'd start thinking about making a class when I can see obvious methods to attach to it -- if it's simply a matter of storing data, a dictionary is suitable, but once I want to add nontrivial manipulations of that data, then it becomes easier to use a class than to use a dictionary plus a set of functions. (Indeed, a class *is* a dictionary plus a set of functions, but conveniently packaged up together in a helpful way.) From your problem description, you'll probably want a function that compares the current item with a previous item, returning some information about any changes (possibly just a boolean "yes there's a change", possibly detailed information on *what* changed and how). You'll want another function (or possibly several) that takes appropriate action based on the results of the first function. If a function depends on detailed knowledge of the structure of complex data that's passed into it, then it's a good candidate to convert to a class method. Your comparison function will definitely require such knowledge, and your action function(s) may or may not require it. The more this information is needed, the stronger the case for packaging the lot of it up into a class, so that all this information is localized in one place. Note that, if you're using a class, then the information about how to parse a line of data is *also* localized in the class, instead of in an isolated function like processline(), and your set of fields (and start/stop points) can be made a class attribute as well. By the way, you can still use the process I showed above for slicing a line to create attributes in a class, by using the setattr() function: class Girl: fields = { 'name': (0,10), 'haircolor': (15,25), 'role': (30,40) } def __init__(self, line): for key, val in self.fields.items(): setattr(self, key, line[val[0]:val[1]]) This will also give you the flexibility of creating subclasses of Girl that use a different dictionary of fields, in case you have different data sources that format your columns slightly differently. But since they're all Girl instances, you can use the same comparison and action methods. >And the answer is, when we need the additional abstraction of handling >objects and flexible access to attributes is necessary? > > Pretty much, yes. But once you have a basic grasp of the concept of OOP, then the cost of creating a class is pretty low, so the point at which you start to benefit by having a class comes pretty easily. Jeff Shannon Technician/Programmer Credit International From wheelcrdan@hotmail.com Wed Apr 2 15:23:01 2003 From: wheelcrdan@hotmail.com (Danny) Date: Wed Apr 2 15:23:01 2003 Subject: [Tutor] 2 Different Development Invirments, IDLE & PythonWin 2 different results Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C2F91A.D4384A80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Everyone, My question is I have downloaded IDLE and PythonWIn I have made this = very simple program=20 password =3D 'foobar' count =3D 0 while password !=3D 'Unicorn': password =3D raw_input('password') if count < 3: count =3D count + 1 print count elif count =3D=3D 3: print 'man thats a hard one' print 'welcome in' When I run this with IDLE, it works fine and exits after 3 tries. But = when you run the same program in PythonWin, it wont exit until you get = the password correctly why is this? Or what could I do in PythonWin to = make it exit after 3 tries? Thanks for everyone help ahead of time. Danny D ------=_NextPart_000_0005_01C2F91A.D4384A80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Everyone,
    My question is I = have downloaded=20 IDLE and PythonWIn I have made this very simple program
 
password =3D 'foobar'
count =3D = 0
while password=20 !=3D 'Unicorn':
    password =3D=20 raw_input('password')
    if count <=20 3:
        count =3D count +=20 1
        print=20 count
    elif count =3D=3D=20 3:
        print 'man thats a hard = one'
print 'welcome in'
When I run this with IDLE, it works = fine and exits=20 after 3 tries. But when you run the same program in PythonWin, it = wont exit=20 until you get the password correctly why is this? Or what could I do=20 in PythonWin to make it exit after 3 tries? Thanks for everyone = help ahead=20 of time.
 
Danny D
------=_NextPart_000_0005_01C2F91A.D4384A80-- From reggie@merfinllc.com Wed Apr 2 15:39:04 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Wed Apr 2 15:39:04 2003 Subject: [Tutor] 2 Different Development Invirments, IDLE & PythonWin 2 different results In-Reply-To: References: Message-ID: <1049315922.5664.5.camel@pika.merfinllc.com> Danny, It's hard to believe you ran this EXACT same program under both IDE's and they behaved differently. In the listing you gave, there were no 'break' statements in the loop and you don't explicitly exit so it seems to me that the only way to exit the loop is to type 'Unicorn'. I don't understand why IDLE would exit after 3 tries. Sorry I couldn't be of more help. On Wed, 2003-04-02 at 12:21, Danny wrote: > Hi Everyone, > My question is I have downloaded IDLE and PythonWIn I have made > this very simple program > > password = 'foobar' > count = 0 > while password != 'Unicorn': > password = raw_input('password') > if count < 3: > count = count + 1 > print count > elif count == 3: > print 'man thats a hard one' > print 'welcome in' > > When I run this with IDLE, it works fine and exits after 3 tries. But > when you run the same program in PythonWin, it wont exit until you get > the password correctly why is this? Or what could I do in PythonWin to > make it exit after 3 tries? Thanks for everyone help ahead of time. > > Danny D -- Reggie From wheelcrdan@hotmail.com Wed Apr 2 15:52:01 2003 From: wheelcrdan@hotmail.com (Danny) Date: Wed Apr 2 15:52:01 2003 Subject: [Tutor] Sorry My Mistake Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C2F91E.D105D270 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Everyone, Sorry the last emai I sent was incorrect I thought it IDLE exited but it = didn't. Sorry for the confusion just alot of confusion on this side with = PythonWin anyways thanks anyways and take care Danny D ------=_NextPart_000_0005_01C2F91E.D105D270 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Everyone,
 
Sorry the last emai I sent was = incorrect I thought=20 it IDLE exited but it didn't. Sorry for the confusion just alot of = confusion on=20 this side with PythonWin anyways thanks anyways and take = care
 
Danny D
 
------=_NextPart_000_0005_01C2F91E.D105D270-- From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 16:13:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 16:13:01 2003 Subject: [Tutor] running py2exe In-Reply-To: Message-ID: > I made a mistake. The error message looked more like the one you had. > So, do you mean to put the command python setup.py py2exe in the setup > program so it looks like: > > > *************************************** > # setup.py > from distutils.core import setup > import py2exe > > setup(name="test", > scripts=["test.py"], > ) Hello! Up to there, 'setup.py' looks ok. But the command: python setup.py py2exe is not meant to be run in your Python script --- you'll need to take that out. Instead, that last command is meant to be used from the Windows command prompt. If you're running Win2k, I believe you can get to a prompt by going to the Start menu, selecting the "Run" command, and type 'cmd' in the box. From there, a console window should pop up. It's at that console window that you can type 'python setup.py py2exe'. If you have more questions, please feel free to ask! From bgailer@alum.rpi.edu Wed Apr 2 16:47:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 2 16:47:01 2003 Subject: [Tutor] 2 Different Development Invirments, IDLE & PythonWin 2 different results In-Reply-To: Message-ID: <5.2.0.9.0.20030402144221.039058b0@66.28.54.253> --=======19C6751F======= Content-Type: text/plain; x-avg-checked=avg-ok-2ABE61DC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 01:21 PM 4/2/2003 -0700, Danny wrote: >Hi Everyone, > My question is I have downloaded IDLE and PythonWIn I have made this > very simple program > >password = 'foobar' >count = 0 >while password != 'Unicorn': > password = raw_input('password') > if count < 3: > count = count + 1 > print count > elif count == 3: > print 'man thats a hard one' >print 'welcome in' >When I run this with IDLE, it works fine and exits after 3 tries. But when >you run the same program in PythonWin, it wont exit until you get the >password correctly why is this? Or what could I do in PythonWin to make it >exit after 3 tries? Thanks for everyone help ahead of time. I agree with Reggie's comments. It should run forever until you enter the correct password. Suggested code simplification (2 lines shorter and easier to read): password = 'foobar' for i in range(3): password = raw_input('password') if password == 'Unicorn': print 'welcome in' break else: print 'man thats a hard one' Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======19C6751F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2ABE61DC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======19C6751F=======-- From charlie@begeistert.org Wed Apr 2 16:55:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Apr 2 16:55:02 2003 Subject: [Tutor] Getting at object names In-Reply-To: <5.2.0.9.0.20030401092740.01a12710@66.28.54.253> References: <5.2.0.9.0.20030401092740.01a12710@66.28.54.253> Message-ID: <20030402235321.13499.2@wonderland.1049319622.fake> Dear all, thanx very much for the explanations. Alan helped me understand _why_ I couldn't do what I wanted: > No, because its just a symbol in the program (OK you could read the > local namespace dictionary but that's messy and not to be encouraged! > Why not just associate the dayname with the key? and came up with practicable solution days = {1:('friday',friday),2:('saturday',saturday).....} for day in d print days[day][0],days[day][1] Jeff's solution but seems slightly more elegant and less subject to typos (I make lots) days = {'1': ('friday', []), '2': ('saturday', []), '3': ('sunday', [])} d = days.keys() d.sort() for day in d: name, values = days[d] print '%s : %s' % (name, values) And Bob came up with a really nice solution which I'm afraid I can't use because I'm currently running Python 2.1.2 on BeOS for development so I'll be going with Jeff's solution for the time being. #subclass list and give it a name attribute: class day(list): def __init__(self, name): self.name = name def set(self, items): self[:] = items Thanx again to all! Charlie From bgailer@alum.rpi.edu Wed Apr 2 16:59:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 2 16:59:01 2003 Subject: [Tutor] Getting at object names In-Reply-To: <20030402235321.13499.2@wonderland.1049319622.fake> References: <5.2.0.9.0.20030401092740.01a12710@66.28.54.253> <5.2.0.9.0.20030401092740.01a12710@66.28.54.253> Message-ID: <5.2.0.9.0.20030402145210.039a8830@66.28.54.253> --=======5AE64183======= Content-Type: text/plain; x-avg-checked=avg-ok-2ABE61DC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:53 PM 4/2/2003 +0200, Charlie Clark wrote: >And Bob came up with a really nice solution which I'm afraid I can't use >because I'm currently running Python 2.1.2 on BeOS for development so I'll >be going with Jeff's solution for the time being. > >#subclass list and give it a name attribute: >class day(list): > def __init__(self, name): > self.name = name > def set(self, items): > self[:] = items You can still use a class: >>> import UserList >>> class day(UserList.UserList): >>> def __init__(self, name): >>> self.name = name >>> def set(self, items): >>> self.data = items >>> instance = day([1,2,3]) >>> instance [1, 2, 3] >>> instance.data = [3,4] >>> instance [3, 4] >>> instance.set([3,4,5]) >>> instance [3, 4, 5] Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======5AE64183======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2ABE61DC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003 --=======5AE64183=======-- From Don Arnold" Message-ID: <034301c2f973$1bc229e0$4813ba3f@defaultcomp> ----- Original Message ----- From: "Danny Yoo" To: "Tutor" Sent: Wednesday, April 02, 2003 12:19 PM Subject: Re: [Tutor] please help (fwd) > [I'm slightly busy at the moment; sorry! I will forward this to > tutor@python.org.] > > ---------- Forwarded message ---------- > Date: Tue, 1 Apr 2003 23:51:15 EST > From: GREENDAY31087@aol.com > To: dyoo@hkn.eecs.berkeley.edu > Subject: Re: [Tutor] please help > > I made a mistake. The error message looked more like the one you had. So, do > you mean to put the command python setup.py py2exe in the setup program so it > looks like: > *************************************** > # setup.py > from distutils.core import setup > import py2exe > > setup(name="test", > scripts=["test.py"], > ) > python setup.py py2exe > *************************************** > -?? > What do you mean? > I've used py2exe just once, but here's my setup.py that worked: ## command line: python setup.py py2exe from distutils.core import setup import py2exe setup(name='TruthTable',scripts=['boolevaluator4.py']) I put it in the same directory as my script (boolevaluator4.py) and executed the command line mentioned in the comment (in fact, I put it in the comment because I could never remember it). HTH, Don From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 20:13:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 20:13:01 2003 Subject: [Tutor] about NLTK In-Reply-To: <20030402162204.30611.qmail@web14503.mail.yahoo.com> Message-ID: On Wed, 2 Apr 2003, Abdirizak abdi wrote: > I have question about the modules, I downloaded NLTK module for win32 > and I followed the instruction for installation from the web, Hi Abdirizak, I've playing a bit with the Natural Language TookKit (NLTK) on Unix, though I haven't tried it on Windows yet. There's so much cool stuff out there, and just not enough time to play with it all... > folder structure is as follows: > > C:\\Python22\\nltk1.0 Hmmm... That's slightly odd; I would have expected it to install into C:\\Python22\\Lib\\site-packages\\nltk instead. Does anyone have a Windows machine handy where they can test out NLTK's installer? You may want to ask on the NLTK help forum on this, as the problem sounds really specific to their Windows installer: http://sourceforge.net/forum/forum.php?forum_id=97413 You may want to see if installing the source package (the tar.gz or zip) will work better. You can install NTLK using the source distribution through the standard distutils command: python setup.py install Distutils should put the package in the proper precise place. Probably. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 20:36:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 20:36:02 2003 Subject: [Tutor] python accounting package In-Reply-To: <862D79D0DADB244E8563C6F9277C02FF022C1191@zabrysvcl01ex01.af.didata.local> Message-ID: On Tue, 1 Apr 2003, Jaco Smuts (ZA) wrote: > I'm playing with the idea of writing my own little accounting app to > automate my personal business accounting. (Very simple). Is anyone aware > of any Python accounting stuff that I could use (not to re-invent the > wheel). Hi Jaco, Your question is a bit specialized, and many of us on Tutor may not be too familiar with business accounting stuff. You may want to check with the folks on the main 'comp.lang.python' newsgroup to see if people can help you find some good resources. You may also want to check out the Vaults of Parnassus: http://www.vex.net/parnassus Parnassus archives the Python communities collection of Python software, and provides a good starting point for looking for source code. I did a search for 'finance' from the search page on Parnassus, and came up with the Quantitative Finance library: http://quantlib.org/ The 'python-finance' Special Interest Group (SIG), http://groups.yahoo.com/group/python-finance/ would have been another good place to ask, had it not been killed by spammers. > I also plan on using MySQL. Any information will be greatly appreciated. There's a section about Database topics on Python.org that you may find helpful: http://python.org/topics/database/ Python by itself doesn't provide direct support for MySQL. You'll need to get a database driver module to properly access MySQL from Python, but thankfully, there's a great module written by Andy Dustman called "MySQLdb": http://sourceforge.net/projects/mysql-python I hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 20:39:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 20:39:02 2003 Subject: [Tutor] silly auto-responder In-Reply-To: <20030329031032.GB32668@tc.niof.net> Message-ID: On Fri, 28 Mar 2003, Rick Pasotto wrote: > Why do I keep getting that silly auto-responder telling me to check the > FAQ? > > I'm *answering* a question, not asking one. It happens to me on occasion too. *grin* Mailman sends the message when it thinks that the user is a first-time poster. The problem is that it appears to have a short term memory! We haven't updated Tutor to use the newest version of the Mailman mailing list software --- we may transition to it pretty soon. Perhaps it will fix the auto-responder bug. But if not, it might be a good opportunity for a bug hunt. From dyoo@hkn.eecs.berkeley.edu Wed Apr 2 20:41:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 2 20:41:00 2003 Subject: [Tutor] Question about 'Predicate Methods' In-Reply-To: <200303241918.55935.ahimsa@onetel.net.uk> Message-ID: On Mon, 24 Mar 2003, ahimsa wrote: > > (In the newest versions of Python, the results of the above tests will > > return the values 'True' and 'False', rather than 1 and 0, so expect > > to see slightly different displays.) > > What version are you referring to here, and what of backwards > compatibility if someone specifically wants the 1 or 0 return (i.e. an > integer) rather than a string (as in 'true'/'false')? Hi Andy, Python 2.2.1 introduced the boolean values 'True' and 'False' as names: http://python.org/peps/pep-0285.html as a gradual step toward having real boolean types in Python. However, the comparison operators still returns 1 or 0 in Python 2.2.1. In Python 2.3, comparisons will return these boolean objects. Code that uses 0 or 1 should still work: ### >>> True == 1 1 >>> type(True) >>> False == 0 1 ### as True and False are subclassed from the integers. Hope this helps! From mwlang@cybrains.net Thu Apr 3 01:17:06 2003 From: mwlang@cybrains.net (Michael Lang) Date: Thu Apr 3 01:17:06 2003 Subject: [Tutor] Python and Delphi Message-ID: <5.1.0.14.2.20030403005139.02106768@mail.mindspring.com> Hi, I am a long-time Delphi programmer who is trying to learn the Python programming language. I learn best by example and would like to post small trivial Delphi code snipplets here and see the translation from Delphi to Python to better understand how to do Python programming. Are there any Delphi (OOP Pascal) developers here that could help out? Would this be too "specialized" for this list? At any rate, I have been totally spoiled by the ability to click on a term and hit F1 to get very specific help on a function or method along with good code examples specifically for using that construct. Does anything like this exist for Python development that would help speed my learning of the language? Michael www.cybrains.net "All things should be as simple as possible, but no simpler" -- Albert Einstein From shalehperry@attbi.com Thu Apr 3 03:10:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Apr 3 03:10:02 2003 Subject: [Tutor] Python and Delphi In-Reply-To: <5.1.0.14.2.20030403005139.02106768@mail.mindspring.com> References: <5.1.0.14.2.20030403005139.02106768@mail.mindspring.com> Message-ID: <200304030008.36155.shalehperry@attbi.com> On Wednesday 02 April 2003 22:15, Michael Lang wrote: > Hi, > > I am a long-time Delphi programmer who is trying to learn the Python > programming language. I learn best by example and would like to post small > trivial Delphi code snipplets here and see the translation from Delphi to > Python to better understand how to do Python programming. Are there any > Delphi (OOP Pascal) developers here that could help out? Would this be too > "specialized" for this list? > I used delphi around 5 years ago, it was a lot of fun and did not have really nice UI. Why not attempt to write some python code and ask for help when it breaks? This is more likely to receive the greatest amount of response. > At any rate, I have been totally spoiled by the ability to click on a term > and hit F1 to get very specific help on a function or method along with > good code examples specifically for using that construct. Does anything > like this exist for Python development that would help speed my learning of > the language? > nothing as nice as the Delphi UI that I am aware of. However, you get the full blown python interpreter (-: I usually have one open while i am editing the code. If i forget something a quick test in the python window and back to the code. Most python methods, classes, etc have documentation embedded in them via the __doc__ variable. From adamg@mailbox.hu Thu Apr 3 04:25:02 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Thu Apr 3 04:25:02 2003 Subject: [Tutor] Python and Delphi In-Reply-To: <5.1.0.14.2.20030403005139.02106768@mail.mindspring.com> Message-ID: Michael wrote: At any rate, I have been totally spoiled by the ability to click on a term and hit F1 to get very specific help on a function or method along with good code examples specifically for using that construct. Does anything like this exist for Python development that would help speed my learning of the language? ----------------------- I think you should try Activestate Python, which has a nice (but sometimes weirdly linked) html help. Together with Activestate Komodo 2.3, the IDE, running on Win32 and linux also, where you can hit shift-F1 which takes you to the online Python manual with search capability. For coding examples you can check http://aspn.activestate.com/ASPN/Cookbook/Python, you can find here some clever examples. This worked for me. Adam From bgailer@alum.rpi.edu Thu Apr 3 11:49:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Apr 3 11:49:01 2003 Subject: [Tutor] Pickle/Shelve Message-ID: <5.2.0.9.0.20030403094455.0391e4c0@66.28.54.253> --=======71C524CB======= Content-Type: text/plain; x-avg-checked=avg-ok-3F673C21; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit I'm running into problems shelving objects that contain references to other objects that contain unPickleable items. Is there a way around this other than writing __getstate__ methods for each object? Is there a switch that says "ignore item if unPickleable", or a way to subclass shelve or pickle to accomplish this? Bob Gailer PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu 303 442 2625 --=======71C524CB======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3F673C21 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======71C524CB=======-- From charlie@begeistert.org Thu Apr 3 12:17:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu Apr 3 12:17:02 2003 Subject: [Tutor] Re: Pickle / Shelve In-Reply-To: <20030403170006.10865.64314.Mailman@mail.python.org> References: <20030403170006.10865.64314.Mailman@mail.python.org> Message-ID: <20030403191832.6287.33@wonderland.1049356500.fake> On 2003-04-03 at 19:00:06 [+0200], bgailer@alum.rpi.edu wrote: > I'm running into problems shelving objects that contain references to > other objects that contain unPickleable items. > > Is there a way around this other than writing __getstate__ methods for > each object? Is there a switch that says "ignore item if unPickleable", > or a way to subclass shelve or pickle to accomplish this? Hi Bill, maybe I can pay you back quicker than I thought but probably not ;-). It seems as if you've already checked out the Cookbook on this but the Cookbook refers to the "Python Standard Library" which covers using copy_reg and marshal to create custom picklers and unpicklers. Do you think this might be useful? Do you have access to this? Charlie From Michael Montagne Thu Apr 3 14:29:02 2003 From: Michael Montagne (Michael Montagne) Date: Thu Apr 3 14:29:02 2003 Subject: [Tutor] Does directory exist? Message-ID: <20030403193206.GA4258@boora.com> What is the best way to check for the existence of a directory? I used os.stat() in a try:except: statement. It seems the os.access() function is intended for this but I can't get it to accept F_OK as the mode argument. -- Michael Montagne http://www.themontagnes.com 503.226.1575 -- From dyoo@hkn.eecs.berkeley.edu Thu Apr 3 15:02:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 3 15:02:01 2003 Subject: [Tutor] Does directory exist? In-Reply-To: <20030403193206.GA4258@boora.com> Message-ID: On Thu, 3 Apr 2003, Michael Montagne wrote: > What is the best way to check for the existence of a directory? I used > os.stat() in a try:except: statement. It seems the os.access() function > is intended for this but I can't get it to accept F_OK as the mode > argument. Hi Michael, There are a set of convenience functions in the 'os.path' subpackage; we can check it out here: http://www.python.org/doc/lib/module-os.path.html In particular, os.path.exists() is probably what you're looking for. Here's a sample of how to use it: ### >>> import os.path >>> os.path.exists('/etc/passwd') 1 >>> os.path.exists('/etc') 1 >>> os.path.exists('/foobar') 0 ### So os.path.exists() works well with both files and directories. Using the os.path module allows us to concentrate on common path-related tasks without having to worry about flags like 'F_OK'. From python@jaydorsey.com Thu Apr 3 15:30:04 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Thu Apr 3 15:30:04 2003 Subject: [Tutor] Does directory exist? In-Reply-To: <20030403193206.GA4258@boora.com> References: <20030403193206.GA4258@boora.com> Message-ID: <3E8C900C.6020508@jaydorsey.com> Michael Montagne wrote: > What is the best way to check for the existence of a directory? > I used os.stat() in a try:except: statement. It seems the os.access() > function is intended for this but I can't get it to accept F_OK as the > mode argument. How about: >>> import os >>> os.path.isdir("/home/me") -- Jay Dorsey python at jay dorsey dot com From Janssen@rz.uni-frankfurt.de Thu Apr 3 15:38:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Apr 3 15:38:02 2003 Subject: [Tutor] Does directory exist? In-Reply-To: <20030403193206.GA4258@boora.com> Message-ID: On Thu, 3 Apr 2003, Michael Montagne wrote: > What is the best way to check for the existence of a directory? > I used os.stat() in a try:except: statement. It seems the os.access() > function is intended for this but I can't get it to accept F_OK as the > mode argument. Your problem is already solved by Danny but for interesset: F_OK is nothing else as a variable defined in the os-modul. So you have to use: os.F_OK Michael > > > -- > Michael Montagne http://www.themontagnes.com 503.226.1575 > -- > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Thu Apr 3 17:35:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Apr 3 17:35:01 2003 Subject: [Tutor] Python and Delphi Message-ID: > I am a long-time Delphi programmer who is trying to learn the Python > programming language. Been there, done that! :-) Now I only use Delphi for hard core Windows or, occasionally for a more sophisticated GUI than I can do with Tkinter... > I learn best by example and would like to post small > trivial Delphi code snipplets here and see the translation from Delphi Thats not a bad strategy to start with but you'll soon find that the diffrences in level between the two languages mean that you have to adopt a new mind set. Object Pascal is a great language but its still a factor of 2 or 3 times more verbose than Python. > At any rate, I have been totally spoiled by the ability to click on a term > and hit F1 to get very specific help on a function or method along with The help function in Python is pretty good but the results depend on the quality of documentation that the developer provided, which varies a lot. So you can always type help(foo) at the >>> prompt and mostly find what you need. But no F1 shortcut i'm afraid. But adding that wouldn't be too hard a project and the beauty of open source means you could do it for IDLE and submit the change as a contribution... OTOH you may find that once you get used to having an interpreter to try out code in a playpen as you write it without going through a full compile/run/debug cycle means you don't miss it as much as you thought. I certainly don't, and I use F1 a lot in delphi!! Although there are many similaritiers between Delphi(OP) and Python there are some fundamental differences in how they provide programmer productivity. Python is far more about experimenting at the >>> prompt till it works then "writing it up" as real code. delphi by contrast makes it easy to do "online research" while coding then seeing iof you understood it after you compile. now while delphi compiles fast you still need a syntactically complete file. The >>> prompt just needs a syntactically complete line! HTH, Alan g. From tim@johnsons-web.com Thu Apr 3 21:06:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Apr 3 21:06:01 2003 Subject: [Tutor] Python and Delphi/Help Function In-Reply-To: References: Message-ID: <20030404021513.GY1573@johnsons-web.com> * alan.gauld@bt.com [030403 13:48]: > > I am a long-time Delphi programmer who is trying to learn the Python > > programming language. > > Been there, done that! :-) > Now I only use Delphi for hard core Windows or, occasionally for a more > sophisticated GUI than I can do with Tkinter... Ah! Put in a lot of miles using "C++ Builder" > > The help function in Python is pretty good but the results depend on the > quality of documentation that the developer provided, which varies a lot. So > you can > always type help(foo) at the >>> prompt and mostly find what you need. > But no F1 shortcut i'm afraid. Alan, I note the help(foo) from the command line in Linux gives me the 'less' pager with documentation. Thus >>>help(tuple) in Linux gives me the pager with tuple docs. But >>>help(tuple) in the Windows interpreter just gives me an error message. (NameError) I currently have 2.2.2 on linux and 2.1.2 on windows. any comments here Alan? Thanks -tim- -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From alan.gauld@bt.com Fri Apr 4 02:22:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Apr 4 02:22:02 2003 Subject: [Tutor] Python and Delphi/Help Function Message-ID: > >>>help(tuple) in the Windows interpreter just gives me an > error message. (NameError) > > I currently have 2.2.2 on linux and 2.1.2 on windows. > any comments here Alan? Install 222 on windows! :-) Seriously, look up help in the docs (the slow way!). I think in versions before 2.2.x you had to import help before using it. Something like: >>> from help import help >>> help (foo) But its been so long I can't recall for sure... Alan G From wesc@fuzzyorange.com Fri Apr 4 02:32:02 2003 From: wesc@fuzzyorange.com (Wesley Chun) Date: Fri Apr 4 02:32:02 2003 Subject: [Tutor] ANN: BayPIGgies mtg Wed Apr 9 7:30pm In-Reply-To: Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: April 9, 2003 @ 7:30pm Where: Stanford University, Palo Alto, CA Agenda: Introduction to Machine Learning and Support Vector Machines Speaker: Asa Ben-Hur The basic concepts of machine learning will be presented, with a focus on Support Vector Machines (SVM), which have shown their effectiveness in many domains of application. Examples of applying the methodology in areas such as text categorization and bioinformatics will be discussed. # Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our 2003 meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope 2 c u tomorrow nite! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://baypiggies.net wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From wesc@deirdre.org Fri Apr 4 02:42:15 2003 From: wesc@deirdre.org (wesc@deirdre.org) Date: Fri Apr 4 02:42:15 2003 Subject: [Tutor] ANN: Python II course (Silicon Valley, CA) Message-ID: <200304040724.h347O4S02758@alpha.ece.ucsb.edu> this is a friendly reminder to ask you to please sign up for Python II ASAP if you're interested. the class starts on Monday, April 14th... more details here: http://artemis.ucsc-extension.edu/~wesc/024d50cd.htm Register online, or contact Sherry at 408-861-3765 or smirkarimi@ucsc-extension.edu to enroll. On a related note, this will be the last course i will be instructing for UC Santa Cruz Extension for a long time. Work, family, and the Python community are making it hard to devote the time necessary. if you're interested in training new Silicon Valley engineers about the wonders of Python, contact me privately, and i will help u get started. -wesley ps. 'twas great seeing familiar & new faces @ PyCon last wk! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, (c)2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://www.baypiggies.net wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://roadkill.com/~wesc/cyberweb/ E-Mail using vi(m)/emacs with M$ outlook: http://groups.google.com/groups?threadm=fcd9edc1.0208281104.752da4bd%40posting.google.com From seb@albert.vcisp.net Fri Apr 4 10:20:01 2003 From: seb@albert.vcisp.net (Sebastian Tennant) Date: Fri Apr 4 10:20:01 2003 Subject: [Tutor] Problems with OSX Python bundle from link on Jack's MacPython page.. Message-ID: --Apple-Mail-4-295389077 Content-Transfer-Encoding: 7bit Content-Type: text/plain; delsp=yes; charset=US-ASCII; format=flowed Hi all, I originally sent this to bob@redivi.com (the bundle maker) but so far nothing. I'm not sure if this is the right list for this sort of query as it's not strictly a programming question. If it isn't perhaps someone could point me in the right direction. However, if anyone can help me / explain what's going on, I'd be v. grateful. Seb Begin forwarded message: > From: Sebastian Tennant > Date: Thu Mar 27, 2003 6:04:30 pm Europe/London > To: bob@redivi.com > Subject: Having a few problems with your bundle... > > Hi there. > > Sorry to trouble you. I've installed the bundle > (pygame-1.3.4-osx-kitchensink.pkg.tar) using the tar command as > advised and can't get Tkinter to work, but first of all was just > wondering if you could explain something to me. I was only really > interested in Tkinter, but thought that there was no harm in a few > extra modules. I didn't realise that the bundle included a full > pyhton2.2 installation so now I think I'm right in saying I've got two > python installations on my machine, (a G4 running OS X 10.2.4); the > pre-compiled Apple bundle, under /usr/lib/pyhton2.2/, and yours, under > /Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/. > Just to confound me more, the new modules that came with the bundle > seem to have ALSO been installed under /usr/lib/pyhton2.2/? > > For instance, when I type pyhton from the command line which > executable am I visiting? > > [sebbyt: /usr] % ls bin/python > -rwxr-xr-x 1 root wheel 784920 Feb 15 20:39 bin/python* > > [sebbyt: /usr] % ls local/bin/python > lrwxr-xr-x 1 sebbyt staff 64 Mar 26 13:36 local/bin/python -> > /Library/Frameworks/Python.framework/Versions/Current/bin/python* > > /usr/local/bin/ is before /usr/bin/ in my PATH so I presume I am > visiting the latter. > > PATH=/sw/bin:/sw/sbin:/Users/sebbyt/bin/powerpc-apple-darwin:/Users/ > sebbyt/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/ > sbin:/usr/X11R6/bin > > I've set my environment variables as follows: > > PYTHONDOCS=/usr/local/share/doc/python2.2 > TK_LIBRARY=/usr/lib/python2.2/lib-tk > TCL_LIBRARY=/System/Library/Tcl/8.3 > > (For TK_LIBRARY I have also tried > /Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/lib-> tk) > > So what actually is the problem I can hear you ask. Well when I try > and test Tkinter by creating a simple button, somethimes I get the > button on screen before Python crashes, sometimes not. Calling 'pydoc > -g' crashes python every time, (being a GUI I assume it utilises > Tkinter), so this is the output within the interpreter from 'pydoc -g' > and the crash report follows after that. > > [sebbyt: ~/.Terminal_folder] % pydoc -g > TkMacOSXDoHLEvent failed : eppc 1 ,kHighLevelEvent > 61657674 0000 aevt,-1708 > RCNE SendEventToEventTarget (eppc 1 ) failed, -9874 > Bus error > > Date/Time: 2003-03-27 16:41:09 +0000 > OS Version: 10.2.4 (Build 6I32) > Host: sebbyt.local. > > Command: python > PID: 2572 > > Exception: EXC_BAD_ACCESS (0x0001) > Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000358 > > Thread 0: > #0 0x9003ea88 in semaphore_wait_signal_trap > #1 0x9003e8a4 in _pthread_cond_wait > #2 0x00444d80 in PyThread_acquire_lock (thread.c:370) > #3 0x00212ef8 in Tkapp_MainLoop (_tkinter.c:1698) > #4 0x003f0814 in PyCFunction_Call (methodobject.c:101) > #5 0x0041e05c in eval_frame (ceval.c:1994) > #6 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #7 0x00420b8c in fast_function (ceval.c:3154) > #8 0x0041e160 in eval_frame (ceval.c:2015) > #9 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #10 0x00420b8c in fast_function (ceval.c:3154) > #11 0x0041e160 in eval_frame (ceval.c:2015) > #12 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #13 0x00420b8c in fast_function (ceval.c:3154) > #14 0x0041e160 in eval_frame (ceval.c:2015) > #15 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #16 0x0041a70c in PyEval_EvalCode (ceval.c:483) > #17 0x0043d4d0 in run_node (pythonrun.c:1084) > #18 0x0043d474 in run_err_node (pythonrun.c:1070) > #19 0x0043d440 in PyRun_FileExFlags (pythonrun.c:1062) > #20 0x0043c4c0 in PyRun_SimpleFileExFlags (pythonrun.c:692) > #21 0x0043bed8 in PyRun_AnyFileExFlags (pythonrun.c:499) > #22 0x0044681c in Py_Main (main.c:369) > #23 0x00001e1c in _start > #24 0x00001c4c in start > > Thread 1: > #0 0x9002578c in select > #1 0x00d84310 in NotifierThreadProc (tkMacOSXNotify.c:1027) > #2 0x90020d28 in _pthread_body > > Thread 2 Crashed: > #0 0x00d033c8 in Tk_FreeGC (tkGC.c:300) > #1 0x00cbfb50 in TkButtonWorldChanged (tkButton.c:1313) > #2 0x00cbfa2c in ConfigureButton (tkButton.c:1255) > #3 0x00cbeed4 in ButtonWidgetObjCmd (tkButton.c:816) > #4 0x00a63610 in EvalObjv (tclParse.c:932) > #5 0x00a637e4 in Tcl_EvalObjv (tclParse.c:1019) > #6 0x00210e18 in Tkapp_Call (_tkinter.c:622) > #7 0x00420a70 in fast_cfunction (ceval.c:3121) > #8 0x0041e0a8 in eval_frame (ceval.c:1996) > #9 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #10 0x00420b8c in fast_function (ceval.c:3154) > #11 0x0041e160 in eval_frame (ceval.c:2015) > #12 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #13 0x00420b8c in fast_function (ceval.c:3154) > #14 0x0041e160 in eval_frame (ceval.c:2015) > #15 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #16 0x00420b8c in fast_function (ceval.c:3154) > #17 0x0041e160 in eval_frame (ceval.c:2015) > #18 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #19 0x003e2bd4 in function_call (funcobject.c:381) > #20 0x003d0604 in PyObject_Call (abstract.c:1666) > #21 0x003d8208 in instancemethod_call (classobject.c:2277) > #22 0x003d0604 in PyObject_Call (abstract.c:1666) > #23 0x00420f98 in do_call (ceval.c:3251) > #24 0x0041e178 in eval_frame (ceval.c:2016) > #25 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #26 0x003e2bd4 in function_call (funcobject.c:381) > #27 0x003d0604 in PyObject_Call (abstract.c:1666) > #28 0x003d8208 in instancemethod_call (classobject.c:2277) > #29 0x003d0604 in PyObject_Call (abstract.c:1666) > #30 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) > #31 0x003d382c in PyInstance_New (classobject.c:558) > #32 0x003d0604 in PyObject_Call (abstract.c:1666) > #33 0x00420f98 in do_call (ceval.c:3251) > #34 0x0041e178 in eval_frame (ceval.c:2016) > #35 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #36 0x003e2bd4 in function_call (funcobject.c:381) > #37 0x003d0604 in PyObject_Call (abstract.c:1666) > #38 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) > #39 0x00414f10 in builtin_apply (bltinmodule.c:99) > #40 0x003f0814 in PyCFunction_Call (methodobject.c:101) > #41 0x0041e05c in eval_frame (ceval.c:1994) > #42 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #43 0x00420b8c in fast_function (ceval.c:3154) > #44 0x0041e160 in eval_frame (ceval.c:2015) > #45 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) > #46 0x003e2bd4 in function_call (funcobject.c:381) > #47 0x003d0604 in PyObject_Call (abstract.c:1666) > #48 0x003d8208 in instancemethod_call (classobject.c:2277) > #49 0x003d0604 in PyObject_Call (abstract.c:1666) > #50 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) > #51 0x00448248 in t_bootstrap (threadmodule.c:192) > #52 0x90020d28 in _pthread_body > > PPC Thread State: > srr0: 0x00d033c8 srr1: 0x0000f030 vrsave: 0x00000000 > xer: 0x00000000 lr: 0x00d033bc ctr: 0x90000ec0 mq: 0x00000000 > r0: 0x00000000 r1: 0xf01003f0 r2: 0x00000000 r3: 0x00000000 > r4: 0x00c761d0 r5: 0x00000010 r6: 0x00000010 r7: 0x00000000 > r8: 0x00052010 r9: 0x00000000 r10: 0x00000000 r11: 0xa00046fc > r12: 0x90000ec0 r13: 0x00000083 r14: 0x001059dc r15: 0x00000000 > r16: 0x00000000 r17: 0x00000000 r18: 0x00000000 r19: 0x0236acd0 > r20: 0x0017b805 r21: 0x001059ec r22: 0xf01008e8 r23: 0x0020c2d0 > r24: 0x001d39c0 r25: 0x00000000 r26: 0x00000004 r27: 0xf01008e8 > r28: 0x0236acd0 r29: 0x00c76930 r30: 0xf01003f0 r31: 0x00d033a8 > > Any help you can give me will be MUCH appreciated. No doubt the > problem is trivial. > > Yours, > > Seb > > > "War is not the answer..." - Marvin Gaye - 'What's Going On?' > --Apple-Mail-4-295389077 Content-Transfer-Encoding: 7bit Content-Type: text/enriched; charset=US-ASCII Hi all, I originally sent this to bob@redivi.com (the bundle maker) but so far nothing. I'm not sure if this is the right list for this sort of query as it's not strictly a programming question. If it isn't perhaps someone could point me in the right direction. However, if anyone can help me / explain what's going on, I'd be v. grateful. Seb Begin forwarded message: From: Sebastian Tennant < Date: Thu Mar 27, 2003 6:04:30 pm Europe/London To: bob@redivi.com Subject: Having a few problems with your bundle... Hi there. Sorry to trouble you. I've installed the bundle (p1614,1413,FFFEygame-1.3.4-osx-kitchensink.pkg.tar)0000,0000,504D using the tar command as advised and can't get Tkinter to work, but first of all was just wondering if you could explain something to me. I was only really interested in Tkinter, but thought that there was no harm in a few extra modules. I didn't realise that the bundle included a full pyhton2.2 installation so now I think I'm right in saying I've got two python installations on my machine, (a G4 running OS X 10.2.4); the pre-compiled Apple bundle, under /usr/lib/pyhton2.2/, and yours, under /Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/. Just to confound me more, the new modules that came with the bundle seem to have ALSO been installed under /usr/lib/pyhton2.2/? For instance, when I type pyhton from the command line which executable am I visiting? FFFC,9D99,5F5B[sebbyt: /usr] % ls bin/python -rwxr-xr-x 1 root wheel 784920 Feb 15 20:39 bin/python* [sebbyt: /usr] % ls local/bin/python lrwxr-xr-x 1 sebbyt staff 64 Mar 26 13:36 local/bin/python -> /Library/Frameworks/Python.framework/Versions/Current/bin/python*E8E5,0000,3633 /usr/local/bin/ is before /usr/bin/ in my PATH so I presume I am visiting the latter. FFFC,9D99,5F5BPATH=/sw/bin:/sw/sbin:/Users/sebbyt/bin/powerpc-apple-darwin:/Users/sebbyt/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/X11R6/bin I've set my environment variables as follows: FFFC,9D99,5F5BPYTHONDOCS=/usr/local/share/doc/python2.2 TK_LIBRARY=/usr/lib/python2.2/lib-tk TCL_LIBRARY=/System/Library/Tcl/8.3 (For TK_LIBRARY I have also tried /Library/Frameworks/Python.framework/Versions/2.2/lib/python2.2/lib-tk) So what actually is the problem I can hear you ask. Well when I try and test Tkinter by creating a simple button, somethimes I get the button on screen before Python crashes, sometimes not. Calling 'pydoc -g' crashes python every time, (being a GUI I assume it utilises Tkinter), so this is the output within the interpreter from 'pydoc -g' and the crash report follows after that. FFFC,9D99,5F5B[sebbyt: ~/.Terminal_folder] % pydoc -g TkMacOSXDoHLEvent failed : eppc 1 ,kHighLevelEvent 61657674 0000 aevt,-1708 RCNE SendEventToEventTarget (eppc 1 ) failed, -9874 Bus error Date/Time: 2003-03-27 16:41:09 +0000 OS Version: 10.2.4 (Build 6I32) Host: sebbyt.local. Command: python PID: 2572 Exception: EXC_BAD_ACCESS (0x0001) Codes: KERN_PROTECTION_FAILURE (0x0002) at 0x00000358 Thread 0: #0 0x9003ea88 in semaphore_wait_signal_trap #1 0x9003e8a4 in _pthread_cond_wait #2 0x00444d80 in PyThread_acquire_lock (thread.c:370) #3 0x00212ef8 in Tkapp_MainLoop (_tkinter.c:1698) #4 0x003f0814 in PyCFunction_Call (methodobject.c:101) #5 0x0041e05c in eval_frame (ceval.c:1994) #6 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #7 0x00420b8c in fast_function (ceval.c:3154) #8 0x0041e160 in eval_frame (ceval.c:2015) #9 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #10 0x00420b8c in fast_function (ceval.c:3154) #11 0x0041e160 in eval_frame (ceval.c:2015) #12 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #13 0x00420b8c in fast_function (ceval.c:3154) #14 0x0041e160 in eval_frame (ceval.c:2015) #15 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #16 0x0041a70c in PyEval_EvalCode (ceval.c:483) #17 0x0043d4d0 in run_node (pythonrun.c:1084) #18 0x0043d474 in run_err_node (pythonrun.c:1070) #19 0x0043d440 in PyRun_FileExFlags (pythonrun.c:1062) #20 0x0043c4c0 in PyRun_SimpleFileExFlags (pythonrun.c:692) #21 0x0043bed8 in PyRun_AnyFileExFlags (pythonrun.c:499) #22 0x0044681c in Py_Main (main.c:369) #23 0x00001e1c in _start #24 0x00001c4c in start Thread 1: #0 0x9002578c in select #1 0x00d84310 in NotifierThreadProc (tkMacOSXNotify.c:1027) #2 0x90020d28 in _pthread_body Thread 2 Crashed: #0 0x00d033c8 in Tk_FreeGC (tkGC.c:300) #1 0x00cbfb50 in TkButtonWorldChanged (tkButton.c:1313) #2 0x00cbfa2c in ConfigureButton (tkButton.c:1255) #3 0x00cbeed4 in ButtonWidgetObjCmd (tkButton.c:816) #4 0x00a63610 in EvalObjv (tclParse.c:932) #5 0x00a637e4 in Tcl_EvalObjv (tclParse.c:1019) #6 0x00210e18 in Tkapp_Call (_tkinter.c:622) #7 0x00420a70 in fast_cfunction (ceval.c:3121) #8 0x0041e0a8 in eval_frame (ceval.c:1996) #9 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #10 0x00420b8c in fast_function (ceval.c:3154) #11 0x0041e160 in eval_frame (ceval.c:2015) #12 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #13 0x00420b8c in fast_function (ceval.c:3154) #14 0x0041e160 in eval_frame (ceval.c:2015) #15 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #16 0x00420b8c in fast_function (ceval.c:3154) #17 0x0041e160 in eval_frame (ceval.c:2015) #18 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #19 0x003e2bd4 in function_call (funcobject.c:381) #20 0x003d0604 in PyObject_Call (abstract.c:1666) #21 0x003d8208 in instancemethod_call (classobject.c:2277) #22 0x003d0604 in PyObject_Call (abstract.c:1666) #23 0x00420f98 in do_call (ceval.c:3251) #24 0x0041e178 in eval_frame (ceval.c:2016) #25 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #26 0x003e2bd4 in function_call (funcobject.c:381) #27 0x003d0604 in PyObject_Call (abstract.c:1666) #28 0x003d8208 in instancemethod_call (classobject.c:2277) #29 0x003d0604 in PyObject_Call (abstract.c:1666) #30 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) #31 0x003d382c in PyInstance_New (classobject.c:558) #32 0x003d0604 in PyObject_Call (abstract.c:1666) #33 0x00420f98 in do_call (ceval.c:3251) #34 0x0041e178 in eval_frame (ceval.c:2016) #35 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #36 0x003e2bd4 in function_call (funcobject.c:381) #37 0x003d0604 in PyObject_Call (abstract.c:1666) #38 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) #39 0x00414f10 in builtin_apply (bltinmodule.c:99) #40 0x003f0814 in PyCFunction_Call (methodobject.c:101) #41 0x0041e05c in eval_frame (ceval.c:1994) #42 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #43 0x00420b8c in fast_function (ceval.c:3154) #44 0x0041e160 in eval_frame (ceval.c:2015) #45 0x0041f5a4 in PyEval_EvalCodeEx (ceval.c:2574) #46 0x003e2bd4 in function_call (funcobject.c:381) #47 0x003d0604 in PyObject_Call (abstract.c:1666) #48 0x003d8208 in instancemethod_call (classobject.c:2277) #49 0x003d0604 in PyObject_Call (abstract.c:1666) #50 0x004207f0 in PyEval_CallObjectWithKeywords (ceval.c:3039) #51 0x00448248 in t_bootstrap (threadmodule.c:192) #52 0x90020d28 in _pthread_body PPC Thread State: srr0: 0x00d033c8 srr1: 0x0000f030 vrsave: 0x00000000 xer: 0x00000000 lr: 0x00d033bc ctr: 0x90000ec0 mq: 0x00000000 r0: 0x00000000 r1: 0xf01003f0 r2: 0x00000000 r3: 0x00000000 r4: 0x00c761d0 r5: 0x00000010 r6: 0x00000010 r7: 0x00000000 r8: 0x00052010 r9: 0x00000000 r10: 0x00000000 r11: 0xa00046fc r12: 0x90000ec0 r13: 0x00000083 r14: 0x001059dc r15: 0x00000000 r16: 0x00000000 r17: 0x00000000 r18: 0x00000000 r19: 0x0236acd0 r20: 0x0017b805 r21: 0x001059ec r22: 0xf01008e8 r23: 0x0020c2d0 r24: 0x001d39c0 r25: 0x00000000 r26: 0x00000004 r27: 0xf01008e8 r28: 0x0236acd0 r29: 0x00c76930 r30: 0xf01003f0 r31: 0x00d033a8 Any help you can give me will be MUCH appreciated. No doubt the problem is trivial. Yours, Seb FFFD,2725,4240 "War is not the answer..." - Marvin Gaye - 'What's Going On?' --Apple-Mail-4-295389077-- From tim@johnsons-web.com Fri Apr 4 12:04:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Fri Apr 4 12:04:02 2003 Subject: [Tutor] Python and Delphi/Help Function In-Reply-To: References: Message-ID: <20030404171325.GA1573@johnsons-web.com> * alan.gauld@bt.com [030403 22:32]: > > >>>help(tuple) in the Windows interpreter just gives me an > > error message. (NameError) > > > > I currently have 2.2.2 on linux and 2.1.2 on windows. > > any comments here Alan? > > Install 222 on windows! :-) Duly noted. I will. > Seriously, look up help in the docs (the slow way!). > I think in versions before 2.2.x you had to import help before using it. > > Something like: > > >>> from help import help > >>> help (foo) Doesn't appear to be there at all (see above). I sure glad I stumbled across this thread. help() is a really nice feature. I work primarily in Linux and generally target *nix-style servers, but I am also quite impressed with what I have seen of the PythonWin IDE. I didn't see where is supported large projects with sessions, etc, ... but the environment is quite nice. -tim- -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From alan.gauld@bt.com Fri Apr 4 13:15:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Apr 4 13:15:01 2003 Subject: [Tutor] Problems with OSX Python bundle from link on Jack's M acPython page.. Message-ID: > someone could point me in the right direction. You can find out exactly which version you are running by typing $ which python that will at least confirm the version that runs when you type python at a prompt. > However, if anyone can help me / explain what's going on, I'd be v. grateful. This is somewhat beyond my ken however. My OS X install is just the vanilla one from the MacPython page. Alan G From tlo@aw.sgi.com Fri Apr 4 14:16:28 2003 From: tlo@aw.sgi.com (Terence Lo) Date: Fri Apr 4 14:16:28 2003 Subject: [Tutor] newbie: retrieving a program's return code via python Message-ID: <032d01c2fade$ccd17d00$ca411dc6@ms.aliaswavefront.com> hi i've got a newbie question: suppose my python script launches a command-line win32 application. how do i go about retrieving the return/exit code which that application sends out? thx in advance. Terence. From dyoo@hkn.eecs.berkeley.edu Fri Apr 4 16:12:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 4 16:12:02 2003 Subject: [Tutor] newbie: retrieving a program's return code via python In-Reply-To: <032d01c2fade$ccd17d00$ca411dc6@ms.aliaswavefront.com> Message-ID: On Fri, 4 Apr 2003, Terence Lo wrote: > suppose my python script launches a command-line win32 application. > how do i go about retrieving the return/exit code which that application > sends out? Hi Terence, The os.system() function's return value should capture that value. You may want to look at: http://www.python.org/doc/lib/os-process.html closely --- os.system() tries to pack two values into a single number, so it's a little tricky to use at first. The documentation of os.wait() (it's a little below the os.system() docs) explains which bits mean what. Please feel free to ask questions about it if you get stuck on decoding the return value. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri Apr 4 16:19:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 4 16:19:02 2003 Subject: [Tutor] Problems with OSX Python bundle from link on Jack's MacPython page.. In-Reply-To: Message-ID: On Fri, 4 Apr 2003, Sebastian Tennant wrote: > I originally sent this to bob@redivi.com (the bundle maker) but so far > nothing. Hi Sebastian, By the way, I wouldn't don't take it too personally if someone doesn't respond directly; they may be a bit busy. That's why asking on a community forum is usually a more reliable way to get answers. > I'm not sure if this is the right list for this sort of query as it's > not strictly a programming question. If it isn't perhaps someone could > point me in the right direction. However, if anyone can help me / > explain what's going on, I'd be v. grateful. This is definitely within jursidiction of the 'pythonmac' Special Interest Group; they'd have the Macintosh expertise to help figure out what's going on. You can find them at this link: http://www.python.org/sigs/pythonmac-sig/ I'm sure people there would be happy to get the problem fixed. Good luck to you! From bwglitch@hotpop.com Fri Apr 4 21:14:02 2003 From: bwglitch@hotpop.com (BW Glitch) Date: Fri Apr 4 21:14:02 2003 Subject: [Tutor] Re: If not global, how? Message-ID: <5.2.0.9.0.20030404205000.00be6e48@pop.hotpop.com> On 12:00 PM 3/31/2003 -0500, tutor-request@python.org feed this fish to the sharks: >In the app that I am developing, I have some callbacks >that need data from other methods. I am trying to >figure out how to make that data available without >making it global. Here is an example: > >This class is instantiated. >[snip] I don't know if it may be possible, but calling something like: callback(lambda: myFunction(value)) Might work. I haven't worked enough with the lambda to know if this is possible, but I've done it the other way around. Can someone correct me? -- Andres Rosado Email: andresr@despammed.com ICQ: 66750646 Homepage: http://andres980.tripod.com/ Get my PGP key at http://andres980.tripod.com/pgp-key.asc To find fault is easy; to do better may be difficult. -- Plutarch From rob@zoism.org Sat Apr 5 03:11:01 2003 From: rob@zoism.org (Rob Brown-Bayliss) Date: Sat Apr 5 03:11:01 2003 Subject: [Tutor] generla import questions Message-ID: <1049530228.20683.4.camel@musicbox> hi, I have a question about import. Say I have an app that does import a import b import c and some actual code. And in module b I have import c Are there now two copies of c in memory, are does all the class data and variables etc only exist once? Or put hit this way, if module c is: abc = "123" and module a does c.abc = "1234" in some function, and module b then prints c.abc what gets printed? -- * Rob Brown-Bayliss * ================= * zoism.org From din22@cox.net Sat Apr 5 04:54:02 2003 From: din22@cox.net (david) Date: Sat Apr 5 04:54:02 2003 Subject: [Tutor] inheriting __init__ arguments Message-ID: <001101c2fb59$5704f900$fc550144@pn.at.cox.net> This is a multi-part message in MIME format. ------=_NextPart_000_000E_01C2FB27.0C415620 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hello everyone.=20 if i make a class like this class A: def __init__(self,name): self.name=3Dname then i make another class that inherits from A its name attribute class B(A): def __init__(self, address): A.__init__(self,name) self.address=3Daddress but instances of B have addresses also. how can B inherit its name from initializing A? if my question makes any sense , please explain? ------=_NextPart_000_000E_01C2FB27.0C415620 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
hello everyone.
if i make a class like = this
 
class A:
    def=20 __init__(self,name):
       =20 self.name=3Dname
 
then i make another class that inherits = from A its=20 name attribute
 
class B(A):
    def __init__(self,=20 address):
       =20 A.__init__(self,name)
       =20 self.address=3Daddress
 
but instances of B have addresses=20 also.
how can B inherit its name from = initializing=20 A?
 
if my question makes any sense , please = explain?
 
------=_NextPart_000_000E_01C2FB27.0C415620-- From Don Arnold" Message-ID: <091b01c2fb77$148efb70$4813ba3f@defaultcomp> ----- Original Message ----- From: "david" To: Sent: Saturday, April 05, 2003 3:54 AM Subject: [Tutor] inheriting __init__ arguments hello everyone. if i make a class like this class A: def __init__(self,name): self.name=name then i make another class that inherits from A its name attribute class B(A): def __init__(self, address): A.__init__(self,name) self.address=address but instances of B have addresses also. how can B inherit its name from initializing A? if my question makes any sense , please explain? [my reply:] Your question makes perfect sense. You just need to pass name as an argument to B( ) so it can forward it on to A's __init__: class A: def __init__(self,name): self.name=name class B(A): def __init__(self, name, address): ## added name parameter A.__init__(self,name) self.address=address me = B('Don','12345 Main St') print me.name print me.address >>> Don >>> 12345 Main St HTH, Don From wkoorts@mweb.co.za Sat Apr 5 09:52:01 2003 From: wkoorts@mweb.co.za (Wayne Koorts) Date: Sat Apr 5 09:52:01 2003 Subject: [Tutor] extracting html source Message-ID: Hi, What's the simplest way to extract the value from a 'span' tag on= a specified web page (or any tag for that matter)? (i already= used urllib to get the html) and there is only one span tag on= the page. Regards, Wayne wkoorts@mweb.co.za From a_abdi406@yahoo.com Sat Apr 5 11:44:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Sat Apr 5 11:44:02 2003 Subject: [Tutor] about nltk installation Message-ID: <20030405164345.18076.qmail@web14508.mail.yahoo.com> --0-1953224754-1049561025=:18009 Content-Type: text/plain; charset=us-ascii hi, I have question about the modules, I downloaded NLTK module for win32 and I followed the instruction for installation from the web, having dowloaded I the wizardinstallation guided me to complete the installation and it installed the same directory as Python22, I opened the python interactive window to check whether the installation was successfull I called the module as follows: >>> from nltk.token import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named nltk.token >>> I consulted the FAQ before posting the question, so what is going on ? folder structure is as follows: C:\\Python22\\nltk1.0 thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more --0-1953224754-1049561025=:18009 Content-Type: text/html; charset=us-ascii

hi,

I have question about the modules, I downloaded NLTK module for win32 and I followed the instruction for installation from the web, having dowloaded I the wizardinstallation guided me to complete the installation and it installed the same directory as Python22,  I opened the python interactive window to check whether the installation was successfull I called the module as follows:

>>> from nltk.token import *
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ImportError: No module named nltk.token
>>>

I consulted the FAQ before posting the question, so what is going on ?

folder structure is as follows:

C:\\Python22\\nltk1.0

thanks in advance                  



Do you Yahoo!?
Yahoo! Tax Center - File online, calculators, forms, and more --0-1953224754-1049561025=:18009-- From charlie@begeistert.org Sat Apr 5 12:27:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Apr 5 12:27:01 2003 Subject: [Tutor] Re: Tutor import In-Reply-To: <20030405170005.15827.83721.Mailman@mail.python.org> References: <20030405170005.15827.83721.Mailman@mail.python.org> Message-ID: <20030405192852.1779.1@wonderland.1049559309.fake> On 2003-04-05 at 19:00:05 [+0200], tutor-request@python.org wrote: > Message: 7 > From: Rob Brown-Bayliss > To: PythonTutor List > Organization: > Date: 05 Apr 2003 20:10:10 +1200 > Subject: [Tutor] generla import questions > > > hi, I have a question about import. > > Say I have an app that does > > import a > import b > import c > > and some actual code. > > And in module b I have > > import c > > Are there now two copies of c in memory, are does all the class data and > variables etc only exist once? > > Or put hit this way, if module c is: The answer is think about the namespaces. If you do this in the interpreter it will be easier and use dir() "c" gets imported directly into your namespace and is thus directly accessible c.print "hi" will do whatever "print" does in c anything that is imported by "b" is available only in "b" ie., b.c.print "hi" has to be used in this case. Confusion is pretty much impossible except if you use "from b import *" in which case I think the most recent object will be used. See the "diamond rule" on how this stuff works in classes. Charlie From dyoo@hkn.eecs.berkeley.edu Sat Apr 5 16:26:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Apr 5 16:26:01 2003 Subject: [Tutor] about nltk installation In-Reply-To: <20030405164345.18076.qmail@web14508.mail.yahoo.com> Message-ID: On Sat, 5 Apr 2003, Abdirizak abdi wrote: > I have question about the modules, I downloaded NLTK module for win32 > and I followed the instruction for installation from the web, having > dowloaded I the wizardinstallation guided me to complete the > installation and it installed the same directory as Python22, I opened > the python interactive window to check whether the installation was > successfull I called the module as follows: Hi Abdirizak, Hmm... I tried answering you about this a week ago; were you able to get my reply? Here's a link to my reply: http://mail.python.org/pipermail/tutor/2003-April/021665.html Have you had success installing NLTK thorugh the Distutils system? Try downloading the source package, and then type: python setup.py install at your system's prompt; Distutils should take care of the rest. Hopefully. *grin* > folder structure is as follows: > > C:\\Python22\\nltk1.0 Yeah, this doesn't look right to me at all; third-party modules should live in the Lib/site-packages directory, so something looks a little weird about the folder structure. Good luck! From missive@hotmail.com Sat Apr 5 21:27:02 2003 From: missive@hotmail.com (Lee Harr) Date: Sat Apr 5 21:27:02 2003 Subject: [Tutor] Re: generla import questions Message-ID: >Say I have an app that does > >import a >import b >import c > >and some actual code. > >And in module b I have > >import c > >Are there now two copies of c in memory, are does all the class data and >variables etc only exist once? > Just one copy >Or put hit this way, if module c is: > >abc = "123" > >and module a does c.abc = "1234" in some function, and module b then >prints c.abc what gets printed? > Try it. That is one of many cool things about python: you can fire up the interpreter and type things at it and see what it says. 21:05 >cat > c.py abc = "123" 21:21 >cat > a.py import c c.abc = "1234" 21:22 >python Python 2.2 (#1, Jan 23 2002, 06:46:11) [GCC 2.95.3 20010315 (release) [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>>import c >>>c.abc '123' >>>import a >>>c.abc '1234' >>> _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From GREENDAY31087@aol.com Sun Apr 6 13:27:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Sun Apr 6 12:27:02 2003 Subject: [Tutor] icons on exe? Message-ID: <142.e8c7fc9.2bc1af19@aol.com> --part1_142.e8c7fc9.2bc1af19_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit OK, I have been using py2exe for a week now, but is there any way to change the icon of the created exe file? --part1_142.e8c7fc9.2bc1af19_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable OK, I have been using py2exe for a week now, but is th= ere any way to change the icon of the created exe file? --part1_142.e8c7fc9.2bc1af19_boundary-- From op73418@mail.telepac.pt Sun Apr 6 16:33:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Apr 6 15:33:02 2003 Subject: [Tutor] inheriting __init__ arguments References: <001101c2fb59$5704f900$fc550144@pn.at.cox.net> Message-ID: <001101c2fb67$4e2d7380$54190dd5@violante> This is a multi-part message in MIME format. ------=_NextPart_000_000E_01C2FB6F.AF86E4B0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable As in add another argument to B's initializer? e.g. class B(A): def __init__(self, name, address): A.__init__(self, name) self.address =3D address Now, with b =3D B('John Doe', 'Homeless') you just get his name via b.name. If you have any questions keep hollering With my best regards, G. Rodrigues ----- Original Message -----=20 From: david=20 To: tutor@python.org=20 Sent: Saturday, April 05, 2003 10:54 AM Subject: [Tutor] inheriting __init__ arguments hello everyone.=20 if i make a class like this class A: def __init__(self,name): self.name=3Dname then i make another class that inherits from A its name attribute class B(A): def __init__(self, address): A.__init__(self,name) self.address=3Daddress but instances of B have addresses also. how can B inherit its name from initializing A? if my question makes any sense , please explain? ------=_NextPart_000_000E_01C2FB6F.AF86E4B0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
As in add another argument to B's = initializer?=20 e.g.
 
class B(A):
    def __init__(self, = name,=20 address):
       =20 A.__init__(self, name)
       =20 self.address =3D address
 
Now, with
 
b =3D B('John Doe', = 'Homeless')
 
you just get his name via = b.name.
 
If you have any questions keep=20 hollering
 
With my best regards,
G. Rodrigues
 
----- Original Message -----
From:=20 david =
Sent: Saturday, April 05, 2003 = 10:54=20 AM
Subject: [Tutor] inheriting = __init__=20 arguments

hello everyone.
if i make a class like = this
 
class A:
    def=20 __init__(self,name):
       =20 self.name=3Dname
 
then i make another class that = inherits from A=20 its name attribute
 
class B(A):
    def __init__(self, = address):
       =20 A.__init__(self,name)
       =20 self.address=3Daddress
 
but instances of B have addresses=20 also.
how can B inherit its name from = initializing=20 A?
 
if my question makes any sense , = please=20 explain?
 
------=_NextPart_000_000E_01C2FB6F.AF86E4B0-- From andi@buxach.de Sun Apr 6 16:56:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Sun Apr 6 15:56:01 2003 Subject: [Tutor] common data access and timing Message-ID: <20030406215533.2fda21a5.andi@buxach.de> ave greetings to the list, i am new here :) Does anybody know RedCode or CoreWar ? I am currently working on a real-time version of this game, but i have a problem with the program structure. There is a datafield (the core), which must be accessed and changed regularly (let's say every 500ms). I am new to python, so how can i do such a time-trigger or sleep or wait? On the other side, the programm must handle several clients. I already have the network-socket-thingy, but i have problems with my inner-programm process-communication. The programm is structured as follows: 1 master daemon, for handling new clients x clients(fork), 1 for each client 1 core part(fork), for handling the core The clients must give commands to the core part, i thought the best solution would be pipes, so i made two pipes. One from master daemon to core-part and the other from core-part to master daemon. The clients take the pipe ends from the master daemon to send their commands. problem: reading the pipe with read(), seems not to work, so i used readline(), but now i must add and later subtract a '\n'. Could this be done more elegant? The main problem is the core part. It must include this timer and a proper communication with the clients. How should i do this? for info on CoreWar: http://www.sci.fi/~iltzu/corewar/guide.html -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de Kio estis kaj pasis, tion tempo frakasis From alan.gauld@bt.com Sun Apr 6 19:05:08 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Apr 6 18:05:08 2003 Subject: [Tutor] Re: generla import questions Message-ID: OK, I'll have a go at taking a diffeerent angle on this. >Say I have an app that does > >import a >import b >import c > >and some actual code. > >And in module b I have > >import c > >Are there now two copies of c in memory, are does all the class data and >variables etc only exist once? > Remember that a module in Python is an object much like any other object. c is the name of a module object and when ytou import c you import the *name* 'c' which referes to that module object. Thus it doesn't matter into how many diffrent namespaces you import the name c it will refer to the same module object. If you change that modules internal data then it will be changed for all the referenbces since they are all referencing the same module object. An import is very different to a C include statement. HTH, Alan G From antone.heyward@verizon.net Mon Apr 7 00:24:03 2003 From: antone.heyward@verizon.net (Antone) Date: Sun Apr 6 23:24:03 2003 Subject: [Tutor] Date to seconds conversion Message-ID: <000101c2fcb4$ef1bbb00$6001a8c0@blakout> What is the easiest way to convert a date (03/03/2003) to seconds? From dyoo@hkn.eecs.berkeley.edu Mon Apr 7 00:34:05 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 6 23:34:05 2003 Subject: [Tutor] icons on exe? In-Reply-To: <142.e8c7fc9.2bc1af19@aol.com> Message-ID: On Sun, 6 Apr 2003 GREENDAY31087@aol.com wrote: > OK, I have been using py2exe for a week now, but is there any way to > change the icon of the created exe file? Hello! According to: http://py2exe.sourceforge.net/ there's an optional '--icon' flag that you can add to that 'python setup.py py2exe' command; using '--icon' should let you decorate the EXE with your own icon file. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Apr 7 00:38:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 6 23:38:01 2003 Subject: [Tutor] Date to seconds conversion In-Reply-To: <000101c2fcb4$ef1bbb00$6001a8c0@blakout> Message-ID: On Sun, 6 Apr 2003, Antone wrote: > What is the easiest way to convert a date (03/03/2003) to seconds? Hi Antone, We need more specific information; in particular, can you explain in more detail what uou mean by turning a date into seconds? Distance is something that we measure, but to do the measurement, we need a point of reference. Are you trying to count the number of seconds since 03/01/2003, or 01/01/2003, or 01/01/1970, or 01/01/0001, or...? Talk to you later! From revanna@mn.rr.com Mon Apr 7 16:35:02 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Mon Apr 7 15:35:02 2003 Subject: [Tutor] Date to seconds conversion In-Reply-To: <000101c2fcb4$ef1bbb00$6001a8c0@blakout> References: <000101c2fcb4$ef1bbb00$6001a8c0@blakout> Message-ID: <200304071434.42438.revanna@mn.rr.com> On Sunday 06 April 2003 22:22, Antone wrote: > What is the easiest way to convert a date (03/03/2003) to seconds? If you're looking for "seconds from the epoch", use the time module in python's standard library. http://www.python.org/doc/current/lib/module-time.html localtime([secs]) Like gmtime() but converts to local time. The dst flag is set to 1 when DST applies to the given time. Changed in version 2.1: Allowed secs to be omitted. mktime(tuple) This is the inverse function of localtime(). Its argument is the full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform- dependent. time() Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. Some samples of the code: >>> import time >>> time.localtime() (2003, 4, 7, 14, 30, 38, 0, 97, 1) >>> time.mktime((2003, 4, 7, 14, 30, 38, 0, 97, 1)) 1049743838.0 >>> time.mktime((2003, 03, 04, 0, 0, 0, 0, 0, 0)) 1046757600.0 >>> Hope this helps. Anna From aicolburn@yahoo.com Mon Apr 7 16:47:02 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Mon Apr 7 15:47:02 2003 Subject: [Tutor] [Almost OT]Getting Started with CGI Message-ID: <20030407194601.84158.qmail@web41608.mail.yahoo.com> Hi all -- I'm quite interested in learning about Python and the web, developing web based forms that send the data people input on to a spreadsheet, etc. My problem is that I don't know a whole lot about CGI and I'm not sure my server will run Python scripts. (I'm quite comfortable with HTML, though.) Checking out the documentation for my campus' server I find: "The campus webserver permits running of CGI scripts through CGIwrap, which assures that your scripts run under your own account. Although other languages could potentially be used, just about everyone uses Perl for CGI scripts. You may either import scripts that you find out on the Internet or write them yourself. To enable them to run you must create a "cgi-bin" directory under your htdocs directory and make sure that the permissions allow public read and execute access but not write access." I'm comfortable with all the things mentioned in this paragraph. The problem, again, is whether I can set things up to run Python scripts. Do I need to get one of my campus network buddies to download and set up some sort of Python module? Is there a way for me to install files in my own cgi-bin directory, allowing me to be in control and run the scripts? (The campus uses some flavor of UNIX; I'm not up on Unix--I'm a Windows guy--but if I tell you it's "IRIX64 swift 6.5" will that help?) Bottom line: me and Python? OK. HTML? OK. CGI and/or UNIX? Not so OK. :-) Any suggestions about where to start? ... As always, thank you! Al C. p.s. I've seen a couple of the tutorials on CGI, and look forward to reading them--after taking care of the starting point(s) above. __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more http://tax.yahoo.com From KKGOLFER@aol.com Mon Apr 7 17:07:02 2003 From: KKGOLFER@aol.com (KKGOLFER@aol.com) Date: Mon Apr 7 16:07:02 2003 Subject: [Tutor] Help with creating a Python file for Report Generation Message-ID: <1580CE18.1CE8BA22.006F9B01@aol.com> Does anyone have a Python file already created that generates a report.......I need to copy tables and graphs out an Excel workbook and place them each individually into PowerPoint slides (same file).........I'm a newbie at this with no programming background. I can tailor files reasonably well, but starting from scratch....not there yet. Thank you. From am@fx.ro Mon Apr 7 18:09:02 2003 From: am@fx.ro (Adrian Maier) Date: Mon Apr 7 17:09:02 2003 Subject: [Tutor] looking for alternatives to tabular widget (Tkinter) Message-ID: <20030509023904.A231@coto> Hello! I really need a program for managing all the cdroms i have (data cdroms). Since I haven't found anything suitable for me that runs on Linux, I have begun to write my own application ... in python (using PostgreSQL for storing the data). I have already written a small utility that reads the cdrom and inserts the data in the database (it was amazingly easy .. Python's os.path.walk() did everything almost itself). The next phase is creating a nice user interface for browsing the contents of the cdroms, using Tkinter. Since Tkinter doesn't provide any widget for displaying tabular data, i am not sure how could i display the contents of the following table: create table DIRS ( CD integer, // cdrom id DIR integer, // directory id DIR_NAME text, // directory name CATEG integer, // category DESC varchar(50) ); // description The first 3 columns are read-only. The user should be able to modify easily the last 2 columns (Category and Description). When the user navigates from one directory to another, the program should display the files contained in that directory in a similar manner (this is to be done later). I thought about it and i came up with an idea, but i'm not sure if it is a good one: - using a ListBox for the read-only fields (i could concatenate them, or i could use only DIR_NAME). Let's say that 15 records will be visible at one time. - creating 15 pairs of Entry widgets - the user jumps from one recod to another using the Listbox, and the program will sinchronize the Entry fields so that they will allways contain the values that correspond to the directories visible in the Listbox. - the data is stored into a list of dictionaries (done already) /----------\ | dir1 | ( category1 ) ( description1 ) | dir2 | ( category2 ) ( description2 ) | dir3 | ( category3 ) ( description3 ) ...... .... .... | | ( category14 ) ( description14 ) | dir15 | ( category15 ) ( description15 ) \----------/ Does this sound feasible? Is there perhaps a better approach? Thank you for spending some time to read my question. Adrian Maier (am@fx.ro) From am@fx.ro Mon Apr 7 19:02:02 2003 From: am@fx.ro (Adrian Maier) Date: Mon Apr 7 18:02:02 2003 Subject: [Tutor] [Almost OT]Getting Started with CGI In-Reply-To: <20030407194601.84158.qmail@web41608.mail.yahoo.com>; from aicolburn@yahoo.com on Mon, Apr 07, 2003 at 12:46:01PM -0700 References: <20030407194601.84158.qmail@web41608.mail.yahoo.com> Message-ID: <20030509033207.A294@coto> Alan Colburn (aicolburn@yahoo.com) a scris : > The problem, again, is whether I can set > things up to run Python scripts. Do I need to get one > of my campus network buddies to download and set up > some sort of Python module? You might need to tell them to install Python itself. It appears that Python comes with a module called 'cgi', so i guess you won't need any additional modules (but maybe you need modules for database access?) > Is there a way for me to > install files in my own cgi-bin directory, allowing me > to be in control and run the scripts? (The campus uses > some flavor of UNIX; I'm not up on Unix--I'm a Windows > guy--but if I tell you it's "IRIX64 swift 6.5" will > that help?) There are at least 2 ways for transferring your files to that directory: 1. use ftp to transfer the files. 2. if you'll be able to get a "shell account" it would be great: this means that you'll be able to connect to that server with ssh and type commands as if you were at the console of that server. Cool, but you need to learn basic UNIX commands. It depends on the admin if they create such accounts or not. > Bottom line: me and Python? OK. HTML? OK. CGI and/or > UNIX? Not so OK. :-) > Any suggestions about where to start? ... As always, > thank you! First, find out if they have Python installed on that server. If not, convince them to install it. Second, write your Python script. (i can't tell you much about this, except that there is a module called cgi. Read its docs.) The first line of the script will have to be something like: #!/usr/bin/python This tells the operating system which is the interpreter to be used for executing your script ( ask the guys that administer the server about this: they know exactly where it is located). Third, transfer your file to your directory on the server. The admin should be able to tell you exactly how to do this. Ask him to tell you how to set the file permissions (the script has to be set as executable with the chmod utility: chmod 704 your_script.py ) I hope i wasn't too dense, but it's late here and i'm tired... Best regards, Adrian Maier (am@fx.ro) From GREENDAY31087@aol.com Mon Apr 7 20:34:01 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Mon Apr 7 19:34:01 2003 Subject: [Tutor] tkinter question Message-ID: <181.19266f73.2bc364b7@aol.com> --part1_181.19266f73.2bc364b7_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I wanted to know if I can put text in a frame itself. Also, can I change the color of a frame? --part1_181.19266f73.2bc364b7_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable I wanted to know if I can put text in a frame itself.=20= Also, can I change the color of a frame? --part1_181.19266f73.2bc364b7_boundary-- From phthenry@earthlink.net Mon Apr 7 21:59:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Apr 7 20:59:01 2003 Subject: [Tutor] dictionary entries within dictionary Message-ID: <20030407205800.N10955@localhost.localdomain> I can't figure out how to set up and access dictionaries within dictionaries. I set up my dictionary as follows: self.__styles_dict = {'para': {0:{}}, 'char':{0:{}}} Then try to add a value to this dictionary: self.__styles_dict[self.__type_of_style][self.__styles_num][att] = value I get an error message that key 15 cannot be found. In other words, I can't add a value to the inside entry of the dictionary. How do I do this? Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From reggie@merfinllc.com Mon Apr 7 22:17:04 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Mon Apr 7 21:17:04 2003 Subject: [Tutor] dictionary entries within dictionary In-Reply-To: <20030407205800.N10955@localhost.localdomain> References: <20030407205800.N10955@localhost.localdomain> Message-ID: <1049764593.19848.18.camel@pika> --=-CQbFXlPxH5uXK0tZXZQE Content-Type: text/plain Content-Transfer-Encoding: quoted-printable Paul, I'm assuming that self.__styles_num is 15 and that is what is causing you the problem. If that is the case, you can do what you want in one of at least 2 ways: x =3D self.__styles_dict[self.__type_of_style] if self.__styles_num not in x: x[self.__styles_num] =3D {} x[self.__styles_num][att] =3D value =09 or self.__styles_dict[self.__type_of_style].setdefault(self.__styles_num, {}) =3D value I hope I interpreted your question correctly and this will be of some use to you. On Mon, 2003-04-07 at 17:58, Paul Tremblay wrote: > I can't figure out how to set up and access dictionaries within > dictionaries. >=20 > I set up my dictionary as follows: >=20 > self.__styles_dict =3D {'para': {0:{}}, 'char':{0:{}}} >=20 > Then try to add a value to this dictionary: >=20 > self.__styles_dict[self.__type_of_style][self.__styles_num][att] =3D valu= e >=20 > I get an error message that key 15 cannot be found. In other words, I > can't add a value to the inside entry of the dictionary. >=20 > How do I do this? >=20 > Thanks >=20 > Paul --=20 Reggie --=-CQbFXlPxH5uXK0tZXZQE Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iD8DBQA+kiLxkeFt9Tpkup0RAjTtAKCf56KkE3g3+w1UXeDljbXOYaxCAwCfZ4P9 8sycimzOxk+ktjQZFQ7OuwM= =GzyX -----END PGP SIGNATURE----- --=-CQbFXlPxH5uXK0tZXZQE-- From jeff@ccvcorp.com Mon Apr 7 23:05:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Apr 7 22:05:03 2003 Subject: [Tutor] dictionary entries within dictionary References: <20030407205800.N10955@localhost.localdomain> Message-ID: <3E922EB3.8070603@ccvcorp.com> Paul Tremblay wrote: >I can't figure out how to set up and access dictionaries within >dictionaries. > >I set up my dictionary as follows: > >self.__styles_dict = {'para': {0:{}}, 'char':{0:{}}} > >Then try to add a value to this dictionary: > >self.__styles_dict[self.__type_of_style][self.__styles_num][att] = value > >I get an error message that key 15 cannot be found. In other words, I >can't add a value to the inside entry of the dictionary. > > If you're getting errors within dense lines like that, it often helps to take things apart and look at them one step at a time. First, let's reformat your dictionary definition so we can make a bit more sense of it: self.__styles_dict = { 'para' : { 0 : {} }, 'char' : { 0 : {} } } Now, look at the code in which you try to add something: style_dict = self.__styles_dict[self.__type_of_style] style = style_dict[self.__styles_num] style[att] = value Using these three lines in place of your one, we can see that self.__type_of_style needs to be either 'para' or 'char', and that currently, whichever of those it is, self.__styles_num must be 0. In that case, you're adding 'att: value' to one of the most-deeply-nested dicts, both of which start out empty. I suspect that your problem is that self.__styles_num is actually 15, and you have no such number defined within your style_dict. If you want to be able to create new sub-dictionaries on the fly if they don't already exist, then you can keep that line broken apart, and catch the KeyErrors. style_dict = self.__styles_dict[self.__type_of_style] try: style = style_dict[self.__styles_num] except KeyError: style = {} style_dict[self.__styles_num] = style style[att] = value If you want to be able to create style types, as well, then you'll need to catch the key error for the first dict access as well: try: style_dict = self.__styles_dict[self.__type_of_style] except KeyError: style_dict = { 0 : {} } self.__styles_dict[self.__type_of_style] = style_dict It might help to think of your nested dictionaries as a tree. Each item that's another dictionary is a twig, and items within the most-deeply-nested dictionaries (such as your att:value pair) are leaves. (Try sketching out the structure, like you'd see for a family tree.) Assignment, like your original code tries to do, can only create new leaves, not new twigs. You have to build those twigs before you can add leaves to them. (To stick with the family tree example, you need to create children before those new children can have grandchildren...) Hope this helps. Jeff Shannon Technician/Programmer Credit International From tbrauch@mindless.com Tue Apr 8 00:08:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Mon Apr 7 23:08:02 2003 Subject: [Tutor] CGI Help Message-ID: <002d01c2fd7b$efb95320$6600a8c0@tbrauch> I'm trying to start (re)learning a little cgi programming with python. Three years ago in a class, I wrote a very simple html page and script. I uploaded it to my server space at school and all worked fine. Now, I am out of school and running my own RHL 8.0 Linux box with Apache. I tried putting the files on my box but it doesn't want to work. Here is what I have: -----simple.html-----


Enter your password:
Are you: Male Female

Check any interests:
Computer Science
Skiing
Kayaking

---------- I know, it is bad HTML, but I was young and ignorant. -----simple2.py----- #!/usr/bin/python import cgi import smtplib print "Content-type: text/html\n" form=cgi.FieldStorage() #cgi.print_form(form) email='' if form.has_key('email'): email=form['email'].value print "Your email address is", email, "
" gender='' if form.has_key('gender'): gender=form['gender'].value print "You are", gender, "
" int1='' if form.has_key('int1'): int1=form['int1'].value print "You enjoy", int1, "
" int2='' if form.has_key('int2'): int2=form['int2'].value print "You enjoy", int2, "
" int3='' if form.has_key('int3'): int3=form['int3'].value print "You enjoy", int3, "
" smtp_object=smtplib.SMTP('localhost') from_address='tbrauch@localhost' to_addresses=['tbrauch@localhost'] message="""Subject: Form results Here are your form results! I am """+gender+""". I enjoy"""+int1+int2+int3+""".""" print smtp_object.sendmail(from_address,to_addresses,message) ---------- Again, ugly coding, but like I said, I was ignorant. And, three years ago, it worked. I got an A on this lab assignment, so it must have worked. Here are the permissions I have set: [root@linux0 simple]# dir total 28 -rw-r-xr-x 1 root root 978 Apr 7 23:05 simple2.py -rw-r--r-- 1 root root 676 Apr 7 22:48 simple.html -rw-r-xr-x 1 root root 628 Apr 7 22:48 simple.py The problem I get is when I click "Send It!" on the simple.html webpage, I get to look at my simple2.py code, but it does not execute. Any ideas what I might be doing wrong? - Tim From tbrauch@mindless.com Tue Apr 8 01:07:07 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue Apr 8 00:07:07 2003 Subject: [Tutor] CGI Help References: <74DAD2F23F03F7438D9BE3436C6846F701290653@AACC-MAIL.aacc.cc.md.us> Message-ID: <006701c2fd84$2a7646a0$6600a8c0@tbrauch> From: "Seabrook, Richard" From: Timothy M. Brauch [mailto:tbrauch@mindless.com] [ deleted ] Here are the permissions I have set: [root@linux0 simple]# dir total 28 -rw-r-xr-x 1 root root 978 Apr 7 23:05 simple2.py -rw-r--r-- 1 root root 676 Apr 7 22:48 simple.html -rw-r-xr-x 1 root root 628 Apr 7 22:48 simple.py The problem I get is when I click "Send It!" on the simple.html webpage, I get to look at my simple2.py code, but it does not execute. Any ideas what I might be doing wrong? - Tim ========================================================= Could be a path problem. Try checking the httpd error log (probably in /var/log/httpd) to see what program it's trying to execute. Dick S. ========================================================= There are no lines in my error_log that says anything is going wrong. Here is what my access_log has to say about it: win98.tbrauch - - [07/Apr/2003:23:07:36 -0400] "GET /simple/simple.html HTTP/1.1" 200 676 "http://192.168.xxx.xxx/simple/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR 1.0.3705)" win98.tbrauch - - [07/Apr/2003:23:07:38 -0400] "POST /simple/simple2.py HTTP/1.1" 200 978 "http://192.168.xxx.xxx/simple/simple.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR 1.0.3705)" win98.tbrauch - - [07/Apr/2003:23:08:27 -0400] "POST /simple/simple2.py HTTP/1.1" 200 978 "http://192.168.xxx.xxx/simple/simple.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR 1.0.3705)" Note, win98.tbrauch is my windows computer. I have tried accessing the files from it. And, 192.168.xxx.xxx is the internal IP address for my linux computer. I feel like it might be a path or permissions problem, but I'm not really sure what to change. I've been playing with Linux on my own for about 5 months now, so I'm a newbie. Oh, one more thing. I tried: [root@linux0 simple]# python simple2.py And it worked fine, it sent the email and no errors. However, when I try: [root@linux0 simple]# ./simple2.py : bad interpreter: No such file or directory Other files work if I try ./file_name.py, even if I put them in the same directory, just not this one. - Tim From missive@hotmail.com Tue Apr 8 01:16:18 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Apr 8 00:16:18 2003 Subject: [Tutor] Re: Help with creating a Python file for Report Generation Message-ID: >Does anyone have a Python file already created that generates >a report.......I need to copy tables and graphs out an Excel workbook and >place them each individually into PowerPoint slides (same file).........I'm >a newbie at this with no programming background. I can tailor files >reasonably well, but starting from scratch....not there yet. PyGDChart http://www.nullcube.com/software/pygdchart.html PyChart http://www.hpl.hp.com/personal/Yasushi_Saito/pychart/ GracePlot http://graceplot.sourceforge.net/ _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From am@fx.ro Tue Apr 8 02:16:25 2003 From: am@fx.ro (Adrian Maier) Date: Tue Apr 8 01:16:25 2003 Subject: [Tutor] [Almost OT]Getting Started with CGI In-Reply-To: <20030509033207.A294@coto>; from am@fx.ro on Fri, May 09, 2003 at 03:32:08AM +0300 References: <20030407194601.84158.qmail@web41608.mail.yahoo.com> <20030509033207.A294@coto> Message-ID: <20030509104635.B312@coto> Adrian Maier (am@fx.ro) a scris : > Third, transfer your file to your directory on the server. > The admin should be able to tell you exactly how to do this. > Ask him to tell you how to set the file permissions > (the script has to be set as executable with the chmod utility: > chmod 704 your_script.py ) Ooops: that should have been chmod 705 your_script.py Best regards, Adrian Maier From am@fx.ro Tue Apr 8 02:17:08 2003 From: am@fx.ro (Adrian Maier) Date: Tue Apr 8 01:17:08 2003 Subject: [Tutor] CGI Help In-Reply-To: <006701c2fd84$2a7646a0$6600a8c0@tbrauch>; from tbrauch@mindless.com on Tue, Apr 08, 2003 at 12:06:00AM -0400 References: <74DAD2F23F03F7438D9BE3436C6846F701290653@AACC-MAIL.aacc.cc.md.us> <006701c2fd84$2a7646a0$6600a8c0@tbrauch> Message-ID: <20030509104518.A312@coto> Timothy M. Brauch (tbrauch@mindless.com) a scris : > From: "Seabrook, Richard" > > From: Timothy M. Brauch [mailto:tbrauch@mindless.com] > [ deleted ] > > Here are the permissions I have set: > > [root@linux0 simple]# dir > total 28 > -rw-r-xr-x 1 root root 978 Apr 7 23:05 simple2.py > -rw-r--r-- 1 root root 676 Apr 7 22:48 simple.html > -rw-r-xr-x 1 root root 628 Apr 7 22:48 simple.py The scripts are not executable for the owner. I'd suggest: chmod 755 *.py (If i guess correctly, are you usually working as root? It is better to create some account and log in as root only when you need to configure something) > [root@linux0 simple]# ./simple2.py > : bad interpreter: No such file or directory The error probably refers to the interpreter specified in the first line of your script. Are you sure that /usr/bin/python is valid? Also, you may need to configure Apache (httpd.conf) before it will be able to execute your CGIs. I am not an expert in configuring Apache. I can only give you two hints. There is an option (ExecCGI if i remember correctly) that needs to be set for each directory that contains CGIs. (by default it isn't set because of security reasons) Apache knows when to execute a cgi based on the file's extension. The extension is cgi by default. You could either: a. rename your files to simple2.cgi or simple2.py.cgi b. configure apache to treat .py files as CGIs. Good luck. -- Adrian Maier (am@fx.ro, 0723.002.097) From phthenry@earthlink.net Tue Apr 8 02:53:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue Apr 8 01:53:01 2003 Subject: [Tutor] dictionary entries within dictionary In-Reply-To: <3E922EB3.8070603@ccvcorp.com> References: <20030407205800.N10955@localhost.localdomain> <3E922EB3.8070603@ccvcorp.com> Message-ID: <20030408015238.P10955@localhost.localdomain> On Mon, Apr 07, 2003 at 07:06:43PM -0700, Jeff Shannon wrote: > It might help to think of your nested dictionaries as a tree. Each item > that's another dictionary is a twig, and items within the > most-deeply-nested dictionaries (such as your att:value pair) are > leaves. (Try sketching out the structure, like you'd see for a family > tree.) Assignment, like your original code tries to do, can only create > new leaves, not new twigs. You have to build those twigs before you can > add leaves to them. (To stick with the family tree example, you need to > create children before those new children can have grandchildren...) Thanks. This makes sense. Using nested dictionaries is very tricky. I have to extract something from the big dictionary to make a temporary dictionary, then make a smaller dictionary to add to that, and finally add the whole thing to the permanent dictionary. It is too bad one can't directly assign values, as I was trying to do. (In perl, one has to store nested structures as referenes, and then dereference them--which is even trickier.) Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From Jaco.Smuts@za.didata.com Tue Apr 8 08:05:02 2003 From: Jaco.Smuts@za.didata.com (Jaco.Smuts@za.didata.com) Date: Tue Apr 8 07:05:02 2003 Subject: [Tutor] Can you make a build in one step Message-ID: <862D79D0DADB244E8563C6F9277C02FF022C11FD@zabrysvcl01ex01.af.didata.local> Hi there summary: I would like to run a build in one go for my new project. Python does not make/compile/build as C for instance, but what I want to be able to do (in one go) is: - running various unit tests - syntax checking - building distributions (http://www.python.org/doc/1.6/dist/dist.html) I am currently developing on windows, but I could move the dev environment to linux. Trying to comply to: http://www.joelonsoftware.com/articles/fog0000000043.html thanks Jaco sorry, nothing I can do about the lenthy disclaimer *************************************************************************************** This message contains information intended solely for the addressee, which is confidential or private in nature and subject to legal privilege. If you are not the intended recipient, you may not peruse, use, disseminate, distribute or copy this message or any file attached to this message. Any such unauthorised use is prohibited and may be unlawful. If you have received this message in error, please notify the sender immediately by e-mail, facsimile or telephone and thereafter delete the original message from your machine. Furthermore, the information contained in this message, and any attachments thereto, is for information purposes only and may contain the personal views and opinions of the author, which are not necessarily the views and opinions of Dimension Data (South Africa) (Proprietary) Limited or its subsidiaries and associated companies ("Dimension Data"). Dimension Data therefore does not accept liability for any claims, loss or damages of whatsoever nature, arising as a result of the reliance on such information by anyone. Whilst all reasonable steps are taken to ensure the accuracy and integrity of information transmitted electronically and to preserve the confidentiality thereof, Dimension Data accepts no liability or responsibility whatsoever if information or data is, for whatsoever reason, incorrect, corrupted or does not reach its intended destination. ************************************************************************************* From rhseabrook@aacc.edu Tue Apr 8 09:18:02 2003 From: rhseabrook@aacc.edu (Seabrook, Richard) Date: Tue Apr 8 08:18:02 2003 Subject: [Tutor] CGI Help Message-ID: <74DAD2F23F03F7438D9BE3436C6846F701290655@AACC-MAIL.aacc.cc.md.us> See response below. -----Original Message----- From: Timothy M. Brauch [mailto:tbrauch@mindless.com] Sent: Tue 4/8/2003 12:06 AM To: Seabrook, Richard; Python Tutor Cc:=09 There are no lines in my error_log that says anything is going wrong. = Here is what my access_log has to say about it: win98.tbrauch - - [07/Apr/2003:23:07:36 -0400] "GET /simple/simple.html = HTTP/1.1" 200 676 "http://192.168.xxx.xxx/simple/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR = 1.0.3705)" win98.tbrauch - - [07/Apr/2003:23:07:38 -0400] "POST /simple/simple2.py = HTTP/1.1" 200 978 "http://192.168.xxx.xxx/simple/simple.html" "Mozilla/4.0 (compatible; = MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR 1.0.3705)" win98.tbrauch - - [07/Apr/2003:23:08:27 -0400] "POST /simple/simple2.py = HTTP/1.1" 200 978 "http://192.168.xxx.xxx/simple/simple.html" "Mozilla/4.0 (compatible; = MSIE 6.0; Windows 98; YComp 5.0.2.6; .NET CLR 1.0.3705)" Note, win98.tbrauch is my windows computer. I have tried accessing the = files from it. And, 192.168.xxx.xxx is the internal IP address for my linux computer. I feel like it might be a path or permissions problem, but I'm not = really sure what to change. I've been playing with Linux on my own for about 5 months now, so I'm a newbie. Oh, one more thing. I tried: [root@linux0 simple]# python simple2.py And it worked fine, it sent the email and no errors. However, when I = try: [root@linux0 simple]# ./simple2.py : bad interpreter: No such file or directory Other files work if I try ./file_name.py, even if I put them in the same = directory, just not this one. - Tim =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D Check the first line of your simple2.py file very carefully to make sure it doesn't have a DOS CRLF combination at the end rather than just a UNIX LF (newline). If you're working between Win98 and Linux it's easy to have this happen, and in most cases the shell won't interpret the shebang line (#!/usr/bin/python) correctly with DOS end-of-record markers. If you open simple2.py with Vim it will probably say (DOS) at the bottom. Dick S. From abli@freemail.hu Tue Apr 8 11:09:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Apr 8 10:09:01 2003 Subject: [Tutor] tkinter question In-Reply-To: <181.19266f73.2bc364b7@aol.com> References: <181.19266f73.2bc364b7@aol.com> Message-ID: <20030408140743.GA1345@hooloovoo> GREENDAY31087 wrote: > I wanted to know if I can put text in a frame itself. No. You need to put the text into a widget (a Label, for example), and put that widget into the frame. (If you set the label's options right, the widget itself wont be visible, so the text will look like being in the frame. (I think the default options will do.)) > Also, can I change the color of a frame? You can change the background color, by passing in an option when you create the frame or by calling frame.config(), like this: import Tkinter frame=Tkinter.Frame(background='red') frame.pack() frame.config(bg='blue') (bg is a synonim for background, they do the same.) Abel Daniel From abli@freemail.hu Tue Apr 8 12:16:20 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Apr 8 11:16:20 2003 Subject: [Tutor] looking for alternatives to tabular widget (Tkinter) In-Reply-To: <20030509023904.A231@coto> References: <20030509023904.A231@coto> Message-ID: <20030408151358.GA1577@hooloovoo> Adrian Maier wrote: > I really need a program for managing all the cdroms i have > (data cdroms). Since I haven't found anything suitable for me > that runs on Linux, Not even gtktalog? (http://www.nongnu.org/gtktalog/) Looks pretty neat. (Haven't used it, though.) > - using a ListBox for the read-only fields (i could concatenate > them, or i could use only DIR_NAME). Let's say that 15 > records will be visible at one time. > > - creating 15 pairs of Entry widgets > > - the user jumps from one recod to another using the Listbox, > and the program will sinchronize the Entry fields so that > they will allways contain the values that > correspond to the directories visible in the Listbox. > > - the data is stored into a list of dictionaries (done already) > > /----------\ > | dir1 | ( category1 ) ( description1 ) > | dir2 | ( category2 ) ( description2 ) > | dir3 | ( category3 ) ( description3 ) > ...... .... .... > | | ( category14 ) ( description14 ) > | dir15 | ( category15 ) ( description15 ) > \----------/ > > > Does this sound feasible? Is there perhaps a better approach? Tkinter itself doesn't have a table widget you need, but others already needed such thing, so you might try re-using thier solution. For example http://www.novagrid.com/page.php?p=spreadsheet.html looks pretty neat. (I never used it.) (Another one would be to use Pmw, it has a table-like widget in the contrib directory, altough you might need to modify it to allow editing the data) Of course, you only need a limited set of features (for example the number of columns is fixed), so writing your own should be pretty strait-forward. One thing I would do differently: You mention using Listboxes for navigation. However, a part of the data would be outside of the listbox. This would mean that by scrolling the listbox, you would break the rows, as a part of the row would be scrolled and the rest wouldn't. Of course this wont be a problem if you hardcode the size of the listbox and make the window big enough so that everything is visible, and the scrollbar can't be scrolled simply because it doesn't have enough lines to need it. But in this case, why are you using a listbox at all? You aren't using any features of a listbox, you could simple create 15 Labels under eachother to reach the same effect. An other idea would be to use ScrolledFrame from the Pmw widgets. With that you could create Labels or Entrys as needed for each piece of data, put them into the the ScrolledFrame which would take care of scrolling it. I think this is the way the widget in Pmw's contrib dir works. Abel Daniel From abli@freemail.hu Tue Apr 8 12:30:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Apr 8 11:30:02 2003 Subject: [Tutor] Can you make a build in one step In-Reply-To: <862D79D0DADB244E8563C6F9277C02FF022C11FD@zabrysvcl01ex01.af.didata.local> References: <862D79D0DADB244E8563C6F9277C02FF022C11FD@zabrysvcl01ex01.af.didata.local> Message-ID: <20030408152901.GB1577@hooloovoo> Jaco.Smuts wrote: > Hi there > > summary: > I would like to run a build in one go for my new project. > Python does not make/compile/build as C for instance, but what I want to be > able to do (in one go) is: > - running various unit tests > - syntax checking You mean running pychecker, right? if the unit tests pass, the syntax must be correct, and if the unit test don't catch a possible syntax problem (ie. a part of the code isn't tested) then you should fix (i.e. write more) unit tests. (At least that's what i gather from reading a bit about XP, never done that myself.) > - building distributions (http://www.python.org/doc/1.6/dist/dist.html) Build systems for C and other compiled languages are important because building a big program usually takes a lot of time. Build systems speed this up by only rebuilding the parts which must be rebuilt (that part of the source-code, or a part it depended on changed). So systems like 'make' are a must for bigger projects. Python, however, has this basically built in (thats what the .pyc files are for). If your project isn't too big, then a simple script could do it. Or you could try a more 'advanced' framework, like Scons (http://www.scons.org/). (I didn't try it). Its written in python and it's cross-platform (runs on windows NT). However, be avare that using a big framework means that you have to get comfortable with yet another software, which always takes time. Folks at comp.lang.python might give you more first-hand experience. Abel Daniel From alpha_bravo@adelphia.net Tue Apr 8 13:52:05 2003 From: alpha_bravo@adelphia.net (Aaron Harrier) Date: Tue Apr 8 12:52:05 2003 Subject: [Tutor] Open GL question Message-ID: <000e01c2fe08$951bb650$6501a8c0@aaronhome> This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C2FDCD.E8A90830 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello all I am just starting to learn this language and I know that many = people have written many modules. I was wondering if there is a current = Open GL library and/or GLUT library out there that I can import into = python so that I can utilize python to learn Open GL. Thanks Aaron ------=_NextPart_000_000B_01C2FDCD.E8A90830 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello all
 
    I am just starting = to learn this=20 language and I know that many people have written many modules.  I = was=20 wondering if there is a current Open GL library and/or GLUT library out = there=20 that I can import into python so that I can utilize python to learn Open = GL.
 
Thanks
Aaron
 
 
------=_NextPart_000_000B_01C2FDCD.E8A90830-- From bobsmith327@hotmail.com Tue Apr 8 14:05:02 2003 From: bobsmith327@hotmail.com (bob smith) Date: Tue Apr 8 13:05:02 2003 Subject: [Tutor] Open GL question Message-ID: Hi Aaron, Try: http://pyopengl.sourceforge.net/ If you're interested in writing games with Python, look at: http://pygame.org/ >From: "Aaron Harrier" >To: >Subject: [Tutor] Open GL question >Date: Tue, 8 Apr 2003 12:53:53 -0700 > >Hello all > > I am just starting to learn this language and I know that many people >have written many modules. I was wondering if there is a current Open GL >library and/or GLUT library out there that I can import into python so that >I can utilize python to learn Open GL. > >Thanks >Aaron > > _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From dyoo@hkn.eecs.berkeley.edu Tue Apr 8 15:54:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 8 14:54:01 2003 Subject: [Tutor] dictionary entries within dictionary In-Reply-To: <20030408015238.P10955@localhost.localdomain> Message-ID: On Tue, 8 Apr 2003, Paul Tremblay wrote: > On Mon, Apr 07, 2003 at 07:06:43PM -0700, Jeff Shannon wrote: > > It might help to think of your nested dictionaries as a tree. Each item > > that's another dictionary is a twig, and items within the > > most-deeply-nested dictionaries (such as your att:value pair) are > > leaves. (Try sketching out the structure, like you'd see for a family > > tree.) Assignment, like your original code tries to do, can only create > > new leaves, not new twigs. You have to build those twigs before you can > > add leaves to them. (To stick with the family tree example, you need to > > create children before those new children can have grandchildren...) > > Thanks. This makes sense. > > Using nested dictionaries is very tricky. I have to extract something > from the big dictionary to make a temporary dictionary, then make a > smaller dictionary to add to that, and finally add the whole thing to > the permanent dictionary. It is too bad one can't directly assign > values, as I was trying to do. Hi Paul, We may want to try the setdefault() method of a dictionary; it provides for the same kind of convenience as the "autovivifying" feature in Perl: ### >>> d = {} >>> d.setdefault('a', {}).setdefault('alpha', {})[0] = 1 >>> d {'a': {'alpha': {0: 1}}} >>> d.setdefault('a', {}).setdefault('beta', {})[0] = 42 >>> d {'a': {'alpha': {0: 1}, 'beta': {0: 42}}} ### That being said, doing this sort of nested dictionary by hand might not be the best way to organize our data --- it's forcing us to think about dictionaries within dictionaries. And while it might be easy to construct, it's difficult to read. Using some sort of class structure might be a better way to make this more palatable. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Apr 8 16:03:25 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 8 15:03:25 2003 Subject: [Tutor] Open GL question In-Reply-To: <000e01c2fe08$951bb650$6501a8c0@aaronhome> Message-ID: On Tue, 8 Apr 2003, Aaron Harrier wrote: > Hello all > > I am just starting to learn this language and I know that many > people have written many modules. I was wondering if there is a current > Open GL library and/or GLUT library out there that I can import into > python so that I can utilize python to learn Open GL. Here you go: http://pyopengl.sourceforge.net/ *grin* Please feel free to ask questions about Python here; we'll be happy to help. From tpc@csua.berkeley.edu Tue Apr 8 18:01:33 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Apr 8 17:01:33 2003 Subject: [Tutor] newbie question Message-ID: <20030408135937.X16030-100000@localhost.name> Hello Danny, thank you for letting me know about the tutor list. I have joined and I thought I should direct this question to you since you wrote the manual I am learning Python from. On pages 12 and 13 you specify two programs to take words from standard input, count how many times a word appears, and print the results out: import sys from string import strip words = [] while 1: w = strip(sys.stdin.readline()) if not w: break words.append(w) words.sort() i=0 while i < len(words): current_word, count = words[i], 0 while i < len(words) and words[i] == current_word: count = count + 1 i = i + 1 print current_word, count and: import sys from string import strip dict = {} while 1: w = strip(sys.stdin.readline()) if not w: break dict[w] = dict.get(w, 0) + 1 for word, count in dict.items(): print word, count The problem is when I try to run these programs standalone it seems to hang and I have to hit Ctrl-d which gives me this message: Traceback (most recent call last): File "/usr/local/apache2/htdocs/test.py", line 7, in ? w = strip(sys.stdin.readline()) KeyboardInterrupt When I try to run the program with arguments from the command line it hangs and I have to hit Ctrl-d which returns nothing: [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning Am I doing something wrong ? From oplin_eater@yahoo.com Tue Apr 8 18:34:01 2003 From: oplin_eater@yahoo.com (Not Important) Date: Tue Apr 8 17:34:01 2003 Subject: [Tutor] moving files Message-ID: <20030408213306.99539.qmail@web41808.mail.yahoo.com> --0-1964813059-1049837586=:99108 Content-Type: text/plain; charset=us-ascii I can't seem to find a module to move file is there one or any other way to move files? --------------------------------- Do you Yahoo!? Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1964813059-1049837586=:99108 Content-Type: text/html; charset=us-ascii

I can't seem to find a module to move file

is there one or any other way to move files?



Do you Yahoo!?
Yahoo! Platinum - Watch CBS' NCAA March Madness, live on your desktop! --0-1964813059-1049837586=:99108-- From dyoo@hkn.eecs.berkeley.edu Tue Apr 8 18:35:08 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 8 17:35:08 2003 Subject: [Tutor] newbie question [standard input] In-Reply-To: <20030408135937.X16030-100000@localhost.name> Message-ID: On Tue, 8 Apr 2003 tpc@csua.berkeley.edu wrote: > Hello Danny, thank you for letting me know about the tutor list. Hello! Welcome aboard! > I have joined and I thought I should direct this question to you since > you wrote the manual I am learning Python from. Uh oh. The quicky introduction I wrote at: http://hkn.eecs.berkeley.edu/~dyoo/python/intro/introduction.ps is really a brief dive into Python. For more comprehensive and complete Python tutorials, you may want to look at: http://python.org/doc/Newbies.html instead. Please understand that I wrote that introduction.ps to help advertise Python, but that introduction was never meant to survive beyond that semester... *grin* > On pages 12 and 13 you specify two programs to take words from standard > input [some text cut] > The problem is when I try to run these programs standalone it seems to > hang and I have to hit Ctrl-d which gives me this message: > > Traceback (most recent call last): > File "/usr/local/apache2/htdocs/test.py", line 7, in ? > w = strip(sys.stdin.readline()) > KeyboardInterrupt > > When I try to run the program with arguments from the command line it > hangs and I have to hit Ctrl-d which returns nothing: > > [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning > [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning > [root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning Ah! The term 'standard input' is subtly different from 'command line argument'; although they are both conceptually "inputs" to a program, they are two different entry points and are treated separately. This can be initially confusing at first --- and now that you bring it up, it does seem slightly kludgy... hmmm... Anyway, the statements above have sent to the 'test.py' the three command line arguments: ['good', 'good', 'morning']. Our dilemma is that the program is looking for content within the 'standard input' passage, and not through the command line arguments. Let's see how to feed data through the 'standard input' method. Try preparing a text file called 'sample.txt', and then try from your shell: $ cat sample.txt | python test.py The command above is an example of a "pipeline": the pipe symbol '|' tells the system to take the output of the first command, and feed it as standard input to the second command. The unix command 'cat' takes all filenames in its command line arguments, opens each file, and spews the contents into standard output... and the pipeline turns the standard output of the left hand side into the standard input of the right hand side. Play around with pipelines a bit, and the concept of standard input and output should become clearer. If we go back to what had been happening before: What was happening originally was that, because the program had not been started off from a pipeline, your Unix operating system was assuming that the 'standard input' would come from stuff that you type in next. The program was not actually hanging, but just waiting for you to start typing. *grin* So if you want, try: python test.py and then start typing lines of words, one word per line. Finally, press Control-D to tell the system that you're done typing into standard input. [Slightly off topic: It looks like you're also beginning to learn Unix on your own system! Cool. Since it's the beginning of the spring semester in Berkeley, I think the Self Paced Center (SPC) is open: there are some Unix tutors there that you can talk to: http://www-inst.eecs.berkeley.edu/~selfpace/newpage/spc-front.html The folks at the SPC are pretty friendly; if you see Carol, say hi for me. *grin* You should definitely NOT normally be running programs as the 'root' user on your machine. I recommend adding and using a regular non-privileged user account while you experiment with Python.] Good luck to you! From bgailer@alum.rpi.edu Tue Apr 8 20:41:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue Apr 8 19:41:02 2003 Subject: [Tutor] moving files In-Reply-To: <20030408213306.99539.qmail@web41808.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030408173905.029e1188@66.28.54.253> --=======5477503======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-53C0322D; boundary="=====================_36174115==.ALT" --=====================_36174115==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-53C0322D; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:33 PM 4/8/2003 -0700, Not Important wrote: >I can't seem to find a module to move file >is there one or any other way to move files? Check out the shutil module. "The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal." Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_36174115==.ALT Content-Type: text/html; x-avg-checked=avg-ok-53C0322D; charset=us-ascii Content-Transfer-Encoding: 8bit At 02:33 PM 4/8/2003 -0700, Not Important wrote:
I can't seem to find a module to move file
is there one or any other way to move files?

Check out the shutil module.
"The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal."

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_36174115==.ALT-- --=======5477503======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-53C0322D Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======5477503=======-- From alpha_bravo@adelphia.net Tue Apr 8 21:37:02 2003 From: alpha_bravo@adelphia.net (Aaron Harrier) Date: Tue Apr 8 20:37:02 2003 Subject: [Tutor] Open GL question References: Message-ID: <006c01c2fe49$9ca37160$6501a8c0@aaronhome> Thanks Bob and Danny, guess this so far negates my wanting to shell out the cash for MVC++.net. Anyway I suppose while I am writing I will ask if you guys have the link to the windows module so I can utilice MFCs if need be or just open a window with menus for that matter. I know I have seen this someplace and I am sorry if this is a very silly questions :). ----- Original Message ----- From: "Danny Yoo" To: "Aaron Harrier" Cc: Sent: Tuesday, April 08, 2003 12:02 PM Subject: Re: [Tutor] Open GL question > > > On Tue, 8 Apr 2003, Aaron Harrier wrote: > > > Hello all > > > > I am just starting to learn this language and I know that many > > people have written many modules. I was wondering if there is a current > > Open GL library and/or GLUT library out there that I can import into > > python so that I can utilize python to learn Open GL. > > Here you go: > > http://pyopengl.sourceforge.net/ > > *grin* > > Please feel free to ask questions about Python here; we'll be happy to > help. > > From zmerch@30below.com Tue Apr 8 21:56:01 2003 From: zmerch@30below.com (Roger Merchberger) Date: Tue Apr 8 20:56:01 2003 Subject: [Tutor] Cross-class data sharing... Message-ID: <5.1.0.14.2.20030408204437.00a942c8@mail.30below.com> ... My name is Roger... and I'm a newbie... [[ Is there a 12-step program for this??? :-O ]] Well, only a newbie to Python, and OOP programming. Anyway, I'm reading _Programming Python_ and lemme tell ya, it's a good book, but it's a "thick" read! As a programming practice, I've been working with Tkinter creating entry fields & action buttons for an MPEG Bitrate calculator, where it takes the file path from one frame, and the filename from another frame. Clicking a button puts the fields together, opens a file, and writes a small script, code to follow. The 2 frames in question are set up as classes, and everything seems to work [kinda] until it comes to the cross-class Entry data fields... After futzing with this for 3 hours last nite, I realized that I don't think my book covered that yet... I could prolly hack it up without classes, but a) I wanted to see if I could do it, and b) it would be nice to have the code reuse ability of classes for future programs. Any pointers to help me along my path? Thanks to one and all! Roger "Merch" Merchberger =-=-=-=-=-=-= snip here -- code follows =-=-=-=-=-=-=-= #!/usr/bin/python # This is my first attempt at a fromthebrain gui proggie... from Tkinter import * import sys class zfile(Frame): def __init__(self,master=None): Frame.__init__(self,master) Pack.config(self) zlabel=Label(self) zlabel.config(text="Show Prepend Text",width=20) zlabel.pack(side=LEFT) self.zshow=StringVar() zshowent=Entry(self) zshowent.config(width=50) zshowent.config(textvariable=self.zshow) self.zshow.set('') zshowent.pack(side=LEFT) def state(self): return self.zshow.get() class get_path(Frame): def __init__(self,master=None,zfile=''): Frame.__init__(self,master) Pack.config(self) avilabel=Label(self) avilabel.config(text="AviScript Path",width=20) avilabel.pack(side=LEFT) self.avipath=StringVar() avient=Entry(self) avient.config(width=50) avient.config(textvariable=self.avipath) self.avipath.set('h:/!tivo/bork.avs') avient.pack(side=LEFT) def state(self): return self.avipath.get() def wrtfile(fname,addstring): fileout = open(fname,"w") zout = [ '# bork... to see if it can append...\n' ] d2v='vid=MPEG2Source("%s.d2v")\n' % addstring wav='aud=WAVSource("%s.wav")\n' % addstring therest = [ 'AudioDub(vid,aud)\n', 'DelayAudio(.0xx)\n', 'src=ResampleAudio(44100)\n', '\n', 'src\n' ] zout.append(d2v) zout.append(wav) for bing in therest: zout.append(bing) fileout.writelines(zout) # now for the main loop... if __name__ == '__main__': root=Tk() fname=zfile(root) addstr=get_path(root) dz=Frame(root) aviout=Button(dz,text="AviOut",command=wrtfile(fname,addstr)) aviout.pack(side=RIGHT) aviout=Button(dz,text="Die",command=root.destroy) aviout.pack(side=RIGHT) dz.pack() # root.mainloop() From am@fx.ro Wed Apr 9 00:49:01 2003 From: am@fx.ro (Adrian Maier) Date: Tue Apr 8 23:49:01 2003 Subject: [Tutor] looking for alternatives to tabular widget (Tkinter) In-Reply-To: <20030408151358.GA1577@hooloovoo>; from abli@freemail.hu on Tue, Apr 08, 2003 at 05:13:58PM +0200 References: <20030509023904.A231@coto> <20030408151358.GA1577@hooloovoo> Message-ID: <20030509222222.A600@coto> Abel Daniel (abli@freemail.hu) a scris : > Adrian Maier wrote: > > Not even gtktalog? (http://www.nongnu.org/gtktalog/) > Looks pretty neat. (Haven't used it, though.) I didn't know about it. > Tkinter itself doesn't have a table widget you need, but others already > needed such thing, so you might try re-using thier solution. For example > http://www.novagrid.com/page.php?p=spreadsheet.html > looks pretty neat. (I never used it.) > (Another one would be to use Pmw, it has a table-like widget in the > contrib directory, altough you might need to modify it to allow editing > the data) > > Of course, you only need a limited set of features (for example the > number of columns is fixed), so writing your own should be pretty > strait-forward. > But in this case, why are you using a listbox at all? You aren't using > any features of a listbox, you could simple create 15 Labels under > eachother to reach the same effect. Good point. > An other idea would be to use ScrolledFrame from the Pmw widgets. > With that you could create Labels or Entrys as needed for each piece of > data, put them into the the ScrolledFrame which would take care of > scrolling it. I think this is the way the widget in Pmw's contrib dir > works. Thank you for the ideas. I'll investigate these options. I guess i could also try to use a Canvas ? ( there could be a problem with editing, though) Best wishes, -- Adrian Maier (am@fx.ro, 0723.002.097) From hsteiger@comcast.net Wed Apr 9 01:01:08 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Wed Apr 9 00:01:08 2003 Subject: [Tutor] Testing for response from a Web site Message-ID: <000501c2fe4c$71515380$0201a8c0@eagle> To All: How can I test the response of a server on a Web site to a request that occurs when I attempt to access the Web site? I am using the Windows XP operating system. For example, if I select a link to a Web site, the server can respond in (I think) only 3 different ways: 1) It can simply ignore the request. 2) It can honor the request and I can therefore download some data, or... 3) It might send my PC some other response that I can test for in a Python program, that tells the program that the site is not accessible or available. Here is the code I am using: _________________________________________________ metURL = "http://isl715.nws.noaa.gov/tdl/forecast/tdl_etamet.txt" f_object = open("c:\\python_pgms\\plot_guidance\\met_data.txt", 'w') try: print "\nBEGIN DOWNLOADING ETA (MET) MOS" metall = urllib.urlopen(metURL).read() f_object.write(metall) f_object.close() except: print "Could not obtain data from Web" f_object.close() ____________________________________________________ As it stands now, the program will just say the data is old, when I really should say something like "could not connect with the site." What additional test(s) can I perform to catch other responses from a server, especially one in which the server will not honor my request? Thanks for any help. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From alpha_bravo@adelphia.net Wed Apr 9 01:44:02 2003 From: alpha_bravo@adelphia.net (Aaron Harrier) Date: Wed Apr 9 00:44:02 2003 Subject: [Tutor] Idle & PythonWin Message-ID: <009501c2fe6c$10c58b60$6501a8c0@aaronhome> This is a multi-part message in MIME format. ------=_NextPart_000_0092_01C2FE31.644FD000 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello again...I seem to be here a lot these days. I installed Python 2.2 a few days ago and today in confusion I also = installed win32all. Aside from now having the option to run win32,MFCs = and have the choice between IDLE and PythonWin does anyone know if this = should cause an issue? They seem to have both installed in the same = directory. Aaron ------=_NextPart_000_0092_01C2FE31.644FD000 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hello again...I seem to be here a lot = these=20 days.
 
    I installed Python = 2.2 a few=20 days ago and today in confusion I also installed win32all.  Aside = from now=20 having the option to run win32,MFCs and have the choice between IDLE and = PythonWin does anyone know if this should cause an issue?  They = seem to=20 have both installed in the same directory.
 
Aaron
------=_NextPart_000_0092_01C2FE31.644FD000-- From hsteiger@comcast.net Wed Apr 9 02:00:01 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Wed Apr 9 01:00:01 2003 Subject: [Tutor] Executing more than one program at a time Message-ID: <000501c2fe54$ba7d7f90$0201a8c0@eagle> To All: How does one execute more than one program at a time in Python? Within my program, I display a canvas, but then when I try to start a Windows program from within this program, nothing happens. It is as if the computer is still fixed on the canvas that is displayed and can't do anything else. The way around this is to start the other program first, THEN display the canvas. In Tcl/Tk, I remember being able to execute the Tcl/Tk script, and from within the script, also start the Windows WordPad program. Here is that Tcl/Tk code snipet: command {exec "\\program files\\accessories\\wordpad.exe" /p "\\my documents\\misc_obs\\$file_name" &} The last character "&" is used to do this in Tcl/Tk, which I believe runs the program in the background, or at least tells the computer to run more than one thing at a time. I am using Windows XP. How do you do this in Python? Thanks. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From charlie@begeistert.org Wed Apr 9 04:33:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Apr 9 03:33:01 2003 Subject: [Tutor] Re: Tutor Testing for response from a Web site In-Reply-To: <20030409044402.29781.68774.Mailman@mail.python.org> References: <20030409044402.29781.68774.Mailman@mail.python.org> Message-ID: <20030409093201.978.2@wonderland.1049870521.fake> > To All: > > How can I test the response of a server on a Web site to a request that > occurs when I attempt to access the Web site? I am using the Windows XP > operating system. > > For example, if I select a link to a Web site, the server can respond in > (I think) only 3 different ways: > > 1) It can simply ignore the request. > 2) It can honor the request and I can therefore download > some data, or... > 3) It might send my PC some other response that I can > test for in a Python program, that tells the program that the site > is not accessible or available. > > Here is the code I am using: > _________________________________________________ > metURL = "http://isl715.nws.noaa.gov/tdl/forecast/tdl_etamet.txt" > f_object = open("c:\\python_pgms\\plot_guidance\\met_data.txt", 'w') > > try: > print "\nBEGIN DOWNLOADING ETA (MET) MOS" > metall = urllib.urlopen(metURL).read() > f_object.write(metall) > f_object.close() > except: > print "Could not obtain data from Web" > f_object.close() > As it stands now, the program will just say the data is old, when I really should say > something like "could not connect with the site." > > What additional test(s) can I perform to catch other responses from a > server, especially one in which the server will not honor my request? Hi Henry, first tip: use "/" rather than "\\" in your paths, it'll make your life easier and your code more portable! Python makes sure that the path is correct. Does anybody know why Microsoft / Seattle Computer Products decided to use "\" instead of "/" as a path separator in QDOS? Was it like this in CP/M? I don't understand how your script can say that the data is old - you aren't comparing it with anything but the reason it's not telling you if it can't connect is that your except clause catches everything. If Python can't open a url it will raise an IOError: [Errno socket error] host not found for invalid hosts but not an error message for missing pages - they just return empty strings when read. If I understand you correctly, you want to know if a file is on the server and if so how old it is. To do this you need to look at the http-header returned by the server and urllib.urlopen() is too high level for this. Like many things in Python urllib actually uses other modules to do the work for it, ie. the sockets module to make connections. Depending on what you want to do you might want to use sockets directly but you should also look at urllib2 which is supposed to be customisable for exactly this kind of thing. Charlie From sudhirchauhan1@yahoo.co.in Wed Apr 9 05:37:01 2003 From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=) Date: Wed Apr 9 04:37:01 2003 Subject: [Tutor] LDAP/MS active directory support In-Reply-To: Message-ID: <20030409083602.280.qmail@web8202.mail.in.yahoo.com> --0-379102629-1049877362=:91177 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit hi all, i was wondering weather PYTHON has some sort of Interfacing module to call LDAP directory in general and M$ Active directory in particular. Any pointer in this regards are welcome as i am trying to find out something in python using which i can access Active Directory object. regards, sudhir Catch all the cricket action. Download Yahoo! Score tracker --0-379102629-1049877362=:91177 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit

hi all,

 

i was wondering weather PYTHON has some sort of Interfacing module to call LDAP directory in general and M$ Active directory in particular.

Any pointer in this regards are welcome as i am trying to find out something in python using which i can access Active Directory object.

 

regards,

sudhir

 

Catch all the cricket action. Download Yahoo! Score tracker --0-379102629-1049877362=:91177-- From abli@freemail.hu Wed Apr 9 12:29:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Wed Apr 9 11:29:02 2003 Subject: [Tutor] looking for alternatives to tabular widget (Tkinter) In-Reply-To: <20030509222222.A600@coto> References: <20030509023904.A231@coto> <20030408151358.GA1577@hooloovoo> <20030509222222.A600@coto> Message-ID: <20030409152802.GA958@hooloovoo> Adrian Maier wrote: > I guess i could also try to use a Canvas ? ( there could be a > problem with editing, though) With a Canvas, you would get a more flexible widget at the expense of having to write much more code. Using a frame and normal tkinter widgets, creating a fixed, 3x15 cell spreadsheet-like widget is simply creating the widgets and grid()-ig them. About the same is true for something more dinamical (i.e. variable number of rows and columns). You can do the same with a canvas, and add more graphical elemets (like rounded corners, etc.). I think such things would be simply superflous for a simple spreadsheet-like widget, but they would need a lot of time to code. And apart from such features, a canvas wouldn't have any advantage over a frame. I would stick to a frame (or a ScrolledFrame from Pmw) Abel Daniel From charlie@begeistert.org Wed Apr 9 13:07:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Apr 9 12:07:01 2003 Subject: [Tutor] Executing more than one program at a time In-Reply-To: <20030409160006.5168.53397.Mailman@mail.python.org> References: <20030409160006.5168.53397.Mailman@mail.python.org> Message-ID: <20030409180644.5480.8@wonderland.1049870521.fake> > How does one execute more than one program at a > time in Python? > command {exec "\\program files\\accessories\\wordpad.exe" /p "\\my > documents\\misc_obs\\$file_name" &} > > The last character "&" is used to do this in Tcl/Tk, which I believe runs > the program in the background, or at least tells the computer to run more > than one thing at a time. I am using Windows XP. > > How do you do this in Python? In Python itself? You might look at threads but I think want you want to do is start an external process. "exec" is possible check the os-module but you might want to look at popen as well. I'm afraid I can't help you much with how they work but if you've got Tcl experience you should be okay. Charlie From brian@dungeoncrawl.org Wed Apr 9 13:47:02 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Wed Apr 9 12:47:02 2003 Subject: [Tutor] Slicing Question Message-ID: <5.2.0.9.0.20030409124423.0268b008@localhost> I wrote this line of code today: if fileName[:-5][-4:].lower() == "test": What it does it take a file name that I already know ends in ".java", cut off the ".java" part, and see if the last 4 letters are test. I was wondering if there's a simpler way of doing this? -- "Words are poison." - Nick on love From jeff@ccvcorp.com Wed Apr 9 14:00:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 9 13:00:02 2003 Subject: [Tutor] Idle & PythonWin References: <009501c2fe6c$10c58b60$6501a8c0@aaronhome> Message-ID: <3E9451F2.6090903@ccvcorp.com> Aaron Harrier wrote: > Hello again...I seem to be here a lot these days. > > I installed Python 2.2 a few days ago and today in confusion I > also installed win32all. Aside from now having the option to run > win32,MFCs and have the choice between IDLE and PythonWin does anyone > know if this should cause an issue? They seem to have both installed > in the same directory. Presuming that you're referring to the python.org distribution of Python 2.2, what you've done is exactly the way that the win32all extensions are intended to be used. That package just adds a bit to the pre-existing Python install. If you're using ActiveState's ActivePython installer, then the win32all package is already included, and it's not necessary to install win32all again, but (provided that the versions are similar) it shouldn't cause any problems. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Apr 9 14:06:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 9 13:06:02 2003 Subject: [Tutor] Slicing Question References: <5.2.0.9.0.20030409124423.0268b008@localhost> Message-ID: <3E945353.5050009@ccvcorp.com> Brian Christopher Robinson wrote: > I wrote this line of code today: > > if fileName[:-5][-4:].lower() == "test": > > What it does it take a file name that I already know ends in ".java", > cut off the ".java" part, and see if the last 4 letters are test. I > was wondering if there's a simpler way of doing this? You can do it all with one slicing operation, by specifying a start point as well as an end point. if fileName[-9:-5].lower() == "test": [...] You can also use some of the features of the os.path module, which are designed for handling filenames, to allow you to write something that'll be more flexible. We can throw in a string method as well: import os base, ext = os.path.splitext(fileName) if base.endswith("test"): [...] This doesn't require knowing anything about the extension that we're stripping off, nor does it require figuring out how long "test" is, so it'd be easier to check for an arbitrary string there (perhaps determined elsewhere in your program). Jeff Shannon Technician/Programmer Credit International From andi@buxach.de Wed Apr 9 14:09:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Wed Apr 9 13:09:01 2003 Subject: [Tutor] Slicing Question In-Reply-To: <5.2.0.9.0.20030409124423.0268b008@localhost> References: <5.2.0.9.0.20030409124423.0268b008@localhost> Message-ID: <20030409190823.6eb1f6cd.andi@buxach.de> Wed, 09 Apr 2003 12:46:26 -0400: Brian Christopher Robinson > I wrote this line of code today: > > if fileName[:-5][-4:].lower() == "test": > > What it does it take a file name that I already know ends in ".java", > cut off the ".java" part, and see if the last 4 letters are test. I > was wondering if there's a simpler way of doing this? if fileName[-9:-5].lower() == "test": would be my suggestion, but i am a newbie myself :-P -- Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de Amikeco aparte, afero aparte From jeff@ccvcorp.com Wed Apr 9 14:11:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 9 13:11:01 2003 Subject: [Tutor] Executing more than one program at a time References: <000501c2fe54$ba7d7f90$0201a8c0@eagle> Message-ID: <3E945473.8030101@ccvcorp.com> (I seem to be having some trouble with my mailer. If this arrives multiple times, please disregard the extras.) Henry Steigerwaldt wrote: >To All: > >How does one execute more than one program at a >time in Python? > >Within my program, I display a canvas, but then when >I try to start a Windows program from within this >program, nothing happens. It is as if the computer is >still fixed on the canvas that is displayed and can't do >anything else. > It's hard to say without looking at your code, exactly what is happening. Is your canvas window responding to appropriate events? Where in your code are you trying to start this other program? One possibility that occurs to me is that you may be starting the GUI's message loop, and then trying to launch the other program *after* you start the message loop, in that same segment of code. This won't work, because when you start a message loop, your program remains inside of that loop until it shuts down. You can either start the outside program (using os.popen() or os.system("start ..."), depending on your exact needs) before you enter the message loop, or from some event handler (which will be called from inside the message loop). If this doesn't help, feel free to post a short bit of code that illustrates what's happening. Jeff Shannon Technician/Programmer Credit International From python@jaydorsey.com Wed Apr 9 14:18:07 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Wed Apr 9 13:18:07 2003 Subject: [Tutor] Slicing Question In-Reply-To: <5.2.0.9.0.20030409124423.0268b008@localhost> References: <5.2.0.9.0.20030409124423.0268b008@localhost> Message-ID: <3E9455B7.70101@jaydorsey.com> Brian Christopher Robinson wrote: > I wrote this line of code today: > > if fileName[:-5][-4:].lower() == "test": > > What it does it take a file name that I already know ends in ".java", > cut off the ".java" part, and see if the last 4 letters are test. I was > wondering if there's a simpler way of doing this? > How about slicing it like this: >>> if fileName[-9:-5].lower() == "test": ... print "there it is" ... there it is Alternatively, you could use a regular expression >>> x = "blahblahtest.java" >>> import re >>> reFilename = re.compile(".+test.java", re.I) >>> if reFilename.search(x): ... print "there it is" ... there it is -- Jay Dorsey python at jay dorsey dot com From francois.granger@free.fr Wed Apr 9 14:37:30 2003 From: francois.granger@free.fr (Francois Granger) Date: Wed Apr 9 13:37:30 2003 Subject: [Tutor] Slicing Question In-Reply-To: <5.2.0.9.0.20030409124423.0268b008@localhost> References: <5.2.0.9.0.20030409124423.0268b008@localhost> Message-ID: At 12:46 -0400 09/04/2003, in message [Tutor] Slicing Question, Brian Christopher Robinson wrote: >I wrote this line of code today: > >if fileName[:-5][-4:].lower() == "test": > >What it does it take a file name that I already know ends in >".java", cut off the ".java" part, and see if the last 4 letters are >test. I was wondering if there's a simpler way of doing this? if filename.lower().find('test.java') > -1: or using split. It depend on what else you do to the filename. -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From francois.granger@free.fr Wed Apr 9 17:48:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Wed Apr 9 16:48:02 2003 Subject: [Tutor] Slicing Question In-Reply-To: <3E9455B7.70101@jaydorsey.com> References: <5.2.0.9.0.20030409124423.0268b008@localhost> <3E9455B7.70101@jaydorsey.com> Message-ID: At 13:17 -0400 09/04/2003, in message Re: [Tutor] Slicing Question, Jay Dorsey wrote: >Brian Christopher Robinson wrote: >>I wrote this line of code today: >> >>if fileName[:-5][-4:].lower() == "test": >> >>What it does it take a file name that I already know ends in >>".java", cut off the ".java" part, and see if the last 4 letters >>are test. I was wondering if there's a simpler way of doing this? >> > >Alternatively, you could use a regular expression > > >>> x = "blahblahtest.java" > >>> import re > >>> reFilename = re.compile(".+test.java", re.I) >>>> if reFilename.search(x): >... print "there it is" >... >there it is This one will catch "blahblahtestejava.java" a better one would be: ".+test\.java$" \ to escape the dot, and $ for end of string. -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From python@jaydorsey.com Wed Apr 9 18:19:04 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Wed Apr 9 17:19:04 2003 Subject: [Tutor] Slicing Question In-Reply-To: References: <5.2.0.9.0.20030409124423.0268b008@localhost> <3E9455B7.70101@jaydorsey.com> Message-ID: <3E948E3A.4010202@jaydorsey.com> Francois Granger wrote: > This one will catch "blahblahtestejava.java" > > a better one would be: ".+test\.java$" > \ to escape the dot, and $ for end of string. > I was just testing your regular expression skills ;-). j/k. Good catch. In my haste, I neglected to pay attention to detail. -- Jay Dorsey python at jay dorsey dot com From magnus@thinkware.se Wed Apr 9 21:19:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 9 20:19:01 2003 Subject: [Tutor] Help with creating a Python file for Report Generation In-Reply-To: <20030408051625.28369.13747.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030410020548.022f9e00@www.thinkware.se> KKGOLFER@aol.com wrote: >Does anyone have a Python file already created that generates a >report.......I need to copy tables and graphs out an Excel workbook and >place them each individually into PowerPoint slides (same >file).........I'm a newbie at this with no programming background. I can >tailor files reasonably well, but starting from scratch....not there yet. I fear this might be a bit beyond newbie level. Working with Microsoft applications isn't trivial... I think you need lots of slides to save time by developing a programmed solution, and if you are just working with transfer from Excel to PowerPoint, you might be better off doing this in VBA... Of course, this deppends a bit on how your Excel data looks. If it's very regular, it might be less tricky to automate, but if it's sometimes data here, and sometimes data there...you will have a lot of things that you need to describe in your program. For details on how to work with windows applications in Python, you might be more successful asking the gurus at the win32 mailing list. See: http://mail.python.org/mailman/listinfo/python-win32 From phthenry@earthlink.net Wed Apr 9 23:53:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed Apr 9 22:53:01 2003 Subject: [Tutor] Slicing Question In-Reply-To: References: <5.2.0.9.0.20030409124423.0268b008@localhost> <3E9455B7.70101@jaydorsey.com> Message-ID: <20030409225231.C3483@localhost.localdomain> Good point. But personally I like Jeff Shanon's suggestion that you use os.path, a nifty and powerful module for doing exactly what the origial poster wanted. Paul On Wed, Apr 09, 2003 at 10:47:03PM +0200, Francois Granger wrote: > > At 13:17 -0400 09/04/2003, in message Re: [Tutor] Slicing Question, > Jay Dorsey wrote: > >Brian Christopher Robinson wrote: > >>I wrote this line of code today: > >> > >>if fileName[:-5][-4:].lower() == "test": > >> > >>What it does it take a file name that I already know ends in > >>".java", cut off the ".java" part, and see if the last 4 letters > >>are test. I was wondering if there's a simpler way of doing this? > >> > > > >Alternatively, you could use a regular expression > > > > >>> x = "blahblahtest.java" > > >>> import re > > >>> reFilename = re.compile(".+test.java", re.I) > >>>> if reFilename.search(x): > >... print "there it is" > >... > >there it is > > This one will catch "blahblahtestejava.java" > > a better one would be: ".+test\.java$" > \ to escape the dot, and $ for end of string. > > -- > Hofstadter's Law : > It always takes longer than you expect, even when you take into > account Hofstadter's Law. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From antone.heyward@verizon.net Thu Apr 10 00:03:02 2003 From: antone.heyward@verizon.net (Antone) Date: Wed Apr 9 23:03:02 2003 Subject: [Tutor] Executing more than one program at a time In-Reply-To: <3E945473.8030101@ccvcorp.com> Message-ID: <000001c2ff0d$8e75fcb0$6001a8c0@blakout> This how I do it. This way you create a separate process for the = external program you want to run. This uses the win32process module. If your programming on windows its great. def viewfile(): si =3D win32process.STARTUPINFO() viewfile =3D 'notepad.exe '+ self.filename info =3D win32process.CreateProcess(None,viewfile,None,None,0, \ = win32process.NORMAL_PRIORITY_CLASS, \ None,None,si) Self.filename =3D "c:\whateverfile.txt" Viewfile() -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org] On Behalf = Of Jeff Shannon Sent: Wednesday, April 09, 2003 1:12 PM To: tutor@python.org Cc: Henry Steigerwaldt Subject: Re: [Tutor] Executing more than one program at a time (I seem to be having some trouble with my mailer. If this arrives=20 multiple times, please disregard the extras.) Henry Steigerwaldt wrote: >To All: > >How does one execute more than one program at a >time in Python? > >Within my program, I display a canvas, but then when >I try to start a Windows program from within this >program, nothing happens. It is as if the computer is >still fixed on the canvas that is displayed and can't do >anything = else. > It's hard to say without looking at your code, exactly what is = happening. Is your canvas window responding to appropriate events? Where in your = code are you trying to start this other program? One possibility that occurs to me is that you may be starting the=20 GUI's message loop, and then trying to launch the other program=20 *after* you start the message loop, in that same segment of code.=20 This won't work, because when you start a message loop, your program=20 remains inside of that loop until it shuts down. You can either start=20 the outside program (using os.popen() or os.system("start ..."),=20 depending on your exact needs) before you enter the message loop, or=20 from some event handler (which will be called from inside the message=20 loop). If this doesn't help, feel free to post a short bit of code that = illustrates what's happening. Jeff Shannon Technician/Programmer Credit International _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From a_abdi406@yahoo.com Thu Apr 10 00:49:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Apr 9 23:49:02 2003 Subject: [Tutor] about indexing program Message-ID: <20030410034809.36303.qmail@web14506.mail.yahoo.com> --0-293633342-1049946489=:34564 Content-Type: text/plain; charset=us-ascii Hi, I was trying to understand and run a program which indexes a files in XML directory the program is from this webpage which has a lot of python recipes: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/155582 when I try to run it gives an error which is as follows: Shelf.__init__(self, anydbm.open(filename, flag)) File "C:\Python22\lib\anydbm.py", line 86, in open return mod.open(file, flag, mode) File "C:\Python22\lib\dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) error: (2, 'No such file or directory') >>> it is also compalaining about this import statement: from TextSplitter import TextSplitter is there any module for this "TextSplitter" ? I am runing the program by passing to it an XML file as argument. Can anyone help me figure out what is going on how I can make this program work ? I would also appreciate some comments about it ? thanks in advance --------------------------------- Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more --0-293633342-1049946489=:34564 Content-Type: text/html; charset=us-ascii

Hi,

I was trying to understand and run a program which indexes a files in XML directory the program is from this webpage which has a lot of python recipes:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/155582

when I try to run it gives an error which is as follows:

  Shelf.__init__(self, anydbm.open(filename, flag))
  File "C:\Python22\lib\anydbm.py", line 86, in open
    return mod.open(file, flag, mode)
  File "C:\Python22\lib\dbhash.py", line 16, in open
    return bsddb.hashopen(file, flag, mode)
error: (2, 'No such file or directory')
>>>

it is also compalaining about this import statement:

from TextSplitter import TextSplitter

is there any module for this "TextSplitter" ?

I am runing the program by passing to it an XML file as argument.

Can anyone help me figure out what is going on how I can make this program work ?    I would also appreciate some comments about it ?

thanks in advance 

 



Do you Yahoo!?
Yahoo! Tax Center - File online, calculators, forms, and more --0-293633342-1049946489=:34564-- From charlie@begeistert.org Thu Apr 10 04:49:28 2003 From: charlie@begeistert.org (charlie@begeistert.org) Date: Thu Apr 10 03:49:28 2003 Subject: Subject: [Tutor] Re: Tutor Testing for response from a Web site In-Reply-To: <002e01c2ff17$4701dbb0$0201a8c0@eagle> References: <002e01c2ff17$4701dbb0$0201a8c0@eagle> Message-ID: <20030410094835.760.2@wonderland.1049959947.fake> Henry, I'm keeping this on the list where the real gurus are as there rarely to be found here ;-) Okay, MAL is coming round today but that's mere coincidence! On 2003-04-10 at 06:11:35 [+0200], you wrote: > Charlie: > > Thanks for responding. > > I just wanted to know how to test for a connection that cannot for one > reason or another, be made with a server. > > >From your response, I checked into the "IOError." I am not sure > about how to use these, but from some examples in some Python books I > have, here are some questions I hope you can answer for me: > > 1) Is the following code ok now in order to catch the no connection > possibility? > 2) After the IOError exception, I also included another exception that > as you said, catches every possible error. Is this correct too the > way I coded this after the other exception? well, you don't need to print "unknown error" you can actually get all the information from the traceback. Try print sys.exc_info() instead. I still don't see the need to carry on execution with other errors as your script probably isn't doing what you want. > 3) Can this code be written so that I only need to have ONE > f_object.close() statement if any exception occurs? As it stands > now, I have to repeat it for each exception. Yes, you just add a finally: f_object.close() at the end. > 4) Is there some built in time limit, say one minute, in which Python > tries to connect to a server before giving up and calling the > exception? If so, can one regulate how long Python waits before > giving up and calling the exception, and can one regulate how many > times Python tries to connect? I could put things in a loop to do > that I guess. Yes, I think urllib.urlopen() has a two minute timeout. You might be able to set this yourself. This is from the docs for urlilib2: urlopen(url, data=None) -- basic usage is that same as original urllib. pass the url and optionally data to post to an HTTP URL, and get a file-like object back. One difference is that you can also pass a Request instance instead of URL. Raises a URLError (subclass of IOError); for HTTP errors, raises an HTTPError, which can also be treated as a valid response. This basically means you can get more useful error messages. import urllib, sys metURL = "http://isl715.nws.noaa.gov/tdl/forecast/tdl_etamet.txt" # f_object = open("c:\\python_pgms\\plot_guidance\\met_data.txt", 'w') f_object = open("c:/python_pgms/plot_guidance/met_data.txt", "w") # this is easier to read and more portable try: # print "\nBEGIN DOWNLOADING ETA (MET) MOS" print "BEGIN DOWNLOADING ETA (MET) MOS" # this is Python so we don't need more \n than absolutely necessary metall = urllib.urlopen(metURL).read() f_object.write(metall) except IOError: print "Server connection could not be made." except: print "Something has gone wrong" print sys.exc_info() finally: f_object.close() >Thanks much for your help! > > Henry Steigerwaldt > Hermitage, TN > Email: hsteiger@comcast.net Charlie From ovidiu.bivolaru@ravantivirus.com Thu Apr 10 10:53:02 2003 From: ovidiu.bivolaru@ravantivirus.com (Ovidiu Bivolaru) Date: Thu Apr 10 09:53:02 2003 Subject: [Tutor] More documentation Message-ID: <1049982269.7944.12.camel@ovidiu.rav.local> Hello, Where can I find some good examples about debugging and trace in Python? Also, if somebody can point some Python tutorials with examples, because the library reference is not enough sometimes. Thank you, Ovidiu -- Ovidiu Bivolaru Senior Technical Support Engineer - RAV Division Tel./Fax: +40-21-321.78.03 Hotline: +40-21-321.78.59; Please visit http://www.ravantivirus.com Worry less! RAV is watching. From csmith@blakeschool.org Thu Apr 10 12:22:03 2003 From: csmith@blakeschool.org (Christopher Smith) Date: Thu Apr 10 11:22:03 2003 Subject: [Tutor] proxy requiring authentication Message-ID: I have read on in the doc's that proxies that require authentication are not supported by urllib's functionality. I also read a PEP that said that this is in process for a future release. In the meantime, is it easy to explain why one can't just open a socket through python and print the required commands to the proxy? Here, for example, is how someone did it in Java: #class S #{ # public static void main(String args[]) # { # try { # Socket s = new Socket("proxy.server.name", 80); # # OutputStream os = s.getOutputStream(); # PrintWriter pw = new PrintWriter(os); # # InputStream is = s.getInputStream(); # InputStreamReader isr = new InputStreamReader(is); # BufferedReader br = new BufferedReader(isr); # # //send request # pw.println("GET http://www.google.com HTTP/1.1"); # pw.println("Proxy-Authorization: Basic "+ # Base64.encodeString("username:password")); # pw.println(""); // this blank line completes the request # pw.flush(); # # //get reply # String str = br.readLine(); # while (str != null) # { # System.out.println(str); # str = br.readLine(); # } # } catch (Exception e) { # System.err.println(e); # } # }//main() # #} Can this be translated into Python? I don't know much about working with sockets but read the docs and attempted the following without success (I only show the first few lines because the connection could not even be established): ### import socket theproxyserver='the.proxy.server' #but I used our proxy name theproxyport=42 #but I used the real port number s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((theproxyserver, theproxyport)) #fails with error (49, can't assign address) ### Thanks for any help. /c From jeff@ccvcorp.com Thu Apr 10 13:47:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 10 12:47:01 2003 Subject: Subject: [Tutor] Re: Tutor Testing for response from a Web site References: <002e01c2ff17$4701dbb0$0201a8c0@eagle> <20030410094835.760.2@wonderland.1049959947.fake> Message-ID: <3E95A059.2010008@ccvcorp.com> charlie@begeistert.org wrote: >>3) Can this code be written so that I only need to have ONE >> f_object.close() statement if any exception occurs? As it stands >> now, I have to repeat it for each exception. >> >> >Yes, you just add a finally: f_object.close() at the end. > [...] >try: ># print "\nBEGIN DOWNLOADING ETA (MET) MOS" > print "BEGIN DOWNLOADING ETA (MET) MOS" ># this is Python so we don't need more \n than absolutely necessary > metall = urllib.urlopen(metURL).read() > f_object.write(metall) >except IOError: > print "Server connection could not be made." >except: > print "Something has gone wrong" > print sys.exc_info() >finally: > f_object.close() > > This actually doesn't *quite* work. You can't have an 'except:' clause and a 'finally:' clause hanging off the same 'try:'. You need to nest them: try: try: print "Begin Downloading..." metall = urllib.urlopen(metURL).read() f_object.write(metall) except IOError: print "Server connection could not be made." except: print "Something has gone wrong." print sys.exc_info() finally: f_object.close() In this particular case, you don't really even need the 'finally', because any possible exception is already being caught, so execution will always continue. That might not be a good idea, though -- if you're getting no connection, or if you're having other unspecified errors, it might be best to go ahead and terminate the program, or perhaps return from the function this is in and try it again in ten minutes... In those cases, you could add a 'sys.exit(1)' or a 'return' to each except clause, the 'finally' will ensure that f_object gets closed, and a successful download will leave execution continuing just after the 'finally' while an exception would end execution (within this scope). Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Apr 10 14:14:25 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 10 13:14:25 2003 Subject: [Tutor] about indexing program References: <20030410034809.36303.qmail@web14506.mail.yahoo.com> Message-ID: <3E95A531.2020304@ccvcorp.com> Abdirizak abdi wrote: > when I try to run it gives an error which is as follows: > > Shelf.__init__(self, anydbm.open(filename, flag)) > File "C:\Python22\lib\anydbm.py", line 86, in open > return mod.open(file, flag, mode) > File "C:\Python22\lib\dbhash.py", line 16, in open > return bsddb.hashopen(file, flag, mode) > error: (2, 'No such file or directory') > >>> > Well, you've cut out the part of the exception traceback that tells where exactly this is coming from in the recipe's code, but at a guess, you're feeding it a filename that doesn't exist. The shelf is trying to open a file (presumably the index file) but can't find it. This could conceivably also be caused by running the script from a directory other than the one in which the previously-created index file is located -- I haven't looked at it closely enough to determine whether it's allowing for different directories or not. > it is also compalaining about this import statement: > > from TextSplitter import TextSplitter > > is there any module for this "TextSplitter" ? > Well, it looks like this TextSplitter is not actually used anywhere within this recipe. How odd. My guess here is that the recipe's author cut this code out of an existing module of his, and forgot to remove this line. I bet that you can delete this line without any problems. > I am runing the program by passing to it an XML file as argument. > Ah -- look at the usage notes in the script. "xmlIndexer -c filename " " to create an index of all xml files in current directory in 'filename'" "xmlIndexer -f filename -s searchPattern" " to search the current index 'filename' for 'searchPattern'" You wouldn't ever need to pass this an XML file. When you're creating an index, you pass it a filename (presumably nonexistent) to use for the index file, and it will build an index of all the XML files in your current directory. When you're trying to access that index, you pass it the name of that same index file. That index file is a special shelve, not an XML file Jeff Shannon Technician/Programmer Credit International From revanna@mn.rr.com Thu Apr 10 14:39:01 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Thu Apr 10 13:39:01 2003 Subject: Subject: [Tutor] Re: Tutor Testing for response from a Web site In-Reply-To: <3E95A059.2010008@ccvcorp.com> References: <002e01c2ff17$4701dbb0$0201a8c0@eagle> <20030410094835.760.2@wonderland.1049959947.fake> <3E95A059.2010008@ccvcorp.com> Message-ID: <200304101238.25400.revanna@mn.rr.com> On Thursday 10 April 2003 11:48, Jeff Shannon wrote: > charlie@begeistert.org wrote: > >>3) Can this code be written so that I only need to have ONE > >> f_object.close() statement if any exception occurs? As it stands > >> now, I have to repeat it for each exception. > > > >Yes, you just add a finally: f_object.close() at the end. > > [...] > > >try: > ># print "\nBEGIN DOWNLOADING ETA (MET) MOS" > > print "BEGIN DOWNLOADING ETA (MET) MOS" > ># this is Python so we don't need more \n than absolutely necessary > > metall = urllib.urlopen(metURL).read() > > f_object.write(metall) > >except IOError: > > print "Server connection could not be made." > >except: > > print "Something has gone wrong" > > print sys.exc_info() > >finally: > > f_object.close() > > This actually doesn't *quite* work. You can't have an 'except:' clause > and a 'finally:' clause hanging off the same 'try:'. You need to nest > them: > > try: > try: > print "Begin Downloading..." > metall = urllib.urlopen(metURL).read() > f_object.write(metall) > except IOError: > print "Server connection could not be made." > except: > print "Something has gone wrong." > print sys.exc_info() > finally: > f_object.close() Just to make sure *I'm* understanding things here... this 'finally' will *always* execute regardless of whether there were any exceptions. Right? > In this particular case, you don't really even need the 'finally', > because any possible exception is already being caught, so execution > will always continue. That might not be a good idea, though -- if > you're getting no connection, or if you're having other unspecified > errors, it might be best to go ahead and terminate the program, or > perhaps return from the function this is in and try it again in ten > minutes... In those cases, you could add a 'sys.exit(1)' or a > 'return' to each except clause, the 'finally' will ensure that f_object > gets closed, and a successful download will leave execution continuing > just after the 'finally' while an exception would end execution (within > this scope). So, f_object gets closed whether download was successful or not, as a "clean-up" action after the download has been attempted. Yes? Just trying to make sure I understand. Anna From jeff@ccvcorp.com Thu Apr 10 15:51:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 10 14:51:01 2003 Subject: Subject: [Tutor] Re: Tutor Testing for response from a Web site References: <002e01c2ff17$4701dbb0$0201a8c0@eagle> <20030410094835.760.2@wonderland.1049959947.fake> <3E95A059.2010008@ccvcorp.com> <200304101238.25400.revanna@mn.rr.com> Message-ID: <3E95BD73.7070004@ccvcorp.com> Anna Ravenscroft wrote: >On Thursday 10 April 2003 11:48, Jeff Shannon wrote: > >>This actually doesn't *quite* work. You can't have an 'except:' clause >>and a 'finally:' clause hanging off the same 'try:'. You need to nest >>them: >> >>try: >> try: >> print "Begin Downloading..." >> metall = urllib.urlopen(metURL).read() >> f_object.write(metall) >> except IOError: >> print "Server connection could not be made." >> except: >> print "Something has gone wrong." >> print sys.exc_info() >>finally: >> f_object.close() >> >> > >Just to make sure *I'm* understanding things here... this 'finally' will >*always* execute regardless of whether there were any exceptions. Right? > > >[...] >So, f_object gets closed whether download was successful or not, as a >"clean-up" action after the download has been attempted. Yes? > >Just trying to make sure I understand. > Yes, exactly. The 'finally' clause will always execute, no matter how the 'try' block is exited (whether by exception, by return, by sys.exit(), or by simply reaching the end and continuing). The only thing that will stop a 'finally' clause from executing is a complete crash of the Python interpreter, which almost never happens unless there's a problem in an extension module. (Or if the interpreter is killed from outside, as might be necessary if it's caught in an infinite loop or a deadlock while inside the try block.) This makes a 'finally' clause an ideal way to make sure that cleanup always happens. Jeff Shannon Technician/Programmer Credit International From cdsomerl@murray-ky.net Thu Apr 10 16:25:03 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Thu Apr 10 15:25:03 2003 Subject: [Tutor] assinging to object attributes from file input Message-ID: <000401c2ff96$57fe0e00$e612953f@www> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C2FF6C.6F2B1340 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit What is the best way to assign values read in from a file to object attributes? Make my objects in a class with null values and then use a function to read the file and assign to the object? Thanks Chris ------=_NextPart_000_0005_01C2FF6C.6F2B1340 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable

What is the best way to assign values read in from a = file to object attributes? Make my objects in a class with null values and then = use a function to read the file and assign to the = object?

 

Thanks

Chris

------=_NextPart_000_0005_01C2FF6C.6F2B1340-- From jeff@ccvcorp.com Thu Apr 10 16:48:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 10 15:48:03 2003 Subject: [Tutor] assinging to object attributes from file input References: <000401c2ff96$57fe0e00$e612953f@www> Message-ID: <3E95CAB4.2080104@ccvcorp.com> Chris Somerlot wrote: > What is the best way to assign values read in from a file to object > attributes? Make my objects in a class with null values and then use a > function to read the file and assign to the object? > Depends on how the file is laid out, and what the attributes are like. I tend to like using __init__() to do this, either by passing it an entire line (if the file is, say, fixed-width columns, I can encapsulate column widths within the class too), or by splitting the line on the field-separator (tab, comma, whatever) and then passing in the list of values. But using __init__() may imply that I'll only be creating instances of this class from lines in this (type of) file. Under other circumstances (instances may come from a variety of sources with a variety of optional attributes), it may make more sense to do as you mention, initializing "empty" instances and then assign attributes to them as needed. Jeff Shannon Technician/Programmer Credit International From nano@intermatik.co.id Fri Apr 11 00:14:02 2003 From: nano@intermatik.co.id (Nova Sano S. Surbakti) Date: Thu Apr 10 23:14:02 2003 Subject: [Tutor] List comprehension Message-ID: <000201c2ffd8$3b251520$0a01a8c0@jrwd> Dear List-ers, How can I simplify this lines: > sum = 0 > myList = [1,2,3,4,5,6] > for each in myList: > sum += each Into shorter, more elegant line(s)? TFYH, Nano --Peace!-- From fredm@smartypantsco.com Fri Apr 11 00:53:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Thu Apr 10 23:53:02 2003 Subject: [Tutor] List comprehension In-Reply-To: <000201c2ffd8$3b251520$0a01a8c0@jrwd> Message-ID: <5.1.0.14.0.20030411134735.038a8160@192.168.1.1> Hi Nano: Danny Yoo has already answered your question in January this year. You can find Danny's answer at http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1503341 In short, the way to do it is to use the reduce() function: import operator myList = [1,2,3,4,5,6] sum = reduce(operator.add, myList) All the best, Fred Milgrom At 10:12 AM 11/04/03 +0700, Nova Sano S. Surbakti wrote: >Dear List-ers, > >How can I simplify this lines: > > sum = 0 > > myList = [1,2,3,4,5,6] > > for each in myList: > > sum += each > >Into shorter, more elegant line(s)? > >TFYH, >Nano >--Peace!-- From cdsomerl@murray-ky.net Fri Apr 11 01:36:02 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Fri Apr 11 00:36:02 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? Message-ID: <000001c2ffe3$600f7500$e612953f@www> This is a multi-part message in MIME format. ------=_NextPart_000_0001_01C2FFB9.773F8780 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Here is a snippet of my code: # line item = [transactions (dict), associations (list), goal (int)] line_item = [{'Date': ()}, [], 0] # budget = {dictionary of line_items} grossinc = {} #define budget line items grossinc['salary'] = line_item grossinc['interest'] = line_item grossinc['dividends'] = line_item grossinc['other'] = line_item grossinc['salary'][goal] = 3333 grossinc['other'][goal] = 575 results in : >>> grossinc {'salary': [{'Date': ()}, [], 575], 'dividends': [{'Date': ()}, [], 575], 'other': [{'Date': ()}, [], 575], 'interest': [{'Date': ()}, [], 575]} It assigned 575 to all of them! I want to it to be: {'salary': [{'Date': ()}, [], 3333], 'dividends': [{'Date': ()}, [], 0], 'other': [{'Date': ()}, [], 0], 'interest': [{'Date': ()}, [], 575]} Can anyone point me in the right direction? I can't seem to make sense of this. Thanks Chris ------=_NextPart_000_0001_01C2FFB9.773F8780 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable

Here is a snippet of my = code:

 

<snippet>

# line item =3D = [transactions (dict), associations (list), goal (int)]

line_item =3D [{'Date': ()}, [], 0]

 

# budget =3D {dictionary = of line_items}

grossinc =3D = {}

 

#define budget line = items

grossinc['salary'] =3D line_item

grossinc['interest'] =3D line_item

grossinc['dividends'] =3D line_item

grossinc['other'] =3D line_item

 

grossinc['salary'][goal] =3D = 3333

grossinc['other'][goal] =3D = 575

</snippet>

 

results= in = :

 

>>> grossinc

{'salary': [{'Date': ()}, [], 575], 'dividends': = [{'Date': ()}, [], 575], 'other': [{'Date': ()}, [], 575], 'interest': [{'Date': = ()}, [], 575]}

 

It assigned 575 to all of them! I want to it to = be:

 

{'salary': [{'Date': ()}, [], 3333], 'dividends': = [{'Date': ()}, [], 0], 'other': [{'Date': ()}, [], 0], 'interest': [{'Date': ()}, = [], 575]}

 

Can anyone point me in the right direction? I = can’t seem to make sense of this…

 

Thanks

Chris

------=_NextPart_000_0001_01C2FFB9.773F8780-- From shalehperry@attbi.com Fri Apr 11 01:53:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Apr 11 00:53:01 2003 Subject: [Tutor] List comprehension In-Reply-To: <5.1.0.14.0.20030411134735.038a8160@192.168.1.1> References: <5.1.0.14.0.20030411134735.038a8160@192.168.1.1> Message-ID: <200304102151.56241.shalehperry@attbi.com> On Thursday 10 April 2003 20:50, Alfred Milgrom wrote: > Hi Nano: > > Danny Yoo has already answered your question in January this year. > You can find Danny's answer at > http://aspn.activestate.com/ASPN/Mail/Message/python-Tutor/1503341 > > In short, the way to do it is to use the reduce() function: > > import operator > myList = [1,2,3,4,5,6] > > sum = reduce(operator.add, myList) > danny did a good job of explaining reduce. How about the list comprehension anyways? A list comprehension does not work here because only expressions are allowed and assignment is not an expression. Beyond that, a list comprehension creates a new list. In this case, the extra list is not needed and the time and memory it uses would be wasted. From shalehperry@attbi.com Fri Apr 11 01:58:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Apr 11 00:58:01 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? In-Reply-To: <000001c2ffe3$600f7500$e612953f@www> References: <000001c2ffe3$600f7500$e612953f@www> Message-ID: <200304102157.07954.shalehperry@attbi.com> Chris is confused about why a seemingly simple assignment ends up changing all of the elements in his dictionary. On Thursday 10 April 2003 21:32, Chris Somerlot wrote: > > #define budget line items > grossinc['salary'] = line_item > grossinc['interest'] = line_item > grossinc['dividends'] = line_item > grossinc['other'] = line_item > here is your problem. Each one of these assignments is *NOT* a copy but just a reference. So all of your dictionary entries are just references to the same variable. >>> a = myList >>> b = myList >>> a [1, 2, 3, 4, 5, 6] >>> b [1, 2, 3, 4, 5, 6] >>> a[2] = 10 >>> a [1, 2, 10, 4, 5, 6] >>> b [1, 2, 10, 4, 5, 6] You will see this referred to as a "shallow copy". What you want is called a "deep copy". >>> import copy >>> c = copy.deepcopy(myList) >>> c[2] = 0 >>> a [1, 2, 10, 4, 5, 6] >>> b [1, 2, 10, 4, 5, 6] >>> c [1, 2, 0, 4, 5, 6] Hope that helps. From charlie@begeistert.org Fri Apr 11 05:40:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Apr 11 04:40:02 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? In-Reply-To: <20030411043602.18038.35639.Mailman@mail.python.org> References: <20030411043602.18038.35639.Mailman@mail.python.org> Message-ID: <20030411103919.925.3@wonderland.1050046227.fake> Hi Chris, please set your mailer to send plain text. It would be so nice if Mailman either refused HTML-mail or just threw the HTML out then we wouldn't get this and the associated junk all the time (in this case well over fifty lines) :-( > This is a multi-part message in MIME format. > > ------=_NextPart_000_0001_01C2FFB9.773F8780 > Content-Type: text/plain; > charset="us-ascii" > Content-Transfer-Encoding: 7bit > Here is a snippet of my code: > > > # line item = [transactions (dict), associations (list), goal (int)] > line_item = [{'Date': ()}, [], 0] > > # budget = {dictionary of line_items} > grossinc = {} > > #define budget line items > grossinc['salary'] = line_item > grossinc['interest'] = line_item > grossinc['dividends'] = line_item > grossinc['other'] = line_item > > grossinc['salary'][goal] = 3333 > grossinc['other'][goal] = 575 > > > results in : > > >>> grossinc > {'salary': [{'Date': ()}, [], 575], 'dividends': [{'Date': ()}, [], > 575], 'other': [{'Date': ()}, [], 575], 'interest': [{'Date': ()}, [], > 575]} > > It assigned 575 to all of them! I want to it to be: > > {'salary': [{'Date': ()}, [], 3333], 'dividends': [{'Date': ()}, [], 0], > 'other': [{'Date': ()}, [], 0], 'interest': [{'Date': ()}, [], 575]} > > Can anyone point me in the right direction? I can't seem to make sense of > this. What are you trying to do exactly? The problem seems to stem from the subtle difference between references and copies. I cannot understand why you are assigning the whole line item to different parts of a dictionary but by doing this grossinc['salary'] is the a reference to the same object as grossinc['other'], ie. line_item and so you're just overwriting line_item However, I can't actually see this working with line_item[goal] or even line_item['goal'] as I don't see "goal" being initialised anywhere in order to slice the list and it's you can't use it as a key in a list. Could you please provide a more detailed description of what you want to do. I think the first step to the solution will be to model the data correctly. Charlie From charlie@begeistert.org Fri Apr 11 05:51:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Apr 11 04:51:02 2003 Subject: [Tutor] List comprehension In-Reply-To: <20030411043602.18038.35639.Mailman@mail.python.org> References: <20030411043602.18038.35639.Mailman@mail.python.org> Message-ID: <20030411104948.998.4@wonderland.1050046227.fake> On 2003-04-11 at 06:36:02 [+0200], tutor-request@python.org wrote: > Subject: [Tutor] List comprehension > > Dear List-ers, > > How can I simplify this lines: > > sum = 0 > > myList = [1,2,3,4,5,6] > > for each in myList: > > sum += each > > Into shorter, more elegant line(s)? Although Albert has shown you how to do this with reduce() I don't actually think there is any need to shorten or make this more elegant. compare sum = reduce(operator.add, myList) with for x in myList: sum += x which is shorter? which is more elegant? reduce() is shorter and returns the desired value directly but I personally have to look reduce() up in a book every time I see it. But I think you wanted to know if you could do this with list (in)comprehensions. I don't think so as they always return lists, ie. you might expect [sum + x for x in myList] but this just adds "sum" to each value in the list and returns a new list with these calculated values. Charlie From cdsomerl@murray-ky.net Fri Apr 11 10:03:01 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Fri Apr 11 09:03:01 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? In-Reply-To: <20030411103919.925.3@wonderland.1050046227.fake> Message-ID: <000601c3002a$259e1790$e612953f@www> > What are you trying to do exactly? The problem seems to stem from the > subtle difference between references and copies. I cannot understand why > you are assigning the whole line item to different parts of a dictionary > but by doing this grossinc['salary'] is the a reference to the same object > as grossinc['other'], ie. line_item and so you're just overwriting > line_item > However, I can't actually see this working with line_item[goal] or even > line_item['goal'] as I don't see "goal" being initialised anywhere in > order > to slice the list and it's you can't use it as a key in a list. > > Could you please provide a more detailed description of what you want to > do. I think the first step to the solution will be to model the data > correctly. > > Charlie I see that you're right, I want to create a new instance of line_item each time and add it into the dictionary grossinc instead of making a reference, but I'm still confused about a good way to do that. Make a class? My code should have read: # line item = [list of transactions (dict), associations (list), goal (int)] line_item = [{'Date': ()}, [], 0] # budget = {dictionary of line_items} grossinc = {} #define budget line items grossinc['salary'] = line_item grossinc['interest'] = line_item grossinc['dividends'] = line_item grossinc['other'] = line_item grossinc['salary'][2] = 3333 grossinc['other'][2] = 575 From am@fx.ro Fri Apr 11 10:42:08 2003 From: am@fx.ro (Adrian Maier) Date: Fri Apr 11 09:42:08 2003 Subject: [Tutor] proxy requiring authentication In-Reply-To: ; from csmith@blakeschool.org on Thu, Apr 10, 2003 at 10:22:00AM -0500 References: Message-ID: <20030411190923.A272@coto> Christopher Smith (csmith@blakeschool.org) a scris : > Can this be translated into Python? I don't know much about working with > sockets but read the docs and attempted the following without success (I > only show the first few lines because the connection could not even be > established): > > ### > import socket > theproxyserver='the.proxy.server' #but I used our proxy name > theproxyport=42 #but I used the real port number > s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > s.bind((theproxyserver, theproxyport)) #fails with error (49, can't assign > address) > ### I guess you should use s.connect instead of s.bind . 'bind' is used when you intend to listen on that port (which happens inside programs that act like servers). You probably got that error because your program is trying to 'bind' a port that is lower than 1024. On Unix, only root may listen on those ports. But, you don't need to listen on any port ... you need to connect as a client to the proxy (using s.connect). I hope this helps. -- Adrian Maier (am@fx.ro) From charlie@begeistert.org Fri Apr 11 11:38:10 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Apr 11 10:38:10 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? In-Reply-To: <000601c3002a$259e1790$e612953f@www> References: <000601c3002a$259e1790$e612953f@www> Message-ID: <20030411163743.3372.13@wonderland.1050046227.fake> On 2003-04-11 at 14:59:10 [+0200], you wrote: > I see that you're right, I want to create a new instance of line_item > each time and add it into the dictionary grossinc instead of making a > reference, but I'm still confused about a good way to do that. Make a > class? My code should have read: > > # line item = [list of transactions (dict), associations (list), goal > (int)] > line_item = [{'Date': ()}, [], 0] > > # budget = {dictionary of line_items} > grossinc = {} > > #define budget line items > grossinc['salary'] = line_item > grossinc['interest'] = line_item > grossinc['dividends'] = line_item > grossinc['other'] = line_item > > grossinc['salary'][2] = 3333 > grossinc['other'][2] = 575 A dictionary or list of dictionaries will probably be fine. I'd like to help you set this up but I need to see how you create a line_item You might want something like this items = [] or items = {} it really depends on what you want to do with your data. I think a list might be what you want in this case. you can then insert items/line_items into your structure, I think a dictionary is the write thing for this. ie. item = {'transactions':'', 'associations':'', 'goal':0} you can then do something like new_item = item.copy() new_item['transactions'] = ### I've have no idea what you really .... items.append(new_item) Try this with a few items and then look at the resulting list "items" to see if it makes sense. Charlie (non-Guru of the week) From jeff@ccvcorp.com Fri Apr 11 14:19:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Apr 11 13:19:02 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? References: <000601c3002a$259e1790$e612953f@www> Message-ID: <3E96F969.9060607@ccvcorp.com> Chris Somerlot wrote: >>What are you trying to do exactly? The problem seems to stem from the >>subtle difference between references and copies. >> > >I see that you're right, I want to create a new instance of line_item >each time and add it into the dictionary grossinc instead of making a >reference, but I'm still confused about a good way to do that. Make a >class? > You could do this with a class, and that would probably be my preferred way, especially if there's any common tasks that need to be done on line_items -- those can easily become methods of the class. You can also continue using nested lists and dictionaries, just be sure to create new ones for each line_item instead of just referring to the same one. This can be done by using copy.deepcopy(), as Sean suggested, or you could write a quick "factory function" that creates a new, independent line_item each time it's called. def new_line_item(): return [ {'Date': ()}, [], 0 ] grossinc['salary'] = new_line_item() grossinc['interest'] = new_line_item() grossinc['dividends'] = new_line_item() grossinc['other'] = new_line_item() However, I do think that a class will allow you more flexibility later on, not to mention ease of use. class line_item: def __init__(self, trans = None, assoc = None, goal = 0): if not trans: trans = {'Date': ()} if not assoc: assoc = [] self.transactions = trans self.associations = assoc self.goal = goal grossinc['salary'] = line_item() grossinc['interest'] = line_item() grossinc['dividends'] = line_item() grossinc['other'] = line_item(goal = 575) grossinc['salary'].goal = 3333 Note that this makes it easier to refer to parts of each line item, since you can use a named attribute instead of the cryptic [2], and it also allows for more flexibility in creating items that are already initalized. By the way, you may wonder why I have default values of "None" for the dict and list attributes, and then create the appropriate object later. This is because default parameters are only evaluated once, so if I had a dict or list as a default parameter, you'd end up with every line_item having references to the *same* dict and list -- a close parallel to your original problem. By passing in None as the default, and then creating new objects as needed, I ensure that every line_item gets its own transaction dict and associations list. (I don't bother with this for the goal, because integers are not mutable, therefore it doesn't really matter if all line_items share the same 0 or not.) See http://www.python.org/doc/FAQ.html#6.25 for a bit more information about this. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Fri Apr 11 15:07:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 11 14:07:01 2003 Subject: [Tutor] Summing a list of numbers / writing small functions In-Reply-To: <20030411104948.998.4@wonderland.1050046227.fake> Message-ID: > > How can I simplify this lines: > > > sum = 0 > > > myList = [1,2,3,4,5,6] > > > for each in myList: > > > sum += each > > > > Into shorter, more elegant line(s)? > > Although Albert has shown you how to do this with reduce() I don't > actually think there is any need to shorten or make this more elegant. > > compare > sum = reduce(operator.add, myList) > with > for x in myList: sum += x > > which is shorter? which is more elegant? Hello! I think both ways work perfectly well. The important thing, though, is to see if we do this summation frequently. If so, it's probably worth it to define a add_all() function to capture that idea of adding up elements in a list. We've seen two ways of doing it: ### def add_all(myList): sum = 0 for x in myList: sum += x return sum ### and ### def add_all(myList): return reduce(operator.add, myList) ### As soon as we have some sort of definition for summation --- as soon as we give it a name --- we can use it as part of our language! ### >>> add_all(range(10)) 45 >>> add_all([2, 4, 6, 8]) + add_all([1, 3, 5, 7, 9]) 45 ### add_all(), then, is a very elegant way of doing summations. *grin* Hope this helps! From cdsomerl@murray-ky.net Fri Apr 11 16:33:02 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Fri Apr 11 15:33:02 2003 Subject: [Tutor] assignment to 1 item in dict assigns to all items in dict? In-Reply-To: <3E96F969.9060607@ccvcorp.com> Message-ID: <000901c30060$a0c96740$e612953f@www> OK, so it seems to me I have 2 options for building my data model: nesting lists and dictionaries (making sure to create new instances instead of references), or an object model by implementing classes > You could do this with a class, and that would probably be my preferred > way, especially if there's any common tasks that need to be done on > line_items -- those can easily become methods of the class. > Note that this makes it easier to refer to parts of each line item, > since you can use a named attribute instead of the cryptic [2], and it > also allows for more flexibility in creating items that are already > initalized. I'm going to need to iterate through (and sum) attributes that are (currently) lists in dictionaries, as well as attributes that are in separate, similar lists in a dictionary. Would this be easier if I switched over to the object data model? And will using one way over the other lead to speed or private variable issues that I have not figured out yet? Thanks for your help Chris From scott_list@mischko.com Fri Apr 11 16:51:01 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 11 15:51:01 2003 Subject: [Tutor] Perl vs. Python's way of handling references. Message-ID: <200304111250.34650.scott_list@mischko.com> Here's two code snippets, one in Perl, the other Python: > $ perl > $one = 1; > $two = 2; > %dict = ( a => 'one', b => 'two' ); > print ${ $dict{a} }, "\n" > Ctrl-D > 1 > > The above in python ... You have to say: > > $ python > Python 2.2.1 (#1, Aug 30 2002, 12:15:30) > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> one = 1 > >>> two = 2 > >>> dict = {'a':'one','b':'two'} > >>> print vars()[ dict['a'] ] > > 1 > > notice how you have to use the vars function instead of a simple memory > lookup as you do in perl. Its no big deal for this simple case, but when > your data structures are deeply nested, it makes a huge difference. I've been discussing this issue regarding on the Perl Tutor list. I'm new to Python and fairly new to Perl and I'd like to learn how significant this issue is "when your data structures are deeply nested" from the perspective of Python programmers who've had to deal with this issue. Is there a better way of dealing with this issue that I'm not seeing here (better than using the vars() construct)? TIA, Scott From tbrauch@mindless.com Fri Apr 11 17:13:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Fri Apr 11 16:13:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. References: <200304111250.34650.scott_list@mischko.com> Message-ID: <006701c30066$a0ea9c20$6600a8c0@tbrauch> > > The above in python ... You have to say: > > > > $ python > > Python 2.2.1 (#1, Aug 30 2002, 12:15:30) > > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > > > > >>> one = 1 > > >>> two = 2 > > >>> dict = {'a':'one','b':'two'} > > >>> print vars()[ dict['a'] ] > > > > 1 > > If I'm not mistaken, and I might be, this is not quite right. Or, at least, not how I would do it. Let's look at this... >>> one = 1 >>> two = 2 >>> one 1 >>> two 2 >>> my_dict = {'a':'one','b':'two'} >>> my_dict['a'] 'one' Hmm, but you want the value 'one' is holding. Try this... >>> eval(my_dict['a']) 1 Although, I must admit, I am a little confused on the >>> one = 1 and why it's not >>> 'one' = 1 Or, why then in the dictionary, you decide 'a':'one', with quotes. I think someone is getting sloppy with quotes. So, let's test this little fix and watch what we do with quotes. >>> my_dict['a'] = one >>> my_dict['a'] 1 Ah, so now, you can do this in Python to get the desired effect... >>> one = 1 >>> two = 2 >>> my_dict = {'a':one,'b':two} >>> my_dict['a'] 1 No need for vals() anything. This seems intuitive to me. I mean, if I look up a word in a real dictionary, I want the definition, not something that tells me where I can go look to find the definition (like a memory reference seems to be to me). Oh, and a point of style. dict = {...} is bad in Python. One must be very careful renaming the default functions like this. I don't know if I quite answered the question, but maybe at least this is food for thought. - Tim From python@jaydorsey.com Fri Apr 11 17:14:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Fri Apr 11 16:14:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <200304111250.34650.scott_list@mischko.com> References: <200304111250.34650.scott_list@mischko.com> Message-ID: <3E9721D1.1090909@jaydorsey.com> Scott Chapman wrote: > Here's two code snippets, one in Perl, the other Python: > > >>$ perl >>$one = 1; >>$two = 2; >>%dict = ( a => 'one', b => 'two' ); >>print ${ $dict{a} }, "\n" >>Ctrl-D >>1 >> >>The above in python ... You have to say: >> >>$ python >>Python 2.2.1 (#1, Aug 30 2002, 12:15:30) >>[GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 >>Type "help", "copyright", "credits" or "license" for more information. >> >> >>>>>one = 1 >>>>>two = 2 >>>>>dict = {'a':'one','b':'two'} >>>>>print vars()[ dict['a'] ] >> >>1 >> >>notice how you have to use the vars function instead of a simple memory >>lookup as you do in perl. Its no big deal for this simple case, but when >>your data structures are deeply nested, it makes a huge difference. > > > I've been discussing this issue regarding on the Perl Tutor list. I'm new to > Python and fairly new to Perl and I'd like to learn how significant this > issue is "when your data structures are deeply nested" from the perspective > of Python programmers who've had to deal with this issue. > > Is there a better way of dealing with this issue that I'm not seeing here > (better than using the vars() construct)? > > TIA, > Scott > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor I'm most likely not understanding the question properly (never worked in Perl before, still fairly new to Python), but are you looking for this syntax: >>> one = 1 >>> two = 2 >>> dict = {'a':one,'b':two} >>> print dict['a'] 1 jay From scott_list@mischko.com Fri Apr 11 17:32:02 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 11 16:32:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <006701c30066$a0ea9c20$6600a8c0@tbrauch> References: <200304111250.34650.scott_list@mischko.com> <006701c30066$a0ea9c20$6600a8c0@tbrauch> Message-ID: <200304111331.16229.scott_list@mischko.com> On Friday 11 April 2003 13:12, Timothy M. Brauch wrote: > > > The above in python ... You have to say: > > > > > > $ python > > > Python 2.2.1 (#1, Aug 30 2002, 12:15:30) > > > [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 > > > Type "help", "copyright", "credits" or "license" for more > > information. > > > > >>> one = 1 > > > >>> two = 2 > > > >>> dict = {'a':'one','b':'two'} > > > >>> print vars()[ dict['a'] ] > > > > > > 1 > > If I'm not mistaken, and I might be, this is not quite right. Or, at > least, not how I would do it. > > Let's look at this... > > >>> one = 1 > >>> two = 2 > >>> one > > 1 > > >>> two > > 2 > > >>> my_dict = {'a':'one','b':'two'} > >>> my_dict['a'] > > 'one' > > Hmm, but you want the value 'one' is holding. Try this... > > >>> eval(my_dict['a']) > > 1 > > Although, I must admit, I am a little confused on the > > >>> one = 1 > > and why it's not > > >>> 'one' = 1 > > Or, why then in the dictionary, you decide 'a':'one', with quotes. I > think someone is getting sloppy with quotes. So, let's test this > little fix and watch what we do with quotes. The quotes are used here to see if it's like Perl. It isn't. > >>> my_dict['a'] = one > >>> my_dict['a'] > > 1 > > Ah, so now, you can do this in Python to get the desired effect... > > >>> one = 1 > >>> two = 2 > >>> my_dict = {'a':one,'b':two} > >>> my_dict['a'] > > 1 Not really. Python's got my_dict['a'] pointing at the actual 1 in memory, not the variable one: Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> one = 1 >>> two = 2 >>> my_dict = {'a':one,'b':two} >>> my_dict['a'] 1 >>> one = 3 >>> >>> my_dict['a'] 1 >>> id (one) 135313084 >>> id (1) 135313168 >>> id (my_dict['a']) 135313168 vars() is needed (or eval()) to do the trick like Perl. I'm wondering if there's a way to do this that works better in deeply nested structures, which was the point made by the person on Perl Tutor. > No need for vals() anything. This seems intuitive to me. I mean, if > I look up a word in a real dictionary, I want the definition, not > something that tells me where I can go look to find the definition > (like a memory reference seems to be to me). > > Oh, and a point of style. dict = {...} is bad in Python. One must be > very careful renaming the default functions like this. Didn't realize that was a built in. Scott From scott_list@mischko.com Fri Apr 11 17:35:31 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 11 16:35:31 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <3E9721D1.1090909@jaydorsey.com> References: <200304111250.34650.scott_list@mischko.com> <3E9721D1.1090909@jaydorsey.com> Message-ID: <200304111334.35359.scott_list@mischko.com> On Friday 11 April 2003 13:13, Jay Dorsey wrote: > Scott Chapman wrote: > I'm most likely not understanding the question properly (never worked in > Perl before, > > still fairly new to Python), but are you looking for this syntax: > >>> one = 1 > >>> two = 2 > >>> dict = {'a':one,'b':two} > >>> print dict['a'] > > 1 > This does not work as expected. Chage the value of the variable one and you don't change the value of dict['a']: >>> one = 1 >>> two = 2 >>> my_dict = {'a':one,'b':two} >>> my_dict['a'] 1 >>> one = 3 >>> >>> my_dict['a'] 1 >>> id (one) 135313084 >>> id (1) 135313168 >>> id (my_dict['a']) 135313168 The id()'s show that dict['a'] is not pointing to the variable one but to it's value, 1. This is one of the unique things python does with it's namespaces. Scott From dyoo@hkn.eecs.berkeley.edu Fri Apr 11 18:02:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 11 17:02:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <200304111334.35359.scott_list@mischko.com> Message-ID: > This does not work as expected. Chage the value of the variable one and > you don't change the value of dict['a']: > > >>> one = 1 > >>> two = 2 > >>> my_dict = {'a':one,'b':two} Hi Scott, This is an interesting topic! It might help to see what this is actually doing, by drawing a simplified picture of our program's universe. Here's what it might look like to ASCII people: my_dict | | v +--------------+ | | one---------------> 1 <---------|-my_dict['a'] | | | | | two---------------> 2 <---------|-my_dict['b'] | | | +--------------+ That is, 'one' and 'two' are names that refer to some integer objects. Assignment is an action that gets a name to point to an object. my_dict itself is a container, and we see that my_dict['a'] and mydict['b'] also refer to those same integer objects. Ok, let's go through a few more statements. ### > >>> my_dict['a'] > 1 > >>> one = 3 ### At this point, we assign 'one' to a new integer object, so our diagram has changed. Let's see what it might look like: my_dict | | +--> 3 v | +--------------+ | | | one------------+ 1 <---------|-my_dict['a'] | | | | | two---------------> 2 <---------|-my_dict['b'] | | | +--------------+ When we compare against the original diagram, we can notice that when we say: one = 3 we redirect the name 'one' to point to 3. The key thing to see, however, is that we don't change the arrow that my_dict['a'] points to: it still points to 1. And we see that this is true: ### > >>> my_dict['a'] > 1 ### > The id()'s show that dict['a'] is not pointing to the variable one but > to it's value, 1. This is one of the unique things python does with > it's namespaces. This isn't really about namespaces: it's more about seeing what variable names are, and what assignment means. If we want, we can "adding a level of indirection", so that it looks like changes to 'one' reflect to changes in 'my_dict'. We can make our system look like this: my_dict 1 | ^ | | | | v | +--------------+ +---+ | | one--------------->| | |<---------|-my_dict['a'] | +---+ | | | | two---------------> 2 <---------|-my_dict['b'] | | | +--------------+ I'm using boxes to symbolize "mutable" containers. This diagram shows that we can make 'one' and my_dict['a'] refer to a list. ### >>> one = [1] >>> two = 2 >>> my_dict = {'a' : one, 'b' : two} >>> one[0] = 3 >>> one [3] >>> two 2 >>> my_dict {'a': [3], 'b': 2} ### Is this the effect that you are looking for? Please feel free to ask questions about this. Good luck! From aicolburn@yahoo.com Fri Apr 11 18:33:01 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Fri Apr 11 17:33:01 2003 Subject: [Tutor] FTPing a file while keeping Line Feeds Message-ID: <20030411212622.92561.qmail@web41601.mail.yahoo.com> This is an easy question, but I can't seem to find the answer! After creating an ftplib.FTP object called 'ftp' and opening a file for writing, I download a text file via the command: ftp.retrlines('RETR textFile', file.write) textFile transfers to file, but textFile's line feeds don't transfer. How do I transfer textFile such that the line feeds are kept? (Specifically, textFile contains comma separated values, with each line in the file representing a different row in a spreadsheet.) As always, thanks! -- Al p.s. If you've got a quick reference to where I SHOULD have been looking [online] for this info, that too would be great. __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - File online, calculators, forms, and more http://tax.yahoo.com From Janssen@rz.uni-frankfurt.de Fri Apr 11 19:57:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Apr 11 18:57:01 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <200304111250.34650.scott_list@mischko.com> Message-ID: On Fri, 11 Apr 2003, Scott Chapman wrote: > Here's two code snippets, one in Perl, the other Python: > > > $ perl > > $one = 1; > > $two = 2; > > %dict = ( a => 'one', b => 'two' ); this set up key-string pairs, right? You propably explain what this perl syntax does, because tutor@python.org isn't the place with the deepest insight into perl syntax. Me for my part am asking, why the interpreter doesn't complain about "a" written as non string. Does the interpreter A) take it implicite as a string? Or B) did you indeed set up a variable a? The value part are strings and no nested references or how to call it, otherwise you need to use $one.... look forward: > > print ${ $dict{a} }, "\n" I've detected a very supicios ${ } around the hash lookup "$dict{a}" ;-) Does $dict{a} indeed returns 'one' as a mere string and the second ${ } is shell like syntax for variable lookup (like ${HOME} )? Then, it's the same hack in both languages. --- What did you wanted to show us? How perl can store "values as variables" (just to give it a name) into datastructures? How you can transform $one anywhere and retrieve the updated value from %dict? My advice is to forget this. Python has its own ways to handle "shared values": classes or nifty default-argument-tricks or ?. It's already hard enough with just this stuff. No need to reimplement perl behaviour or programming style (No, i'm not saying perl's bad, but I'm saying that python is a different language). Michael From dyoo@hkn.eecs.berkeley.edu Fri Apr 11 19:58:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 11 18:58:02 2003 Subject: [Tutor] FTPing a file while keeping Line Feeds In-Reply-To: <20030411212622.92561.qmail@web41601.mail.yahoo.com> Message-ID: On Fri, 11 Apr 2003, Alan Colburn wrote: > This is an easy question, but I can't seem to find the > answer! After creating an ftplib.FTP object called > 'ftp' and opening a file for writing, I download a > text file via the command: > > ftp.retrlines('RETR textFile', file.write) > > textFile transfers to file, but textFile's line feeds don't transfer. Hi Alan, Just to make sure: by "line feeds", do you mean the carriage return characters '\r'? If so, then the behavior that we're running into is expected: FTP text transfers are supposed to translate line endings to the one that your computer natively uses. As a concrete example: if the file originally had '\n', and we run the program to download the file to our Windows machine, FTP will transparently translate all the '\n' to '\r\n'. > How do I transfer textFile such that the line feeds are kept? > (Specifically, textFile contains comma separated values, with each line > in the file representing a different row in a spreadsheet.) In this case, if we want to keep the file verbatim, with no line-ending translation, we should use the 'retrbinary' binary mode download. In binary mode, a file is treated as a stream of bytes, not lines, so it does no translation. > p.s. If you've got a quick reference to where I SHOULD have been looking > [online] for this info, that too would be great. Ideally, the official documentation at: http://www.python.org/doc/lib/module-ftplib.html http://www.python.org/doc/lib/ftp-objects.html should have given a few good examples of common uses of ftplib. The first link does show an example of retreiving a file with retrbinary, but doesn't really explain the subtleties of text-vs-binary transfers. Hmmm... If you feel that the documentation should be improved to explain this in detail, perhaps one of us here on Tutor can write something short, and send it over to the python-doc SIG. Good luck to you! From scott_list@mischko.com Fri Apr 11 20:14:01 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 11 19:14:01 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: References: Message-ID: <200304111613.36910.scott_list@mischko.com> On Friday 11 April 2003 15:56, Michael Janssen wrote: > What did you wanted to show us? How perl can store "values as variables" > (just to give it a name) into datastructures? How you can transform $one > anywhere and retrieve the updated value from %dict? > > My advice is to forget this. Python has its own ways to handle "shared > values": classes or nifty default-argument-tricks or ?. It's already hard > enough with just this stuff. No need to reimplement perl behaviour or > programming style (No, i'm not saying perl's bad, but I'm saying that > python is a different language). I wasn't trying to show the list anything relating to Perl vs. Python. I was demonstrating how Perl does references and how Python does them. The Perl advocate on the Perl Tutorial list was the fellow I was quoting on the original post. He said that you must use vars() in python to do the trick like you do in Perl with it's reference syntax. He said that this is a drawback to Python when you get into deeply nested structures. I wanted some opinions from the Python list as to whether or not this is a drawback or not from a Python programmers perspective and if there are any easier solutions than using vars() or eval() that might work better for deeply nested structures, or is there a better way to do the data structures altogether. Scott From wheelcrdan@hotmail.com Fri Apr 11 20:24:01 2003 From: wheelcrdan@hotmail.com (Danny) Date: Fri Apr 11 19:24:01 2003 Subject: [Tutor] Help with simple program using while loops and lists Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C3004E.F39C1F10 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Everyone, Thanks ahead of time for everyone help. This program seems like it = should be easy. All I want it to do is give the user a menu with three = options. That seems easy but with the second and the third option does = not do what I would except. I want the program to if they pick option 2 = is print the questions and the answers, and print them one question and = one answer on each line. Then break out of the loop and exit. The third = option if they pick that all I want it to do is just break out of the = loop and exit the program. Sounds easy but I been working all day and = can't get it to do those simple tasks. Here is that program. =20 ## This program runs a test of knowledge true =3D 1 false =3D 00 menu_item =3D 0 list =3D [] while menu_item < 3: print '---------------------------' print '1. Take the test?' print '2. View the questions, and the answer.' print '3. Quit the program. ' menu_item =3D input('Pick an item from the menu: ') if menu_item =3D=3D 1: current =3D 0 if len(list) > 0: while current < len(list): print current,'. ',list[current] current =3D current + 1 print "Ok here we go" break elif menu_item =3D=3D 2: print get_questions() break else: menu_item =3D=3D 3 print "good bye" break =20 # First get the test questions # Later this will be modified to use file io. def j_questions(): return [["What color is the daytime sky on a clear day?"],\ ["What is the answer to life, the universe and = everything\n"],\ ["What is a three letter word for mouse trap?"]] def get_questions(): if menu_item =3D=3D 1 or 2: #notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?", = "blue"],\ ["What is the answer to life, the universe and = everything?","42"],\ ["What is a three letter word for mouse trap?", "cat"]] else: return =20 =20 #This will test a single question # it takes a single question in #it returns true if the user typed the correct answer, othrewise false def check_questions(question_and_answer): #extract the question and the answer from the list question =3D question_and_answer[0] answer =3D question_and_answer[1] #give the question to the user given_answer =3D raw_input(question) #compare the user's answer to the testers answer if answer =3D=3D given_answer: print "Correct!!" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) =3D=3D 0: print "No questions were given." # the return exits the function return index =3D 0 right =3D 0 while index < len(questions): #Check the question if check_questions(questions[index]): right =3D right + 1 #Go to the next question index =3D index + 1 #Notice the order of the computation, first multiply, the divide print "You got",right*100/len(questions),"% right out = of",len(questions) #now lests run the questions run_test(get_questions()) Thanks again and talk to you all again soon=20 Danny D ------=_NextPart_000_0005_01C3004E.F39C1F10 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Everyone,
 
Thanks ahead of time for everyone help. = This=20 program seems like it should be easy. All I want it to do is give the = user a=20 menu with three options. That seems easy but with the second and the = third=20 option does not do what I would except. I want the program to if they = pick=20 option 2 is print the questions and the answers, and print them one = question and=20 one answer on each line. Then break out of the loop and exit. The = third=20 option if they pick that all I want it to do is just break out of the = loop and=20 exit the program. Sounds easy but I been working all day and can't get = it to do=20 those simple tasks. Here is that program.
 
   
## This program = runs a test=20 of knowledge
true =3D 1
false =3D 00
menu_item =3D 0
list = =3D []
while=20 menu_item < 3:
    print=20 '---------------------------'
    print '1. Take the=20 test?'
    print '2. View the questions, and the=20 answer.'
    print '3. Quit the program.=20 '
    menu_item =3D input('Pick an item from the menu: = ')
    if menu_item =3D=3D=20 1:
        current =3D=20 0
        if len(list) >=20 0:
            = while=20 current <=20 len(list):
          = ;     =20 print current,'.=20 ',list[current]
         =       =20 current =3D current +=20 1
           &n= bsp;   =20 print "Ok here we=20 go"
           =     =20 break
    elif menu_item =3D=3D=20 2:
        print=20 get_questions()
       =20 break
    = else:
       =20 menu_item =3D=3D 3
        print = "good=20 bye"
       =20 break
          &nbs= p;    =20
# First get the test questions
# Later this will be modified to = use file=20 io.
def j_questions():
    return [["What color is = the=20 daytime sky on a clear=20 day?"],\
          &= nbsp;=20 ["What is the answer to life, the universe and=20 everything\n"],\
         = ;  =20 ["What is a three letter word for mouse trap?"]]
 
def = get_questions():
    if=20 menu_item =3D=3D 1 or 2:
        = #notice how=20 the data is stored as a list of=20 lists
        return [["What color = is the=20 daytime sky on a clear day?",=20 "blue"],\
          =  =20 ["What is the answer to life, the universe and=20 everything?","42"],\
        &= nbsp;  =20 ["What is a three letter word for mouse trap?", = "cat"]]
   =20 else:
       =20 return
    
   
 
#This will test a single question
# = it takes a=20 single question in
#it returns true if the user typed the correct = answer,=20 othrewise false
 
def=20 check_questions(question_and_answer):
    #extract the = question and the answer from the list
    question =3D = question_and_answer[0]
    answer =3D=20 question_and_answer[1]
    #give the question to the=20 user
    given_answer =3D=20 raw_input(question)
    #compare the user's answer to = the=20 testers answer
    if answer =3D=3D=20 given_answer:
        print=20 "Correct!!"
        return=20 true
    = else:
       =20 print "Incorrect, correct=20 was:",answer
        return=20 false
    # This will run through all the=20 questions
 
def = run_test(questions):
    if=20 len(questions) =3D=3D 0:
        = print "No=20 questions were given."
        # = the=20 return exits the function
       =20 return
    index =3D 0
    right =3D = 0
    while index <=20 len(questions):
        #Check the = question
        if=20 check_questions(questions[index]):
      = ;     =20 right =3D right + 1
        #Go to = the next=20 question
          &= nbsp;=20 index =3D index + 1
        = #Notice the=20 order of the computation, first multiply, the=20 divide
        print "You=20 got",right*100/len(questions),"% right out = of",len(questions)
 
#now lests run the=20 questions
run_test(get_questions())
Thanks again and talk to you all again = soon=20
Danny D
------=_NextPart_000_0005_01C3004E.F39C1F10-- From dyoo@hkn.eecs.berkeley.edu Fri Apr 11 20:47:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 11 19:47:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <200304111613.36910.scott_list@mischko.com> Message-ID: Hi Scott, > > My advice is to forget this. Python has its own ways to handle "shared > > values": classes or nifty default-argument-tricks or ?. It's already > > hard enough with just this stuff. No need to reimplement perl > > behaviour or programming style (No, i'm not saying perl's bad, but I'm > > saying that python is a different language). > > I wasn't trying to show the list anything relating to Perl vs. Python. > I was demonstrating how Perl does references and how Python does them. > The Perl advocate on the Perl Tutorial list was the fellow I was quoting > on the original post. He said that you must use vars() in python to do > the trick like you do in Perl with it's reference syntax. ^^^^^ I think the operative word here is "trick". *grin* There is no trick necessary to do nested data structures in Python, which I think is the main point of contention here! Let's dig in and talk more about this. In older versions of Perl, the symbolic name trick you showed us, ### (Perl < 5) code ### $one = 1; $two = 2; %dict = ( a => 'one', b => 'two' ); print ${ $dict{a} }, "\n" ### was necessary to get nested structures working: Perl didn't have proper references before Perl 5, so it used 'symbolic' references to compensate. This is a hack because, to get another depth of data structure in there, we'd need to introduce another set of variables. And arbitrarily deep data structures? Ouch. In Perl 5, the language introduced the idea of "hard" references to avoid this soft-reference hack. In fact, most Perl programmers today would (or should!) discourage the code above because of its use of "symbolic" references. I'm surprised no one at the Perl tutor group mentioned it: please tell them not to use symbolic references! Since Perl 5 has real hard references, Perl programmers should prefer the following code: ### Perl 5 code $hash = { a => { one => 1 }, b => { two => 2 } } ### That is, $dict is a reference to a hashtable that maps to another reference to a hashtable. This is a true nested data structure, and generalizes well to deeply nested structures. The equivalent code in Python actually doesn't look that different than this. ### dict = { 'a' : { 'one' : 1 }, 'b' : { 'two' : 2 }} ### And this is the way we can create deeply nested data structures. > I wanted some opinions from the Python list as to whether or not this is > a drawback or not from a Python programmers perspective and if there are > any easier solutions than using vars() or eval() that might work better > for deeply nested structures, or is there a better way to do the data > structures altogether. It's a different way altogether: we do not need to use the vars() or eval() hack in Python or Perl to get nested data structures right. So our point of confusion was based on the Perl 4 way of doing nested structure. You need to tell your friend to review 'perl perlreftut': they should see some new stuff in there that they haven't seen before. Please feel free to ask more questions about this: I hope that this clears up some of the confusion! From scott_list@mischko.com Fri Apr 11 20:52:22 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 11 19:52:22 2003 Subject: [Tutor] Help with simple program using while loops and lists In-Reply-To: References: Message-ID: <200304111650.21095.scott_list@mischko.com> Define your functions before you call them. Scott From Janssen@rz.uni-frankfurt.de Fri Apr 11 21:46:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Apr 11 20:46:02 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <200304111613.36910.scott_list@mischko.com> Message-ID: On Fri, 11 Apr 2003, Scott Chapman wrote: > I wasn't trying to show the list anything relating to Perl vs. Python. I was > demonstrating how Perl does references and how Python does them. The Perl > advocate on the Perl Tutorial list was the fellow I was quoting on the > original post. He said that you must use vars() in python to do the trick > like you do in Perl with it's reference syntax. He said that this is a > drawback to Python when you get into deeply nested structures. > > I wanted some opinions from the Python list as to whether or not this is a > drawback or not from a Python programmers perspective and if there are any > easier solutions than using vars() or eval() that might work better for > deeply nested structures, or is there a better way to do the data structures > altogether. eval() and ${ } is both as simple, isn't it? ##What happens actually? d1 = {"a": "one"} set up a string value "one" for a string key "a". *given* that "one" is a variable (in global namespace) you can do: eval(d1["a"]) eval("one") ---> eval() evaluates the python expression "one" in global namespace. vars()[d1["a"]] vars()["one"] ---> this looks up "one" in a dictionary returned by vars() (try "print vars()" to get an impression what vars() does). But although you *can* do it, this is not the python way of handling data. In other words: you seldom find a python scripts that relies on this kind of hack. Honest: The best way to reduce problems with eval()/vars() is to reduce its usage no matter how deep you data structure is. ##Deep data structure with strings to call related variables with eval() [Disclaimer: this is a complete test scenario. This is *not* the way you should wite python scripts] # data at the bottom. one = 1 two = 2 # a collection aDict = {1: "one", 2:"two"} # next level of nesting (upper) caller = "aDict" # next level of nesting (deeper) DeepDict = {"wert": "asdf"} three = "DeepDict" aDict[3] = "three" ----> is this what you have meant (If not you should provide your own example, because it's very likly that no python programmer can provide one from her/his background)? eval(eval(caller)[1]) --> 1 eval(eval(caller)[3]) --> "three" eval(eval(eval(caller)[3]))["wert"] --> "asdf" Beside the need to count the amount of evals, I can't see a problem with call-data-not-by-name-but-with-eval(string). Note: hopefully nobody actually does this. ## It's not clear to me, what's the subject of the example: A) the way of retrieving data from deep-nested structures? B) the effect that "one" is modified and the updated value is found via ${ %dict{a} }? A): python does it another way. Shall we give you some examples? B): why modify a value and retrieve it from somewhere else? When you want to organize "shared data" you propably better organize it with classes. Michael From shalehperry@attbi.com Fri Apr 11 22:05:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Apr 11 21:05:01 2003 Subject: [Tutor] Summing a list of numbers / writing small functions In-Reply-To: References: Message-ID: <200304111804.03461.shalehperry@attbi.com> > > As soon as we have some sort of definition for summation --- as soon as we > give it a name --- we can use it as part of our language! > and this name is the important thing. for i in something: do something is a loop. I have to look at what it iterates over, what the loop is doing, etc to get my head around it. When i see reduce(operator.add, foo) I know what is happening in one succinct bite. This is important for OTHER people who read your code. In python the loops are fairly standard but in say java or C++ replacing a loop with a named function is a definite win. From sudhirchauhan1@yahoo.co.in Sat Apr 12 13:47:01 2003 From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=) Date: Sat Apr 12 12:47:01 2003 Subject: [Tutor] Help with simple program using while loops and lists In-Reply-To: Message-ID: <20030412164546.4075.qmail@web8203.mail.in.yahoo.com> Hi , how about this order of placement of your lines. i did not modify anything except commenting one line. this will make it work at least :) regards, sudhir ## This program runs a test of knowledge # First get the test questions # Later this will be modified to use file io. def j_questions(): return [["What color is the daytime sky on a clear day?"],\ ["What is the answer to life, the universe and everything\n"],\ ["What is a three letter word for mouse trap?"]] def get_questions(): if menu_item == 1 or 2: #notice how the data is stored as a list of lists return [["What color is the daytime sky on a clear day?", "blue"],\ ["What is the answer to life, the universe and everything?","42"],\ ["What is a three letter word for mouse trap?", "cat"]] else: return #This will test a single question # it takes a single question in #it returns true if the user typed the correct answer, othrewise false def check_questions(question_and_answer): #extract the question and the answer from the list question = question_and_answer[0] answer = question_and_answer[1] #give the question to the user given_answer = raw_input(question) #compare the user's answer to the testers answer if answer == given_answer: print "Correct!!" return true else: print "Incorrect, correct was:",answer return false # This will run through all the questions def run_test(questions): if len(questions) == 0: print "No questions were given." # the return exits the function return index = 0 right = 0 while index < len(questions): #Check the question if check_questions(questions[index]): right = right + 1 #Go to the next question index = index + 1 #Notice the order of the computation, first multiply, the divide print "You got",right*100/len(questions),"% right out of",len(questions) #now lests run the questions true = 1 false = 00 menu_item = 0 list = [] while menu_item < 3: print '---------------------------' print '1. Take the test?' print '2. View the questions, and the answer.' print '3. Quit the program. ' menu_item = input('Pick an item from the menu: ') if menu_item == 1: current = 0 if len(list) > 0: while current < len(list): print current,'. ',list[current] current = current + 1 print "Ok here we go" break elif menu_item == 2: run_test(get_questions()) break else: menu_item == 3 print "good bye" break ________________________________________________________________________ Missed your favourite TV serial last night? Try the new, Yahoo! TV. visit http://in.tv.yahoo.com From scott_list@mischko.com Sat Apr 12 17:24:02 2003 From: scott_list@mischko.com (Scott Chapman) Date: Sat Apr 12 16:24:02 2003 Subject: [Tutor] dict(sequence) and dict(mapping) Message-ID: <200304121322.22027.scott_list@mischko.com> I'm looking at help(__builtins__) in Python 2.2.1. It shows: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs. | dict(seq) -> new dictionary initialized as if via: | d = {} | for k, v in seq: | d[k] = v I can say: test_dict = dict() to create a empty dictionary. How do I use the other two forms of this syntax: test_dict = dict(mapping) test_dict = dict(sequence) Please give me some sample mappings and sequences that work in this syntax notation. Thanks! Scott From trivas7@rawbw.com Sun Apr 13 00:36:04 2003 From: trivas7@rawbw.com (Thomas Rivas) Date: Sat Apr 12 23:36:04 2003 Subject: [Tutor] class (or static) variable? Message-ID: <200304122039.46606.trivas7@rawbw.com> Hello-- Is MyClass.item in the following an example of a class (Java/C++ 'static') variable? #!/bin/env python class MyClass: item=42 def __init__(self): self.item = 24 def __str__(self): return str(self.item) x=MyClass() print x.item print x print MyClass.item # prints: # 24 # 24 # 42 Thanks, Tom -- I like Boolean logic. NOT From antonmuhin at rambler.ru" References: <200304122039.46606.trivas7@rawbw.com> Message-ID: <12622475317.20030413202231@rambler.ru> Hello Thomas, Sunday, April 13, 2003, 7:39:46 AM, you wrote: TR> Hello-- TR> Is MyClass.item in the following an example of a class (Java/C++ 'static') TR> variable? TR> #!/bin/env python TR> class MyClass: TR> item=42 TR> def __init__(self): TR> self.item = 24 TR> def __str__(self): TR> return str(self.item) TR> x=MyClass() TR> print x.item TR> print x TR> print MyClass.item TR> # prints: TR> # 24 TR> # 24 TR> # 42 TR> Thanks, TR> Tom TR> -- TR> I like Boolean logic. NOT I suppose, yes: PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> class Foo: ... a = 42 ... def __init__(self): ... self.a = 24 ... >>> foo = Foo() >>> foo.a 24 >>> Foo.a 42 >>> id(foo.a) 9816512 >>> id(Foo.a) 9816332 >>> hth, -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <200304121322.22027.scott_list@mischko.com> Message-ID: <17422476799.20030413202233@rambler.ru> Hello Scott, Sunday, April 13, 2003, 12:22:21 AM, you wrote: SC> I'm looking at help(__builtins__) in Python 2.2.1. SC> It shows: SC> class dict(object) SC> | dict() -> new empty dictionary. SC> | dict(mapping) -> new dictionary initialized from a mapping object's SC> | (key, value) pairs. SC> | dict(seq) -> new dictionary initialized as if via: SC> | d = {} SC> | for k, v in seq: SC> | d[k] = v SC> I can say: SC> test_dict = dict() SC> to create a empty dictionary. SC> How do I use the other two forms of this syntax: SC> test_dict = dict(mapping) SC> test_dict = dict(sequence) SC> Please give me some sample mappings and sequences that work in this syntax SC> notation. SC> Thanks! SC> Scott I hope the following example will be of help. Note, that dict creates a copy of object and, therefore, differs from assignment. PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> d = {'a': 1, 'b': 2} >>> l = (('a', 1), ('b', 2)) >>> print dict(d) {'a': 1, 'b': 2} >>> print dict(l) {'a': 1, 'b': 2} >>> d_copy = dict(d) >>> d_copy['c'] = 3 >>> d_copy {'a': 1, 'c': 3, 'b': 2} >>> d {'a': 1, 'b': 2} >>> -- Best regards, anton mailto:antonmuhin@rambler.ru From wheelcrdan@hotmail.com Sun Apr 13 13:38:01 2003 From: wheelcrdan@hotmail.com (Danny) Date: Sun Apr 13 12:38:01 2003 Subject: [Tutor] Help with a while or a for loop that only allows three tries Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C301A8.9FC88D00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Everyone I'm working through the ActivePython Documents. One of the exercises is = to make a password program that exits after three tries. I'm confused = I've tried some different things having none of them be successful.=20 Also some times I see a while loop that starts out like=20 while 1: =20 what does that tiring to say, only go through the loop once. Or is that = a I if so what would you use something like that example for? ------=_NextPart_000_0005_01C301A8.9FC88D00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Everyone
 
I'm working through the ActivePython = Documents. One=20 of the exercises is to make a password program that exits after three = tries. I'm=20 confused I've tried some different things having none of them be = successful.=20
 
Also some times I see a while loop that = starts out=20 like
 
while 1:
       =
what does that tiring to say, only go = through the=20 loop once. Or is that a I if so what would you use something like that = example=20 for?
------=_NextPart_000_0005_01C301A8.9FC88D00-- From R. Alan Monroe" References: Message-ID: <77701226360.20030413131643@columbus.rr.com> > Also some times I see a while loop that starts out like > while 1: > what does that tiring to say, only go through the loop once. Or is > that a I if so what would you use something like that example for? "while 1:" means the same thing as "while true:" Bascially it would run forever, because 1 is always 1, or true is always true. Alan From Don Arnold" Message-ID: <040301c301e0$3d5fdaa0$2a11ba3f@defaultcomp> ----- Original Message ----- From: "Danny" To: Sent: Sunday, April 13, 2003 11:37 AM Subject: [Tutor] Help with a while or a for loop that only allows three tries Hi Everyone I'm working through the ActivePython Documents. One of the exercises is to make a password program that exits after three tries. I'm confused I've tried some different things having none of them be successful. Also some times I see a while loop that starts out like while 1: what does that tiring to say, only go through the loop once. Or is that a I if so what would you use something like that example for? [-- my reply --] A while loop executes its body as long as its condition is true. 1 will always evaluate as true, so using it as the looping condition gives an endless loop. With an endless loop, there should be a condition in the loop body that causes the loop to terminate, usually by executing the break statement. So, your password program could look something like this: tries = 0 while 1: password = raw_input('Enter your password: ') if password == 'DANNY': print 'password accepted' break else: tries += 1 if tries == 3: print 'invalid password' break Or, you could use the value of your loop counter in the while condition: tries = 0 while tries < 3: password = raw_input('Enter your password: ') if password == 'DANNY': print 'password accepted' break else: tries += 1 else: print 'invalid password' The while/else construct may look a little strange, but it's pretty simple: the else clause only executes if the loop terminated normally (in other words, it wasn't exited with a break statement). HTH, Don From cdsomerl@murray-ky.net Sun Apr 13 19:37:02 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Sun Apr 13 18:37:02 2003 Subject: [Tutor] new object attribute from string? Message-ID: <000201c3020c$c228e930$e612953f@www> Is it possible to make a new object attribute or blank dictionary from the value of a string? IE I have a string 'dict' and I want dict = {} or object.dict Thanks Chris From op73418@mail.telepac.pt Sun Apr 13 20:07:09 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Apr 13 19:07:09 2003 Subject: [Tutor] new object attribute from string? References: <000201c3020c$c228e930$e612953f@www> Message-ID: <001501c30211$5dd8ba50$02140dd5@violante> ----- Original Message ----- From: "Chris Somerlot" To: Sent: Sunday, April 13, 2003 11:33 PM Subject: [Tutor] new object attribute from string? > Is it possible to make a new object attribute or blank dictionary from > the value of a string? > > IE I have a string 'dict' and I want dict = {} or object.dict > One way is #Get dict class builtin by evaluating string. cls = eval('dict') #Call class. obj = cls() The builtin eval evaluates an *expression* in the current namespace and returns the result. Since what we get is a class object (dict) we just call it to get an instance of it - an empty dictionary. But are you sure you want to do this? Calling pieces of code via strings (by eval or exec) usually denotes Evil Programming, so if you tell us a little more about what you are trying to accomplish maybe we can advise better ways to do it. Usually, such needs of mapping strings to pieces of code are met by Python dictionaries where the keys are the strings and the values functions or callables. E.g. something like this my_dict = {} my_dict['dict'] = dict And now you just do my_dict['dict']() You can even wrap the whole thing in syntax-sugar via classes. Something like this should be enough (Python > 2.2) class callable_dict(dict): def __call__(self, key, *args, **kwargs): return self[key](*args, **kwargs) And now the above my_dict['dict']() is just my_dict('dict') > Thanks > Chris > > All the best, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Sun Apr 13 22:25:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 13 21:25:01 2003 Subject: [Tutor] Help with a while or a for loop that only allows three tries In-Reply-To: <77701226360.20030413131643@columbus.rr.com> Message-ID: On Sun, 13 Apr 2003, R. Alan Monroe wrote: > > Also some times I see a while loop that starts out like while 1: what > > does that tiring to say, only go through the loop once. Or is that a I > > if so what would you use something like that example for? > > "while 1:" means the same thing as "while true:" Bascially it would run > forever, because 1 is always 1, or true is always true. So whenever we say say something like: while 1: ## do something we are setting up a potential "infinite loop" that will continue to repeat until we do something spectacular, like 'breaking' out of a loop: ### >>> while 1: ... command = raw_input("enter a value, or type 'quit' to quit: ") ... if command == 'quit': ... break ... print "I don't understand", command ... enter a value, or type 'quit' to quit: jump I don't understand jump enter a value, or type 'quit' to quit: w I don't understand w enter a value, or type 'quit' to quit: e I don't understand e enter a value, or type 'quit' to quit: quit >>> ### Ok, the code was a little useless there, but I hope it gets the idea across... *grin* So this 'while 1' set-up is common in situations where we want to repeat something until some situation changes. [As a side note, it's actually now possible for us to write: while True: pass ## <--- put body of while loop here instead In Python 2.2, a 'True' boolean value (and, symmetrically, a 'False' value) is being slowly phased into the Python language. We might as well use it. *grin* Still, expect to see 'while 1:' a while yet, since us old fogies need some time to adjust to this traumatic change to the language.] If you feel uncomfortable about setting up the loop like there, there is a another way to arrange things to a similar effect: ### command = raw_input("enter a value, or type 'quit' to quit: ") while command != 'break': print "I don't understand", command command = raw_input("enter a value, or type 'quit' to quit: ") ### This is an alternative way to phrase that idea of looping. The reason we don't see this approach as much is because there's a little bit of redundancy in the first and last lines, but it's an equally valid way to do the looping. In fact, for your original question about limiting the number of loops to at most three times, this form may be more convenient for you. If you have more questions, please feel free to ask! From dyoo@hkn.eecs.berkeley.edu Sun Apr 13 22:34:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 13 21:34:01 2003 Subject: [Tutor] new object attribute from string? In-Reply-To: <001501c30211$5dd8ba50$02140dd5@violante> Message-ID: > > Is it possible to make a new object attribute or blank dictionary from > > the value of a string? > > You can even wrap the whole thing in syntax-sugar via classes. Something > like this should be enough (Python > 2.2) > > class callable_dict(dict): > def __call__(self, key, *args, **kwargs): > return self[key](*args, **kwargs) Hello! It is possible to dynamically add new attributes to our objects. Each object in Python has an internal '__dict__' dictionary that keeps track of all of its attributes: ### >>> class TestAttribute: ... def __init__(self, name): ... self.name = name ... def printInternals(self): ... print "my dictionary looks like this:", self.__dict__ ... >>> t1 = TestAttribute('Chris') >>> t1.printInternals() my dictionary looks like this: {'name': 'Chris'} ### And we're already very familiar with dictionaries: we can easily add new attributes by assigning another key to that __dict__ionary. ### >>> t1.__dict__['question'] = 'new object attribute from string?' >>> t1.question 'new object attribute from string?' >>> t1.printInternals() my dictionary looks like this: {'question': 'new object attribute from string?', 'name': 'Chris'} ### Hope this helps! From idiot1@netzero.net Mon Apr 14 01:04:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Mon Apr 14 00:04:02 2003 Subject: [Tutor] news update` Message-ID: <3E9A3376.20502@netzero.net> ok, was busy with family, server upgrades, MY MODEM DYING, and general chaos. The chaos is over, the modem is replaced, the server is working and the upgrade to it is delayed another month at least,so to hell with it, I am back mangling TL into stranger and morewonderful functionality. The ability to CREATE lists is complete. I am now working on the scripts for DELETING lists. A couple of other features sit on the back burner for 1.7.0, I still want 1.6.0 complete before burninh my limited candle on them. AS for 1.6.0, a new x header on traffic,new installer,more sophisticated way to handle aliases, automation of the compiling of new aliases with a cron job, bypassing aliases file security issues with a SOFT ln link. Updates on manuals. The BETA scripts are running NOW at http://www.tinylist.org/ and delivered this message to you. -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From jamesgross@sunhome.biz Mon Apr 14 12:50:02 2003 From: jamesgross@sunhome.biz (jamesgross@sunhome.biz) Date: Mon Apr 14 11:50:02 2003 Subject: [Tutor] Text processing basic Q Message-ID: <4014.68.14.208.155.1050335324.squirrel@mail.zoper.com> HI- I have a log file(from irc chat #plone) that I would like to print. The log file has lines that start with * that I would like to delete from the file. Yesterday from #python helped answer how to select a line that starts with a * by line.startswith('*'), so now what would the code be for a script to 1. load the file 2. start at the beginning of the file 3. if line start with * then delete 4. move to the next line in the file 5. save the file Thanks in advance, James From antonmuhin at rambler.ru" References: <4014.68.14.208.155.1050335324.squirrel@mail.zoper.com> Message-ID: <16217565007.20030414201250@rambler.ru> Hello jamesgross, Monday, April 14, 2003, 7:48:44 PM, you wrote: jsb> HI- jsb> I have a log file(from irc chat #plone) that I would jsb> like to print. The log file has lines that start with * that I would like jsb> to delete from jsb> the file. jsb> Yesterday from #python helped answer how to select a line that jsb> starts with a * by line.startswith('*'), so now what would the code be jsb> for a script to jsb> 1. load the file jsb> 2. start at the beginning of the file jsb> 3. if line start with * then delete jsb> 4. move to the next line in the file jsb> 5. save the file jsb> Thanks in advance, James WARNING: not tested file_name = ... input_file = file(file_name) filtered_lines = [l for l in input_file if not l.startswith('*')] input_file.close() output_file = file(file_name, 'w') for l in filtered_lines: output_file.write(l) output_file.close() If you want les memory-consuming version, create a filtered file and cpy it later into original file. HTH -- Best regards, anton mailto:antonmuhin@rambler.ru From bgailer@alum.rpi.edu Mon Apr 14 13:22:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Mon Apr 14 12:22:01 2003 Subject: [Tutor] Text processing basic Q In-Reply-To: <16217565007.20030414201250@rambler.ru> References: <4014.68.14.208.155.1050335324.squirrel@mail.zoper.com> <4014.68.14.208.155.1050335324.squirrel@mail.zoper.com> Message-ID: <5.2.0.9.0.20030414101633.025e52c8@66.28.54.253> --=======58CB2582======= Content-Type: text/plain; x-avg-checked=avg-ok-58308FD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit >[snip] a script to > > > 1. load the file > > 2. start at the beginning of the file > > 3. if line start with * then delete > > 4. move to the next line in the file > > 5. save the file > >file_name = ... > >input_file = file(file_name) >filtered_lines = [l for l in input_file if not l.startswith('*')] ### >SHOULD BE input_file.readlines() >input_file.close() > >output_file = file(file_name, 'w') >for l in filtered_lines :### COULD BE output_file.writelines(filtered_lines) > output_file.write(l) >output_file.close() Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======58CB2582======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-58308FD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======58CB2582=======-- From alan.gauld@bt.com Mon Apr 14 13:37:05 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Apr 14 12:37:05 2003 Subject: [Tutor] new object attribute from string? Message-ID: > It is possible to dynamically add new attributes to our objects. Each > object in Python has an internal '__dict__' dictionary that > keeps track of all of its attributes: > > ### > >>> class TestAttribute: > ... def __init__(self, name): > ... self.name = name > ... def printInternals(self): > ... print "my dictionary looks like this:", self.__dict__ > > And we're already very familiar with dictionaries: we can > easily add new attributes by assigning another key to > that __dict__ionary. But since we can achieve the same by simply assigning to a new attribute there is no need for such complexity >>> t1.question = 'new object attribute from string?' Achieves the same result > >>> t1.question > 'new object attribute from string?' Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From steve_weaver@peoplesoft.com Mon Apr 14 14:18:03 2003 From: steve_weaver@peoplesoft.com (steve_weaver@peoplesoft.com) Date: Mon Apr 14 13:18:03 2003 Subject: [Tutor] Out of Office Response: Tutor digest, Vol 1 #2369 - 12 msgs Message-ID: I will be out of the office starting Monday, April 14, 2003 and will not return until Thursday, April 17, 2003. I will respond to your message when I return. From lobow@brturbo.com Mon Apr 14 16:50:02 2003 From: lobow@brturbo.com (Diego Prestes) Date: Mon Apr 14 15:50:02 2003 Subject: [Tutor] Canvas Widget Message-ID: <3E9B10E5.1030202@brturbo.com> Hi there, Im trying to use canvas in tkinter but when I put the widget it always stay in the top of the program. I try to make a frame with the side=TOP to put the buttons of the toolbar but it stay in bottom. Someone know if I can change the side of the canvas? and other question. Someone know how can I create a rectangle, for example, using the mouse? Diego From dyoo@hkn.eecs.berkeley.edu Mon Apr 14 17:20:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 14 16:20:02 2003 Subject: [Tutor] new object attribute from string? In-Reply-To: Message-ID: On Mon, 14 Apr 2003 alan.gauld@bt.com wrote: > > It is possible to dynamically add new attributes to our objects. Each > > object in Python has an internal '__dict__' dictionary that > > keeps track of all of its attributes: > > > > ### > > >>> class TestAttribute: > > ... def __init__(self, name): > > ... self.name = name > > ... def printInternals(self): > > ... print "my dictionary looks like this:", self.__dict__ > > > > And we're already very familiar with dictionaries: we can > > easily add new attributes by assigning another key to > > that __dict__ionary. > > But since we can achieve the same by simply assigning to a new attribute > there is no need for such complexity > > >>> t1.question = 'new object attribute from string?' > > Achieves the same result > > > >>> t1.question > > 'new object attribute from string?' [warning; slightly advanced code ahead] Hi Alan, Yes, the direct way works too. *grin* In certain really dynamic code, the attribute name itself may not known until "runtime", when the program is actively running. For example, here's a toy class that demonstrates the kind of dynamism we can do in Python: ### from __future__ import nested_scopes class PleaseWrapper(object): """Wraps around an object and puts a please()ing wrapper around every attribute of our class.""" def __init__(self, wrapped_object): self.__wrapped_object = wrapped_object for key, value in self.__wrapped_object.__dict__.items(): self.__dict__[key] = self.__makePleaseFunction(key, value) def __makePleaseFunction(self, key, value): class F(str): def __init__(self2, message): str.__init__(self2, message) self2.__key = key self2.__value = value def please(self2): return self2.__value return F("say please()!") ### The code may look a bit mysterious: what does it do? Well, let's say that we had some class instance, like: ### >>> class Person(object): ... def __init__(self, name): ... self.name = name ... >>> p = Person("Danny") >>> p.name 'Danny' ### and let's say that we wanted it to be a little, well, annoying. *grin* We can make another instance that looks like 'p', but forces us to ask it 'please()' to get the value of anything: ### >>> p2 = PleaseWrapper(p) >>> p2.name 'say please()!' >>> p2.name.please() 'Danny' ### This sort of dynamicism is possible when we can manipulate an object's attributes through the dictionary interface. Hope this helps! From pan" This is a multi-part message in MIME format. --_b79e1f8e1ad6966428ab1b53560d2066b Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable > What's the simplest way to extract the value from a 'span' tag on=3D > a specified web page (or any tag for that matter)? (i already=3D > used urllib to get the html) and there is only one span tag on=3D > the page. > > Regards, > Wayne > wkoorts@mweb.co.za Hi Wayne, Try this: >>> htmlSource =3D 'aaa <span> bbb </span> ccc' >>> import re >>> re.findall('<span>.*</span>', htmlSource) # <=3D=3D [A] ['<span> bbb </span>'] =20 >>> re.findall('<span>(.*)</span>', htmlSource) # <=3D=3D [B] [' bbb '] Note the difference between [A] and [B] If there's a '\n' in between <span> and </span>: >>> b =3D '''aaa <span> bb ... bbb </span> ccc''' >>> b 'aaa <span> bb\n bbb </span> ccc' >>> re.findall(r'<span>[\w\s]*</span>',b) ['<span> bb\n bbb </span>'] >>> re.findall(r'<span>([\w\s]*)</span>',b) [' bb\n bbb '] More: >>> c=3D''' aaa <span> bbb1=20 ... bbb2 ... bbb3 ... </span>''' >>> c ' aaa <span> bbb1 \nbbb2\nbbb3\n</span>' >>> re.findall(r'<span>([\w\s]*)</span>',c) [' bbb1 \nbbb2\nbbb3\n'] hth pan --_b79e1f8e1ad6966428ab1b53560d2066b Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =0A=0A=0A=0A=0A > What's the simplest way to extract the value from a 'span' tag on=3D=0D
=0A > a specified web page (or any tag for that matter)? (i already=3D=0D
=0A > used urllib to get the html) and there is only one span tag on=3D=0D
=0A > the page.=0D
=0A >=0D
=0A > Regards,=0D
=0A > Wayne=0D
=0A > wkoorts@mweb.co.za=0D
=0A=0D
=0AHi Wayne,=0D
=0A=0D
=0ATry this:=0D
=0A=0D
=0A>>> htmlSource =3D 'aaa <span> bbb </span> ccc'=0D
=0A=0D
=0A>>> import re=0D
=0A=0D
=0A>>> re.findall('<span>.*</span>', htmlSource) # <=3D=3D [A]=0D
=0A['<span> bbb </span>'] =20=0D
=0A=0D
=0A>>> re.findall('<span>(.*)</span>', htmlSource) # <=3D=3D [B]=0D
=0A[' bbb ']=0D
=0A=0D
=0A=0D
=0ANote the difference between [A] and [B]=0D
=0A=0D
=0AIf there's a '\n' in between <span> and </span>:=0D
=0A=0D
=0A>>> b =3D '''aaa <span> bb=0D
=0A... bbb </span> ccc'''=0D
=0A=0D
=0A>>> b=0D
=0A'aaa <span> bb\n bbb </span> ccc'=0D
=0A=0D
=0A>>> re.findall(r'<span>[\w\s]*</span>',b)=0D
=0A['<span> bb\n bbb </span>']=0D
=0A=0D
=0A>>> re.findall(r'<span>([\w\s]*)</span>',b)=0D
=0A[' bb\n bbb ']=0D
=0A=0D
=0A=0D
=0AMore:=0D
=0A=0D
=0A>>> c=3D''' aaa <span> bbb1=20=0D
=0A... bbb2=0D
=0A... bbb3=0D
=0A... </span>'''=0D
=0A=0D
=0A>>> c=0D
=0A' aaa <span> bbb1 \nbbb2\nbbb3\n</span>'=0D
=0A=0D
=0A>>> re.findall(r'<span>([\w\s]*)</span>',c)=0D
=0A[' bbb1 \nbbb2\nbbb3\n']=0D
=0A=0D
=0A=0D
=0Ahth=0D
=0Apan
=0A=0A --_b79e1f8e1ad6966428ab1b53560d2066b-- From pan" This is a multi-part message in MIME format. --_b79e1f8e1ad6966428ab1b53560d2066b Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable > What's the simplest way to extract the value from a 'span' tag on=3D > a specified web page (or any tag for that matter)? (i already=3D > used urllib to get the html) and there is only one span tag on=3D > the page. > > Regards, > Wayne > wkoorts@mweb.co.za Hi Wayne, Try this: >>> htmlSource =3D 'aaa <span> bbb </span> ccc' >>> import re >>> re.findall('<span>.*</span>', htmlSource) # <=3D=3D [A] ['<span> bbb </span>'] =20 >>> re.findall('<span>(.*)</span>', htmlSource) # <=3D=3D [B] [' bbb '] Note the difference between [A] and [B] If there's a '\n' in between <span> and </span>: >>> b =3D '''aaa <span> bb ... bbb </span> ccc''' >>> b 'aaa <span> bb\n bbb </span> ccc' >>> re.findall(r'<span>[\w\s]*</span>',b) ['<span> bb\n bbb </span>'] >>> re.findall(r'<span>([\w\s]*)</span>',b) [' bb\n bbb '] More: >>> c=3D''' aaa <span> bbb1=20 ... bbb2 ... bbb3 ... </span>''' >>> c ' aaa <span> bbb1 \nbbb2\nbbb3\n</span>' >>> re.findall(r'<span>([\w\s]*)</span>',c) [' bbb1 \nbbb2\nbbb3\n'] hth pan --_b79e1f8e1ad6966428ab1b53560d2066b Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =0A=0A=0A=0A=0A > What's the simplest way to extract the value from a 'span' tag on=3D=0D
=0A > a specified web page (or any tag for that matter)? (i already=3D=0D
=0A > used urllib to get the html) and there is only one span tag on=3D=0D
=0A > the page.=0D
=0A >=0D
=0A > Regards,=0D
=0A > Wayne=0D
=0A > wkoorts@mweb.co.za=0D
=0A=0D
=0AHi Wayne,=0D
=0A=0D
=0ATry this:=0D
=0A=0D
=0A>>> htmlSource =3D 'aaa <span> bbb </span> ccc'=0D
=0A=0D
=0A>>> import re=0D
=0A=0D
=0A>>> re.findall('<span>.*</span>', htmlSource) # <=3D=3D [A]=0D
=0A['<span> bbb </span>'] =20=0D
=0A=0D
=0A>>> re.findall('<span>(.*)</span>', htmlSource) # <=3D=3D [B]=0D
=0A[' bbb ']=0D
=0A=0D
=0A=0D
=0ANote the difference between [A] and [B]=0D
=0A=0D
=0AIf there's a '\n' in between <span> and </span>:=0D
=0A=0D
=0A>>> b =3D '''aaa <span> bb=0D
=0A... bbb </span> ccc'''=0D
=0A=0D
=0A>>> b=0D
=0A'aaa <span> bb\n bbb </span> ccc'=0D
=0A=0D
=0A>>> re.findall(r'<span>[\w\s]*</span>',b)=0D
=0A['<span> bb\n bbb </span>']=0D
=0A=0D
=0A>>> re.findall(r'<span>([\w\s]*)</span>',b)=0D
=0A[' bb\n bbb ']=0D
=0A=0D
=0A=0D
=0AMore:=0D
=0A=0D
=0A>>> c=3D''' aaa <span> bbb1=20=0D
=0A... bbb2=0D
=0A... bbb3=0D
=0A... </span>'''=0D
=0A=0D
=0A>>> c=0D
=0A' aaa <span> bbb1 \nbbb2\nbbb3\n</span>'=0D
=0A=0D
=0A>>> re.findall(r'<span>([\w\s]*)</span>',c)=0D
=0A[' bbb1 \nbbb2\nbbb3\n']=0D
=0A=0D
=0A=0D
=0Ahth=0D
=0Apan
=0A=0A --_b79e1f8e1ad6966428ab1b53560d2066b-- From jeff@ccvcorp.com Mon Apr 14 18:09:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Apr 14 17:09:02 2003 Subject: [Tutor] new object attribute from string? References: Message-ID: <3E9B23BA.6070305@ccvcorp.com> Danny Yoo wrote: >Yes, the direct way works too. *grin* > >In certain really dynamic code, the attribute name itself may not known >until "runtime", when the program is actively running. > > Under most such circumstances, though, wouldn't it be easier and more straightforward to use setattr()/getattr() instead of directly fiddling with the object's __dict__? >>> class Item: ... pass ... >>> i = Item() >>> i.dict Traceback (most recent call last): File "", line 1, in ? AttributeError: Item instance has no attribute 'dict' >>> attribute = "dict" >>> setattr(i, attribute, {}) >>> i.dict {} >>> getattr(i, attribute) {} >>> Jeff Shannon Technician/Programmer Credit International From pan" This is a multi-part message in MIME format. --_b45c7ec8447d853375efa3a37d34fcd53 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable > Message: 2 > Date: Wed, 09 Apr 2003 09:32:01 +0200 > From: Charlie Clark charlie@begeistert.org>To: tutor@python.org, Henry Steigerwaldt hsteiger@comcast.net> > Subject: [Tutor] Re: Tutor Testing for response from a Web site [...] > correct. Does anybody know why Microsoft / Seattle Computer Products > decided to use "" instead of "/" as a path separator in QDOS? Was it like > this in CP/M? =20 [...] =20 > Charlie =20 To my understanding, the '\' was introduced by Bill Gates and his team when they wanna make an OS that's different from IBM's. IBM used '/', so they created this '\' just to be make it look different. It has been there since the DOS age (or even earlier).=0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D ~~~~~ be shapeless ~~~~~ Runsun Pan, PhD Dept. of Ecology & Evolution U. of Chicago, USA =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --_b45c7ec8447d853375efa3a37d34fcd53 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =0A=0A=0A=0A=0A > Message: 2=0D
=0A > Date: Wed, 09 Apr 2003 09:32:01 +0200=0D
=0A > From: Charlie Clark charlie@begeistert.org>To: tutor@python.org, Henry Steigerwaldt hsteiger@comcast.net>=0D
=0A > Subject: [Tutor] Re: Tutor Testing for response from a Web site=0D
=0A=0D
=0A [...]=0D
=0A=0D
=0A > correct. Does anybody know why Microsoft / Seattle Computer Products=0D
=0A > decided to use "" instead of "/" as a path separator in QDOS? Was it like=0D
=0A > this in CP/M?=0D
=0A =20=0D
=0A [...]=0D
=0A =20=0D
=0A > Charlie=0D
=0A =20=0D
=0ATo my understanding, the '\' was introduced by Bill Gates and his team when they wanna make an OS that's different from IBM's. IBM used '/', so they created this '\' just to be make it look different. It has been there since the DOS age (or even earlier).
=0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
~~~~~ be shapeless ~~~~~

Runsun Pan, PhD
Dept. of Ecology & Evolution
U. of Chicago, USA
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=0A=0A --_b45c7ec8447d853375efa3a37d34fcd53-- From pan" This is a multi-part message in MIME format. --_b45c7ec8447d853375efa3a37d34fcd53 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable > Message: 2 > Date: Wed, 09 Apr 2003 09:32:01 +0200 > From: Charlie Clark charlie@begeistert.org>To: tutor@python.org, Henry Steigerwaldt hsteiger@comcast.net> > Subject: [Tutor] Re: Tutor Testing for response from a Web site [...] > correct. Does anybody know why Microsoft / Seattle Computer Products > decided to use "" instead of "/" as a path separator in QDOS? Was it like > this in CP/M? =20 [...] =20 > Charlie =20 To my understanding, the '\' was introduced by Bill Gates and his team when they wanna make an OS that's different from IBM's. IBM used '/', so they created this '\' just to be make it look different. It has been there since the DOS age (or even earlier).=0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D ~~~~~ be shapeless ~~~~~ Runsun Pan, PhD Dept. of Ecology & Evolution U. of Chicago, USA =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --_b45c7ec8447d853375efa3a37d34fcd53 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =0A=0A=0A=0A=0A > Message: 2=0D
=0A > Date: Wed, 09 Apr 2003 09:32:01 +0200=0D
=0A > From: Charlie Clark charlie@begeistert.org>To: tutor@python.org, Henry Steigerwaldt hsteiger@comcast.net>=0D
=0A > Subject: [Tutor] Re: Tutor Testing for response from a Web site=0D
=0A=0D
=0A [...]=0D
=0A=0D
=0A > correct. Does anybody know why Microsoft / Seattle Computer Products=0D
=0A > decided to use "" instead of "/" as a path separator in QDOS? Was it like=0D
=0A > this in CP/M?=0D
=0A =20=0D
=0A [...]=0D
=0A =20=0D
=0A > Charlie=0D
=0A =20=0D
=0ATo my understanding, the '\' was introduced by Bill Gates and his team when they wanna make an OS that's different from IBM's. IBM used '/', so they created this '\' just to be make it look different. It has been there since the DOS age (or even earlier).
=0A=0A=0A=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D
~~~~~ be shapeless ~~~~~

Runsun Pan, PhD
Dept. of Ecology & Evolution
U. of Chicago, USA
=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=0A=0A --_b45c7ec8447d853375efa3a37d34fcd53-- From brian@dungeoncrawl.org Tue Apr 15 02:46:02 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Tue Apr 15 01:46:02 2003 Subject: [Tutor] Standard way to append to a list? Message-ID: <5.2.0.9.0.20030415013832.023388a0@localhost> Say I have: list = [1, 2, 3] What is the standard way to add 4 to the end of the list? I know: list = list + [4] would work. What else is there? -- reaching out to embrace whatever may come From Simon.Wittber@perth.maptek.com.au Tue Apr 15 03:03:01 2003 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Tue Apr 15 02:03:01 2003 Subject: [Tutor] Standard way to append to a list? Message-ID: <10F0E58C0018054484E329DC494C4D7F9490CC@mexper1> >What is the standard way to add 4 to the end of the list? I know: > >list =3D list + [4] > >would work. What else is there? I've always used: list.append(value) From steve_weaver@peoplesoft.com Tue Apr 15 03:37:03 2003 From: steve_weaver@peoplesoft.com (steve_weaver@peoplesoft.com) Date: Tue Apr 15 02:37:03 2003 Subject: [Tutor] Out of Office Response: Tutor digest, Vol 1 #2370 - 12 msgs Message-ID: I will be out of the office starting Monday, April 14, 2003 and will not return until Thursday, April 17, 2003. I will respond to your message when I return. From nano@intermatik.co.id Tue Apr 15 07:59:01 2003 From: nano@intermatik.co.id (nano@intermatik.co.id) Date: Tue Apr 15 06:59:01 2003 Subject: [Tutor] data sharing Message-ID: <1039.202.158.29.104.1050404305.squirrel@intermatik.co.id> Hi pythonmania, Thanks for many advices you've given in my previous problem [list comprehension]. Now, StraightToProblem: I have an object "Class_A" that get a big data from MySQL to do search/sort etc. How can I share that data, so that if other object "Class_B", "Class_C" need the same data, they can use it, without have to call it from MySQL. Best Regards, Nano' From pan@uchicago.edu Tue Apr 15 08:14:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue Apr 15 07:14:02 2003 Subject: [Tutor] Re: extracting html source In-Reply-To: <20030415054602.4108.77111.Mailman@mail.python.org> References: <20030415054602.4108.77111.Mailman@mail.python.org> Message-ID: <1050405115.3e9be8fbc0710@webmail-b.uchicago.edu> Hi all, My apology to this group for those redundant and unreadable emails I sent in the previous Tutor digest, Vol 1 #2361. It's due to a webmail client of a webhost company called icdsoft. They have checkboxes for [ ] don't use MIME format [ ] don't use HTML format I thought I could send a pure ASCII email by unchecking both of them but obviously I was wrong. I have no idea why the emails I sent out from their webmail only cause problems when sending to this list. But I've given up using their webmail client. Below is a readable reply (hope so) to Wayne's question: Hi Wayne, Try this: a= 'aaa bbb ccc' >>> import re >>> re.findall('.*', htmlSource) # <=3D=3D [A] [' bbb '] =20 >>> re.findall('(.*)', htmlSource) # <=3D=3D [B] [' bbb '] Note the difference between [A] and [B] If there's a '\n' in between and : >>> b =3D '''aaa bb .. bbb ccc''' >>> b 'aaa bb\n bbb ccc' >>> re.findall(r'[\w\s]*',b) [' bb\n bbb '] >>> re.findall(r'([\w\s]*)',b) [' bb\n bbb '] More: >>> c=3D''' aaa bbb1=20 .. bbb2 .. bbb3 .. ''' >>> c ' aaa bbb1 \nbbb2\nbbb3\n' >>> re.findall(r'([\w\s]*)',c) [' bbb1 \nbbb2\nbbb3\n'] hth pan From krier115@student.liu.se Tue Apr 15 08:23:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 15 07:23:02 2003 Subject: [Tutor] data sharing In-Reply-To: <1039.202.158.29.104.1050404305.squirrel@intermatik.co.id> References: <1039.202.158.29.104.1050404305.squirrel@intermatik.co.id> Message-ID: <20030415112230.GA10506@n14.ryd.student.liu.se> On Tue, Apr 15, 2003 at 05:58:25PM +0700, nano@intermatik.co.id wrote: > Hi pythonmania, > > Thanks for many advices you've given in my previous problem [list > comprehension]. > > Now, StraightToProblem: > I have an object "Class_A" that get a big data from MySQL to do > search/sort etc. How can I share that data, so that if other object > "Class_B", "Class_C" need the same data, they can use it, without have to > call it from MySQL. If I understand you right, you want to give the data to the other objects, but you just don't want to touch MySQL again, is that right? So say that we have you first class here >>> class Class_A: ... def getBigText(self): ... self.bigText = getThingsFromMySQL() If you then add methods like this in your other classes: >>> class Class_B: ... def giveText(self, text): ... self.text = text and the same for Class_C You could to something like this in your main program: a = Class_A() b = Class_B() c = Class_C() a.getBigText() b.giveText(a.bigText) c.giveText(a.bigText) now the objects b and c of Class_A and Class_B respectively will have an own copy of the text extracted from MySQL. This text they will have in their attribute text. So we have now that a.bigText == b.text == c.text. Keep in mind that they now have different copies of the text, so if you update the text the a object it will not get updated in the other objects. As I understood it this was what you were after, but of course I could be mistaken :) Hope it helps! Regards, Kristoffer > > Best Regards, > > Nano' > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From krier115@student.liu.se Tue Apr 15 08:44:01 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 15 07:44:01 2003 Subject: [Tutor] data sharing In-Reply-To: <20030415112230.GA10506@n14.ryd.student.liu.se> References: <1039.202.158.29.104.1050404305.squirrel@intermatik.co.id> <20030415112230.GA10506@n14.ryd.student.liu.se> Message-ID: <20030415113959.GA12024@n14.ryd.student.liu.se> > Keep in mind that they now have different copies of the text, so if you > update the text the a object it will not get updated in the other > objects. As I understood it this was what you were after, but of course > I could be mistaken :) Just have to add a bit to this. I blatantly assumed that you data was a large string, in which case the changed wouldn't show at the other objects. However, if you have a mutable object (lika a list), the changed _will_ show at the other objects too. A thing to certainly keep in mind. Sorry for the confusion. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From rick@niof.net Tue Apr 15 08:57:01 2003 From: rick@niof.net (Rick Pasotto) Date: Tue Apr 15 07:57:01 2003 Subject: [Tutor] Standard way to append to a list? In-Reply-To: <5.2.0.9.0.20030415013832.023388a0@localhost> References: <5.2.0.9.0.20030415013832.023388a0@localhost> Message-ID: <20030415115606.GE9580@tc.telocity.com> On Tue, Apr 15, 2003 at 01:44:38AM -0400, Brian Christopher Robinson wrote: > Say I have: > > list = [1, 2, 3] > > What is the standard way to add 4 to the end of the list? I know: > > list = list + [4] > > would work. What else is there? That is not appending. What you are doing there is *merging* two lists. -- "Damn all expurgated books; the dirtiest book of all is the expurgated book." -- Walt Whitman Rick Pasotto rick@niof.net http://www.niof.net From Blake.Garretson@dana.com Tue Apr 15 09:30:02 2003 From: Blake.Garretson@dana.com (Blake.Garretson@dana.com) Date: Tue Apr 15 08:30:02 2003 Subject: [Tutor] Standard way to append to a list? Message-ID: Brian Christopher Robinson writes: >Say I have: >list = [1, 2, 3] >What is the standard way to add 4 to the end of the list? I know: >list = list + [4] >would work. What else is there? Try this: List = [1, 2, 3] List.append(4) Also handy for adding more than one item: List.extend([4,5,6]) By the way, I know this is just an example, but I would avoid using the word "list" since it is a built-in. -Blake Garretson From a_abdi406@yahoo.com Tue Apr 15 11:43:01 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue Apr 15 10:43:01 2003 Subject: [Tutor] about a program Message-ID: <20030415143710.69303.qmail@web14507.mail.yahoo.com> --0-549502866-1050417430=:67447 Content-Type: multipart/alternative; boundary="0-1818477357-1050417430=:67447" --0-1818477357-1050417430=:67447 Content-Type: text/plain; charset=us-ascii hi evryone, I am trying to implemnent a program that searches keywords stored in sveral documents,by first indexing and computing weghting for each document by calculating frequency of each keyword(Term Frequency(TF))and Inverse document frequency(IDF). IDF = log( Number of elements in the collection / frequency of each element) weighting = IDF * TF. I have already setup the indexing by using fileinut() function which indexes the word and the files it occurs like this: 55 comments [('File-03.txt', 4)] 56 speech [('tmp.txt', 5)] 57 frequencies [('tmp.txt', 5)] 58 new [('tmp.txt', 5)] 59 acknowledgments [('File-03.txt', 3)] Can any one give me any idea how I can incoorporate the weighting ? because this is the design that I have chosen and want make it work I really gt stuck....... any suggestions would be appreciated... I have also attached the code thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1818477357-1050417430=:67447 Content-Type: text/html; charset=us-ascii

hi evryone,

I am trying to implemnent a program that searches keywords stored in sveral documents,by first indexing and computing weghting for each document by calculating frequency of each keyword(Term Frequency(TF))and Inverse document

frequency(IDF). IDF =

log( Number of elements in the collection / frequency of each element)

weighting = IDF * TF.

I have already setup the indexing by using fileinut() function which indexes the word and the files it occurs like this:

55 comments [('File-03.txt', 4)]

56 speech [('tmp.txt', 5)]

57 frequencies [('tmp.txt', 5)]

58 new [('tmp.txt', 5)]

59 acknowledgments [('File-03.txt', 3)]

Can any one give me any idea how I can incoorporate the weighting ? because

this is the design that I have chosen and want make it work

I really gt stuck.......

any suggestions would be appreciated... I have also attached the code

thanks in advance



Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1818477357-1050417430=:67447-- --0-549502866-1050417430=:67447 Content-Type: text/plain; name="genIndex.py" Content-Description: genIndex.py Content-Disposition: inline; filename="genIndex.py" import glob, getopt import fileinput,re,shelve,linecache,sys #from TextSplitter import TextSplitter #aword = re.compile(r'\b[\w-]+\b') aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') #using xml as well.----\b[\w-]+\b index={} # Generate an index in file indexFileName def genIndex(indexFileName, extension): """ this function takes a file without the extension and returns the the tokens in the file indexed. it also returns the word, the file found and the line where the word was found """ stop_list = ['from','to','that','by','with','on','the', 'on','a','and','these','of','or','for','can', 'it','is','this','in','an','you', 'your', 'yours','our','his','will','some','are','et', 'we','most','be','those','there','such','other', 'such','like'] fname='*.'+extension #print for testing purposes print "----------------------------------------------------" print fname #print for testing for line in fileinput.input(glob.glob(fname)): #get the filename and location where the word was found(lineNumber) location = fileinput.filename(), fileinput.filelineno() #find all words that are relevante for word in aword.findall(line.lower()): if word[0] != '<': #append the words found in dictionary with file name and location index.setdefault(word,[]).append(location) # open a shelve file and store the result of indexing shelf = shelve.open(indexFileName,'n') count_words = 0 for word in index: #eliminate all stoplist words if word not in stop_list: shelf[word] = index[word] count_words += 1 # used for computing term frequency #print for testing purposes print count_words ,word , "\t" , shelf[word] print "total words", count_words print "---------------------------------------------" shelf.close() #-------------------------------------------------------------- if __name__ == '__main__': import sys # print "hello" for arg in sys.argv[1:]: genIndex(arg, 'txt') --0-549502866-1050417430=:67447-- From david@vdr.to Tue Apr 15 12:23:02 2003 From: david@vdr.to (David Rushforth) Date: Tue Apr 15 11:23:02 2003 Subject: [Tutor] Shadow Passwords Message-ID: <1033.213.201.175.106.1050405527.squirrel@mail.vdr.to> Hi I am trying to create function to create users and passwords for a Linux box using shadow passwords. All goes well except that the passwords are store in plain text. Is there a modules I can use to encrypt the password. Thanx From krier115@student.liu.se Tue Apr 15 12:33:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 15 11:33:02 2003 Subject: [Tutor] Shadow Passwords In-Reply-To: <1033.213.201.175.106.1050405527.squirrel@mail.vdr.to> References: <1033.213.201.175.106.1050405527.squirrel@mail.vdr.to> Message-ID: <20030415153225.GA21779@n14.ryd.student.liu.se> On Tue, Apr 15, 2003 at 04:18:47PM +0500, David Rushforth wrote: > Hi > > I am trying to create function to create users and passwords for a Linux > box using shadow passwords. All goes well except that the passwords are > store in plain text. Is there a modules I can use to encrypt the password. > There is a module called crypt in the standard library. This module contains a function also called crypt which does exactly what you want. You can read more about it in the Python library reference and in crypt(3). Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From tlo@aw.sgi.com Tue Apr 15 13:30:04 2003 From: tlo@aw.sgi.com (Terence Lo) Date: Tue Apr 15 12:30:04 2003 Subject: [Tutor] shutil.rmtree on win32 with read-only files Message-ID: <007101c3036c$81895c00$ca411dc6@ms.aliaswavefront.com> hi there, i was wondering if anyone else has come across this problem. i'm trying to write a customized version of rmtree which can handle win32 read-only files. I've pondered the idea of doing something similar to: os.system('attrib -R ' + path + '/* /S') but unfortunately, the win32/dos attrib command does not contain any recursive directory replacement. or at least i couldn't find a switch that does this. so my question is, is there a quick way of handling or chaning the permissions of read-only files on windows for python or will i have to settle for a recursive function that will do this for me. Any help in this matter would be greatly appreciated. Cheers, Terence From steve_weaver@peoplesoft.com Tue Apr 15 14:40:02 2003 From: steve_weaver@peoplesoft.com (steve_weaver@peoplesoft.com) Date: Tue Apr 15 13:40:02 2003 Subject: [Tutor] Out of Office Response: Tutor digest, Vol 1 #2371 - 11 msgs Message-ID: I will be out of the office starting Monday, April 14, 2003 and will not return until Thursday, April 17, 2003. I will respond to your message when I return. From dyoo@hkn.eecs.berkeley.edu Tue Apr 15 15:32:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 15 14:32:04 2003 Subject: [Tutor] Out of Office Response: Tutor digest, Vol 1 #2371 - 11 msgs [admin message] In-Reply-To: Message-ID: On Tue, 15 Apr 2003 steve_weaver@peoplesoft.com wrote: > I will be out of the office starting Monday, April 14, 2003 and will not > return until Thursday, April 17, 2003. Hello, I've been a little lax about my administrative responsibilities! My apologies for not catching this sooner. I'll set Steve's settings to not deliver Tutor digests to him temporarily. Steve, when you get back from vacation, you can reenable your settings by modifying your Tutor mail options from: http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Tue Apr 15 15:48:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 15 14:48:13 2003 Subject: [Tutor] Canvas Widget In-Reply-To: <3E9B10E5.1030202@brturbo.com> Message-ID: On Mon, 14 Apr 2003, Diego Prestes wrote: > Im trying to use canvas in tkinter but when I put the widget it > always stay in the top of the program. I try to make a frame with the > side=TOP to put the buttons of the toolbar but it stay in bottom. > > Someone know if I can change the side of the canvas? Hi Diego, Tkinter's default "packing" layout system is a little bit weird at first, so let's go through a small example; it might help clear things up. If you want to make something like: +-----------------+---------+ | | | | | Button1 | | |---------+ | Canvas | | | | Button2 | | |---------+ | | | | | Button3 | +-----------------+---------+ To construct something like this, we can think of it as two pieces, a canvas on the left hand side, +-----------------+ | | | | | Canvas | | | | | | | | | | | +-----------------+ plus a frame of buttons on the right hand side: +---------+ | | | Button1 | |---------+ | | | Button2 | |---------+ | | | Button3 | +---------+ Here's some example Tkinter code that constructs a window like this: ### >>> import Tkinter >>> root = Tkinter.Tk() >>> canvas = Tkinter.Canvas(root) >>> canvas.pack(side=Tkinter.LEFT) >>> button_frame = Tkinter.Frame(root) >>> button_frame.pack(side=Tkinter.RIGHT) >>> b1, b2, b3 = (Tkinter.Button(text="Button1"), ... Tkinter.Button(text="Button2"), ... Tkinter.Button(text="Button3")) >>> b1.pack(side=Tkinter.TOP) >>> b2.pack(side=Tkinter.TOP) >>> b3.pack(side=Tkinter.TOP) ### The order of packing can matter: you may want to experiment with your interactive interpreter to see what happens if we pack the button_frame to the LEFT first, and then the canvas. > and other question. Someone know how can I create a rectangle, for > example, using the mouse? You may want to look at Fredrik's tutorial on Tkinter: http://www.pythonware.com/library/tkinter/introduction/ In particular, if we look at the Canvas documentation: http://www.pythonware.com/library/tkinter/introduction/x2102-methods.htm we can see a method called "create_rectangle" that takes a "bounding box". Here's an example call to create_rectangle: ### >>> canvas.create_rectangle(((10, 10), (20, 20))) 1 ### A gloriously puny rectangle should show up on the upper left hand corner of the canvas. *grin* To do drawing with a mouse, you may need to read a little bit about "event handling". Here's a link to the Events section of Tkinter tutorial: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm Please feel free to ask questions on Tutor; we'll be happy to help clear up the confusing parts. Good luck! From alan.gauld@freenet.co.uk Tue Apr 15 15:56:02 2003 From: alan.gauld@freenet.co.uk (Alan Gauld) Date: Tue Apr 15 14:56:02 2003 Subject: [Tutor] RE: Why MS chose \ References: <20030415160006.3157.24297.Mailman@mail.python.org> Message-ID: <000501c30380$6f0176d0$6401a8c0@xp> Having digest problems so answering this indirectly... My understanding of the reason for the choice of \ was that / was already in use. MS DOS(and its precursor) were originally cheap clones of CP/M and CP/M programs conventionally used / for command line options. (CP/M didn't have paths as we know them...) Thus when MS had to introduce paths(DOS 2?) they chose the opposite form of slash. I just checked and certainly the CP/M assembler and MBASIC interpreters both used '/' for commandline options as did the original CP/M wordstar. So it sounds reasonable. Alan G From rhseabrook@aacc.edu Tue Apr 15 16:03:02 2003 From: rhseabrook@aacc.edu (Seabrook, Richard) Date: Tue Apr 15 15:03:02 2003 Subject: [Tutor] RE: Why MS chose \ Message-ID: <74DAD2F23F03F7438D9BE3436C6846F77DE40B@AACC-MAIL.aacc.cc.md.us> -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk]=20 Sent: Tuesday, April 15, 2003 2:54 PM To: tutor@python.org Subject: [Tutor] RE: Why MS chose \ Having digest problems so answering this indirectly... My understanding of the reason for the choice of \ was=20 that / was already in use. MS DOS(and its precursor) were=20 originally cheap clones of CP/M and CP/M programs=20 conventionally used / for command line options. (CP/M didn't have paths as we know them...) [Seabrook, Richard] Seems to me I remember using double slashes // in IBM OS360 JCL back in the 60s but I don't know if Gates & Co. go back that far. Before that it was pretty much * in IBSYS, $ in IBJOB and @ in UNIVAC systems if I recall correctly. Dick S. From Nova Sano S. Surbakti" References: <20030415160006.3157.24297.Mailman@mail.python.org> Message-ID: <1442813539.20030416093245@intermatik.co.id> trpo> If I understand you right, you want to give the data to the other trpo> objects, but you just don't want to touch MySQL again, is that right? trpo> So say that we have you first class here >>>> class Class_A: trpo> ... def getBigText(self): trpo> ... self.bigText = getThingsFromMySQL() trpo> If you then add methods like this in your other classes: >>>> class Class_B: trpo> ... def giveText(self, text): trpo> ... self.text = text trpo> and the same for Class_C trpo> You could to something like this in your main program: trpo> a = Class_A() trpo> b = Class_B() trpo> c = Class_C() trpo> a.getBigText() trpo> b.giveText(a.bigText) trpo> c.giveText(a.bigText) trpo> now the objects b and c of Class_A and Class_B respectively will have an trpo> own copy of the text extracted from MySQL. This text they will have in trpo> their attribute text. So we have now that a.bigText == b.text == c.text. trpo> Keep in mind that they now have different copies of the text, so if you trpo> update the text the a object it will not get updated in the other trpo> objects. As I understood it this was what you were after, but of course trpo> I could be mistaken :) trpo> Hope it helps! trpo> Regards, trpo> Kristoffer Hi all, Thanks Kristoffer for your advice. Actually, those different classes are not executed at the same time. So it will be called any time, depend on the request by the user. In this case a user want to search for a certain thing from an Inventory table, from a SearchForm. After that or at the same time another user want to get another thing from same table. What I think I want to do is: Load data from table then keep it in memory. Each time the SearchForm want to get the data, it don't have to touch MySQL again, but search the data from memory? What I'm doing right now is get the data from MySQL each time the SearchForm executed, and it seems too slow. Thanks! Nano' From francois.granger@free.fr Wed Apr 16 03:46:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Wed Apr 16 02:46:02 2003 Subject: [Tutor] shutil.rmtree on win32 with read-only files In-Reply-To: <007101c3036c$81895c00$ca411dc6@ms.aliaswavefront.com> References: <007101c3036c$81895c00$ca411dc6@ms.aliaswavefront.com> Message-ID: At 12:31 -0400 15/04/2003, in message [Tutor] shutil.rmtree on win32 with read-only files, Terence Lo wrote: >hi there, > >i was wondering if anyone else has come across this problem. i'm trying to >write a customized version of rmtree which can handle win32 read-only files. > >I've pondered the idea of doing something similar to: >os.system('attrib -R ' + path + '/* /S') > >but unfortunately, the win32/dos attrib command does not contain any >recursive directory replacement. or at least i couldn't find a switch that >does this. Have a look to os.path.walk() in the Python documentation -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From krier115@student.liu.se Wed Apr 16 05:10:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Wed Apr 16 04:10:02 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2371 - 11 msgs In-Reply-To: <1442813539.20030416093245@intermatik.co.id> References: <20030415160006.3157.24297.Mailman@mail.python.org> <1442813539.20030416093245@intermatik.co.id> Message-ID: <20030416080757.GA24700@n14.ryd.student.liu.se> On Wed, Apr 16, 2003 at 09:32:45AM +0700, Nova Sano S. Surbakti wrote: > What I think I want to do is: > Load data from table then keep it in memory. Each time the SearchForm > want to get the data, it don't have to touch MySQL again, but search > the data from memory? > > What I'm doing right now is get the data from MySQL each time the > SearchForm executed, and it seems too slow. > If I catch you right, your program is executed once for every search made, is that so? In that case there really isn't any way for you to share the data manually between the different executions. However, I do not think it should be a problem. What will happen is that after you first catch the data from mysql, your computer will buffer that data in memory, as long as it has the space to do so. So subsequent searches will have to touch MySQL again, but the request will not take close to as long as the first one because the data is cached (assuming there isn't a long time between your searches so your computer has decided to replace the data in the cache with more recent things). I would say that it is totally feasible to do the request from the database every time, after all, that's what databases are for :). If you really really want to share the data in an object between searches, it gets a bit complicated. You need to have a process running all the time then, because you can't have control over the memory otherwise. Then when the search is made your newly started process could communicate with the always running one and get the data that way. But I don't even think this will be faster than reading from MySQL all the time, because that data will be in memory too. And if it isn't, your OS has chosen to discard it to get something more important in, it probably had a good reason to do so (that is your program haven't been ran in a while and the memory could be used for better things). Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From dana@pixelenvy.ca Wed Apr 16 10:56:02 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Wed Apr 16 09:56:02 2003 Subject: [Tutor] Counting # of dictionary keys In-Reply-To: Message-ID: Hi everyone, I'm curious about the following: >>> len(your_dict) What is the complexity of this operation? Does it run in time O(1) or O(n)? If it doesn't, is there a O(1) method for determining the number of key/value pairs in a dictionary? Dana dana@pixelenvy.ca From magnus@thinkware.se Wed Apr 16 11:40:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 16 10:40:03 2003 Subject: [Tutor] Perl vs. Python's way of handling references. In-Reply-To: <20030412160005.4782.34032.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030416152240.00be4090@www.thinkware.se> Hi Scott, and welcome to Pythondom. I suppose you will soon figure out which language of Perl and Python you prefer when it comes to handling different data structures. Direct comparisions are always difficult, since different tool lead to different approaches. Using an approach which is optimal in one language, might be far from optimal in another. My subjective opinions, based on personal experience, follows... At 11 Apr 2003 16:13:36 -0700, Scott Chapman wrote: >I wasn't trying to show the list anything relating to Perl vs. Python. I was >demonstrating how Perl does references and how Python does them. The Perl >advocate on the Perl Tutorial list was the fellow I was quoting on the >original post. He said that you must use vars() in python to do the trick >like you do in Perl with it's reference syntax. He said that this is a >drawback to Python when you get into deeply nested structures. This reminds me of a friend who was terribly angry over a Macintosh computer, since no menu items or manuals showed him how to format a diskette. It was so easy in DOS. You just type "FORMAT A:", insert the diskette, press enter and wait. Here, he didn't have a clue. Do you have to buy preformatted Mac diskettes, or what? Finally, he called a friend, who just told him to insert the diskette in the computer. A dialog appeared at once, asking him if he wanted to format the diskette. He would never have had any trouble with this if he had been a complete computer newbie (or used to Macs). It was his "DOS conditioning" that prevented him from trying the obvious. In Python the obvious usually works. In Perl you need to know an obscure way, and you probably love that or leave it. This Perl guy is describing a non-issue in Python. To use Python effectively, you need to understand that variables are references to objects, as someone pointed out before. It's also important to understand the difference between mutable and immutable objects. But data structures and dereferencing problems is simply a non-issue in Python. You rarely hear people ask about nesting lists in lists etc in Python, since it's trivial. It just works as you would expect, unless you have been "exposed" to something like Perl, and become "damaged" by that. It's just like my friend who never inserted the diskette since he assumed that it must be more difficult than that. The one related issue that does appear in Python is that people put the same, mutable object in several places, and then get surprised when changing it in one place changes it everywhere. Exactly the same thing can happen in Perl, but there it's only one of many, many troubles on the road to a working data structure. Nested data structures is a kludge in Perl. Initially, you couldn't create nested structures at all, so eval and typeglob had to be used to fake it. The use of variable names as strings comes from this stone age practice. You shouldn't have to use that. Today, there is support for nested structures in Perl, but it's so difficult to deal with that it requires more than 30 pages of explanation in "Programming Perl" (2nd ed). That chapter (ch 4) is full of descriptions of common mistakes and how differently you have to do things in different cases. The text is much more about how to handle the syntax, than about working with data structures. This is a clear indication of bad design in my opinion. I never managed to learn it in Perl. In python I never understood that it was an issue at all. It simply worked. Just a simple thing like the following python: >>> a = [1, 2, 3] >>> b = ('x', a) >>> c = [a, b] >>> print c[1][1][2] 3 You don't need to be a rocket scientist to write that. As a little test, I tried to write the same thing in Perl, but I gave up after a few minutes. It's just to weird for me, with ->, $, $$, @, () vs [], \ etc. Perl is simply too full of legacy from old unix tools to be close to consistent. Maybe I'm terribly stupid, but it's as if my IQ drop 30-40% when I try to solve things in Perl instead of Python. Still, I was a Perl programmer before I was a Python programmer. Sure, you can become a master of Perl with practice, but I rather spend time wrestling with other problems than pure language syntax. It's not by chance that there are "obfuscated Perl contests" but no "obfuscated Python contests". Python programmers don't want their code to be difficult to understand. That's why they stick to Python. You should also think twice about constructing deeply nested data structures. If you type "import this" in a recent Python interpreter, you will get some Python wisdom for free. Note the fifth row: "Flat is better than nested." :) A few quotes: http://mail.python.org/pipermail/python-list/2002-November/129160.html : >I talked my other colleagues into using {Python} for our CS 1 >course this fall. ... In the past I would be swamped during office >hours with students wanting help deciphering C++ compiler errors. >This semester almost nobody has stopped by for syntax issues. In my opinion, Perl is more difficult than C++ in syntax. A couple from http://c2.com/cgi/wiki?PythonDiscussion : >"Python is an excellent language for learning object orientation. >(It also happens to be my favorite OO scripting language.) ... All >objects in Python are implemented as hash tables, unlike in Perl, in >which you have to choose a representation (or looking at it more >optimistically, where you are free to choose the optimal representation)." >Sriram Srinivasan, >AdvancedPerlProgramming, page 120. >I found it to be one of the most intuitive languages I've ever >worked with -- you can often just guess the syntax and it works. >Its other great strength is its scalability; it makes sense from >command-line interaction all the way up to large-scale modular programs. -- Magnus Lycka, magnus@thinkware.se Thinkware AB, www.thinkware.se From bgailer@alum.rpi.edu Wed Apr 16 13:12:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 16 12:12:02 2003 Subject: [Tutor] Counting # of dictionary keys In-Reply-To: References: Message-ID: <5.2.0.9.0.20030416100620.02fcfc88@66.28.54.253> --=======3B0B1409======= Content-Type: text/plain; x-avg-checked=avg-ok-7FF3611; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 08:54 AM 4/16/2003 -0500, Dana Larose wrote: > >>> len(your_dict) >What is the complexity of this operation? Does it run in time O(1) or >O(n)? This question is best answered by someone who knows the innards of the interpreter. I ran a test, created a dict d with almost 10,000,000 entries. Took several minutes. Began to exceed RAM. len(d) took no observable time. So I guess O(1) is the answer. >If it doesn't, is there a O(1) method for determining the number of >key/value pairs in a dictionary? You could extend dict by creating a class with dict as the superclass, and provide your own __len__ method to return a count. You'd also need __setitem__ and __delitem__ methods in which you'd inc/dec/rement a class property counter. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======3B0B1409======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-7FF3611 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======3B0B1409=======-- From tim.one@comcast.net Wed Apr 16 13:54:07 2003 From: tim.one@comcast.net (Tim Peters) Date: Wed Apr 16 12:54:07 2003 Subject: [Tutor] Counting # of dictionary keys In-Reply-To: Message-ID: [Dana Larose] > I'm curious about the following: > > >>> len(your_dict) > > What is the complexity of this operation? Does it run in time O(1) or > O(n)? This is the implementation today (in dictobject.c): static int dict_length(dictobject *mp) { return mp->ma_used; } So it's constant-time today, and has been in the C implementation of Python since the beginning. The language reference manual doesn't guarantee this, but it's unlikely to change. From lobow@brturbo.com Wed Apr 16 15:30:02 2003 From: lobow@brturbo.com (Diego Prestes) Date: Wed Apr 16 14:30:02 2003 Subject: [Tutor] wxPython tutorial Message-ID: <3E9DA10D.80105@brturbo.com> Someone know where I can found a tutorial for wxPython? Diego From krier115@student.liu.se Wed Apr 16 15:39:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Wed Apr 16 14:39:02 2003 Subject: [Tutor] wxPython tutorial In-Reply-To: <3E9DA10D.80105@brturbo.com> References: <3E9DA10D.80105@brturbo.com> Message-ID: <20030416183817.GA2307@n14.ryd.student.liu.se> On Wed, Apr 16, 2003 at 03:29:33PM -0300, Diego Prestes wrote: > Someone know where I can found a tutorial for wxPython? > > Diego http://www.wxpython.org/tutorial.php Please try searching the web first next time, google provided me with this one extremely easy. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From magnus@thinkware.se Wed Apr 16 20:02:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 16 19:02:02 2003 Subject: [Tutor] Standard way to append to a list? In-Reply-To: <20030415054602.4108.77111.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030417003528.00beae68@www.thinkware.se> At Tue, 15 Apr 2003 01:44:38 -0400, Brian Christopher Robinson wrote: >Say I have: > >list = [1, 2, 3] > >What is the standard way to add 4 to the end of the list? I know: > >list = list + [4] > >would work. What else is there? You said it yourself in the subject line. Please read http://www.python.org/doc/current/lib/typesseq-mutable.html etc. First of all, don't use list as a variable name. It's allowed, but bad practice to use builtin type names as varible names. See below: >>> l = list((1,32,5)) >>> l [1, 32, 5] >>> list = [1,2,3] >>> l = list((1,32,5)) Traceback (most recent call last): File "", line 1, in ? TypeError: 'list' object is not callable :( Since you have reassigned the name list to refer to a particular list object. instead of the list type, you cqan no longer cast tuples to lists... (Well, you can type "__builtins__.list((1,32,5))", but that seems a bit awkward...) Secondly, using "l = l + [4]" or the shorter form "l += [4]", you are doing the following: 1. To start with, you have a list object containing [1,2,3] 2. Then you create a new list object containing [4]. 3. With your assignment you create a new list object, and place the sum of the two lists, i.e. [1,2,3,4] in that. 4. As you rebind the variable name "l" from the list containing [1,2,3] to the one containing [1,2,3,4], you will reduce the reference count on the list containing [1,2,3]. If no other variables etc references that list, it will be garbage collected now (or perhaps a little later if you are running Jython.) 5. The list containing [4] will also be garbage collected as soon as the assignment is done. All this juggling with objects take space and time. Using "l.append(4)" you will just mutate the already existing list object, and append is very fast. Lets test it with the profiler: >>> import profile >>> def add(): ... l = [] ... for i in xrange(10000): ... l = l + [i] ... >>> profile.run('add()') 3 function calls in 4.799 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 4.664 4.664 4.664 4.664 :1(add) 1 0.002 0.002 4.666 4.666 :1(?) 1 0.133 0.133 4.799 4.799 profile:0(add()) 0 0.000 0.000 profile:0(profiler) >>> def add(): ... l = [] ... for i in xrange(10000): ... l.append(i) ... >>> profile.run('add()') 3 function calls in 0.023 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.022 0.022 0.022 0.022 :1(add) 1 0.001 0.001 0.023 0.023 :1(?) 1 0.000 0.000 0.023 0.023 profile:0(add()) 0 0.000 0.000 profile:0(profiler) It seems append is more than 200 times faster in this case. With a shorter list, I'm sure the difference will be smaller though. Adding (+) large lists is much slower than appending to large lists. >>> def add(): ... for i in xrange(1000): ... l = [] ... for j in range(10): ... l = l + [j] ... >>> profile.run('add()') 3 function calls in 0.041 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.040 0.040 0.040 0.040 :1(add) 1 0.000 0.000 0.040 0.040 :1(?) 1 0.000 0.000 0.041 0.041 profile:0(add()) 0 0.000 0.000 profile:0(profiler) >>> def add(): ... for i in xrange(1000): ... l = [] ... for j in range(10): ... l.append(j) ... >>> >>> profile.run('add()') 3 function calls in 0.025 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.025 0.025 0.025 0.025 :1(add) 1 0.000 0.000 0.025 0.025 :1(?) 1 0.000 0.000 0.025 0.025 profile:0(add()) 0 0.000 0.000 profile:0(profiler) Now "l = l + [j]" only takes 60% more time, but append is still a better choice. From revanna@mn.rr.com Wed Apr 16 21:57:01 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Wed Apr 16 20:57:01 2003 Subject: [Tutor] Standard way to append to a list? In-Reply-To: <5.2.1.1.0.20030417003528.00beae68@www.thinkware.se> References: <5.2.1.1.0.20030417003528.00beae68@www.thinkware.se> Message-ID: <200304161955.48455.revanna@mn.rr.com> On Wednesday 16 April 2003 18:01, Magnus Lyckå wrote: > At Tue, 15 Apr 2003 01:44:38 -0400, Brian Christopher Robinson wrote: > >Say I have: > > > >list = [1, 2, 3] > > > >What is the standard way to add 4 to the end of the list? I know: > > > >list = list + [4] > > > >would work. What else is there? > > You said it yourself in the subject line. Please read > http://www.python.org/doc/current/lib/typesseq-mutable.html > etc. > > First of all, don't use list as a variable name. It's > allowed, but bad practice to use builtin type names as > > varible names. > ... l.append(j) > Now "l = l + [j]" only takes 60% more time, but append is still a better > choice. One other thing to watch out for. The first time I tried to use append, I tried: >>> l=l.append(j) # Don't do this - really! When I tried to print l, it was now "None"! That's because append returns None. I didn't realize it wasn't just a fancy way of saying l=l+[j] and it took some discussion with my tutor to figure it out. Keep in mind that append directly modifies l, so you don't need to do any rebinding... Just my $.03 worth... Anna From dyoo@hkn.eecs.berkeley.edu Wed Apr 16 22:00:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 16 21:00:02 2003 Subject: [Tutor] Standard way to append to a list? ['+=' is in-place concatenation] In-Reply-To: <5.2.1.1.0.20030417003528.00beae68@www.thinkware.se> Message-ID: On Thu, 17 Apr 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > Secondly, using "l =3D l + [4]" or the shorter form "l +=3D [4]", you are > doing the following: > > 1. To start with, you have a list object containing [1,2,3] > 2. Then you create a new list object containing [4]. > 3. With your assignment you create a new list object, and > place the sum of the two lists, i.e. [1,2,3,4] in that. > 4. As you rebind the variable name "l" from the list > containing [1,2,3] to the one containing [1,2,3,4], you > will reduce the reference count on the list containing > [1,2,3]. If no other variables etc references that list, > it will be garbage collected now (or perhaps a little > later if you are running Jython.) > 5. The list containing [4] will also be garbage collected as > soon as the assignment is done. Hi Magnus, Clarification on the second form: the expression: l +=3D [4] is called an 'in-place concatenation', and for lists, this actually calls the extend() method! For those with a C bent, here's the relevant code from the Python source: /***/ static PyObject * list_inplace_concat(PyListObject *self, PyObject *other) { other =3D PySequence_Fast(other, "argument to +=3D must be iterable= "); if (!other) return NULL; if (listextend_internal(self, other) < 0) return NULL; Py_INCREF(self); return (PyObject *)self; } /***/ Wait a minute... I can't seem to prove this by overriding the extend() method! ### >>> class mylist(list): =2E.. def extend(self, other): =2E.. print "I'm extend()!" =2E.. list.extend(self, other) =2E.. >>> l =3D mylist([1, 2, 3]) >>> l +=3D [4] >>> l [1, 2, 3, 4] >>> l.extend([4]) I'm extend()! ### Weird! I'm using Python 2.2.1 here; can anyone confirm if this is happening with Python 2.2.2 or 2.3alpha? Does this look like a bug to anyone else? ... Checking SourceForge... nope, I don't see anything about this. Sorry for getting sidetracked... *grin* I'd better check that in my spare time. Anyway the 'in-place concatenation' statement, left_hand_side +=3D right_hand_size is not just syntactic sugar for left_hand_side =3D left_hand_side + right_hand_size Python often does take advantage of the fact that the left hand side is being mutated. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Apr 16 22:21:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 16 21:21:02 2003 Subject: [Tutor] Standard way to append to a list? ['+=' is in-place concatenation] In-Reply-To: Message-ID: On Wed, 16 Apr 2003, Danny Yoo wrote: > Wait a minute... I can't seem to prove this by overriding the extend() > method! > > ### > >>> class mylist(list): > ... def extend(self, other): > ... print "I'm extend()!" > ... list.extend(self, other) > ... > >>> l = mylist([1, 2, 3]) > >>> l += [4] > >>> l > [1, 2, 3, 4] > >>> l.extend([4]) > I'm extend()! > ### > > Weird! I'm using Python 2.2.1 here; can anyone confirm if this is > happening with Python 2.2.2 or 2.3alpha? Does this look like a bug to > anyone else? ... Checking SourceForge... nope, I don't see anything > about this. Hi everyone, Hmmm... I played around with this a little more. It does work if we override __iadd__ (in-place adding): ### >>> class mylist(list): ... def __iadd__(self, other): ... print "I'm __iadd__()" ... return list.__iadd__(self, other) ... >>> l = mylist([1, 2, 3]) >>> l += [4] I'm __iadd__() >>> l [1, 2, 3, 4] ### __iadd__ is briefly mentioned in the Python Standard Reference here: http://python.org/doc/current/ref/sequence-types.html So the system is not totally broken. What appears to be the issue is that __iadd__() for lists is hardcoded to use the primitive C function 'listextend_internal()'. I feel, though, that a list subclass should really check to see if the extend() function has been redefined when it's doing a '+=' operation, to maintain polymorphic behavior. Dunno how that will affect performance, though. In any case, I'll send a bug report to SourceForge later tonight and see how the implementors feel about this... *grin* From dyoo@hkn.eecs.berkeley.edu Wed Apr 16 22:38:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 16 21:38:02 2003 Subject: [Tutor] data sharing In-Reply-To: <1039.202.158.29.104.1050404305.squirrel@intermatik.co.id> Message-ID: On Tue, 15 Apr 2003 nano@intermatik.co.id wrote: > Hi pythonmania, > > Thanks for many advices you've given in my previous problem [list > comprehension]. > > Now, StraightToProblem: I have an object "Class_A" that get a big data > from MySQL to do search/sort etc. How can I share that data, so that if > other object "Class_B", "Class_C" need the same data, they can use it, > without have to call it from MySQL. Hi Nano, A tangent question: just to make sure, when you say "big data", do you mean that the string in your database is huge, or do you mean that the table itself has many rows that make searching for a row very slow? If it's the latter, then you may want to check that your table is "indexed": http://www.mysql.com/doc/en/MySQL_indexes.html If your tables are not indexed, adding an appropriate column index may speed up your object construction dramatically. In some cases, it may speed it so much that you may not need to worry so much about keeping search results in memory. Good luck to you! From scott_list@mischko.com Thu Apr 17 00:37:51 2003 From: scott_list@mischko.com (Scott Chapman) Date: Wed Apr 16 23:37:51 2003 Subject: [Tutor] HTML form pre-populating functionality or hints on building my own Message-ID: <200304161939.11337.scott_list@mischko.com> Hi! I'm wanting to find (or make) a module that will take a HTML file, locate the input-related form tags ( Message-ID: <5.2.0.9.0.20030416225430.00b14510@mail.earthlink.net> Hello, I am new to programming, learning through python, and starting to be productive. But I want to develop graphical application so I am trying to learn wxPython, which I find much more difficult, and with little documentation, especially since I don't know C++ and can't translate the extensive WxWindows docs to python. In any case. My specific problem... See the code below. Creates an MDI with a parent and a child. The parent holds a filemenu, and statusbar, and a toolbar. Unfortunately, the child window doesn't play nicely with the toolbar. What am I doing wrong? Help is appreciated! __________________________________________________________ from wxPython.wx import * from wxPython.grid import * from wxPython.lib.mixins.grid import wxGridAutoEditMixin import sys, os ID_ABOUT = 102 ID_HELP = 103 ID_EXIT = 104 ID_VIEW = 105 ID_OPEND = 107 ID_OPENS = 101 ID_SETUP = 108 ID_OUTPUT = 106 ID_TEST_BUTTON = 109 class DataGrid(wxGrid): def __init__(self, parent): wxGrid.__init__(self, parent, -1) self.wxPostion=(50,50) self.moveTo = None self.CreateGrid(25, 25) self.SetCellValue(6, 0, "123.34") attr = wxGridCellAttr() attr.SetTextColour(wxBLACK) attr.SetBackgroundColour(wxRED) attr.SetFont(wxFont(10, wxSWISS, wxNORMAL, wxBOLD)) self.SetColLabelAlignment(wxALIGN_LEFT, wxALIGN_BOTTOM) class MyParentFrame(wxMDIParentFrame): def __init__(self): wxMDIParentFrame.__init__(self, None, -1, "My App") self.CreateStatusBar() self.SetStatusText("This is the statusbar") tb = wxToolBar(self,-1) tb.AddControl(wxButton(tb, ID_TEST_BUTTON, "Button",wxDefaultPosition, wxDefaultSize)) tb.Realize() FileMenu = wxMenu() FileMenu.Append(ID_OPENS, "Open S&etup File", "Open a setup file for use in this session") FileMenu.Append(ID_OPEND, "Open D&ata File", "Open a data file fo ruse in this session") FileMenu.Append(ID_EXIT, "E&xit", "Terminate the program") ViewMenu = wxMenu() ViewMenu.Append(ID_SETUP, "S&etup", "View the current setup file") ViewMenu.Append(ID_OUTPUT, "O&utput", "View the current output file") HelpMenu = wxMenu() HelpMenu.Append(ID_HELP, "H&elp", "More information about this program") HelpMenu.Append(ID_ABOUT, "A&bout", "More information about this program") menuBar = wxMenuBar() menuBar.Append(FileMenu, "&File") menuBar.Append(ViewMenu, "&View") menuBar.Append(HelpMenu, "&Help") self.SetMenuBar(menuBar) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.TimeToQuit) EVT_MENU(self, ID_OPEND, self.OpenDataFile) DataChildFrame=wxMDIChildFrame(self, -1, "Data View") DataChildFrame.Show(true) dg = DataGrid(DataChildFrame) def OnAbout(self, event): dlg = wxMessageDialog(self, "This sample program shows off\n" "frames, menus, statusbars, and this\n" "message dialog.", "About Me", wxOK | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def test(): pass def TimeToQuit(self, event): self.Close(true) def OpenDataFile(self, event): pass class MyApp(wxApp): def OnInit(self): frame = MyParentFrame() frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() From magnus@thinkware.se Thu Apr 17 03:55:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Apr 17 02:55:02 2003 Subject: [Tutor] Re: extracting html source In-Reply-To: <20030415160006.3157.24297.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030417010434.00bc8dc0@www.thinkware.se> At Tue, 15 Apr 2003 06:11:55 -0500, pan@uchicago.edu wrote: >Try this: > >a= 'aaa bbb ccc' > > >>> import re > > >>> re.findall('.*', htmlSource) # <== [A] >[' bbb '] =20 > > >>> re.findall('(.*)', htmlSource) # <== [B] >[' bbb '] No, please don't! ;) It's been said many times that REs are inadequate for HTML parsing, and the Python standard library contains two HTML parsers already, so why build your own? There is one in htmllib, and one which is better suited for XHTML as well in the HTMLParser library. Here's an example. from HTMLParser import HTMLParser import sys class SpanExtractor(HTMLParser): show = False def handle_starttag(self, tag, attr): if tag == 'span': self.show = True if self.show: sys.stdout.write(self.get_starttag_text()) def handle_endtag(self, tag): if self.show: sys.stdout.write(self.get_starttag_text()) if tag == 'span': self.show = False def handle_data(self, data): if self.show: sys.stdout.write(data) html=''' bla bla bla in the span in the span in the span in the span bla bla ''' p = SpanExtractor() p.feed(html) p.close() If you don't want to include the tags, just swap places of the two if blocks in handle_starttag and handle_endtag. Sure, this is a bit more code than the RE, but soon you will notice that you need to do more stuff, and then this is a much better platform, and one day, you might have a '' inside a comment which will cause problems etc. A really nifty third party module which is great if you have control over the HTML and can put id tags in it is PyMeld. See below: >>> import PyMeld >>> html = '''bla bla ... bla this ... is in ... the spanbla bla ''' >>> p = PyMeld.Meld(html) >>> p.mySpan >>> print p.mySpan this is in the span >>> p.mySpan = "Here is some text.\n" >>> p.mySpan += "Let's add some more..." >>> print p bla bla bla Here is some text. Let's add some more...bla bla You see? You can easily modify parts... >>> print p.mySpan Here is some text. Let's add some more... >>> print p.mySpan._content Here is some text. Let's add some more... Or extract parts, with or without the surrounding tags. >>> p.mySpan.x = "y" >>> print p bla bla bla Here is some text. Let's add some more...bla bla You can also add / change attributes... >>> del p.mySpan.x >>> print p bla bla bla Here is some text. Let's add some more...bla bla Or remove them. There are more features available. See http://www.entrian.com/PyMeld/ -- Magnus Lycka, magnus@thinkware.se Thinkware AB, www.thinkware.se From adamg@mailbox.hu Thu Apr 17 04:10:02 2003 From: adamg@mailbox.hu (Adam Groszer) Date: Thu Apr 17 03:10:02 2003 Subject: [Tutor] getting the current method name Message-ID: Dear All, how to do the following: class x: def y(): print "Hi, my name is",< 'y'>> z=x() z.y() should print "Hi, my name is y" Of course, resolving "< 'y'>>" should not be done with simply 'y' :-) Adam From charlie@begeistert.org Thu Apr 17 05:40:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Thu Apr 17 04:40:02 2003 Subject: [Tutor] RE: Why MS chose \ In-Reply-To: <20030416160006.25732.65443.Mailman@mail.python.org> References: <20030416160006.25732.65443.Mailman@mail.python.org> Message-ID: <20030417103935.2508.13@wonderland.1050563893.fake> > Having digest problems so answering this indirectly... > > My understanding of the reason for the choice of \ was that / was already > in use. MS DOS(and its precursor) were originally cheap clones of CP/M > and CP/M programs conventionally used / for command line options. > (CP/M didn't have paths as we know them...) > > Thus when MS had to introduce paths(DOS 2?) they chose the opposite form > of slash. > > I just checked and certainly the CP/M assembler and MBASIC interpreters > both used '/' for commandline options as did the original CP/M wordstar. > So it sounds reasonable. > > Alan G ... > [Seabrook, Richard] Seems to me I remember using double slashes // in IBM > OS360 JCL back in the 60s but I don't know if Gates & Co. go back that > far. Before that it was pretty much * in IBSYS, $ in IBJOB and @ in > UNIVAC systems if I recall correctly. > Dick S. Thanx to you both. It was my question initially. That's one of the great things about this list: finding out all kinds of interesting bits of computer history. Charlie From krier115@student.liu.se Thu Apr 17 05:49:18 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Thu Apr 17 04:49:18 2003 Subject: [Tutor] getting the current method name In-Reply-To: References: Message-ID: <20030417084842.GA11159@n14.ryd.student.liu.se> On Thu, Apr 17, 2003 at 09:11:02AM +0200, Adam Groszer wrote: > Dear All, > > how to do the following: > > class x: > def y(): > print "Hi, my name is",< 'y'>> > > z=x() > z.y() > should print > "Hi, my name is y" > > Of course, resolving "< 'y'>>" should not be done with > simply 'y' :-) Hello Adam, Here are two ways to do it, but as you see using these methods you still have to type the function name and make it function specific. As far as I know functions in Python aren't self aware so you will have to reference it trough its scope bound name, that is, you have to know the name of it in the code. I'm not totally sure about this, but it's what everything seems like if i haven't missed anything. >>> class x: ... def y(self): ... print 'Hi, my name is', self.y.__name__ ... >>> z = x() >>> z.y() Hi, my name is y >>> class x: ... def y(self): ... print 'Hi, my name is', getattr(self.y, '__name__') ... >>> z = x() >>> z.y() Hi, my name is y -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From wheelcrdan@hotmail.com Thu Apr 17 11:33:02 2003 From: wheelcrdan@hotmail.com (Danny) Date: Thu Apr 17 10:33:02 2003 Subject: [Tutor] Help using Random module Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0021_01C3042A.C0B63510 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Everyone, My question is, I want to use the random module to pick a random number = from 1,100 I read up on it but am very confused about how to use it = properly. What I've tried to say is.=20 def number(x): x =3D random.randrange(1,100) result =3D x return result =20 guess =3D 0 while guess !=3D number: guess =3D input ("guess a number") if guess > number: print "Too High" print guess elif guess < number: print "too Low" print guess print "Just Right" When I run the program the random number is always greater then 100 what = am I doing wrong? Also what does it mean when the module has a uppercase = letter. For example random.Random is that the same as random.random?? = Thanks for everyone help. Danny D ------=_NextPart_000_0021_01C3042A.C0B63510 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi Everyone,
 
My question is, I want to use the = random module to=20 pick a random number from 1,100 I read up on it but am very confused = about how=20 to use it properly. What I've tried to say is. 
 
def number(x):
    x = =3D=20 random.randrange(1,100)
    result =3D = x
   =20 return result
   
guess =3D 0
 
while guess !=3D = number:
    guess=20 =3D input ("guess a number")
 
    if guess >=20 number:
        print "Too=20 High"
        print = guess
 
    elif guess <=20 number:
        print "too=20 Low"
        print = guess
 
print "Just Right"
 
When I run the program the random = number is always=20 greater then 100 what am I doing wrong? Also what does it mean when the = module=20 has a uppercase letter. For example random.Random is that the same as=20 random.random?? Thanks for everyone help.
 
Danny D
------=_NextPart_000_0021_01C3042A.C0B63510-- From rick@niof.net Thu Apr 17 11:34:01 2003 From: rick@niof.net (Rick Pasotto) Date: Thu Apr 17 10:34:01 2003 Subject: [Tutor] running boa constructor Message-ID: <20030417143309.GG9580@tc.telocity.com> I'm running debian/testing and have unzipped boa constructor into /usr/lib/python2.1/site-packages. When I try to run it with the command line: python /usr/lib/python2.1/site-packages/boa-constructor-0.2.0/Boa.py I get: Starting Boa Constructor v0.2.0 importing wxPython Traceback (most recent call last): File "/usr/lib/python2.1/site-packages/boa-constructor-0.2.0/Boa.py", line 177, in ? if wxVERSION < __version__.wx_version: NameError: name 'wxVERSION' is not defined What do I have wrong? -- "Every person who puts money into the hands of a 'government' (so called), puts into its hands a sword which will be used against him, to extort more money from him, and also to keep him in subjection to its arbitrary will." -- Lysander Spooner Rick Pasotto rick@niof.net http://www.niof.net From antonmuhin at rambler.ru" References: Message-ID: <64821100.20030417201731@rambler.ru> Hello Adam, Thursday, April 17, 2003, 11:11:02 AM, you wrote: AG> Dear All, AG> how to do the following: AG> class x: AG> def y(): AG> print "Hi, my name is",< 'y'>> AG> z=x() AG> z.y() AG> should print AG> "Hi, my name is y" AG> Of course, resolving "< 'y'>>" should not be done with AG> simply 'y' :-) AG> Adam Try the following: import sys def get_callee_name(depth = 0): return sys._getframe(depth + 1).f_code.co_name def foo(): print get_callee_name() class Bar: def bar(self): print get_callee_name() def bar_with_class(self): print "%s.%s" % (self.__class__.__name__, get_callee_name()) print "Calling foo" foo() print "Calling Bar.bar()" Bar().bar() print "Calling Bar.bar_with_class()" Bar().bar_with_class() -- Best regards, anton mailto:antonmuhin@rambler.ru From bgailer@alum.rpi.edu Thu Apr 17 13:54:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Apr 17 12:54:02 2003 Subject: [Tutor] Help using Random module In-Reply-To: Message-ID: <5.2.0.9.0.20030417104222.02fba810@66.28.54.253> --=======28D737AD======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-4F531F4E; boundary="=====================_8630489==.ALT" --=====================_8630489==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-4F531F4E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:13 PM 4/16/2003 -0600, Danny wrote: >Hi Everyone, > >My question is, I want to use the random module to pick a random number >from 1,100 I read up on it but am very confused about how to use it >properly. What I've tried to say is. > >def number(x): > x = random.randrange(1,100) > result = x > return result > >guess = 0 > >while guess != number: > guess = input ("guess a number") > > if guess > number: > print "Too High" > print guess > > elif guess < number: > print "too Low" > print guess > >print "Just Right" > >When I run the program the random number is always greater then 100 what >am I doing wrong? "number" refers to a function object. guess < number will always return True. "number()" will call the function. However if you replace number with number() above, it will return a (probably) different value each time. Perhaps what you want is: guess = 0 num = number() while guess != num: and refer to num instead of number from there on. >Also what does it mean when the module has a uppercase letter. For example >random.Random is that the same as random.random?? Names in Python are case sensitive. A little experimentation: >>> import random >>> random.Random >>> random.random > >>> help(random.random) Help on method random in module random: random(self) method of random.Random instance Get the next random number in the range [0.0, 1.0). >>> help(random.Random) Help on class Random in module random: class Random | Random number generator base class used by bound module functions. [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_8630489==.ALT Content-Type: text/html; x-avg-checked=avg-ok-4F531F4E; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:13 PM 4/16/2003 -0600, Danny wrote:

Hi Everyone,
 
My question is, I want to use the random module to pick a random number from 1,100 I read up on it but am very confused about how to use it properly. What I've tried to say is.
 
def number(x):
    x = random.randrange(1,100)
    result = x
    return result
   
guess = 0

 
while guess != number:
    guess = input ("guess a number")

 
    if guess > number:
        print "Too High"
        print guess

 
    elif guess < number:
        print "too Low"
        print guess

 
print "Just Right"
 
When I run the program the random number is always greater then 100 what am I doing wrong?

"number" refers to a function object. guess < number will always return True.
"number()" will call the function. However if you replace number with number() above, it will return a (probably) different value each time.

Perhaps what you want is:

guess = 0
num = number()
while guess != num:

and refer to num instead of number from there on.

Also what does it mean when the module has a uppercase letter. For example random.Random is that the same as random.random??

Names in Python are case sensitive.

A little experimentation:
>>> import random
>>> random.Random
<class random.Random at 0x011516C0>
>>> random.random
<bound method Random.random of <random.Random instance at 0x011527B8>>
>>> help(random.random)
Help on method random in module random:
random(self) method of random.Random instance
    Get the next random number in the range [0.0, 1.0).
>>> help(random.Random)
Help on class Random in module random:
class Random
 |  Random number generator base class used by bound module functions.
[snip]

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_8630489==.ALT-- --=======28D737AD======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4F531F4E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======28D737AD=======-- From antonmuhin at rambler.ru" References: Message-ID: <891072311.20030417202142@rambler.ru> Hello Danny, Thursday, April 17, 2003, 1:13:36 AM, you wrote: D> Hi Everyone, D> My question is, I want to use the random module to pick a random number from 1,100 I read up on it but am very confused about how to use it properly. What I've tried to say is. D> def number(x): D> x = random.randrange(1,100) D> result = x D> return result D> guess = 0 D> while guess != number: D> guess = input ("guess a number") D> if guess > number: D> print "Too High" D> print guess D> elif guess < number: D> print "too Low" D> print guess D> print "Just Right" D> When I run the program the random number is always greater then 100 what am I doing wrong? Also what does it mean when the module has a uppercase letter. For example random.Random is that the same D> as random.random?? Thanks for everyone help. D> Danny D Several bugs slipped into your code: 1. number and number() are quite different and you meant number() . 2. Actually it seems that you meant something like this: current_number = number() and number->current_number Otherwise you'll get new random number each time you call number function -- Best regards, anton mailto:antonmuhin@rambler.ru From jeff@ccvcorp.com Thu Apr 17 14:37:39 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 17 13:37:39 2003 Subject: [Tutor] HTML form pre-populating functionality or hints on building my own References: <200304161939.11337.scott_list@mischko.com> Message-ID: <3E9EE63A.90204@ccvcorp.com> Scott Chapman wrote: >Hi! >I'm wanting to find (or make) a module that will take a HTML file, locate the >input-related form tags (by putting in values from a dictionary (i.e. pre-populate the form). I want a >module that is implemented 100% in python and does _not_ use any special tags >to do this (such as webware, albatross, spyce, etc.) > For simple HTML generation, you can look into the htmlgen module (http://starship.python.net/crew/friedrich/HTMLgen/html/main.html) -- it's a little dated, but should be able to handle basic needs like this. You can use it to generate the appropriate HTML tag for that form element, and then substitute your new element for the existing one. In order to find the necessary tags, you can use one of the HTML parsers that's already distributed with Python. Check out the htmllib and HTMLParser modules. I've never done HTML generation in Python myself, so I can't offer more specific pointers, but hopefully this will be enough to get you started in the right direction. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Apr 17 15:47:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 17 14:47:01 2003 Subject: [Tutor] getting the current method name References: <64821100.20030417201731@rambler.ru> Message-ID: <3E9EF6FB.1030302@ccvcorp.com> antonmuhin at rambler.ru wrote: >AG> how to do the following: > >AG> class x: >AG> def y(): >AG> print "Hi, my name is",< 'y'>> > >Try the following: > >import sys > >def get_callee_name(depth = 0): > return sys._getframe(depth + 1).f_code.co_name > Needless to say, this is black magic. It may work, but one should be careful using it -- it seems very poor programming practice to make an application be dependent on the deep internals of the interpreter it's running on. Among other issues, there's no guarantee that the next version of Python (or the current version of Jython) will have the same call frame structure. (Indeed, I believe that Stackless does *not* have the same structure, and I wouldn't want to put any bets on this working consistently under Stackless...) My immediate thought would be to ask why the name of the current method is needed? There may be a better solution to the problem that is being addressed. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Thu Apr 17 18:09:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Apr 17 17:09:01 2003 Subject: [Tutor] Standard way to append to a list? ['+=' is in-place concatenation] In-Reply-To: References: <5.2.1.1.0.20030417003528.00beae68@www.thinkware.se> Message-ID: <5.2.1.1.0.20030417224650.02b435f0@www.thinkware.se> At 17:59 2003-04-16 -0700, Danny Yoo wrote: >Clarification on the second form: the expression: > > l += [4] > >is called an 'in-place concatenation', and for lists, this actually calls >the extend() method! For those with a C bent, here's the relevant code >from the Python source: Hm... I didn't know that. The language reference calls += in general "augmented assignment". See http://www.python.org/doc/current/ref/augassign.html As you write, the important thing is: "when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead". This is tricky, because seeing x += y as a shorter way of writing x = x + y is then incorrect for lists, as can be seen here: >>> a = [1,2,4] >>> b = a >>> b += [2] >>> a [1, 2, 4, 2] >>> b [1, 2, 4, 2] a and b are still the same object. >>> a = [1,2,4] >>> b = a >>> b = b + [2] >>> a [1, 2, 4] >>> b [1, 2, 4, 2] >>> b = b + [2] means that b no longer refers to the same object as a. As another example, this means that in a ZODB persistent class, "self.prop = self.prop + [x]" will automatically be recognized by the object database, but with "self.prop += [x]" it won't... I could get hit by that... Thanks Danny. BTW, does "when possible" mean anything except list in the standard library? I don't think there is any mutable type except list which can use += in Python. How Python classes behave is obviously depending on how you implement __iadd__, right? The code below is legal python, if not very good... >>> class x(list): ... def __iadd__(self, other): ... return "X" So, I guess "when possible" is mainly a guideline for programmers... E.g. in a Python class, you ought to modify self and end the method with "return self". /Magnus From magnus@thinkware.se Thu Apr 17 19:59:08 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Apr 17 18:59:08 2003 Subject: [Tutor] getting the current method name In-Reply-To: <20030417160005.32673.89696.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030418004736.00bd01a0@www.thinkware.se> At Thu, 17 Apr 2003 09:11:02 +0200, Adam Groszer wrote: >how to do the following: > >class x: > def y(): > print "Hi, my name is",< 'y'>> > >z=x() >z.y() >should print >"Hi, my name is y" > >Of course, resolving "< 'y'>>" should not be done with >simply 'y' :-) Did that! See http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/systemspecifyer/src/matrix.py?rev=1.16&content-type=text/vnd.viewcvs-markup Python is certainly capable of introspection. This function does the trick!: >>> import sys >>> def _fn(): ... return sys._getframe(1).f_code.co_name ... >>> class X: ... def y(self): ... print _fn() ... >>> x = X() >>> x.y() y Another option is to write: >>> class X: ... def y(self): ... print sys._getframe(0).f_code.co_name ... >>> x = X() >>> x.y() y Notice 0 instead of one. Now we want the top-most (or is it bottom-most) frame. I prefer a separate (well commented?) function for such magic though... The docs say about sys._getframe that "This function should be used for internal and specialized purposes only." What does this really imply? That we can't expect the API to remain? From jeff@ccvcorp.com Thu Apr 17 20:29:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Apr 17 19:29:01 2003 Subject: [Tutor] getting the current method name References: <5.2.1.1.0.20030418004736.00bd01a0@www.thinkware.se> Message-ID: <3E9F3902.2030107@ccvcorp.com> Magnus Lycke wrote: > The docs say about sys._getframe that "This function > should be used for internal and specialized purposes only." > > What does this really imply? That we can't expect the API > to remain? I think it's just indicating pretty much what I'd said in my response -- that this is something that's dependent on the internal structure of the interpreter, rather than something that's a meaningful part of the language definition. It seems risky to assume that future/alternate versions of the Python interpreter will always use the same execution frame architecture -- odds of it actually changing may not be that great, but I think this is an appropriate example of what the Law of Demeter tries to discourage. Obviously, someone who's writing a debugger or a code-inspection tool will need to be able to do this sort of thing, but it's not really intended for general usage. (A further hint along those lines is the use of a leading underscore on _getframe(), indicating that this function is intended as a "private" internal function rather than as part of the public API. As is typical of Python, you're allowed access to internals, but you should always be aware that you're using them at your own risk.) I stand by my earlier contention that, absent a truly compelling reason to muck about in the guts of the interpreter, the O.P. can probably find a more appropriate solution to their problem than this. To be honest, I can't think of a reason to *need* the name of the current method/function, except maybe in the specialized cases of a debugger or code inspector. Typically, if I need the name of a method, I'd need it to invoke an arbitrary method via getattr(), and I'd probably be drawing that name from a dictionary somewhere. But when I'm writing a function, I know what name I'm giving it, so I don't really need a way to drag that name out of the interpreter. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Thu Apr 17 20:33:08 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Apr 17 19:33:08 2003 Subject: [Tutor] wxPython tutorial In-Reply-To: <20030417065502.30319.30931.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030418012911.00b82200@www.thinkware.se> At Wed, 16 Apr 2003 15:29:33 -0300, Diego Prestes wrote: > Someone know where I can found a tutorial for wxPython? > >Diego There are three good sources of information for wxPython: * The wxPython demo programs * The wiki: http://wiki.wxpython.org/ * The mailing list: wxPython-users-subscribe@lists.wxwindows.org Robin Dunn and Patrick O'Brien is writing a book, so soon there will be one more good source of information... From magnus@thinkware.se Thu Apr 17 20:58:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Apr 17 19:58:01 2003 Subject: [Tutor] HTML form pre-populating functionality or hints on building my own In-Reply-To: <20030417065502.30319.30931.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030418014007.02b33b90@www.thinkware.se> At Wed, 16 Apr 2003 19:39:11 -0700, Scott Chapman wrote: >I'm wanting to find (or make) a module that will take a HTML file, locate the >input-related form tags (by putting in values from a dictionary (i.e. pre-populate the form). I want a >module that is implemented 100% in python and does _not_ use any special tags >to do this (such as webware, albatross, spyce, etc.) I think my reply on "<021852.htm>extracting html <021852.htm>source" applies equally well to you. If you roll your own, use HTMLParser.HTMLParser, or perhaps htmllib.HTMLParser if you don't need to support XHTML. Don't use a general purpose text parser or RE. Otherwise, if it's ok with you to put id attributes which is completely kosher HTML and XHTML, but not typically included in arbitrary HTML / XHTML files, use PyMeld. With PyMeld, you will use completely clean HTML /XHTML that will be edited and displayed correctly in whatever web browser or editing software the HTML guys use. You will need to have an id attribute in addition to the name attribute though, and typically they will have the same value. This is no big thing though, and it works for any tag. You're not supposed to have name attributes in

or tags for instance, so PyMeld is usable far beyond forms. After all, the id attribute exists to provide a "document-wide unique id" for tags, so if you want to be able to identify individual tags, they *should* have an id attribute. This id attribute might well be the key in your dict. From brian@dungeoncrawl.org Thu Apr 17 21:35:01 2003 From: brian@dungeoncrawl.org (Brian Christopher Robinson) Date: Thu Apr 17 20:35:01 2003 Subject: [Tutor] Sets Message-ID: <5.2.0.9.0.20030417203217.02341680@localhost> I think I read that sets will be a primitive data type in the next version of Python, but what is a good way to implement them now? -- reaching out to embrace whatever may come From shalehperry@attbi.com Thu Apr 17 23:25:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Apr 17 22:25:02 2003 Subject: [Tutor] Sets In-Reply-To: <5.2.0.9.0.20030417203217.02341680@localhost> References: <5.2.0.9.0.20030417203217.02341680@localhost> Message-ID: <200304171923.47658.shalehperry@attbi.com> On Thursday 17 April 2003 17:32, Brian Christopher Robinson wrote: > I think I read that sets will be a primitive data type in the next version > of Python, but what is a good way to implement them now? use a dictionary. From norvell@houseofspearman.org Fri Apr 18 04:58:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Fri Apr 18 03:58:02 2003 Subject: [Tutor] Sets In-Reply-To: <200304171923.47658.shalehperry@attbi.com> References: <5.2.0.9.0.20030417203217.02341680@localhost> <200304171923.47658.shalehperry@attbi.com> Message-ID: <20030418075740.GA13766@houseofspearman.org> On Thursday, 2003.04.17, 19:23:47 -0700, Sean 'Shaleh' Perry wrote: > On Thursday 17 April 2003 17:32, Brian Christopher Robinson wrote: > > I think I read that sets will be a primitive data type in the next version > > of Python, but what is a good way to implement them now? > > use a dictionary. Not that I know a better implementation (I'm new to Python and only recently began studying set theory), but why is using a dictionary a good way to implement sets? According to the set theory text I'm using (and this is the text's notation, not Python code): (1) {a, a} = {a} (2) {a, b} = {b, a} Since dictionaries are unordered (2) above is covered, but wouldn't (1) (if one creates a set class using a dictionary) require a method to get rid of---or ignore---duplicates? Or would one implement a set where the dictionary's key:value pairs are item:frequency and two sets are equal if their respective dictionaries contain the same items, ignoring frequencies > 0? Would the null set then be represented by my_set = {} Or am I using ``sets'' in the wrong context? Thanks for any answers. -- Norvell Spearman From a_abdi406@yahoo.com Fri Apr 18 10:46:38 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Fri Apr 18 09:46:38 2003 Subject: [Tutor] help for dictionary sorting program Message-ID: <20030418134517.39460.qmail@web14503.mail.yahoo.com> --0-2098158533-1050673517=:39089 Content-Type: text/plain; charset=us-ascii Hi,I was working on a function that takes a adictionary as an argument and returns the frequency ordering of elements in the dictionary. I have dictionary set up as follows: Value key frequency positions where the word was foundnatural doc1.txt (89, (17, 22, 26)) the last 3 numbers means the word is found position 17,22,26, and the frequency of that word is 89, the word found is natural and it is from afile called doc1.txt.my intention is to pick-up the items in the dictionary by frequency and Iimplemented the function this way: def SortDict(adict): """ this function sorts the frequency/key pairs in the dictionary by highest to lowest frequency """ counts = {} for word in adict.items(): if counts.has_key(word): counts[word] += 1 else: counts[word] = 1 keys = counts.keys() keys.sort(lambda x, y: cmp(counts[y], counts[x])) print"\n--------------------------------------------" #display the top five elements for i in range(5): print keys + "\t" + counts[keys[i]] print "\n\n" return keys having implemented this way it is giving me a syntax error which is as follws: File "C:\Python22\Ass2Test\SubIndex.py", line 9, in SortDict if counts.has_key(word): TypeError: list objects are unhashable can anyone help me figure out what I am getting wrong ? or suggestany way that I can achieve my objectives. thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-2098158533-1050673517=:39089 Content-Type: text/html; charset=us-ascii

Hi,
I was working on a function that takes a adictionary as an argument and returns the frequency ordering of elements in the dictionary. I have dictionary set up as follows:
 
Value         key        frequency   positions where the word was found
natural    doc1.txt   (89,          (17, 22, 26))
 
the last 3 numbers means the word is found position 17,22,26, and the frequency of that word is 89, the word found is natural and it is from afile called doc1.txt.
my intention is to pick-up the items in the dictionary by frequency and I
implemented the function this way:
 
def SortDict(adict):
        """ this function sorts the frequency/key pairs in the
            dictionary by highest to lowest frequency   """
        counts = {}
        for word in adict.items():
                if counts.has_key(word):
                        counts[word] += 1
                else:
                       
                        counts[word] = 1
            
        keys = counts.keys()
        keys.sort(lambda x, y: cmp(counts[y], counts[x]))
        print"\n--------------------------------------------"
       
       #display the top five elements
        for i in range(5):
                print keys + "\t" + counts[keys[i]]
               
        print "\n\n"
        return keys  
 
having implemented this way it is giving me a syntax error which is as follws:
 
 File "C:\Python22\Ass2Test\SubIndex.py", line 9, in SortDict
    if counts.has_key(word):
TypeError: list objects are unhashable
 
can anyone help me figure out what I am getting wrong ? or suggest
any way that I can achieve my objectives.
 
thanks in advance
 



Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-2098158533-1050673517=:39089-- From magnus@thinkware.se Fri Apr 18 10:49:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Apr 18 09:49:02 2003 Subject: [Tutor] Sets In-Reply-To: <20030418075802.32766.86630.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030418111358.00bd01a0@www.thinkware.se> At Fri, 18 Apr 2003 02:57:41 -0500, Norvell Spearman wrote: >On Thursday, 2003.04.17, 19:23:47 -0700, Sean 'Shaleh' Perry wrote: > > On Thursday 17 April 2003 17:32, Brian Christopher Robinson wrote: > > > I think I read that sets will be a primitive data type in the next > version > > > of Python, but what is a good way to implement them now? > > > > use a dictionary. That's a slightly terse explanation... >Not that I know a better implementation (I'm new to Python and only >recently began studying set theory), but why is using a dictionary a >good way to implement sets? According to the set theory text I'm using >(and this is the text's notation, not Python code): > > (1) {a, a} = {a} > (2) {a, b} = {b, a} Yes. >Since dictionaries are unordered (2) above is covered, but wouldn't (1) >(if one creates a set class using a dictionary) require a method to get >rid of---or ignore---duplicates? No. You store the items in the set as keys in the dictionary. The same key can't occur twice. >Or would one implement a set where the >dictionary's key:value pairs are item:frequency and two sets are equal >if their respective dictionaries contain the same items, ignoring >frequencies > 0? In a simple set class, you could just store 1, or whatever as value. Storing a frequency is an extension to the set behaviour you described above, but it's used now and then. Such a class is often called a "bag" or a "multiset". >Would the null set then be represented by > > my_set = {} Well, wrapped in a class, but yes, that looks empty to me. >Or am I using ``sets'' in the wrong context? No. I searched google for "python set class". For instance, I found these: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52258 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/106469 (Not using dict, since it has to store mutable objects) From kkzuberi@yahoo.com Fri Apr 18 11:36:02 2003 From: kkzuberi@yahoo.com (Khalid Zuberi) Date: Fri Apr 18 10:36:02 2003 Subject: [Tutor] HTML form pre-populating functionality or hints on building my own In-Reply-To: <5.2.1.1.0.20030418014007.02b33b90@www.thinkware.se> Message-ID: <20030418143509.66098.qmail@web41415.mail.yahoo.com> --- Magnus Lyckå wrote: > At Wed, 16 Apr 2003 19:39:11 -0700, Scott Chapman wrote: > >I'm wanting to find (or make) a module that will take a HTML file, locate the > >input-related form tags ( >by putting in values from a dictionary (i.e. pre-populate the form). I want a > >module that is implemented 100% in python and does _not_ use any special tags > >to do this (such as webware, albatross, spyce, etc.) > Check out http://wwwsearch.sourceforge.net/ClientForm/ - Khalid __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com From bh-wages@swbell.net Fri Apr 18 13:07:01 2003 From: bh-wages@swbell.net (Billie) Date: Fri Apr 18 12:07:01 2003 Subject: [Tutor] Getting started with Python Message-ID: <059301c305c4$5d05dca0$7840fea9@BillieWages> This is a multi-part message in MIME format. ------=_NextPart_000_0503_01C30597.269056A0 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit Well, I have lowered the balance in my checking account with the purchase of three Python instructional books. The humor I have found makes me forget about the "seriousness" in what I am doing (trying to teach a 60 y/o woman's brain to learn a new computer language). Though Mark Lutz feels "bus attacks less threatening now," I "do" hope Guido stays clear of buses. And Alan, since I purchased your book (thanks for the DC :), I'm glad to see you a part of this list. *shaking hands* Paint Shop Pro 8's use of Python is what brought me here. Though I learned BASIC programming almost twenty years ago, it is the Word Perfect Macro-like function of scripting in PSP that has regenerated my interest in learning another programming language. I've always had to know how things worked, and thrive on seeking solutions to problems. Other than what is provided in the books, is there a given lesson plan or tutorial on projects for learning anywhere? I've been a little bit intimidated with the CD's so far, but know that I will overcome this......... but I'm in a hurry! I have also saved every post to this list since I first joined it, and will also use it to look for answers I might need. Finally........ as an "old-timer, senior citizen" I totally agree with Mark, when he speaks of Python's ease-of-use, that there still is "no substitute for brains!" I just hope I have enough cells still functioning to undertake this task. Thanks to all who helped me with my book questions, Billie ------=_NextPart_000_0503_01C30597.269056A0 Content-Type: text/x-vcard; name=" Billie.vcf" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename=" Billie.vcf" BEGIN:VCARD VERSION:2.1 N:;Billie FN: Billie EMAIL;PREF;INTERNET:bwages@BWages.net REV:20030418T154204Z END:VCARD ------=_NextPart_000_0503_01C30597.269056A0-- From scott_list@mischko.com Fri Apr 18 14:22:03 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 18 13:22:03 2003 Subject: [Tutor] Regular Expression question Message-ID: <200304172138.16338.scott_list@mischko.com> Is it possible to make a regular expression that will match: '' or '' without having to make it into two complete expressions seperated by a pipe: r'|' I want it to require a space or tab and at least one character before the closing bracket, after 'html', or just the closing bracket. Scott From jeff@ccvcorp.com Fri Apr 18 14:22:15 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Apr 18 13:22:15 2003 Subject: [Tutor] help for dictionary sorting program References: <20030418134517.39460.qmail@web14503.mail.yahoo.com> Message-ID: <3EA03490.8060809@ccvcorp.com> Abdirizak abdi wrote: > Hi, > I was working on a function that takes a adictionary as an argument > and returns the frequency ordering of elements in the dictionary. I > have dictionary set up as follows: > > Value key frequency positions where the word was found > natural doc1.txt (89, (17, 22, 26)) This doesn't really show how your dictionary is defined. You say that 'doc1.txt' is the key, but I'd presume that you'll have many words from doc1.txt, and you'll want a dictionary listing all of them. That indicates that you want to key the dictionary off of the word ('natural' in this case) instead of the filename. I'd probably implement the dictionary something like this: freq_dict = { 'natural' : ('doc1.txt', 89, [17,22,26]), ...] Each item in the dictionary is keyed off of the word, and the value is a tuple containing the filename, the frequency number within that file, and a list of the word positions. If you want to be able to track word frequency in multiple files, you could fairly easily extend this to be a list of such tuples, one for each file, or perhaps even a nested dict keyed off of the filename. > my intention is to pick-up the items in the dictionary by frequency [...] So you want to get a list of all of the key:value pairs, sorted by value[1] ... > def SortDict(adict): > """ this function sorts the frequency/key pairs in the > dictionary by highest to lowest frequency """ > counts = {} > for word in adict.items(): > if counts.has_key(word): > counts[word] += 1 > else: I'm guessing that you didn't include the actual else: clause in order to save space, since having nothing following the else: will result in a syntax error. The problem here is that you're asking for adict.items(), which returns a list of [key, value] pairs, so that word is actually a 2-element list. It looks like you probably want to use adict.keys() instead, which will give you a list of only the keys in adict. You could also write it as for word, value in adict.items(): and take advantage of automatic tuple unpacking. Now, given the example dictionary I showed above, word will be 'natural' and value will be "('doc1.txt', 89, [17,22,26])". However, I'm not sure what you're trying to accomplish here. It looks like you're trying to get a count of the number of times each word occurs in adict. But because dictionary keys must be unique, you're guaranteed that each word in adict occurs only once. If you're trying to sort adict by the frequency of words, remember that you've already got that frequency as part of the value. You just need to reorganize things so that you can use the built-in list sort(). Remember what I said about needing to sort on value[1]? We just need to create a list where value[1] is the first part of each element. If we're iterating through adict.items(), then value is the second part of each item (item[1]). So we build a list that contains (freq, item), sort that list, then discard freq and keep item. (This procedure is frequently called decorate-sort-undecorate.) def sort_by_freq(adict): templist = [] for item in adict.items(): element = (item[1][1], item) templist.append( element ) templist.sort() result = [] for element in templist: result.append( element[1] ) return result We can do this a bit more compactly by using list comprehensions: def sort_by_freq(adict): templist = [ (item[1][1], item) for item in adict.items() ] templist.sort() result = [element[1] for element in templist] return result The result that's returned by this will now be a list of (key, value) pairs, where value is the tuple I described above, with frequency as its middle element. You can then print the first five elements: sorted_list = sort_by_freq(freq_dict) for line in sorted_list[:5]: print "word: %10s freq: %4d" % (line[0], line[1][1]) Hope this helps... Jeff Shannon Technician/Programmer Credit International From Janssen@rz.uni-frankfurt.de Fri Apr 18 15:47:07 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Apr 18 14:47:07 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <200304172138.16338.scott_list@mischko.com> Message-ID: On Thu, 17 Apr 2003, Scott Chapman wrote: > Is it possible to make a regular expression that will match: > '' or '' > without having to make it into two complete expressions seperated by a pipe: > r'|' > > I want it to require a space or tab and at least one character before the > closing bracket, after 'html', or just the closing bracket. def test(expr): for s in ('','', '','', ''): print "%-18s" % s, mt = re.search(expr, s) if mt: print mt.group() else: print test(r"") r"" has a group "([ \t][ \t]+?)" for one following space-tag-combination. This group can be given once or no times. NB: re is powerfull but not suficient for reallife html as Magnus has already stated today. Michael > > Scott > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python@jaydorsey.com Fri Apr 18 15:48:02 2003 From: python@jaydorsey.com (Jay Dorsey) Date: Fri Apr 18 14:48:02 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <200304172138.16338.scott_list@mischko.com> References: <200304172138.16338.scott_list@mischko.com> Message-ID: <3EA04820.1040209@jaydorsey.com> Scott Chapman wrote: > Is it possible to make a regular expression that will match: > '' or '' > without having to make it into two complete expressions seperated by a pipe: > r'|' > > I want it to require a space or tab and at least one character before the > closing bracket, after 'html', or just the closing bracket. > > Scott How about ']+)?>' >>> import re >>> x = re.compile(']+)?>') >>> print x <_sre.SRE_Pattern object at 0x008B63C0> >>> y = '' >>> print x.search(y).group() >>> z = '' >>> print x.search(z).group() >>> a = '' >>> print x.search(a).group() Jay From scott_list@mischko.com Fri Apr 18 15:58:01 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 18 14:58:01 2003 Subject: [Tutor] Regular Expression question In-Reply-To: References: Message-ID: <200304181157.15513.scott_list@mischko.com> On Friday 18 April 2003 11:46, Michael Janssen wrote: > On Thu, 17 Apr 2003, Scott Chapman wrote: > > Is it possible to make a regular expression that will match: > > '' or '' > > without having to make it into two complete expressions seperated by a > > pipe: r'|' > > > > I want it to require a space or tab and at least one character before the > > closing bracket, after 'html', or just the closing bracket. > > def test(expr): > for s in ('','', '','', > ''): > print "%-18s" % s, > mt = re.search(expr, s) > if mt: > print mt.group() > else: print > > > test(r"") > > > > > > > r"" has a group "([ \t][ \t]+?)" for one following > space-tag-combination. This group can be given once or no times. > > NB: re is powerfull but not suficient for reallife html as Magnus has > already stated today. > > Michael Mike, Thanks for the tip. I'm moving forward with this as a first program in Python. I'll have a good look at htmlParser shortly because of Magnus' post. I'm just using this as an exercise and doubt it will ever see production. Thanks! Scott From scott_list@mischko.com Fri Apr 18 16:21:35 2003 From: scott_list@mischko.com (Scott Chapman) Date: Fri Apr 18 15:21:35 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <3EA04820.1040209@jaydorsey.com> References: <200304172138.16338.scott_list@mischko.com> <3EA04820.1040209@jaydorsey.com> Message-ID: <200304181220.30266.scott_list@mischko.com> On Friday 18 April 2003 11:46, Jay Dorsey wrote: > Scott Chapman wrote: > > Is it possible to make a regular expression that will match: > > '' or '' > > without having to make it into two complete expressions seperated by a > > pipe: r'|' > > > > I want it to require a space or tab and at least one character before the > > closing bracket, after 'html', or just the closing bracket. > > > > Scott > > How about > > ']+)?>' > Thanks for the reply. After seeing these replies, it seems clear that you can use the grouping ()'s for more than just capturing a section for output. I think I missed that in the docs I've been reading. I wonder where all this works? For instance, will it work on either side of a '|'? I'll have to play with this further! Thanks! Scott From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 17:29:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 16:29:01 2003 Subject: [Tutor] Getting started with Python In-Reply-To: <059301c305c4$5d05dca0$7840fea9@BillieWages> Message-ID: On Fri, 18 Apr 2003, Billie wrote: > Other than what is provided in the books, is there a given lesson plan > or tutorial on projects for learning anywhere? Hi Billie, The lesson plans given by the LiveWires educational group seem very interesting: http://www.livewires.org.uk/python/ The projects that LiveWires provides are written for a young audience in mind, but they should still be very useful! Here's a link to them: http://www.livewires.org.uk/python/pdfsheets.html > I've been a little bit intimidated with the CD's so far, but know that I > will overcome this......... but I'm in a hurry! I have also saved every > post to this list since I first joined it, and will also use it to look > for answers I might need. All of us here on the list will be happy to help answer your questions. Please feel free to ask Tutor for clarification on any confusing part in the Python books --- we can help augment the book learning with practical hints and advice. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 17:41:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 16:41:00 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <200304181220.30266.scott_list@mischko.com> Message-ID: On Fri, 18 Apr 2003, Scott Chapman wrote: > On Friday 18 April 2003 11:46, Jay Dorsey wrote: > > Scott Chapman wrote: > > > Is it possible to make a regular expression that will match: > > > '' or '' > > > without having to make it into two complete expressions seperated by a > > > pipe: r'|' > > > > > > I want it to require a space or tab and at least one character before the > > > closing bracket, after 'html', or just the closing bracket. > > > > > > Scott > > > > How about > > > > ']+)?>' > > > > Thanks for the reply. After seeing these replies, it seems clear that > you can use the grouping ()'s for more than just capturing a section for > output. Hi Scott, Yes, the grouping parentheses are serving two functions: they are defining a group for both capturing values and for aggregation. There's another set of regular-expression parentheses that don't capture, although they do still aggregate: ### >>> regex = re.compile('(?:a+)(b+)(a+)') >>> matchobj = regex.match('aaaaaabbbbaa') >>> matchobj.group(1) 'bbbb' >>> matchobj.group(2) 'aa' ### Notice that the first set of parentheses, the ones that match again the first set of "aaaa"'s, don't form a captured group. [Wow, "captured group" sound like a term from Go or something... *grin*] The non-grouping parentheses use the special form: (?: The docs on them are a little sparse, but you can read more about them here: http://www.python.org/doc/lib/re-syntax.html Look for the words "non-grouping" and you should see them. There's actually a few Python-specific extensions to the regular-expression grouping that are pretty cool: it's even possible to create "named" groups so that we don't have to do things like column counting to keep track of groups. > I think I missed that in the docs I've been reading. I wonder where all > this works? For instance, will it work on either side of a '|'? I'll > have to play with this further! It sounds like you're getting interested in regular expressions. You may find AMK's "Regular Expression HOWTO" a slightly gentler introduction to regular expressions: http://www.amk.ca/python/howto/regex/ Best of wishes to you! From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 17:58:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 16:58:01 2003 Subject: [Tutor] Sets In-Reply-To: <5.2.1.1.0.20030418111358.00bd01a0@www.thinkware.se> Message-ID: On Fri, 18 Apr 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > That's a slightly terse explanation... > > >Not that I know a better implementation (I'm new to Python and only > >recently began studying set theory), but why is using a dictionary a > >good way to implement sets? According to the set theory text I'm using > >(and this is the text's notation, not Python code): > > > > (1) {a, a} =3D {a} > > (2) {a, b} =3D {b, a} Hello! By the way, those two examples do work in Python. We have to remember, though, that Python's dictionaries don't exactly map to sets, since sets don't have the "value" component. To test out those two examples, let's just use a proxy '1' as our value: ### >>> {'a' : 1, 'a' : 1} =3D=3D {'a': 1} ## Example 1 1 >>> {'a' : 1, 'b' : 1} =3D=3D {'b' : 1, 'a' : 1} ## Example 2 1 >>> {'a' : 1, 'b' : 1} =3D=3D {'b' : 1, 'c' : 1} ## {a, b} !=3D {b, c= } 0 ### The only thing is that dictionaries are a bit more fullly featured than strict mathematical sets. That is, we are only paying attention to the 'key' component of each key/value pair of a dictionary --- we're only using dictionaries just for their set-like behavior with their keys. That being said, Python 2.3 will have a 'sets' module: http://www.python.org/doc/2.3a1/whatsnew/node2.html so as soon as the new version of Python 2.3 comes out, we'll be able to wholeheartedly suggest folks to use the 'sets' module. The direction of the language, in the longer term, suggests that we'll have built-in notation for defining sets that's much closer to the notation in a math book. Python Enhancement Proposal 218 describes what this language extension might look like: http://www.python.org/peps/pep-0218.html So we have things to look forward to. *grin* Until then, we can use dictionaries as a tool for implementing sets. Good luck! From mhansen@cso.atmel.com Fri Apr 18 18:56:40 2003 From: mhansen@cso.atmel.com (Mike Hansen) Date: Fri Apr 18 17:56:40 2003 Subject: [Tutor] Copy Files, Dates Message-ID: <3EA07458.4080204@cso.atmel.com> Hi, I'm new to Python. For my first Python program, I thought I'd have it parse a log file and E-mail me if it found any errors in the log file in the last two days. Here's a couple of questions: How do you copy files using Python? I just want to copy the log file before I start processing it. Unless I'm missing something, I've seen how to rename and delete files, but I don't see copy. First I need to find out if a string is a Date. Is there any IsDate like function? Also, is there a module that compares dates? Thanks, Mike From Kurt.Kurniawan@rbs.org.au Fri Apr 18 18:58:02 2003 From: Kurt.Kurniawan@rbs.org.au (Kurt Kurniawan) Date: Fri Apr 18 17:58:02 2003 Subject: [Tutor] need help with dbi problem Message-ID: Hi all, I'm a newbie to python, especially with its DB intearction. I'm experimenting with some data retrieval from M$ SQL server DB. One of the column has a binary data type and Python translate that as dbiRaw and memory address behind it. My questions is: how can I get a string value of this ? Some sort of string casting ? I tried str( ...) and didn't work. I'm using PythonWin with Python 2.2 I hope somebody can give a hint .. thank's ********************************************************************************* - NOTICE - The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon, this information by persons or entities other than the intended recipient is prohibited. If you have received this email in error, please notify the sender and delete the material from your computer. Internet communications are not secure. You should scan this message and any attachments for viruses. Under no circumstances do we accept liability for any loss or damage which may result from your receipt of this message or any attachments. ********************************************************************************* From Doug.Shawhan@ge.com Fri Apr 18 18:58:13 2003 From: Doug.Shawhan@ge.com (Doug.Shawhan@ge.com) Date: Fri Apr 18 17:58:13 2003 Subject: [Tutor] RE: Why MS chose \ Message-ID: <47B6167F8E69D31194BA0008C7918D42076FEBFC@msxcvg02itscge.gecits.ge.com> IIRC up to and including DOS 3 one could change this behavior, effectively swapping the switch and the slash. Fortunately I was using an apple// at the time! :-) -----Original Message----- From: Alan Gauld [mailto:alan.gauld@freenet.co.uk] Sent: Tuesday, April 15, 2003 1:54 PM To: tutor@python.org Subject: [Tutor] RE: Why MS chose \ Having digest problems so answering this indirectly... My understanding of the reason for the choice of \ was that / was already in use. MS DOS(and its precursor) were originally cheap clones of CP/M and CP/M programs conventionally used / for command line options. (CP/M didn't have paths as we know them...) Thus when MS had to introduce paths(DOS 2?) they chose the opposite form of slash. I just checked and certainly the CP/M assembler and MBASIC interpreters both used '/' for commandline options as did the original CP/M wordstar. So it sounds reasonable. Alan G _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From hsiehson5@yahoo.com Fri Apr 18 18:58:27 2003 From: hsiehson5@yahoo.com (Y.T. H.) Date: Fri Apr 18 17:58:27 2003 Subject: [Tutor] Help Message-ID: <20030417060530.77410.qmail@web21310.mail.yahoo.com> Dear Sir, This is Andy from Sydney University. I have come across to a few questions that I am wondering if you'd be so kind to give me some suggestion; 1>Which of the following Python statements is NOT used for flow control. a> a,b = 0,1 b> if x < 0: c> while b< 1000: d> for x in a: 2>What output will the following string parsing code be? mystring="the quick brown fox jumped over the lazy dog" print left(mystring,instr(mystring,"fox")-1) 3>What is the principle purpose of a python cgi module? a> to process the contents of an HTML page b> to generate forms containing name/value querystrings or form variables c>to process in a Python script Name/Value pairs from an HTML form or query string d>to dynamically create HTML 4>A scripting language is generally, a> Interpretive b> Used to build complex applications c> Fast and efficient d> Loosely typed Thank you so much for answering them. Sincerely Andy YT H __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com From alan.gauld@blueyonder.co.uk Fri Apr 18 18:58:44 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 18 17:58:44 2003 Subject: [Tutor] getting the current method name References: Message-ID: <009c01c30511$c07d35c0$6401a8c0@xp> > how to do the following: > > class x: > def y(): > print "Hi, my name is",< 'y'>> > > Of course, resolving "< 'y'>>" should not be done with > simply 'y' :-) I'm curious why there would ever be such a need? I can't think of a situation when simply hard coding the name woulfd not be possible, after all you are writing the,method when you do it. I guess the only case might be using a callable object for dynamic object creation. Lets try.... class C: pass c = C() c.f = lambda self: "My name is ..... But no even here we know that the name will be f. I give in, under what circumstance would you not know the current method's name? Alan G From alan.gauld@blueyonder.co.uk Fri Apr 18 18:58:52 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 18 17:58:52 2003 Subject: [Tutor] Sets References: <5.2.0.9.0.20030417203217.02341680@localhost> <200304171923.47658.shalehperry@attbi.com> <20030418075740.GA13766@houseofspearman.org> Message-ID: <004601c30583$eed07780$6401a8c0@xp> > > use a dictionary. > > recently began studying set theory), but why is using a dictionary a > good way to implement sets? Because a dictionary has a unique key mechanism so if you try to add duplicate keys it won't work. So we can build a set based on a dictionary such that: > According to the set theory text I'm using > (1) {a, a} = {a} > (2) {a, b} = {b, a} Only one entry for 'a' can exist It doesn't matter which order you put the elements in. > rid of---or ignore---duplicates? Or would one implement a set where the > dictionary's key:value pairs are item:frequency You could. But frequency should only be one. So I'd just use key:None pairs class Set: def __init__(self,elems = []): self.theSet = dict(elems) def addElement(self, elem): self.theSet[elem] = None def members(self): return self.theSet.keys() def union(self, anotherSet): return Set(self.theSet.items() + anotherSet.theSet.items()) def isEmpty(self): return len(self.theSet.keys()) == 0 etc... > Would the null set then be represented by > my_set = {} Yes. HTH, Alan G. From alan.gauld@blueyonder.co.uk Fri Apr 18 18:58:59 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 18 17:58:59 2003 Subject: [Tutor] help for dictionary sorting program References: <20030418134517.39460.qmail@web14503.mail.yahoo.com> Message-ID: <007301c305d6$56c3f950$6401a8c0@xp> > def SortDict(adict): > """ this function sorts the frequency/key pairs in the > dictionary by highest to lowest frequency """ > counts = {} > for word in adict.items(): At this point word contains a tuple of key,value. I suspect you only want to extract the keys. > if counts.has_key(word): Especially since you are comparing with a key... Alan G. From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 19:34:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 18:34:01 2003 Subject: [Tutor] Help In-Reply-To: <20030417060530.77410.qmail@web21310.mail.yahoo.com> Message-ID: On Wed, 16 Apr 2003, Y.T. H. wrote: > This is Andy from Sydney University. I have come across to a few > questions that I am wondering if you'd be so kind to give me some > suggestion; Dear Andy, We help people who want to learn computer programming using Python. For people who are genuinely trying to learn and play with the language, we are happy to help. But I think you're misunderstanding our role here: we are not here to do your homework. A university student is expected to do more than parrot the answers of other people. And you are expected to do more. > 1>Which of the following Python statements is NOT used > for flow control. > a> a,b = 0,1 > b> if x < 0: > c> while b< 1000: > d> for x in a: Counter question: what is a "flow control" statement? What does the term "control flow" mean to you? What problem did you have with this question? > 2>What output will the following string parsing code > be? > > mystring="the quick brown fox jumped over the lazy > dog" > print left(mystring,instr(mystring,"fox")-1) What problems are you having with this? Have you been able to run this in your interactive interpreter? What problems do you have when you actually try this from the interactive prompt? What does 'left' and 'instr' mean in the statement above? > 3>What is the principle purpose of a python cgi > module? > a> to process the contents of an HTML page > b> to generate forms containing name/value > querystrings or form variables > c>to process in a Python script Name/Value pairs from > an HTML form or query string > d>to dynamically create HTML I don't understand the question here. Why are you giving us multiple choice answers for this? Where are YOUR questions? Again, what problems did you encounter while trying to answer this? > 4>A scripting language is generally, > a> Interpretive > b> Used to build complex applications > c> Fast and efficient > d> Loosely typed Again, the choice of giving us multiple choice answers is an odd one: what are you asking us to do? Please forgive me for my accusatory and harsh tone, but your questions are homework exercises. Perhaps you did not mean to do this, but to ask a public forum to do your homework assignment for you is not only demoralizing for the volunteers here, but personally insulting to all of us. If you really do want to learn about Python, we strongly suggest you look at the introductory web page: http://python.org/doc/Newbies.html and work through a tutorial. The tutorials on that page are valuable resources that you can use to learn ideas of programming, but they require your active effort. Sincerely, Danny Yoo From bgailer@alum.rpi.edu Fri Apr 18 19:44:03 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Fri Apr 18 18:44:03 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: <3EA07458.4080204@cso.atmel.com> Message-ID: <5.2.0.9.0.20030418163929.03043e58@66.28.54.253> --=======6DBD7463======= Content-Type: text/plain; x-avg-checked=avg-ok-5B0351B2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:55 PM 4/18/2003 -0600, Mike Hansen wrote: >[snip] >How do you copy files using Python? Check out the shutil module >First I need to find out if a string is a Date. Is there any IsDate like >function? Also, is there a module that compares dates? Unfortunately there is no standard format for dates. To ask if a string is a date is very vague. Do you have certain formats in mind? Check out the time module. There is a strptime function which takes a string and a format. You'd probably have to try several formats. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======6DBD7463======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-5B0351B2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======6DBD7463=======-- From Don Arnold" Message-ID: <017501c305fd$d2bfdd40$8511ba3f@defaultcomp> ----- Original Message ----- From: "Danny Yoo" To: "Y.T. H." Cc: Sent: Friday, April 18, 2003 5:33 PM Subject: Re: [Tutor] Help > > Please forgive me for my accusatory and harsh tone, but your questions are > homework exercises. Perhaps you did not mean to do this, but to ask a > public forum to do your homework assignment for you is not only > demoralizing for the volunteers here, but personally insulting to all of > us. > Agreed. And Y.T.H. should keep in mind that his instructor could well be a member of this list. Even if it doesn't bother him that he's cheating himself by having other people do his work, maybe it will bother him that he could easily be caught doing it and fail the class. On a lighter note, am I the only one here who thinks Alex Martelli's "Python In A Nutshell" is possibly the best Python book there is? It's clearly written, comprehensive, and stuffed with example code. I can't recommend it highly enough. Don From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 20:08:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 19:08:01 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: <5.2.0.9.0.20030418163929.03043e58@66.28.54.253> Message-ID: On Fri, 18 Apr 2003, Bob Gailer wrote: > At 03:55 PM 4/18/2003 -0600, Mike Hansen wrote: > >[snip] > >How do you copy files using Python? > > Check out the shutil module > > >First I need to find out if a string is a Date. Is there any IsDate like > >function? Also, is there a module that compares dates? > > Unfortunately there is no standard format for dates. To ask if a string > is a date is very vague. Do you have certain formats in mind? Check out > the time module. There is a strptime function which takes a string and a > format. You'd probably have to try several formats. Hi Mike, The third-party package, 'mxDateTime', has a very nice 'parser' module: http://www.egenix.com/files/python/mxDateTime.html With it, we can cook up an isDate() function that's fairly robust: ### from mx.DateTime.Parser import DateTimeFromString def isDate(date_string): """A simple test to see if the date_string is parseable as a date.""" formats = ['euro', 'us', 'altus', 'iso', 'altiso', 'lit', 'alitlit', 'eurlit'] try: parsed_date = DateTimeFromString(date_string, formats) return parsed_date except ValueError: return 0 ### Let's see how it works: ### >>> isDate('April 18, 2003') >>> isDate('Mumbember 18, 2003') 0 ### This isDate() function isn't strictly a boolean function, but since class instances are True values as far as Python is concerned, I think it's close enough. I don't know if this is sufficiently fast or efficient, so you may need to see if it will perform well for you. Good luck to you! From alan.gauld@blueyonder.co.uk Fri Apr 18 20:22:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 18 19:22:01 2003 Subject: [Tutor] Copy Files, Dates References: <3EA07458.4080204@cso.atmel.com> Message-ID: <001501c30600$c0b88270$6401a8c0@xp> > How do you copy files using Python? Finding the right module is one of the hardest bits of learning Python... The one you need here is called shutil - obviously! :-)! > First I need to find out if a string is a Date. Is there any IsDate like > function? There is a string convertion function in the python time module. You might want to use try/except to catch errors: try: # convert the string except: print 'oops! not a date' There is also an addin mxDate module which gets good reviews, it might have something. > Also, is there a module that compares dates? The basic time module lets you convert a date into a numeric value. You can then compare the numbers, subract them to get the difference etc. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo@hkn.eecs.berkeley.edu Fri Apr 18 20:39:08 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 18 19:39:08 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: Message-ID: On Fri, 18 Apr 2003, Danny Yoo wrote: ### > ### > >>> isDate('April 18, 2003') > ### Hmmm... actually, doesn't that look really weird to anyone else? *grin* I didn't notice it before, but the date that it parsed is totally not right. Instead of DateTimeFromString, I tried using DateFromString, with slightly better-but-still-weird values coming from the function. With the substitution to DateFromString, here's what happens now: ### >>> isDate('04-18-2003') >>> isDate('February 12, 2002') >>> isDate('Mumbember 12, 2002') 0 >>> isDate('1999/03/30') 0 >>> isDate('03/30/1999') ### So there's something still wacky here... It might make an interesting project for someone to try improving mx.DateTime.parser.DateFromString to give better results. From shalehperry@attbi.com Fri Apr 18 21:07:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Apr 18 20:07:01 2003 Subject: [Tutor] Sets In-Reply-To: <5.2.1.1.0.20030418111358.00bd01a0@www.thinkware.se> References: <5.2.1.1.0.20030418111358.00bd01a0@www.thinkware.se> Message-ID: <200304181705.49324.shalehperry@attbi.com> On Friday 18 April 2003 06:49, Magnus Lyck=E5 wrote: >>On Thursday, 2003.04.17, 19:23:47 -0700, Sean 'Shaleh' Perry wrote: > > > On Thursday 17 April 2003 17:32, Brian Christopher Robinson wrote: > > > I think I read that sets will be a primitive data type in the next > > > version of Python, but what is a good way to implement them now? > > > > use a dictionary. > > That's a slightly terse explanation... > the original poster appeared to know what sets were and that Python would=20 eventually support them. Did not see the need to explain why dicts were a= =20 good choice. Apparently other readers on the list did desire this info. =20 Sorry about that. From tony@tcapp.com Sat Apr 19 04:28:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sat Apr 19 03:28:01 2003 Subject: [Tutor] Using __setattr__ Message-ID: <5.1.0.14.0.20030419003429.01a9cfa0@smtp.sbcglobal.net> --=====================_34456986==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed I'm trying to use __setattr__ in a class I"m writing, but have been having problems getting it to work. I've looked on Active state and found references to this self.__dict__['modified'] = 1 I would like to know more about what 'modified' = 1 does, and when I would need use it. The books I have on Python don't go into much detail on overloading methods like __setattr__ thanks --=====================_34456986==_.ALT Content-Type: text/html; charset="us-ascii"

I'm trying to use __setattr__ in  a class I"m writing, but have been having problems getting it to work.

I've looked on Active state and found references to this
self.__dict__['modified'] = 1

I would like to know more about what 'modified' = 1 does, and when I would need use it.
The books I have on Python don't go into much detail on overloading methods like __setattr__


thanks


--=====================_34456986==_.ALT-- From tony@tcapp.com Sat Apr 19 07:13:01 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sat Apr 19 06:13:01 2003 Subject: [Tutor] Speeding up import time Message-ID: <5.1.0.14.0.20030419031958.01acd488@smtp.sbcglobal.net> I'm loading the io module, from scipy in one of my programs, as in from scipy import io This particular module takes 3-5 seconds to load on some of the slower systems that I use. Is there anything i can do to improve this import time ? thanks From reavey@nep.net Sat Apr 19 09:44:02 2003 From: reavey@nep.net (reavey) Date: Sat Apr 19 08:44:02 2003 Subject: [Tutor] back-quotes to print dictionary Message-ID: <3EA14397.9090605@nep.net> I found this in instant python tutorial and I'm not sure how it's suposed to work? http://www.hetland.org/python/instant-python.php #!/usr/bin/env python class Basket: def __init__(self, contents = None): self.contents = contents or [] def add(self,element): self.contents.append(element) def print_me(self): result = "" for elem in self.contents: result = result + " " +`element` print "contains:" +result when I run this I get b = Basket() b.add('pear') b.add('apple') b.add('grape') Check add method b.__dict__() {contents:['pear','apple','grape']} check print_me method b.print_me() contents: elementelementelement I expect to see the contents of the dictionary [pear,apple,grape]. The code knows there are three elements but it is not printing the elements? From Don Arnold" Message-ID: <026b01c30675$40371d80$8511ba3f@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: Sent: Saturday, April 19, 2003 2:37 AM Subject: [Tutor] Using __setattr__ > > > I'm trying to use __setattr__ in a class I"m writing, but have been having > problems getting it to work. > > I've looked on Active state and found references to this > self.__dict__['modified'] = 1 > > I would like to know more about what 'modified' = 1 does, and when I would > need use it. When you set an object attribute, a key is added to the object's internal dictionary with the value you supply. So the code above is what happens behind the scenes when you say self.modified = 1. If you override __setattr__, your function will be called whenever you set an attrbute through dot notation (self.a = b). To avoid recursion, your method will have to modify the internal dictionary directly. > The books I have on Python don't go into much detail on overloading methods > like __setattr__ > Alex Martelli's "Python In A Nutshell" gives a good explanation of Python classes (both old- and new-style), as well as descriptions of all of the special methods. One use for overriding __setattr__ would be to implement read-only attributes: class A: def __init__(self): #since we're overriding __setattr__, we have to modify the internal #dictionary directly to set attributes self.__dict__['a'] = 10 self.__dict__['b'] = 20 def __setattr__(self,key,val): if key in ['a','b']: raise AttributeError, 'Attempt to set read-only attribute ' + key else: self.__dict__[key] = val a = A() a.c = 23 print a.a >> 10 print a.b >> 20 print a.c >> 23 a.a = 45 >> Traceback (most recent call last): >> File "D:/Python22/tutor/junk041803.py", line 21, in ? >> a.a = 45 >> File "D:/Python22/tutor/junk041803.py", line 10, in __setattr__ >> raise AttributeError, 'Attempt to set read-only attribute ' + key >> AttributeError: Attempt to set read-only attribute a HTH, Don From Don Arnold" Message-ID: <027601c30676$c6358650$8511ba3f@defaultcomp> ----- Original Message ----- From: "reavey" To: Sent: Saturday, April 19, 2003 7:39 AM Subject: [Tutor] back-quotes to print dictionary > I found this in instant python tutorial and I'm not sure how it's > suposed to work? > http://www.hetland.org/python/instant-python.php > #!/usr/bin/env python > > class Basket: > def __init__(self, contents = None): > self.contents = contents or [] > > def add(self,element): > self.contents.append(element) > > def print_me(self): > result = "" > for elem in self.contents: > result = result + " " +`element` > print "contains:" +result You have a typo in print_me(). Although you're iterating through self.contents using elem, you're appending `element` to the result. Change one of them so they match and it should work. HTH, Don From am@fx.ro Sat Apr 19 10:36:01 2003 From: am@fx.ro (Adrian Maier) Date: Sat Apr 19 09:36:01 2003 Subject: [Tutor] back-quotes to print dictionary In-Reply-To: <3EA14397.9090605@nep.net>; from reavey@nep.net on Sat, Apr 19, 2003 at 08:39:51AM -0400 References: <3EA14397.9090605@nep.net> Message-ID: <20030419190327.A257@coto> reavey (reavey@nep.net) a scris : > I found this in instant python tutorial and I'm not sure how it's > suposed to work? That little program doesn't work at all here : Traceback (most recent call last): File "a.py", line 21, in ? b.print_me() File "a.py", line 13, in print_me result = result + " " +`element` NameError: global name 'element' is not defined But if you replace: result = result + " " +`element` with: result = result + " " + elem then the program does exactly what it is expected to do: contains: pear apple grape If you backquote elem: result = result+" "+`elem` then you'll get: contains: 'pear' 'apple' 'grape' Best wishes. -- Adrian Maier (am@fx.ro) From Janssen@rz.uni-frankfurt.de Sat Apr 19 11:21:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Apr 19 10:21:01 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: <001501c30600$c0b88270$6401a8c0@xp> Message-ID: This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. Send mail to mime@docserver.cac.washington.edu for more info. ---1929210332-485758599-1050762044=:57846 Content-Type: TEXT/PLAIN; charset=US-ASCII On Sat, 19 Apr 2003, Alan Gauld wrote: > Finding the right module is one of the hardest bits of learning > Python... Here is a script, that helps the learner a bit: it searches lib/genindex.html for the function name given on commandline and display its documentation (by now via lynx --> LINUX. webbrowser modul possibly brings better portability). In this case (looking for copy but didn't find shutil) it would report 8 links, which isn't that helpfull for a poor beginner even if some links are irrelevant on first sight. But who knows? This can also be down by browsing genindex.html but this costs a lot of time (genindex.html loads slow) and mouseclicks. Which is the second advantage of my script: You needn't to leave the console and you save mouseclicks :-) I suggest to make an alias from manpy (or some such) to 'python /path/to/manpy.py' to spare even chars. Comments are welcome. Does anyone believe a script like this is indeed helpfull for the beginner (and should be propagated)? Michael ---1929210332-485758599-1050762044=:57846 Content-Type: APPLICATION/octet-stream; name="manpy.py.gz" Content-Transfer-Encoding: BASE64 Content-ID: Content-Description: python manual searcher Content-Disposition: attachment; filename="manpy.py.gz" H4sICEdVoT4AA21hbnB5LnB5AJ1YbVMbRxL+vr+isxSl3UMSyK6rVATmDhPb 4covBPClXMCpRquRds2+ZWYWoaTy3+/pmVlpBXbiO7kKlp1+m6e7n25557v9 Rqv9aVbuy/Ke6pVJqzLYoasPP34Y4zdRIe4kVcsyKxdUVLMmp/tMZ9Nc2lMl 60oZr0ezKqF7qXRmbRDNs3LGLwdToeUsU7TMINcYSptClJTKvLZyOq2WNJM6 UVltoLyWy1flA0UCVqoyX7FIvZap5rQUpZEzmjdlcmgNJcUsHwi1aApZGj2G wrRZIPI+R1ELk/adL5HnffrcFDWZClEqbXBPk6R9a+Xxx6pwSD4e+7iU06mq llqqmK2XPeMMargDOAEsva4UmVRSUs0ACn6V97LMZJlIOqMa18sMNSXO6M35 W6ANFcBSr4b1igYcsb2GsLfVUqgklcqjblQm7+UWZnN4E20mGBJj0wCF06pe qWyRGopOY3p2cPCc6F2WpELm9C9Rai1LOvIP/1S/DZsyG8yVKO/mjTLDmTy2 Vq7STFOtqoUSBeFxrqQkXc3NUih5SKuqoQRJVUi0RnjTxki+IJK3j8hQOtl8 BTPrOzMyRqpCcyb5jzfvP9IbWUolcjpvpnmW0NsskaWWJOCZ3+gU6Z6yGVZ4 zRFc+giANuxasA5JIkNw4WuRnrUuvL0+VQxkJAyHraiyCMaIdUW5MBvN4Rdv vrngjLLSGk6rGrdJhc3pMstzmkpqtJw3OdcUZOmXs6ufPny8opP3n+iXk4uL k/dXnw7XlY5sOktZUecZDONOSIFZIXQYePfq4vQnaJy8PHt7dvUJ8dPrs6v3 ry4v6fWHCzqh85OLq7PTj29PLuj848X5h8tXQ6JLyUFxp/4JtnObHcXFZESW a3fnT0gn6r7JZ5QKVJqSiczuEZdAHderv84ZbIi8AmnYbjEdCA8pm1NZmT4t VYYiQQs+yabtnjaffTork2Gf/v4DXUnAI+k8FwmyeNmw/vPnB316WWnDku9O iA6ejUajwej5wfdEHy9PAkDKJFVpdP+KfyB7zAlw44+UFLM8KyXtuEiZ9LSN aipx/cwWyZyUWE6ykjt3Kg3K5Dvu8lczpNxqoVnVKmi57gX1LLfqFPfZRzfv 1yK5Ewup912T7qemyHtfMGHxkXImZ4F8gJtS5JP7TC6lNcocxFo70GNinJMU esUoSjajERlup8Eg5w7vAhcWyuggcLgDiCFz4TDTiDPy8cbjgLmuBjSGQoCM 185iz0v0uNgd37C3umJJPNgWclcabJFWaC0C8qF8yEw0isGKk0mjgcFkgquE Yejpak17R95Oy1/HwUDR2LOfTYiSc6ksh2alNsgbI5BnUyWA/aDYFi5EslEI Bhqnludtp7syAE4Vk8Uy417wbjXTlht32o6eYLBc6y4rNdMBgndJ4JlDtVBM /MFMzmkhDQglMmLhMUVKxxYGTKb7oZJFdS/t8SEzeaNKGlk5+ZBIYPtvkTfy lVKVGrfnB3aebEIP4GDi43/ROgwHOoxbMZSvi5Ml+akrt4QcBBsOuQMo14ZH kqeP08VxV1VZF07TNKZSmcitHEPdkSsgh3LzJw6HTWe0FfgZNdQWYD+EILRk 7vXg+dv0IBjGBEUtv00Bl4QjnCVptwOeNAjKVhsdhQuMbcyshyF3bLjdKWVF W8dYJ3KuTWIL47DvjW+3goVfM9WvMNs0WqbvpgcWE1eObpVxgwnVqHiLKFmQ 55+HOeDCsoaFvpOzCTP5i3WhXY9uh3kF0oA3X1lnHKWrrM4V1i35tF07JLNV 5oEtdOakSQr0I/7hYUFfvFwBxeUY6wBu0zIYOQbjtumgx7ukAUpswL4H9IjA yCJ6TH171MO/PbK+fARJWlVaTrhto4WqmnqWJWaCPcFsollgbFkywDjmDYlP 7YVYV2CRtaSbSd2GVjYFYMxl+dikPf2MswP7xHDbTG+LOcf8QTWxFXnds7Te u43pmD5vzltzj4SCtfW7PpXs4LesfhQLhpcoFzIa9TncvVEcb8w6aKNwd3dv V2MJ3t0d4DcNBoNjPOtwyz8+uxRxBKCTCLZirLOfY3uwQyNmU15stWFW/4Im Ru7dOnT7zPnBLeLr8fc/3LKRZ2PuiZwvcs/Upg+tnWXKjTLqxA0o1hM2Ck9t bpGwlpSHdLXClvW+KaZIJOC5/vkWC8CYwrgLOcxgtPwcsoR7/rXzHG7D3+nI 9tW6qTo2AWhUx3yDR7CP6TEmLWVv5+vaWRiMbluAtvQ21NX9+B65MX4Y7Gre Ppmg2kBCpKBe6z2dH8GfmfMzPmlxLi2ww9D3FhLf1JM1s0Trp01r/SiTSmFf 7vCP3faw6NVIkZIL+VAPpnaRw0wphLrDXt322YbmOT1bk6Jz7Kbc9k08xGuv GwSe4OhFVXgc0t5aYQ8vbqYujG2d/8+r1+I5+xX38PYV//9r3Nc3Ed1ykmyW CoHB5jOy0zLZhOvODgzPdbwz2LWAxzYvutor2KV3sClWPNcC34cdMl1rL+j3 P1yxI61cFtytcphURY0+jr5eLbF3tZTum4TIedtekZ293FnVZunwc5ILyUaG Oudx+pUJ7PPFkkO34nL1Rb2jmTk+Er3YLnE+2qHbCiMr7MdivA15YeyVFhPL ZkOLl5WPH9NBYZ42axesa9a6hbXCDNfQRvG3tzxndbyJhYpMu+UPuzLbHt+U Nybs2+egbSY7RjpRxEx4HX7djOuu1NBxchRfH6y5KaZgXddPrG4Mpm437A7h L1qOvxCCm+Jb3fO45zwWfs29CXf1TYivxZr/q2XOnMLst92NX+lEb8muwd9o p5scr97Oob82EdhNcjIpRWG/6WDuTCac08nEzx9OreZy88VqsXxxfdO7CW+j f5wf8Z/H1//BX3+L3dtjfm2rAe+P8Lq3NuRqZKsdrX2/STiKCIL/AuaEtC/s EwAA ---1929210332-485758599-1050762044=:57846-- From magnus@thinkware.se Sat Apr 19 11:29:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Apr 19 10:29:01 2003 Subject: [Tutor] Help In-Reply-To: <20030419132401.6555.23735.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030419160610.00b99e30@www.thinkware.se> At Wed, 16 Apr 2003 23:05:30 -0700 (PDT), "Y.T. H." wrote: >Dear Sir, >This is Andy from Sydney University. I have come >across to a few questions that I am wondering if you'd >be so kind to give me some suggestion; Surely. >1>Which of the following Python statements is NOT used >for flow control. >a> a,b = 0,1 >b> if x < 0: >c> while b< 1000: >d> for x in a: Neither. You use pipes and faucets etc for flow control. These are all programming constructs. >2>What output will the following string parsing code >be? > >mystring="the quick brown fox jumped over the lazy >dog" >print left(mystring,instr(mystring,"fox")-1) SyntaxError >3>What is the principle purpose of a python cgi >module? >a> to process the contents of an HTML page >b> to generate forms containing name/value >querystrings or form variables >c>to process in a Python script Name/Value pairs from >an HTML form or query string >d>to dynamically create HTML Neither. The purpose of the cgi module is to make life easier for cgi programmers. >4>A scripting language is generally, >a> Interpretive >b> Used to build complex applications >c> Fast and efficient >d> Loosely typed All of the above, slightly depending on *what* you want to be fast and efficient. (Your work or the computers.) Dear Andy, I'd like to ask *you* something: What are your current career plans? Get a diploma and then live on social welfare money? You don't honestly think you will get a job unless you actually learn stuff, do you? Maybe in the rush around 1998-2000, but not after that... Surely you aren't so confused that you imagine that you can *learn* programming by having someone else do your homework. (Surely noone is *that* daft, even if sending this mail showed that you are less smart than one could expect from someone who is studying programming.) BTW, in my school we could get expelled for cheating. Shall we forward this to the education mailing list? Most professors teaching Python are subscribed to that, right? Although that might not be needed. A lot of them are subscribers her as well I guess. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From pan@uchicago.edu Sat Apr 19 18:54:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Sat Apr 19 17:54:01 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <20030419160006.11951.30477.Mailman@mail.python.org> References: <20030419160006.11951.30477.Mailman@mail.python.org> Message-ID: <1050789181.3ea1c53d6a207@webmail.uchicago.edu> Hi all, For a long time I've been wondering how you guys read and reply the py Tutor emails. Is there any package, any module that can let you read one specific message and just hit one [reply] button to reply that message to either the sender or the list? The commonly-used email clients seem to fail in this regard, and I have been bothered by having to cut and paste the message body when replying. pan From charlie@begeistert.org Sat Apr 19 19:09:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Apr 19 18:09:01 2003 Subject: [Tutor] Help In-Reply-To: <20030419160006.11951.30477.Mailman@mail.python.org> References: <20030419160006.11951.30477.Mailman@mail.python.org> Message-ID: <20030420000832.394.1@wonderland.1050788536.fake> Following Magnus' lead I thought we could at least make an interesting thread out of this. Having look at the questions I am a bit worried about the level of competence expected at this university so it might be an idea to forward it to the appropriate education list with the subject: are these questions appropriate for university education? The results could go to Useless Python to make the site really worthy of its name. > >1>Which of the following Python statements is NOT used > >for flow control. > >a> a,b = 0,1 > >b> if x < 0: > >c> while b< 1000: > >d> for x in a: > > Neither. You use pipes and faucets etc for flow control. These are all > programming constructs. 1) The amount you drink 2) Availability of amenities 3) Bladder muscles (can be trained) 4) Pampers (if all else fails) > >2>What output will the following string parsing code > >be? > > > >mystring="the quick brown fox jumped over the lazy dog" > >print left(mystring,instr(mystring,"fox")-1) > > SyntaxError Is this Python? Oh my, I thought it was easier than that! Answer: it doesn't matter 'cos the fox lands in some very sticky mud. Counterquestion: is this actually parsing? I don't have a definition to hand but just combining two functions doesn't really seem like parsing. Any -5 for illegibility. > >3>What is the principle purpose of a python cgi > >module? > >a> to process the contents of an HTML page > >b> to generate forms containing name/value > >querystrings or form variables > >c>to process in a Python script Name/Value pairs from > >an HTML form or query string > >d>to dynamically create HTML > > Neither. The purpose of the cgi module is to make life easier for cgi > programmers. Good answer, Magnus, but note the question refers to _a_ python cgi module. Maybe there are others? Just imagine a Python cgi module that emulated perl's cgi handling? Or it might be a trick question? "There should be one and preferably only one obvious way of doing things." Or so I've heard said. > >4>A scripting language is generally, > >a> Interpretive > >b> Used to build complex applications > >c> Fast and efficient > >d> Loosely typed > > All of the above, slightly depending on *what* you want to be fast and > efficient. (Your work or the computers.) Anything apart from "c" would be equally applicable to literary (or medial) criticism or even production. Imagine Shakespearean drama written in Python: def Hamlet(**args): pass b = rawinput("is it nobler in the mind to suffer the slings and arrow of outrageous fortune Or to take arms against a sea of troubles?") if b or not b: Hamlet(king=kill, sister=kill, everybody=kill) NB. this is untested and probably won't work but imagine we're on the verge of a whole new discipline! "once more into the breach my friends!" while not dead: rush_into_fight() "is this a dagger I see before me?" if item instance(Dagger): stab(self, item) "Now is the winter of our discontent" import time now = time.shakespeare("Richard III") Charlie From bgailer@alum.rpi.edu Sat Apr 19 19:55:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Apr 19 18:55:02 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <1050789181.3ea1c53d6a207@webmail.uchicago.edu> References: <20030419160006.11951.30477.Mailman@mail.python.org> <20030419160006.11951.30477.Mailman@mail.python.org> Message-ID: <5.2.0.9.0.20030419165321.01a16f48@66.28.54.253> --=======25A46007======= Content-Type: text/plain; x-avg-checked=avg-ok-48CA3A00; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:53 PM 4/19/2003 -0500, pan@uchicago.edu wrote: >Is there any package, any module that can let you read one specific message >and just hit one [reply] button to reply that message to either the sender >or the list? > >The commonly-used email clients seem to fail in this regard... Could you mention the ones you're having trouble with? I use Eudora,and it works fine. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======25A46007======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-48CA3A00 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.467 / Virus Database: 266 - Release Date: 4/1/2003 --=======25A46007=======-- From shalehperry@attbi.com Sat Apr 19 20:17:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Apr 19 19:17:01 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <1050789181.3ea1c53d6a207@webmail.uchicago.edu> References: <20030419160006.11951.30477.Mailman@mail.python.org> <1050789181.3ea1c53d6a207@webmail.uchicago.edu> Message-ID: <200304191616.03303.shalehperry@attbi.com> On Saturday 19 April 2003 14:53, pan@uchicago.edu wrote: > Hi all, > > For a long time I've been wondering how you guys read > and reply the py Tutor emails. Is there any package, > any module that can let you read one specific message > and just hit one [reply] button to reply that message > to either the sender or the list? > > The commonly-used email clients seem to fail in this > regard, and I have been bothered by having to cut and > paste the message body when replying. > The mailer I use (kmail from KDE under Debian Linux) gives me three options: if I press 'ctrl-l' I get "reply to list" and only the list is replied to. This works because I have told kmail that the folder I sort python-tutor mail into contains the mailing list "tutor@python.org". if I press 'ctrl-r' I get the standard reply-to honoring. if I press 'ctrl-a' I get "reply to all" which replies to the first address and cc's everyone else. This works well for me. From revanna@mn.rr.com Sat Apr 19 21:18:01 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Sat Apr 19 20:18:01 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <1050789181.3ea1c53d6a207@webmail.uchicago.edu> References: <20030419160006.11951.30477.Mailman@mail.python.org> <1050789181.3ea1c53d6a207@webmail.uchicago.edu> Message-ID: <200304191917.56408.revanna@mn.rr.com> On Saturday 19 April 2003 16:53, pan@uchicago.edu wrote: > Hi all, > > For a long time I've been wondering how you guys read > and reply the py Tutor emails. Is there any package, > any module that can let you read one specific message > and just hit one [reply] button to reply that message > to either the sender or the list? > > The commonly-used email clients seem to fail in this > regard, and I have been bothered by having to cut and > paste the message body when replying. Are you getting a digest version of the list? If so, it's not your mailreader, it's just that you would prefer individual mails rather than a daily digest. To fix this, you need to reset your settings on the following question: Would you like to receive list mail batched in a daily digest? No Yes Go to the http://mail.python.org/mailman/listinfo/tutor to update it. HTH Anna From pan@uchicago.edu Sat Apr 19 22:44:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Sat Apr 19 21:44:02 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <5.2.0.9.0.20030419165321.01a16f48@66.28.54.253> References: <20030419160006.11951.30477.Mailman@mail.python.org> <20030419160006.11951.30477.Mailman@mail.python.org> <5.2.0.9.0.20030419165321.01a16f48@66.28.54.253> Message-ID: <1050802911.3ea1fadf6774f@webmail-b.uchicago.edu> =A4=DE=A5=CE Bob Gailer : > Could you mention the ones you're having trouble with? I use Eudora,and= it=20 > works fine. I'm using a 'webmail' client called 'Horde' or something ... it's not that it has some problem, but just inconvinient.=20 Everytime I read the tutor digest, first I have to scroll all=20 the way (and quite often back and forth and back and forth) before=20 I can find the messege that interest me. If i wanna reply, I have=20 to cut and paste the message body, then cut and paste it's title to=20 the newly compositing window before I reply. That's somehow troublesome for a lazy guy like me.=20 Take this reply as an example, if I didnt' cut and paste the msg title, the title shown on the tutor digest after it received this would have=20 been "Re: Tutor digest, Vol 1 #2379 - 3 msgs" (instead of "Any good=20 way to read Tutor mails? ", which is definitely not suitable. IMHO, the current technology should be able to give us something that you just see the title of all messages in "one window" (means dont' need to scroll). If u are interested in any mnsg, just click and read it, and if wanna reply, just click a button.=20 =A4=DE=A5=CE Anna Ravenscroft : > Are you getting a digest version of the list? I have too many emails a day so I prefer the digest mode. > Sean 'Shaleh' Perry shalehperry@attbi.com : > >The mailer I use (kmail from KDE under Debian Linux) gives me three opti= ons: > >if I press 'ctrl-l' I get "reply to list" and only the list is replied t= o. =20 >This works because I have told kmail that the folder I sort python-tutor= mail=20 >into contains the mailing list "tutor@python.org". > >if I press 'ctrl-r' I get the standard reply-to honoring. > >if I press 'ctrl-a' I get "reply to all" which replies to the first addr= ess=20 >and cc's everyone else. > >This works well for me. That sounds great but you still have scroll back/forth to find=20 a specific msg and also cut/paste to reply, if you are using a digest mode like mentioned above. pan From Janssen@rz.uni-frankfurt.de Sat Apr 19 23:30:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Apr 19 22:30:01 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <1050802911.3ea1fadf6774f@webmail-b.uchicago.edu> Message-ID: On Sat, 19 Apr 2003 pan@uchicago.edu wrote: > I'm using a 'webmail' client called 'Horde' or something ... [it's IMP (Internet Mailing Programm) from horde.org] > IMHO, the current technology should be able to give us something > that you just see the title of all messages in "one window" (means > dont' need to scroll). If u are interested in any mnsg, just > click and read it, and if wanna reply, just click a button. Interesting point. In order to bend it to current technologies: "one window" must be the index-page of your email-client. But to display the message-parts of the digest on this level, every digested message needs to starts with an unixfrom-line (for mbox-format), as unixfrom indicates start of message. That would be easy to implement into digest-code (resulting in a huge message send that appears to be a lot of messages in the index-list), but unfortunately (or luckily from a not so specific point :-) MTA's are suppose to "escape" faked unixfrom lines in the middle of a messages. That leaves the solution to local side (your side): You might parse your digest message and split it into several messages (with proper Subject and From=20headers). Given, that the digests have a clear format, this is not that hard to do, but requires shell-access to your ISP and tools like procmail on the server (Python not to mention ;-). Doing something like a different representation-type for digest mail within IMP sounds like a tricky and not so good idea to me. Sending the digest as attachment and establish a digest-file-format mailreader knows to handle could be more reliable but also long ranged (Sending as mbox attached and saving into mail-dir would be a workaround for the mbox-able world). > =A4=DE=A5=CE Anna Ravenscroft : > > > Are you getting a digest version of the list? > > I have too many emails a day so I prefer the digest mode. ISP-side limit or convenience? For the later, why not filter tutor mails into another imap-folder? IMP has dump filtercapabilities but sufficient for this task (given, that your ISP has enabled this feature). I have got filter and folders for any of my mailinglists and would have gotten mad if not ;-) I delete regularly all posts with "new" flag (which indicates the subject hasn't interest me) and old posts from time to time. Michael From neal@bcn.boulder.co.us Sun Apr 20 00:10:02 2003 From: neal@bcn.boulder.co.us (Neal McBurnett) Date: Sat Apr 19 23:10:02 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <1050802911.3ea1fadf6774f@webmail-b.uchicago.edu>; from pan@uchicago.edu on Sat, Apr 19, 2003 at 08:41:51PM -0500 References: <20030419160006.11951.30477.Mailman@mail.python.org> <20030419160006.11951.30477.Mailman@mail.python.org> <5.2.0.9.0.20030419165321.01a16f48@66.28.54.253> <1050802911.3ea1fadf6774f@webmail-b.uchicago.edu> Message-ID: <20030419210912.H21011@feynman> The answer to your question depends on exactly how the digests are formatted. Please "bounce" or forward one of the digests you get from this list to me, since I'm curious. Unfortunately, I think in this world of spam, viruses, many different clients and list managers, etc, it is harder and harder to get satisfactory results from digest modes. Though Mailman is considering a feature enhancement to provide "index" digests which just contain web links to the articles, which might suit you. In the Unix world there are many tools that can be used, e.g. "formail" perhaps with "procmail", emacs "undigest.el", "mutt", etc. depending on whether it is a plain text digest (RFC1153) or a MIME digest. Mailman can be configured to generate either. I'm not sure why, but I don't think users can pick the format, and the default seems to be plain text, whereas MIME would seem to be more widely supported. Neal McBurnett http://bcn.boulder.co.us/~neal/ Signed and/or sealed mail encouraged. GPG/PGP Keyid: 2C9EBA60 On Sat, Apr 19, 2003 at 08:41:51PM -0500, pan@uchicago.edu wrote: > =A4=DE=A5=CE Bob Gailer : >=20 > > Could you mention the ones you're having trouble with? I use Eudora,a= nd it=20 > > works fine. >=20 > I'm using a 'webmail' client called 'Horde' or something ... > it's not that it has some problem, but just inconvinient.=20 > Everytime I read the tutor digest, first I have to scroll all=20 > the way (and quite often back and forth and back and forth) before=20 > I can find the messege that interest me. If i wanna reply, I have=20 > to cut and paste the message body, then cut and paste it's title to=20 > the newly compositing window before I reply. That's somehow > troublesome for a lazy guy like me.=20 >=20 > Take this reply as an example, if I didnt' cut and paste the msg title, > the title shown on the tutor digest after it received this would have=20 > been "Re: Tutor digest, Vol 1 #2379 - 3 msgs" (instead of "Any good=20 > way to read Tutor mails? ", which is definitely not suitable. >=20 > IMHO, the current technology should be able to give us something > that you just see the title of all messages in "one window" (means > dont' need to scroll). If u are interested in any mnsg, just > click and read it, and if wanna reply, just click a button.=20 >=20 > =A4=DE=A5=CE Anna Ravenscroft : >=20 > > Are you getting a digest version of the list? >=20 > I have too many emails a day so I prefer the digest mode. >=20 > > Sean 'Shaleh' Perry shalehperry@attbi.com : > > > >The mailer I use (kmail from KDE under Debian Linux) gives me three op= tions: > > > >if I press 'ctrl-l' I get "reply to list" and only the list is replied= to. =20 > >This works because I have told kmail that the folder I sort python-tut= or mail=20 > >into contains the mailing list "tutor@python.org". > > > >if I press 'ctrl-r' I get the standard reply-to honoring. > > > >if I press 'ctrl-a' I get "reply to all" which replies to the first ad= dress=20 > >and cc's everyone else. > > > >This works well for me. >=20 > That sounds great but you still have scroll back/forth to find=20 > a specific msg and also cut/paste to reply, if you are using a digest > mode like mentioned above. >=20 > pan >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From idiot1@netzero.net Sun Apr 20 03:00:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun Apr 20 02:00:02 2003 Subject: [Tutor] something written in python is coming to light soon Message-ID: <3EA237A8.6080307@netzero.net> Because of the excellent tutilidge of this list, something is about to impact with a remarkable spllat on the internet; hopefully it will be more successful than my attempts at improving my spelling. http://www.listville.net/ . -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From dyoo@hkn.eecs.berkeley.edu Sun Apr 20 05:39:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 20 04:39:00 2003 Subject: [Tutor] back-quotes to print dictionary [use pychecker --- it's cool!] In-Reply-To: <20030419190327.A257@coto> Message-ID: > But if you replace: > > result = result + " " +`element` > with: > result = result + " " + elem > > then the program does exactly what it is expected to do: > > contains: pear apple grape Hi everyone, By the way, folks on the list may be interested in the 'pychecker' utility: http://pychecker.sourceforge.net/ 'Pychecker' can often catch typos and common bugs so that we don't get zapped so easily. For example, here's pychecker's output when I ran it on reavey's basket code: ### bash-2.05a$ pychecker basket.py Processing basket... Warnings... basket.py:10: Local variable (elem) not used basket.py:11: No global (element) found ### Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Apr 20 05:55:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 20 04:55:02 2003 Subject: [Tutor] Using __setattr__ In-Reply-To: <026b01c30675$40371d80$8511ba3f@defaultcomp> Message-ID: > > I'm trying to use __setattr__ in a class I"m writing, but have been > > having problems getting it to work. Hi Tony, Out of curiosity: are you using __setattr__ as an experiment with the language feature, or is there a particular bit of your code that can be improved if you use __setattr__? If it's the second reason, there might be an easier way to tackle what you're trying to do. Hmmm... can you tell us more about the class that you're writing? Good luck! From tony@tcapp.com Sun Apr 20 06:21:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Sun Apr 20 05:21:02 2003 Subject: [Tutor] Using __setattr__ In-Reply-To: References: <026b01c30675$40371d80$8511ba3f@defaultcomp> Message-ID: <5.1.0.14.0.20030420021138.01b69b48@tcapp.com> --=====================_23074289==_.ALT Content-Type: text/plain; charset="us-ascii"; format=flowed Hi Danny, >>Out of curiosity: are you using __setattr__ as an experiment with the > >>language feature, or is there a particular bit of your code that can be > >>improved if you use __setattr__? Both, actually. I've created a class, which for all practical purposes, contains fields such as class Address: def __init__(self, address_str): name = address_str address = address_str phone = address_str In all actuality, I'm working on a program for work, so I don't want to give out any sensitive information. However, the concept is the same, the class members have been changed to protect the innocent. The name, address, phone data is passed to the application, as a colon separated string- like this Name:Mr Smith;Address:123 Main St;Phone:408-123-4567; Since I don't want the application to deal with parsing the data, I thought I would experiment with doing it inside the class itself. It actually seems to work quite well, but it took me awhile to get it working. My __setattr__() looks like this def __setattr__(self, name, addr_str): if name in ['Name', 'Address', 'Phone' ]: name_loc = string.find(value_str, name) if name_loc != -1: pair = string.split(value_str[name_loc:], ';',1) pair1 = string.split(pair[0], ':',1) self.__dict__[name] = pair1[1] else: print"\nname %s NOT found" % name raw_input("\nPAUSED") After looking through ActiveState, I've found some posts which showed a __setattr__() that contained this self.__dict__['modified'] = 1 But I don't understand what this is, or when I need to use it. In fact, the guy who posted it said that self.__dict__['modified'] = 0 had to be done in __init__(), or the __setattr__ he posted, would not work. I tried to go back and find that post, but I couldn't find it. The original poster was talking about cataloging MP3's, so I should go back to Active State and search for MP3, so I can point you to the specific example. Anyway, I was intrigued with the technique, and it works in my program. It may not be an elegant way of coding in Python, but it works. I'd be interested in hearing your thoughts. thanks Tony >If it's the second reason, there might >be an easier way to tackle what you're trying to do. Hmmm... can you tell >us more about the class that you're writing? > > >Good luck! --=====================_23074289==_.ALT Content-Type: text/html; charset="us-ascii"
Hi Danny,


>>Out of curiosity: are you using __setattr__ as an experiment with the
>>language feature, or is there a particular bit of your code that can be
>>improved if you use __setattr__? 


Both, actually.

I've created a class, which for all practical purposes, contains fields such as

class   Address:

        def __init__(self, address_str):

                name    = address_str
                address = address_str
                phone    = address_str


In all actuality, I'm working on a program for work, so I don't want to give out any sensitive information.
However, the concept is the same, the class members have been changed to protect the innocent.

The name, address, phone data is passed to the application, as a colon separated string- like this
Name:Mr Smith;Address:123 Main St;Phone:408-123-4567;

Since I don't want the application to deal with parsing the data, I thought I would experiment with doing it inside the class itself.
It actually seems to work quite well, but it took me awhile to get it working.

My __setattr__() looks like this

       def      __setattr__(self, name, addr_str):

               if name in ['Name', 'Address', 'Phone' ]:
                   name_loc = string.find(value_str, name)
                   if name_loc != -1:
                       pair = string.split(value_str[name_loc:], ';',1)
                       pair1 = string.split(pair[0], ':',1)
                       self.__dict__[name] = pair1[1]
                   else:
                       print"\nname %s NOT found" % name
                       raw_input("\nPAUSED")


After looking through ActiveState, I've found some posts which showed a __setattr__()
that contained this
self.__dict__['modified'] = 1

But I don't understand what this is, or when I need to use it.
In fact, the guy who posted it said that
self.__dict__['modified'] = 0 had to be done in __init__(), or the __setattr__
he posted, would not work.


I tried to go back and find that post, but I couldn't find it.
The original poster was talking about cataloging MP3's, so I should go back to Active State
and search for MP3, so I can point you to the specific example.

Anyway, I was intrigued with the technique, and it works in my program.
It may not be an elegant way of coding in Python, but it works.

I'd be interested in hearing your thoughts.

thanks


Tony






If it's the second reason, there might
be an easier way to tackle what you're trying to do.  Hmmm... can you tell
us more about the class that you're writing?


Good luck!
--=====================_23074289==_.ALT-- From alan.gauld@freenet.co.uk Sun Apr 20 12:51:02 2003 From: alan.gauld@freenet.co.uk (Alan Gauld) Date: Sun Apr 20 11:51:02 2003 Subject: [Tutor] Any good way to read Tutor mails? References: <20030419160006.11951.30477.Mailman@mail.python.org> <1050789181.3ea1c53d6a207@webmail.uchicago.edu> <200304191917.56408.revanna@mn.rr.com> Message-ID: <008901c30754$a6b0d580$6401a8c0@xp> > Are you getting a digest version of the list? > > If so, it's not your mailreader, it's just that you would prefer individual > mails rather than a daily digest. To fix this, you need to reset your > settings on the following question: Hmm, I get the digest in MIME format and it seems to work OK. I get a list of message titles, I can select any one for reading and hit Reply or Reply-All to reply and the subject etc are all copied across ok. That's using Outlook or Outlook Express. (I actually prefer the way OE does it with a simple list over Outlook which gives me a split pane window) OTOH If you are using a web mail client that will depend entirely on how it handles MIME attachments. Alan G. From charlie@begeistert.org Sun Apr 20 13:03:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sun Apr 20 12:03:02 2003 Subject: [Tutor] Any good way to read Tutor mails? In-Reply-To: <20030420092102.12827.73835.Mailman@mail.python.org> References: <20030420092102.12827.73835.Mailman@mail.python.org> Message-ID: <20030420180155.489.1@wonderland.1050853203.fake> > Hi all, > > For a long time I've been wondering how you guys read and reply the py > Tutor emails. Is there any package, any module that can let you read one > specific message and just hit one [reply] button to reply that message to > either the sender or the list? > > The commonly-used email clients seem to fail in this regard, and I have > been bothered by having to cut and paste the message body when replying. Hi pan, In the BeOS the default behaviour of e-mail clients is to include only selected text in an e-mail which makes replying to the digest quite easy: I just mark the message I want to reply to and press reply. It doesn't, however, automatically do reply to all which is how I like to reply to this list. I think Eudora used to be like that but the last time I used it didn't do this any more. I've thought about possible ways of improving things like a tree display: it's quite easy on the BeOS because every e-mail is an individual file. As has already been said it should be quite easy to parse a digest mail (from Mailman) as the separators and many of the headers are kept. So I might come up with something like this for the BeOS. That said this is a very niche OS so it wouldn't have much relevance for other systems which _generally_ use the mbox format. I recently got into trouble on the FreeBSD list which up until recently was Majordomo based because a lot of users depend on the mail-id's for threading in their programs (I think Mutt does this) and digests make a mess of such id's. Someone else is likely to have had a similar idea and possibly come up with a solution. What OS are you using? But if you're using a web-mail client I don't know what can be done other than write your own using the new mail module and HTML to give you internal anchors and possibly multi-part forms. This would be an interesting project and not to difficult I think. Charlie From scott_list@mischko.com Sun Apr 20 15:31:10 2003 From: scott_list@mischko.com (Scott Chapman) Date: Sun Apr 20 14:31:10 2003 Subject: [Tutor] Regular Expression question In-Reply-To: References: Message-ID: <200304201112.10004.scott_list@mischko.com> On Friday 18 April 2003 13:40, Danny Yoo wrote: > > Thanks for the reply. After seeing these replies, it seems clear that > > you can use the grouping ()'s for more than just capturing a section for > > output. > > Hi Scott, > > Yes, the grouping parentheses are serving two functions: they are defining > a group for both capturing values and for aggregation. It appears that the aggregation functions of parenthesis are limited. This does not work: )|([ \t:].+?>) string being what the regex tested: caught: blah> :subtype> tag1 tag2> This doesn't work either: test(r'') Traceback (most recent call last): File "./testre.py", line 19, in ? test(r'') File "./testre.py", line 6, in test mt = re.search(expr, s) File "/usr/lib/python2.2/sre.py", line 137, in search return _compile(pattern, flags).search(string) File "/usr/lib/python2.2/sre.py", line 228, in _compile raise error, v # invalid expression sre_constants.error: unbalanced parenthesis Scott From Janssen@rz.uni-frankfurt.de Sun Apr 20 16:42:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Apr 20 15:42:01 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <200304201112.10004.scott_list@mischko.com> Message-ID: On Sun, 20 Apr 2003, Scott Chapman wrote: > It appears that the aggregation functions of parenthesis are limited. This > does not work: > > )|([ \t:].+?>) Seems to be a point, where re gets very sophisticated ;-) You should try to explain in plain words what this re is expected to do (and each part of it). This often helps to find logical mistakes (Pointer: "ab|c" doesn't look for ab or ac but for ab or c). On the other hand, you should possibly use a different overall design: instead of one very tricky all-purpose regexp you should break your html in first step into tags, then get the type of the tag then the attributes then the values of the attributes (or any order like this). This way, you look for a complete tag and give it to a function to analyse this tag further (look if it match certain conditions or retrieve the content). When I would try to "simply" parse html without a complete htmlParser, I would do it this way. > test(r'') > > > Traceback (most recent call last): ... > sre_constants.error: unbalanced parenthesis []-brackets build a character set. With '[([ \t]*)([ \t:].+?)]' they are simply missused. '(([ \t]*)([ \t:].+?))' is working but a noop for aggregation (not for retrieving values). Michael From billintucson@yahoo.com Sun Apr 20 17:11:01 2003 From: billintucson@yahoo.com (Bill Gillespie) Date: Sun Apr 20 16:11:01 2003 Subject: [Tutor] A finished serial line telemetry, data log file generator program. Thanks for the groups help! Message-ID: <20030420201028.48527.qmail@web11804.mail.yahoo.com> Hi Folks, Thanks much for the help I had a couple of months back on ideas for reading a serial line, and then creating a log file from the data the microcontroller returns via the serail line. Here's the code that's working now: any advice on improvements is always welcome. A question regarding these emails; is this list archived and searchable from some URL? Thanks again, Bill #! /usr/local/bin/python #**********************************************************# # # # 4m OFTC Logging Program, Bill Gillespie, NOAO. # # March 20, 2002 # # # # ********************************************** # # # # This program's basic function is to query and log data # # strings from the 4 meter telescope facilities # # Oil and Floor Temperature Microcontroller. # # # #**********************************************************# #------- Fetch modules ----# #------- the pyserial module had to be installed for this program --# import serial, os, sys, time, string #------- Get Time String ---------------------------------------------------# timenow = time.ctime(time.time()) timenow = timenow[4:25] #-------- Set up the serial line for R/W -------# dev=serial.Serial('/dev/tty***', 4800, 7, 1, timeout=1) dev.flush() #-------- Fetch the main values with oftc device calls ------# dev.write('oftv\r') OFTV = dev.readlines() OFTV = `OFTV` # OFTV converted from object to a string dev.flush() dev.write('osetpoint?\r') Oset = dev.readlines() Oset = `Oset` # Oset is now a string (was object) dev.flush() dev.write('fsetpoint?\r') Fset = dev.readlines() Fset = `Fset` # ditto above dev.flush() #------- Print the TIME string to the log file --------# LogFile = open("/usr/local/gui/oftc/oftc-log-file.txt", "a") LogFile.write("%-22s" % (timenow)) #------- Clean data strings of unwanted characters --------# OFTV = OFTV.replace(","," ") OFTV = OFTV.replace("'"," ") Oset = Oset.replace(","," ") Oset = Oset.replace("'"," ") Fset = Fset.replace(","," ") Fset = Fset.replace("'"," ") #------- Parse strings and print log data to log file -------# OilSetPt = string.split(Oset) # splits the string into list based on white space. LogFile.write("%5s" % OilSetPt[2]) # prints new list item 1,to log file. (OGS, OGR, OSX, OXR, OPR, OSP, AMP, spr, tb1) = string.split(OFTV)[12:21] LogFile.write("%5s %5s %5s %5s %5s %5s %5s %5s %8s" % (OGS, OGR, OSX, OXR, OPR, OSP, AMP, spr, tb1)) FloorSetPt = string.split(Fset) # splits the string into list based on white space. LogFile.write("%5s" % FloorSetPt[2]) # prints new list item 1, to the log file. (FGS, FGR, FT1, FT2, FT3, spr, spr, spr, tb2) = string.split(OFTV)[32:41] LogFile.write("%5s %5s %5s %5s %5s %5s %5s %5s %8s" % (FGS, FGR, FT1, FT2, FT3, spr, spr, spr, tb2)) LogFile.write("\n") LogFile.close() #------- flush and close the serial line --------# dev.flush() dev.close() __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com From dyoo@hkn.eecs.berkeley.edu Sun Apr 20 19:10:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Apr 20 18:10:02 2003 Subject: [Tutor] Using __setattr__ In-Reply-To: <5.1.0.14.0.20030420021138.01b69b48@tcapp.com> Message-ID: > The name, address, phone data is passed to the application, as a colon > separated string- like this > Name:Mr Smith;Address:123 Main St;Phone:408-123-4567; Hi Tony, [Off-topic note: this reminds me a little of the 'bencoding' format that Bittorrent uses to serialize its data: http://bitconjurer.org/BitTorrent/protocol.html ] > Since I don't want the application to deal with parsing the data, I > thought I would experiment with doing it inside the class itself. It > actually seems to work quite well, but it took me awhile to get it > working. > > My __setattr__() looks like this > def __setattr__(self, name, addr_str): > if name in ['Name', 'Address', 'Phone' ]: > name_loc = string.find(value_str, name) > if name_loc != -1: > pair = string.split(value_str[name_loc:], ';',1) > pair1 = string.split(pair[0], ':',1) > self.__dict__[name] = pair1[1] > else: > print"\nname %s NOT found" % name > raw_input("\nPAUSED") Ah, I think I understand now. The code can actually be rewritten to avoid __setattr__ altogether: how about just adding a method called initFromString()? ### def initFromString(self, name, addr_str): if name in ['Name', 'Address', 'Phone' ]: name_loc = string.find(value_str, name) if name_loc != -1: pair = string.split(value_str[name_loc:], ';',1) pair1 = string.split(pair[0], ':',1) setattr(self, name, pair1[1]) else: print"\nname %s NOT found" % name raw_input("\nPAUSED") ### It's not really an adding: it's more like a renaming of your __setattr__() definition. *grin* In many cases, we want to avoid the magical nature of __setattr__(). Renaming it to something nonmagical is one way to make the code simpler. We can call initFromString() with a simple method call, like this: ### s = "Name:Mr Smith;Address:123 Main St;Phone:408-123-4567;" address = Address() address.initFromString('Name', s) address.initFromString('Address', s) address.initFromString('Phone', s) ### Once we have this, we might notice that we may want to initialize all of the values in our attribute from the string at once. So the code reorganization allows us to consider if something like: ### s = "Name:Mr Smith;Address:123 Main St;Phone:408-123-4567;" address = Address() address.initAllFromString(s) ## maybe something like this is a good ## idea... ? ### so that you may not need to explicitely name the attributes that you'd like to set. If you knew all the attributes in advance, there wouldn't be a point to read them dynamically, since we'd be able to do something like: address.Name = lookupValueInString('Name', s) address.Address = lookupValueinString('Address', s) ... which would be easier for a person to read and understand. Modifying __setattr__() can often unnecessarily complicate the definition of a class, because it introduces an intrusive change to the way we initialize our object's attributes. Unless we're doing something really special, we may find it's a good idea to avoid redefining __setattr__() in Python. By the way, Jeff Shannon correctly pointed out that, in most cases, we also don't have to manually futz with __dict__ to add dynamic attributes. http://mail.python.org/pipermail/tutor/2003-April/021815.html I stand properly chastised. *grin* It's often a lot simpler to use the getattr() and setattr() functions. So I've subsituted: self.__dict__[name] = pair1[1] with: setattr(self, name, pair1[1]) so that things look less magical. I hope this helps! From pan@uchicago.edu Sun Apr 20 20:36:39 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Sun Apr 20 19:36:39 2003 Subject: [Tutor] RE: running boa constructor Message-ID: <1050881719.3ea32eb73a75a@webmail-b.uchicago.edu> >Rick Pasotto rick@niof.net >Thu Apr 17 10:34:01 2003 > >I'm running debian/testing and have unzipped boa constructor into >/usr/lib/python2.1/site-packages. When I try to run it with the command line: > >python /usr/lib/python2.1/site-packages/boa-constructor-0.2.0/Boa.py > >I get: > >Starting Boa Constructor v0.2.0 >importing wxPython >Traceback (most recent call last): > File "/usr/lib/python2.1/site-packages/boa-constructor-0.2.0/Boa.py", line 177, in ? > if wxVERSION < __version__.wx_version: >NameError: name 'wxVERSION' is not defined > >What do I have wrong? The newest version of Boa contructor is actually an untested version. There are several of files missing one or more 'import ???' statements, resulting in many "name ???? is not defined" errors. That wastes a lot of time for whoever interested in that package. I believe one of the developers posted a message in one of the related forums, saying that the users have to either use an older version instead, or manully find and add "imports" into 3 different files. But, according to my experiences I caught like 5 missed imports, and the one you mentioned, 'wxVERSION', is not in those I caught. Boa Constructor looks like a wonderful package, I have no idea why those developers didn't want to fix that simple problem, which can be easily solved by adding several imports. I think the only way out is to find where this wxVERSION is defined, and add import whereever it is needed. pan From scott_list@mischko.com Mon Apr 21 01:15:08 2003 From: scott_list@mischko.com (Scott Chapman) Date: Mon Apr 21 00:15:08 2003 Subject: [Tutor] Regular Expression question In-Reply-To: References: Message-ID: <200304202114.33846.scott_list@mischko.com> On Sunday 20 April 2003 12:41, Michael Janssen wrote: > On Sun, 20 Apr 2003, Scott Chapman wrote: > > It appears that the aggregation functions of parenthesis are limited. > > This does not work: > > > > )|([ \t:].+?>) > > Seems to be a point, where re gets very sophisticated ;-) Seems to me to be a point where re fails to get very sophisticated! > You should try to explain in plain words what this re is expected to do > (and each part of it). This often helps to find logical mistakes > (Pointer: "ab|c" doesn't look for ab or ac but for ab or c). This is actually supposed to be quite simple: or [ \t:].+?> I wanted to see if parenthesis would work for grouping in this context. They don't work here. > On the other hand, you should possibly use a different overall design: > instead of one very tricky all-purpose regexp you should break your html > in first step into tags, then get the type of the tag then the attributes > then the values of the attributes (or any order like this). I'm not seriously considering using RE to parse the HTML. I'm already looking into HTMLParser. I don't like it very well but I can make it work. This stuff is to help me learn re at this point. > This way, you look for a complete tag and give it to a function to analyse > this tag further (look if it match certain conditions or retrieve the > content). When I would try to "simply" parse html without a complete > htmlParser, I would do it this way. > > > test(r'') > > > > > > Traceback (most recent call last): > > ... > > > sre_constants.error: unbalanced parenthesis > > []-brackets build a character set. With '[([ \t]*)([ \t:].+?)]' they are > simply missused. '(([ \t]*)([ \t:].+?))' is working but a noop for > aggregation (not for retrieving values). My point in trying this was again to see how useful the parenthesis are for grouping. I understand that []-brackets are used to indicate "one of the contents of the brackets". I'd like to see parenthesis work for grouping on either side of a | (boolean OR indicator) and inside of square brackets to allow selection of one among a group of items in parenthesis; again a boolean OR situation. No go! Oh well. Maybe the language guru's can add it in at some point. I'm not savvy enough about re to know if this is a good idea or not. It would make it possible to do some very nice stuff with re that's currently not this simple. I think it would make re a lot more powerful. Scott From dyoo@hkn.eecs.berkeley.edu Mon Apr 21 02:40:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 21 01:40:02 2003 Subject: [Tutor] Regular Expression question In-Reply-To: <200304202114.33846.scott_list@mischko.com> Message-ID: > > > It appears that the aggregation functions of parenthesis are limited. > > > This does not work: > > > > > > )|([ \t:].+?>) Hi Scott, Let me see if i can decipher this one... *grin* To make this easier on my eyes, I will spread out the regular expression a bit so I see where the groups form. I'll try to break: )|([ \t:].+?>) using some informal indentation. ) | ( [ \t:] .+?> ) ... This actually looks syntactically ok to me! (One note: we can collapse the '[ \t]' parts by using the metacharacter for whitespace, '\s'). Let me try it really fast to see if this does raise that improper indentation error: ### >>> regex = re.compile(r''' ... ... ) ... | ... ( ... [\s:] ... .+? ... )''', re.VERBOSE) >>> regex.match('') <_sre.SRE_Match object at 0x15e740> >>> regex.match('>> regex.match('') ## ?? >>> regex.match('>> regex.match('::::::') ## that's better! <_sre.SRE_Match object at 0x111da0> ### So I'm not getting a unbalanced parentheses error, though I am running into some unexpected behavior with what the pattern recognizes. Ah, I see now. We'll explain that mysterious behavior above in just a moment, so let's dive into the rest of your question. > This is actually supposed to be quite simple: > followed by either: > [ \t]*> > or > [ \t:].+?> Scott, the ORing operator '|' has really low precedence, so if we say something like: )|([ \t:].+?>) Python's regular expression engine is actually breaking it down into ) | ([ \t:].+?>) That is, instead of telling the regex engine this: > followed by either: > [ \t]*> > or > [ \t:].+?> we've actually told it to recognize this instead: > > or > [ \t:].+?> To fix this, we may want to use parentheses (either grouping or non grouping should work) to get that 'either' behavior that you want: ) | ( [ \t:] .+?> ) ) Please feel free to ask more questions on this; regular expressions have a few zaps that we need to be wary of --- the way that the OR operator works is one of those zaps. As you play with regular expressions, you may want to use VERBOSE mode to define them: verbose mode lets us use indentation to make the regex more readable to humans. I hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Apr 21 02:53:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 21 01:53:01 2003 Subject: [Tutor] Using __setattr__ (fwd) Message-ID: Hi Tony, Let me send this off to tutor@python.org too --- this'll let other people jump in when I say something screwy or totally wrong... *grin* > With that in mind, I guess I could call the function you wrote below, > from __init__() ??? Yes! We can send that source string as a parameter to the __init__ method, and have __init__ delegate some of the work off to that hypothetical initWithString() method. Talk to you later! ---------- Forwarded message ---------- Date: Sun, 20 Apr 2003 20:53:32 -0700 From: Tony Cappellini To: Danny Yoo Subject: Re: [Tutor] Using __setattr__ Hi Danny, thanks for the advice. Since this class isn't intended to be derived from, or used by other people/programs, I want the string to be parsed during class instantiation. I also don't want any methods to be called explicitly by the caller. Pass the string in, and that's it. With that in mind, I guess I could call the function you wrote below, from __init__() ??? >The code can actually be rewritten to avoid __setattr__ altogether: how >about just adding a method called initFromString()? > >### > def initFromString(self, name, addr_str): > if name in ['Name', 'Address', 'Phone' ]: > name_loc = string.find(value_str, name) > if name_loc != -1: > pair = string.split(value_str[name_loc:], ';',1) > pair1 = string.split(pair[0], ':',1) > setattr(self, name, pair1[1]) > else: > print"\nname %s NOT found" % name > raw_input("\nPAUSED") >### > >It's not really an adding: it's more like a renaming of your __setattr__() >definition. *grin* In many cases, we want to avoid the magical nature of >__setattr__(). Renaming it to something nonmagical is one way to make the >code simpler. > > >We can call initFromString() with a simple method call, like this: > >### >s = "Name:Mr Smith;Address:123 Main St;Phone:408-123-4567;" >address = Address() >address.initFromString('Name', s) >address.initFromString('Address', s) >address.initFromString('Phone', s) >### > > >Once we have this, we might notice that we may want to initialize all of >the values in our attribute from the string at once. So the code >reorganization allows us to consider if something like: > >### >s = "Name:Mr Smith;Address:123 Main St;Phone:408-123-4567;" >address = Address() >address.initAllFromString(s) ## maybe something like this is a good > ## idea... ? >### > >so that you may not need to explicitely name the attributes that you'd >like to set. If you knew all the attributes in advance, there wouldn't be >a point to read them dynamically, since we'd be able to do something like: > > address.Name = lookupValueInString('Name', s) > address.Address = lookupValueinString('Address', s) > ... > >which would be easier for a person to read and understand. > > >Modifying __setattr__() can often unnecessarily complicate the definition >of a class, because it introduces an intrusive change to the way we >initialize our object's attributes. Unless we're doing something really >special, we may find it's a good idea to avoid redefining __setattr__() >in Python. > > >By the way, Jeff Shannon correctly pointed out that, in most cases, we >also don't have to manually futz with __dict__ to add dynamic attributes. > > http://mail.python.org/pipermail/tutor/2003-April/021815.html > >I stand properly chastised. *grin* It's often a lot simpler to use the >getattr() and setattr() functions. So I've subsituted: > > self.__dict__[name] = pair1[1] > >with: > > setattr(self, name, pair1[1]) > >so that things look less magical. > > >I hope this helps! From dyoo@hkn.eecs.berkeley.edu Mon Apr 21 03:01:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 21 02:01:03 2003 Subject: [Tutor] Speeding up import time In-Reply-To: <5.1.0.14.0.20030419031958.01acd488@smtp.sbcglobal.net> Message-ID: On Sat, 19 Apr 2003, Tony Cappellini wrote: > > > I'm loading the io module, from scipy in one of my programs, as in > > from scipy import io > > This particular module takes 3-5 seconds to load on some of the slower > systems that I use. > Is there anything i can do to improve this import time ? Hi Tony, You may want to chat with the Scientific Python folks about this actually; module importing should probably not take that long, especially if the module has been precompiled into bytecode (as it should be). Also, module importing should be a one-time thing, so as long as you don't have to keep spawning up new instances of Python, you should be ok, as you'll only incur the importing cost once. Now that I looked at it, I see that a lot of the code in scipy looks like C extension modules... I'd definitely ask on the scipy lists for this one; perhaps 'weave' or one of the other modules in scipy has a long startup time? I don't think there's anything casual we can do as users to speed up the import of a C extension module, so we need to chat with the scipy developers for this one. For your convenience, here's a link to the scipy mailing lists: http://www.scipy.org/site_content/MailList I hope that you can find the answers you're looking for. Good luck! From sudhirchauhan1@yahoo.co.in Mon Apr 21 07:03:02 2003 From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=) Date: Mon Apr 21 06:03:02 2003 Subject: [Tutor] SENDING ATTACHMENT USING SMTPLIB In-Reply-To: Message-ID: <20030421100227.99588.qmail@web8203.mail.in.yahoo.com> hi ALL, How i can send a attachment using smtplib. I am able to send plain mails, now my problem is that i want to send an HTML file as an attachemnt. Is this possible? regards, sudhir ________________________________________________________________________ Missed your favourite TV serial last night? Try the new, Yahoo! TV. visit http://in.tv.yahoo.com From mhansen@cso.atmel.com Mon Apr 21 10:41:40 2003 From: mhansen@cso.atmel.com (Mike Hansen) Date: Mon Apr 21 09:41:40 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: <001501c30600$c0b88270$6401a8c0@xp> References: <3EA07458.4080204@cso.atmel.com> <001501c30600$c0b88270$6401a8c0@xp> Message-ID: <3EA3F4D2.3030408@cso.atmel.com> Alan Gauld responded to Mike's question: >>How do you copy files using Python? >> >> > >Finding the right module is one of the hardest bits of learning >Python... >The one you need here is called shutil - obviously! :-)! > Thanks. I didn't think to look at that module. Mike From mhansen@cso.atmel.com Mon Apr 21 10:45:02 2003 From: mhansen@cso.atmel.com (Mike Hansen) Date: Mon Apr 21 09:45:02 2003 Subject: [Tutor] Copy Files, Dates In-Reply-To: References: Message-ID: <3EA3F5AD.6030605@cso.atmel.com> Danny Yoo wrote: >On Fri, 18 Apr 2003, Danny Yoo wrote: > >### > > >>### >> >> >>>>>isDate('April 18, 2003') >>>>> >>>>> >> >> >> >### > >Hmmm... actually, doesn't that look really weird to anyone else? *grin* I >didn't notice it before, but the date that it parsed is totally not right. > > > >Instead of DateTimeFromString, I tried using DateFromString, with slightly >better-but-still-weird values coming from the function. With the >substitution to DateFromString, here's what happens now: > >### > > >>>>isDate('04-18-2003') >>>> >>>> > > > >>>>isDate('February 12, 2002') >>>> >>>> > > > >>>>isDate('Mumbember 12, 2002') >>>> >>>> >0 > > >>>>isDate('1999/03/30') >>>> >>>> >0 > > >>>>isDate('03/30/1999') >>>> >>>> > >### > >So there's something still wacky here... It might make an interesting >project for someone to try improving mx.DateTime.parser.DateFromString to >give better results. > Hmmm..I'll take a close look at mxDate before using it. I'll also explore other solutions to my IsDate() function. Thanks. Mike From KodeKruncherDude@aol.com Mon Apr 21 12:23:01 2003 From: KodeKruncherDude@aol.com (KodeKruncherDude@aol.com) Date: Mon Apr 21 11:23:01 2003 Subject: [Tutor] Possible to compile python to executable binary? Message-ID: <60.2ffafa43.2bd566a1@aol.com> --part1_60.2ffafa43.2bd566a1_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hey, I'm just curious: Is it possible to compile *.py scripts to an executable binary file? If possible, how? Will the machine need python installed for the executable to run? --part1_60.2ffafa43.2bd566a1_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Hey, I'm just curious: Is it possible to compile *.py=20= scripts to an executable binary file? If possible, how? Will the machine nee= d python installed for the executable to run? --part1_60.2ffafa43.2bd566a1_boundary-- From rob@jam.rr.com Mon Apr 21 12:29:01 2003 From: rob@jam.rr.com (Rob Andrews) Date: Mon Apr 21 11:29:01 2003 Subject: [Tutor] Possible to compile python to executable binary? In-Reply-To: <60.2ffafa43.2bd566a1@aol.com> References: <60.2ffafa43.2bd566a1@aol.com> Message-ID: <3EA40F40.6000608@jam.rr.com> KodeKruncherDude@aol.com wrote: > Hey, I'm just curious: Is it possible to compile *.py scripts to an > executable binary file? If possible, how? Will the machine need python > installed for the executable to run? It is indeed possible to create Windows .exe files from Python programs. http://uselesspython.com/newsite/py2exeHOWTO.txt is a not-very-pretty document showing the full glory of the process, including all the links you need to get started. -Rob A. From alan.gauld@blueyonder.co.uk Mon Apr 21 13:53:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Apr 21 12:53:02 2003 Subject: [Tutor] A finished serial line telemetry, data log file generator program. Thanks for the groups help! References: <20030420201028.48527.qmail@web11804.mail.yahoo.com> Message-ID: <00b201c307db$4b6d6a80$6401a8c0@xp> > Here's the code that's working now: any advice on improvements is > always welcome. Looks OK to me Bill. Nice use of comments on code that is inherently less self documenting that usual Python code! To be really picky you could have defined some constants to make it more readable and maintainable instead of some of the "magic numbers" in the serial calls. But there aren't too many for that to be a big problem. > A question regarding these emails; is this list > archived and searchable from some URL? Yes, ActiveState have an archive which can be searched. The Python.org site has archives too but they were not searchable last time I looked. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From a_abdi406@yahoo.com Mon Apr 21 14:33:02 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Mon Apr 21 13:33:02 2003 Subject: [Tutor] about a dictionary use Message-ID: <20030421162757.38543.qmail@web14510.mail.yahoo.com> --0-675989952-1050942476=:35796 Content-Type: text/plain; charset=us-ascii Hi,I have a program that uses a dictionary for indexing, the program reads several files, and and puts the words in the dictionary, after that it uses that dictionary and updates some values and puts in another dictionary: the question is if I want use the last dictionary for searching do I need to store it in a list such as "Shelve" so that I can access lateror I can keep the last dictionary for searching ? below is what have as a code: adict = {} temp = aword.findall(file.lower()) i = -1 #print temp # prints a listfor test #eliminate all stoplist words for word in temp: if word[0] != '<' and word not in stop_list: #print s # prints each word i = i + 1 #add the word tokens and their positions #to dictionary adict.setdefault(word,[]).append(i) nwords = math.log(i + 1) tempDict = {} for word, positions in adict.items(): # coumpute the word frequency frequency = int (100 * (len(positions) / nwords)) # this dictionary puts the keys with multiple variables tempDict.setdefault(word,[]).append(key) tempDict.setdefault(word,[]).append(frequency) tempDict.setdefault(word,[]).append(positions) --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-675989952-1050942476=:35796 Content-Type: text/html; charset=us-ascii
Hi,
I have a program that uses a dictionary for indexing, the program reads several files, and and puts the words in the dictionary, after that it uses that dictionary and updates some values and puts in another dictionary: the question is if I want use the last dictionary for searching do I need to store it in a list such as "Shelve" so that I can access later
or I can keep the last dictionary for searching ? below is what have as a code:
 
adict = {}
        temp = aword.findall(file.lower())
        i = -1
        #print temp # prints a listfor test  #eliminate all stoplist words
        for word in temp:
            if word[0] != '<' and word not in stop_list:
                  
                    #print s # prints each word
                    i = i + 1     
                    #add the word tokens and their positions
                    #to dictionary
                    adict.setdefault(word,[]).append(i)
 
          nwords = math.log(i + 1)
          tempDict = {}

        for word, positions in adict.items():               
            # coumpute the word frequency
            frequency = int (100 * (len(positions) / nwords))
           
            # this dictionary puts the keys with multiple variables
            tempDict.setdefault(word,[]).append(key)
            tempDict.setdefault(word,[]).append(frequency)
            tempDict.setdefault(word,[]).append(positions)



Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-675989952-1050942476=:35796-- From alan.gauld@freenet.co.uk Mon Apr 21 15:58:10 2003 From: alan.gauld@freenet.co.uk (Alan Gauld) Date: Mon Apr 21 14:58:10 2003 Subject: [Tutor] Possible to compile python to executable binary? References: <60.2ffafa43.2bd566a1@aol.com> Message-ID: <00d001c30837$f66f0400$6401a8c0@xp> > Hey, I'm just curious: Is it possible to compile *.py scripts to an > executable binary file? Yes. There are at least 2 tools, the best known is py2exe. > Will the machine need python installed for the executable to run? Yes, but the binary file will include the python interpreter inside so you don't need to install python separately. OTOH if you distribute many of these binaries you effectively wind up with multiple copies of Python on your PC... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From csmith@blakeschool.org Mon Apr 21 17:55:01 2003 From: csmith@blakeschool.org (Christopher Smith) Date: Mon Apr 21 16:55:01 2003 Subject: [Tutor] urlopen object and read() method Message-ID: I submitted the following to sourceforge regarding the failure of the read() method on a urllib object to read until the EOF (unless it is my failure to understand how this works): In the 2.2.2 docs on http://python.org/doc/current/lib/module-urllib.html it says that the object returned by urlopen supports the read()method and that this and other methods "have the same interface as for file objects -- see section 2.2.8". In that section on page http://python.org/doc/current/lib/bltin-file-objects.html it says about the read() method that "if the size argument is negative or omitted, [read should] read all data until EOF is reached." I was a bit surprised when a project that students of mine were working on were failing when they tried to process the data obtained by the read() method on a connection made to a web page. The problem, apparently, is that the read may not obtain all of the data requested in the first request and the total response has to be built up someting like follows: import urllib c=urllib.urlopen("http://www.blakeschool.org") data = '' while 1: packet=c.read() if packet == '': break data+=packet I'm not sure if this is a feature or a bug. Could a file's read method fail to obtain the whole file in one read(), too? It seems that either the documentation should be changed or the read() method for at least urllib objects should be changed. /c Christopher P. Smith The Blake School Minneapolis, MN From dyoo@hkn.eecs.berkeley.edu Mon Apr 21 18:04:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 21 17:04:01 2003 Subject: [Tutor] Regular Expression question [character classes will quote their contents!] In-Reply-To: <200304202114.33846.scott_list@mischko.com> Message-ID: > > > test(r'') Hi Scott, If you're trying to use brackets as grouping operators, that's the problem. The brackets '[' and ']' are meant to define character classes, so the brackets here: test(r'') ^ ^ are very ambiguous to me. > My point in trying this was again to see how useful the parenthesis are > for grouping. I understand that []-brackets are used to indicate "one > of the contents of the brackets". Here are some examples of character classes: [aeiou] [ \t\n] [()] And that last example is supposed to illustrate a particular feature of character classes: they escape the normal meaning of the special regular expression characters! Character classes are shorthand, and use their own rules for what they treat as special. Let's see what the last case will recognize: ### >>> import re >>> regex = re.compile("[()]+") >>> regex.match("(()()()(((())((())())()") <_sre.SRE_Match object at 0x81680d8> >>> regex.match("foo") >>> ### And now we've just written a regular expression to recognize literal parentheses. *grin* This is probably one of the main problems that you've been running into. The reason that they're "shorthand" is because we don't need them: we can just as easily write something like: (a|e|i|o|u) instead of [aeiou] Using the character class is easier to type, but you have to be aware that its shortcut nature turns on a few more rules that will conflict with what you already know about regular expressions. For example, hyphens in a character class will specify a "range" of characters: [a-z] # (a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z) And things that used to be special (like '.', '+', or '(') are treated as literal characters in a character class. In essense, character classes are a shortcut to let us not have to type so much. > I'd like to see parenthesis work for grouping on either side of a | > (boolean OR indicator) Sounds ok so far. > and inside of square brackets to allow selection of one among a group of > items in parenthesis; And that's the part that probably won't work the way you expect, precisely because the parentheses themselves will be treated as one of the characters in the character class. To get the effect that you want, we can do is something like this: ( [aeiou] | [0123456789] ) "Either a vowel, or a digit." Note that trying something like: ### regex = re.compile("[(aeiou)|(0123456789)]") ### does NOT have the same meaning, since the parentheses themselves (as well as the '|' symbol) end up being part of the character class. ### >>> regex.match('|') <_sre.SRE_Match object at 0x8125fd0> >>> regex.match('a') <_sre.SRE_Match object at 0x8125a58> >>> regex.match('f') ### If we wanted to choose either a vowel or a digit, it's probably easiest just to say: [aeiou0-9] in a single character class. > It would make it possible to do some very nice stuff with re that's > currently not this simple. I think it would make re a lot more > powerful. Regular expressions are powerful, tremendously so. The problem is that they are not necessarily easy for humans to express them properly the first time. *grin* Play around with them a little more, and you should get the hang of them. Please feel free to ask more questions here on Tutor. Good luck! From dyoo@hkn.eecs.berkeley.edu Mon Apr 21 18:26:51 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 21 17:26:51 2003 Subject: [Tutor] Regular Expression question In-Reply-To: Message-ID: On Sun, 20 Apr 2003, Michael Janssen wrote: > > It appears that the aggregation functions of parentheses are limited. > > This does not work: > > > > )|([ \t:].+?>) > > Seems to be a point, where re gets very sophisticated ;-) > > You should try to explain in plain words what this re is expected to do > (and each part of it). This often helps to find logical mistakes > (Pointer: "ab|c" doesn't look for ab or ac but for ab or c). And if it helps, think of consecutive characters as multiplication, and the '|' symbol as addition. That is, regex math --------------------------------- ab|c <==> ab + c Your algebraic training should kick in at this point. *grin* ab|ac <==> ab + ac a(b|c) <==> a(b + c) <==> ab + ac This is what we are trying to say when we mention "precedence". In mathematical expressions, multiplication "binds" more tightly than addition. In regular expressions, concatenation (adjacent characters) "binds" more tightly than alternation (the '|' operator). In both cases, we can use parentheses to override the default way that that things bind together. From alan.gauld@blueyonder.co.uk Mon Apr 21 21:05:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Apr 21 20:05:01 2003 Subject: [Tutor] SENDING ATTACHMENT USING SMTPLIB References: <20030421100227.99588.qmail@web8203.mail.in.yahoo.com> Message-ID: <00d901c30838$339ace40$6401a8c0@xp> > How i can send a attachment using smtplib. I am > able to send plain mails, now my problem is that i > want to send an HTML file as an attachemnt. There is a MIME module, but whether that allows encoding of messages as well as decoding I don't know. RTFM to find out I guess. Alan G From hsiehson5@yahoo.com Mon Apr 21 21:05:10 2003 From: hsiehson5@yahoo.com (Y.T. H.) Date: Mon Apr 21 20:05:10 2003 Subject: [Tutor] Fwd: Please read Message-ID: <20030421235841.95918.qmail@web21308.mail.yahoo.com> --0-1543795895-1050969521=:95588 Content-Type: text/plain; charset=us-ascii Content-Id: Content-Disposition: inline Note: forwarded message attached. __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com --0-1543795895-1050969521=:95588 Content-Type: message/rfc822 Received: from [203.88.228.174] by web21302.mail.yahoo.com via HTTP; Sat, 19 Apr 2003 17:40:52 PDT Date: Sat, 19 Apr 2003 17:40:52 -0700 (PDT) From: "Y.T. H." Subject: Please read To: tutor@python.org MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Length: 965 Dear Sir/Madam, This is Andy...again...if you don't remember, I am the one who have asked you about a few questions regarding to programming, from my excercise....I just want to say sorry for what I did and please believe I didn't mean it...(I was just try to get them done, with much more secure answers from program expert like you)...I believe I must been caused some unhappiness to everyone there, since the tutors have passed my email to every other tutor...Please may you be so kind to forward my apology to every tutors...I understand what I have done wrong here and alot of thanks to some tutors, even though they were not very happy about my email, but they still gave me some leading questions to guide me to think more about the questions.... Once again, Sorry and thank you...and Happy Easter. Sincerely Andy YT H __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com --0-1543795895-1050969521=:95588-- From carroll@tjc.com Tue Apr 22 04:05:03 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Apr 22 03:05:03 2003 Subject: [Tutor] My first contribution Message-ID: I've been playing with Python for about 4 months now. Thanks to the various members of this list who have patiently explained some concepts of the language to me. It took, I guess, because I've now made my first (admittedly trivial) contribution to Python. When I first used nntplib, it bothered me that all the newsgroup headers retrieved by nntplib.xover() were placed in a list all at once. I would have preferred it if they could be passed back to the caller as they were received. For one thing, if there are a lot of headers, it can potentially take up a lot of memory. For another, it might take a lot of time, and it would be nice to be able to indicate to the user that there is some progress going on. At the same time, someone on comp.lang.python was making the same observation; he'd had memory constraint issues on small systems when retrieving a lot of headers. So, I modified nntplib to write the headers to a file or to an open file object. By making a class a subclass of a file object, you could replace the write() method with your own method, and examine the headers to decide which you wanted to keep, provide a progess message, whatever. I then expanded this to support all multi-line outputs from nntplib (I figure, what I want for XOVER, someone else could want for some other NNTP command), and turned it into a patch (720468), which I submitted. It's been accepted, so some day this will be a standard part of Python (2.4?). (The patch really was trivial, because a previous patcher, Travers Naran, really did all the hard work, by putting in similar support for the nntplib.body() method; all I had to do was generalize it to the other methods.) I've never had the opportunity to contribute to an open source project before. Feels good, even if it is a trivial patch. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From shad@mail.kubtelecom.ru Tue Apr 22 07:46:45 2003 From: shad@mail.kubtelecom.ru (Denis Dzyubenko) Date: Tue Apr 22 06:46:45 2003 Subject: [Tutor] matrix operations and 3d drawings Message-ID: <87n0iihkxs.fsf@mail.kubtelecom.ru> Hello, everyone Can you help me with the following: I have a matrix (3x3, for example) and a vector (i.e. 3x1 matrix), I want to multiply them, and the resulting vector I want to draw on screen. In other words, I need function to multiply two matrixes, function to get calculate determinant and rank of matrix, and function to draw 3d line. Is it possible to do this in python? -- Denis. P.S. I am newbie in python-programming. P.P.S. Sorry for my english, it is not my native language. From knguyen@seri.co.uk Tue Apr 22 07:51:03 2003 From: knguyen@seri.co.uk (Khai Nguyen) Date: Tue Apr 22 06:51:03 2003 Subject: [Tutor] a serial communication program Message-ID: <341710540F08E34498A057DEE04DAAD70D4B07@ex1.seri.co.uk> This is a multi-part message in MIME format. ------_=_NextPart_001_01C308BC.B6E4548B Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi all, =20 I have used python for around 4 months and have used its feature directory,= list, etc. for writing small programmes for my daily use .. Since a mont= h I have started studying PYTHONCARD and am very impressed. I have never r= eached that far in other language in such a short term.=20 =20 I like to use Python to rewrite a terminal program written on window2000. F= or this application a simultaneous activation of both serial ports is requi= red. Data communication on the two ports are independent. =20 Could you give me some idea which way is the easiest to tackle this problem= . Is there any serial module library I can use directly for this purpose?= =20 Kind regards =20 Khai Nguyen . ------_=_NextPart_001_01C308BC.B6E4548B Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi all,

 <= /span>

I have used python for around 4 months and have used its feature dir= ectory, list, etc. for writing small programmes for my daily use   .. Since a month I have started studying PYTHONCARD and am very impressed.  I have never reached that far in other language in such a short term. =

 <= /span>

I like to use Python to rewrite a terminal program written on window= 2000. For this application a simultaneous activation of both serial ports is requ= ired. Data communication on the two ports are independent.

 <= /span>

Could you give me some idea which way is the easiest to tackle this problem. Is there any serial module library I can use directly for this purpose?

 <= /span>

Kind regards

 <= /span>

Khai Nguyen



.
------_=_NextPart_001_01C308BC.B6E4548B-- From apb_444@yahoo.com Tue Apr 22 08:58:05 2003 From: apb_444@yahoo.com (Antony Benjamin) Date: Tue Apr 22 07:58:05 2003 Subject: [Tutor] Re:a serial communication program Message-ID: <20030422173001.448182f6.apb_444@yahoo.com> > Khai Nguyen wrote >I like to use Python to rewrite a terminal program written on window2000. For > this application a simultaneous activation of both serial ports is required. > Data communication on the two ports are independent. Could you give me some > idea which way is the easiest to tackle this problem. Is there any serial > module library I can use directly for this purpose? You may use the serial module or pyserial module http://pyserial.sourceforge.net/ I think the above link will be useful to you Please don't send html mails.It is inconvenient for some With rgds, Antony From pan@uchicago.edu Tue Apr 22 13:14:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Tue Apr 22 12:14:01 2003 Subject: [Tutor] Re: a serial communication program In-Reply-To: <20030422105103.31220.42143.Mailman@mail.python.org> References: <20030422105103.31220.42143.Mailman@mail.python.org> Message-ID: <1051028005.3ea56a25be2d7@webmail-b.uchicago.edu> Some links: Universal Serial Port Library http://balder.prohosting.com/ibarona/en/python/uspp/uspp_en.html A finished serial line telemetry http://mail.python.org/pipermail/tutor/2003-April/021922.html And lots more: http://groups.google.com/groups?group=comp.lang.python.*&q=serial HTH. pan From dyoo@hkn.eecs.berkeley.edu Tue Apr 22 15:20:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 22 14:20:02 2003 Subject: [Tutor] matrix operations and 3d drawings In-Reply-To: <87n0iihkxs.fsf@mail.kubtelecom.ru> Message-ID: On Tue, 22 Apr 2003, Denis Dzyubenko wrote: > I have a matrix (3x3, for example) and a vector (i.e. 3x1 matrix), I > want to multiply them, and the resulting vector I want to draw on > screen. > > In other words, I need function to multiply two matrixes, function to > get calculate determinant and rank of matrix, and function to draw 3d > line. Is it possible to do this in python? Hi Denis, For the matrix stuff, see Numeric Python: http://www.pfdubois.com/numpy/ I'm positive that it has functions for doing Matrix calculations like determinant and rank stuff. For 3d stuff, you have a few choices, and you can find out about them from the Vaults of Parnassus: http://www.vex.net/parnassus/ http://py.vaults.ca/parnassus/apyllo.py/302299380 In particular, you may want to check out VPython: http://vpython.org/ I haven't had too much experience with VPython myself, but I've heard that it's a very nice module for doing visualization and 3d stuff. You can look at one concrete application of Numeric Python and VPython: Arthur Siegel's 'PyGeo' project applies both modules to spectacular effect: http://home.netcom.com/%7Eajs/index.html I hope this helps! From zmerch@30below.com Tue Apr 22 16:58:09 2003 From: zmerch@30below.com (Roger Merchberger) Date: Tue Apr 22 15:58:09 2003 Subject: [Tutor] Clipboarding... Message-ID: <5.1.0.14.2.20030422152622.025458d0@mail.30below.com> Okay -- I guess my last question was prolly too general/vague or something, as I didn't get any responses... No matter. I plinkered around with things, said "forget the class stuff for now," plinkered around a bit more, and got my script working... ;-) Now, here's my question(s): I've done quite o'bit of googling around for how to work the clipboard, and I finally stumbled across a win32clipboard module for Python, and I got it working. However, I was also hoping for my proggie to be cross-platform compatible with Linux (and maybe MacOS, for others that might want to run my utility) -- is there cross-platform compatible clipboard Python modules out there, or will I have to have a seperate version for each ported OS? =-= and while I'm here ;-) =-= I haven't googled much for this, but while I've bent everyone's ear... I've found (or been directed towards) good tutorials on Python and on the Tkinter module... but is there a good beginner's tutorial on the OOP and class areas of Python? This is where I need the most help -- I've been a Basic/Perl/APL/Cobol/etc/etc/etc hack for years... but I've done *very* little with classes and OOP programming; and I think Python might be the language to change that... but _Programming Python_ was rather "steep" for me, altho I did read most of it, but the way it bounced in and out of OOP / Classless / Global modes, I'm more confused now than less... Any pointers on this would be greatly appreciated... Thanks! Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- sysadmin, Iceberg Computers zmerch@30below.com What do you do when Life gives you lemons, and you don't *like* lemonade????????????? From alan.gauld@blueyonder.co.uk Tue Apr 22 18:14:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue Apr 22 17:14:01 2003 Subject: [Tutor] My first contribution References: Message-ID: <005d01c30914$162ba1e0$6401a8c0@xp> > command), and turned it into a patch (720468), which I submitted. It's > been accepted, so some day this will be a standard part of Python (2.4?). Way to go! One up on me - I've never had a submission accepted (and only tried twice!) in over 15 years of programming with open source software. Alan g From wolf_binary@hotmail.com Tue Apr 22 22:41:02 2003 From: wolf_binary@hotmail.com (Cameron Stoner) Date: Tue Apr 22 21:41:02 2003 Subject: [Tutor] Fwd: Please read Message-ID: Hi all, I have been kinda out of it with the tutor, but this person sent me an email and if you would explain what this is all about. thanks, Cameron >From: "Y.T. H." >To: tutor@python.org >Subject: [Tutor] Fwd: Please read >Date: Mon, 21 Apr 2003 16:58:41 -0700 (PDT) > > >Note: forwarded message attached. > > >__________________________________________________ >Do you Yahoo!? >The New Yahoo! Search - Faster. Easier. Bingo >http://search.yahoo.com ><< message3.txt >> _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From hsteiger@comcast.net Wed Apr 23 02:33:01 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Wed Apr 23 01:33:01 2003 Subject: [Tutor] List element with replace Message-ID: <000501c304d4$c547a2d0$0201a8c0@eagle> To All: What am I doing wrong with this code? For some reason, I get the error below when trying to remove the "|" character from an existing line of numbers stored in a list element. First in line 2, I remove the x/n from the numbers that are stored in the list element by using the "split" method. Then mexT[0] will contain "74| 51 79| 41 60|" as verified with the output using the print statement in line 4. So far so good. But in line 5, I attempt to remove the "|" character from the line of numbers by using the "replace" method, and hopefully store this result back into mexT[0], but that nasty error occurs below about "list object has no attribute replace." line 1 >>> mexT[0] = "x/n 74| 51 79| 41 60|" line 2 >>> mexT[0] = mexT[0].split()[1:] line 3 >>> print mexT[0] line 4 >>> ['74|', '51', '79|', '55', '79|'] line 5 >>> mexT[0] = mexT[0].replace("|", "") Traceback (most recent call last): File "", line 1, in ? mexT[0] = mexT[0].replace("|", "") AttributeError: 'list' object has no attribute 'replace' >>> Yet, if I use a variable instead of a list element, say "s" and use in place of mexT[0], no error occurs. Example: s = "74| 51 79| 41 60|" s = s.replace("|", "") print s 74 51 79 41 60 How does one use a list element with the replace method as in the example above? Thanks much. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From bkd@graphnet.com Wed Apr 23 04:06:00 2003 From: bkd@graphnet.com (bkd) Date: Wed Apr 23 03:06:00 2003 Subject: [Tutor] looping through and comparing lists of dictionaries Message-ID: <01ee01c30966$8c40ff90$5102020a@graphnet.com> I have two lists of dictionaries. One is freshly downloaded from a telnet screenscrape, the other is read from a file that's a snapshot of the last screenscrape: olddata=[{'name':'Betty','hair':'Blonde','role':'Student'}, {'name':'Veronica','hair':'Brunette','role':'Student'}, {'name':'Maryann','hair':'Brunette','role':'Castaway'}, {'name':'Ginger','hair':'Redhead','role':'Castaway'}, {'name':'Jeanne','hair':'Blond','role':'Genie'}, {'name':'Serena','hair':'Brunette','role':'Genie'}, {'name':'Samantha','hair':'Blond','role':'Witch'}] newdata=[{'name':'Betty','hair':'Redhead','role':'Student'}, {'name':'Veronica','hair':'Redhead','role':'Student'}, {'name':'Maryann','hair':'Brunette','role':'Castaway'}, {'name':'Ginger','hair':'Redhead','role':'Castaway'}, {'name':'Jeanne','hair':'Blond','role':'Genie'}, {'name':'Serena','hair':'Brunette','role':'Genie'}, {'name':'Samantha','hair':'Redhead','role':'Witch'}] I want to find all the girls who have dyed their hair red since the last time I checked. I start by running a loop that pulls all the names of all the Redheads into a list: redheads=[] for girl in range(len(newdata)): if newdata[girl]['hair']=='Redhead': redheads.append(newdata[girl]['name']) this gives me: ['Betty','Veronica','Ginger','Samantha'] for redheads. Now, I need to check olddata to see if any of these girls were redheads, and eliminate them from the list. What I have now is this: for girl in range(len(redheads)): if len(redheads)==0: break else: for line in range(len(olddata)): if len(redheads)==0: break elif olddata[line]['name']<>redheads[girl]: pass elif olddata[line]['hair']=='Redhead': del redheads[girl] But this breaks with an 'index out of range' error. The lesson being, do not mess with the list you're indexing over, make a copy and mess with the copy. But still, I can't help but think there must be a better way to do this. Any suggestions where I should look first? Learning Python and the online documentation seem fairly anemic when it comes to showing how to really wield dictionaries with power, and the Python Cookbook seems to assume one has a bit more knowledge about the language than the bundled docs provide... bkd From emil@lysator.liu.se Wed Apr 23 06:37:07 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Wed Apr 23 05:37:07 2003 Subject: [Tutor] List element with replace In-Reply-To: <000501c304d4$c547a2d0$0201a8c0@eagle> (Henry Steigerwaldt's message of "Thu, 17 Apr 2003 06:30:37 -0500") References: <000501c304d4$c547a2d0$0201a8c0@eagle> Message-ID: <87ist5imhm.fsf@i110.ryd.student.liu.se> Henry Steigerwaldt writes: > To All: > > What am I doing wrong with this code? For some > reason, I get the error below when trying to remove > the "|" character from an existing line of numbers stored > in a list element. > > First in line 2, I remove the x/n from the numbers that > are stored in the list element by using the "split" method. > Then mexT[0] will contain "74| 51 79| 41 60|" as > verified with the output using the print statement in line 4. > So far so good. > > But in line 5, I attempt to remove the "|" character from the > line of numbers by using the "replace" method, and hopefully > store this result back into mexT[0], but that nasty error > occurs below about "list object has no attribute replace." > > line 1 >>> mexT[0] = "x/n 74| 51 79| 41 60|" > line 2 >>> mexT[0] = mexT[0].split()[1:] > line 3 >>> print mexT[0] > line 4 >>> ['74|', '51', '79|', '55', '79|'] > line 5 >>> mexT[0] = mexT[0].replace("|", "") > > Traceback (most recent call last): > File "", line 1, in ? > mexT[0] = mexT[0].replace("|", "") > AttributeError: 'list' object has no attribute 'replace' >>>> > > Yet, if I use a variable instead of a list element, say "s" and > use in place of mexT[0], no error occurs. > > Example: s = "74| 51 79| 41 60|" > s = s.replace("|", "") > print s > 74 51 79 41 60 > > How does one use a list element with the replace method as in the > example above? It could be done with a for loop or list comprehension: >>> for i in range(len(mexT[0])): ... mexT[0][i] = mexT[0][i].replace("|", "") or >>> mexT[0] = [ i.replace("|", "") for i in mexT[0] ] Another option is to first convert the list back to a string with the join method: >>> mexT[0] = " ".join(mexT[0]) /Emil > Thanks much. > > Henry Steigerwaldt > Hermitage, TN > Email: hsteiger@comcast.net > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From Don Arnold" Message-ID: <087e01c30987$821205c0$a310ba3f@defaultcomp> ----- Original Message ----- From: "bkd" To: Sent: Wednesday, April 23, 2003 2:04 AM Subject: [Tutor] looping through and comparing lists of dictionaries > I have two lists of dictionaries. One is freshly downloaded from a telnet > screenscrape, the other is read from a file that's a snapshot of the last > screenscrape: > > olddata=[{'name':'Betty','hair':'Blonde','role':'Student'}, > {'name':'Veronica','hair':'Brunette','role':'Student'}, > {'name':'Maryann','hair':'Brunette','role':'Castaway'}, > {'name':'Ginger','hair':'Redhead','role':'Castaway'}, > {'name':'Jeanne','hair':'Blond','role':'Genie'}, > {'name':'Serena','hair':'Brunette','role':'Genie'}, > {'name':'Samantha','hair':'Blond','role':'Witch'}] > > newdata=[{'name':'Betty','hair':'Redhead','role':'Student'}, > {'name':'Veronica','hair':'Redhead','role':'Student'}, > {'name':'Maryann','hair':'Brunette','role':'Castaway'}, > {'name':'Ginger','hair':'Redhead','role':'Castaway'}, > {'name':'Jeanne','hair':'Blond','role':'Genie'}, > {'name':'Serena','hair':'Brunette','role':'Genie'}, > {'name':'Samantha','hair':'Redhead','role':'Witch'}] > > I want to find all the girls who have dyed their hair red since the last > time I checked. I start by running a loop that pulls all the names of all > the Redheads into a list: > > redheads=[] > for girl in range(len(newdata)): > if newdata[girl]['hair']=='Redhead': > redheads.append(newdata[girl]['name']) > > this gives me: > ['Betty','Veronica','Ginger','Samantha'] > for redheads. > > Now, I need to check olddata to see if any of these girls were redheads, and > eliminate them from the list. > > What I have now is this: > > for girl in range(len(redheads)): > if len(redheads)==0: break > else: > for line in range(len(olddata)): > if len(redheads)==0: break > elif olddata[line]['name']<>redheads[girl]: pass > elif olddata[line]['hair']=='Redhead': del redheads[girl] > > But this breaks with an 'index out of range' error. The lesson being, do not > mess with the list you're indexing over, make a copy and mess with the copy. > > But still, I can't help but think there must be a better way to do this. Any > suggestions where I should look first? Learning Python and the online > documentation seem fairly anemic when it comes to showing how to really > wield dictionaries with power, and the Python Cookbook seems to assume one > has a bit more knowledge about the language than the bundled docs provide... > > bkd > Why not just check the old hair color before adding to the redheads list? redheads = [] for newgirl in newdata: if newgirl['hair'] == 'Redhead': for oldgirl in olddata: if oldgirl['name'] == newgirl['name']: if oldgirl['hair'] != 'Redhead': print '%s used to be a %s' % (newgirl['name'], oldgirl['hair']) redheads.append(newgirl) break print redheads --output-- Betty used to be a Blonde Veronica used to be a Brunette Samantha used to be a Blond [{'hair': 'Redhead', 'role': 'Student', 'name': 'Betty'}, {'hair': 'Redhead', 'role': 'Student', 'name': 'Veronica'}, {'hair': 'Redhead', 'role': 'Witch', 'name': 'Samantha'}] --end output-- Also, since Python's for statement iterates over a collection, it's often cleaner to iterate directly over your list/tuple instead of using range( ) and then indexing into it. HTH, Don From stuart_clemons@us.ibm.com Wed Apr 23 08:43:02 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 23 07:43:02 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file Message-ID: Hi all: I have two files, file1.txt and file 2. txt, each containing numbers. I want to compare the numbers in the files and put an asterisk at the end of the numbers that match, writing the result into a third file, . Hopefully the following illustrates what I'm trying to do: File1.txt 1 3 4 File2.txt 1 2 3 4 5 The result after my slick Python program: File3.txt 1 * 2 3 * 4 * 5 I've tried various combinations of opening the files and 'if' nests, but I can't seem to get it right. Any hints on what structure to use. Thanks in advance. ----- Forwarded by Stuart Clemons/Westford/IBM on 04/23/03 07:30 AM ----- Stuart Clemons To: tutor@python.org 06/06/02 01:57 PM cc: Subject: Reading & printing lines from two different files Hi all: I have two files, file1 and file2. I want to print the first line from file1, then the first line from file2, then the second line from file 1, then the second line from file 2, etc. Here are my files and what the output should look like: File1.txt First line file 1 Second line file 1 Third line file 1 File2.txt First line file 2 Second line file 2 Third line file 3 This is the output I want when the program is run: First line file 1 First line file 2 Second line file 1 Second line file 2 Third line file 1 Third line file 2 I've tried different looping techniques mainly using variations of the structure below, but I can't seem to get the output I want. Any suggestions ? Thanks. infile1 = open('c:\file1.txt', 'r') infile2 = open ('c:\file2.txt', 'r') for line1 in infile1.readlines(): print line1 for line2 in infile2.readlines() print line2 From R. Alan Monroe" References: Message-ID: <166565895524.20030423081335@columbus.rr.com> > I have two files, file1.txt and file 2. txt, each containing numbers. I > want to compare the numbers in the files and put an asterisk at the end of > the numbers that match, writing the result into a third file, . Are the input files always going to be sorted? Alan From stuart_clemons@us.ibm.com Wed Apr 23 09:16:48 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 23 08:16:48 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file Message-ID: Yes, that's the good news ! The input files will always be sorted. Thanks. "R. Alan Monroe" cc: tutor@python.org Subject: Re: [Tutor] Comparing lines in two files, writing result into a third file 04/23/03 08:13 AM Please respond to "R. Alan Monroe" > I have two files, file1.txt and file 2. txt, each containing numbers. I > want to compare the numbers in the files and put an asterisk at the end of > the numbers that match, writing the result into a third file, . Are the input files always going to be sorted? Alan From Bruce Dykes" <087e01c30987$821205c0$a310ba3f@defaultcomp> Message-ID: <02d301c30998$3234dcb0$5102020a@graphnet.com> ----- Original Message ----- From: "Don Arnold" To: "bkd" ; Sent: Wednesday, April 23, 2003 07:00 Subject: Re: [Tutor] looping through and comparing lists of dictionaries > Why not just check the old hair color before adding to the redheads list? > > redheads = [] > > for newgirl in newdata: > if newgirl['hair'] == 'Redhead': > for oldgirl in olddata: > if oldgirl['name'] == newgirl['name']: > if oldgirl['hair'] != 'Redhead': > print '%s used to be a %s' % (newgirl['name'], > oldgirl['hair']) > redheads.append(newgirl) > break > > print redheads > > --output-- > > Betty used to be a Blonde > Veronica used to be a Brunette > Samantha used to be a Blond > [{'hair': 'Redhead', 'role': 'Student', 'name': 'Betty'}, {'hair': > 'Redhead', 'role': 'Student', 'name': 'Veronica'}, {'hair': 'Redhead', > 'role': 'Witch', 'name': 'Samantha'}] > > --end output-- I was thinking that might take too long, but I didn't realize the second loop would *only* be called if the test for Redheadedness was true...I first thought I would be iterating through the old list for every entry in the new list, so I thought to go with creating the list of Redheads first, and using that as the check. But then, the big timesink in this script is the telnet session. Mucho thanks. > Also, since Python's for statement iterates over a collection, it's often > cleaner to iterate directly over your list/tuple instead of using range( ) > and then indexing into it. When I was first starting with Python, that didn't work in some of my scripts, while the range(len()) construct did, so that's just a habit I've since fallen into... Bruce From Janssen@rz.uni-frankfurt.de Wed Apr 23 11:54:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Apr 23 10:54:02 2003 Subject: [Tutor] looping through and comparing lists of dictionaries In-Reply-To: <01ee01c30966$8c40ff90$5102020a@graphnet.com> Message-ID: On Wed, 23 Apr 2003, bkd wrote: > But this breaks with an 'index out of range' error. The lesson being, do not > mess with the list you're indexing over, make a copy and mess with the copy. > > But still, I can't help but think there must be a better way to do this. Any > suggestions where I should look first? Learning Python and the online > documentation seem fairly anemic when it comes to showing how to really > wield dictionaries with power, and the Python Cookbook seems to assume one > has a bit more knowledge about the language than the bundled docs provide... cool, it works: people does learn things like not manipulate lists while iterating about :-) Beside what Don Arnold have already contributed: Why store the dicts into a list? Lists are used when order must be maintained or you want to sort (and it is not simple to sort a list of dict). If both aspects don't occour, you should use a dict of dict. This way you gain much easier lookups: olddata={'Betty': {'hair':'Blonde','role':'Student'}, 'Veronica': {'hair':'Brunette','role':'Student'}, 'Maryann': {'hair':'Brunette','role':'Castaway'}, 'Ginger': {'hair':'Redhead','role':'Castaway'}, 'Jeanne': {'hair':'Blond','role':'Genie'}, 'Serena': {'hair':'Brunette','role':'Genie'}, 'Samantha': {'hair':'Blond','role':'Witch'}, } and the same for nowdata new_redhead = [] for name in newdata.keys(): if newdata[name]['hair'] == 'Redhead' and \ olddata[name]['hair'] != 'Redhead': new_redhead.append(name) in case your data comes indeed sorted-by-name and you want maintain the order with a list, it's even more simple: for old, new in zip(olddata, newdata): if new['hair'] == 'Redhead' and \ olddata['hair'] != 'Redhead': new_redhead.append(new['name']) Michael > From a_abdi406@yahoo.com Wed Apr 23 12:03:03 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Apr 23 11:03:03 2003 Subject: [Tutor] help for implementation.......... Message-ID: <20030423150255.28342.qmail@web14506.mail.yahoo.com> --0-1948235366-1051110175=:27221 Content-Type: text/plain; charset=us-ascii Hi,I was trying to implement a program that indexes documents and incorporates Document frequency (df): i.e. The number of documents that the term occurs in,the list of documents containing the term, and term frequency (tf): The number of times that the term occurs in each document. I have started something I would appreciate if someonewith information retrievial can give me hint or idea to proceed..... this is what i have developed: def index(file, key): """create an index """ stop_list = [ 'about', 'all', 'also', 'an', 'and', 'any', 'are', 'as', 'at', 'be', ...............] # A regular expression for extracting all non xml words aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') adict = {} temp = aword.findall(file.lower()) i = -1 #print temp # prints a listfor test #eliminate all stoplist words for word in temp: if word[0] != '<' and word not in stop_list: i = i + 1 #add the word tokens and their positions #to dictionary adict.setdefault(word,[]).append(i) # used for counting total words temp = 0 test = [] for word in adict.items(): test.append( word ) temp += 1 print test print temp #----------------------------------------------------- print adict #for testing print "i = %d" %(i) # for testing #print "total = %d" %(total) # for testing #incoorporate the frequency calculation and remember we started -1 nwords = math.log(i + 1) print "nwords = %d" %(nwords) # for testing print "---------------" #for testing #---------------------------------------------------------- #create a dictionary that will be used for updating # the initial dictionary created tempDict = {} for word, positions in adict.items(): # coumpute the word frequency TermFreq = int(100 *len(positions) / nwords) #print len(positions), nwords #InvDocFreq = int( temp / len(positions)) #print len(positions), TermFreq , InvDocFreq,temp ,nwords #Inv_Index = int(10 * (TermFreq * InvDocFreq)) # this dictionary puts the keys with multiple variables tempDict.setdefault(word,[]).append(key) tempDict.setdefault(word,[]).append(TermFreq) tempDict.setdefault(word,[]).append(positions) #print tempDict # for testing purpose #call for function sort_by_freq which sorts the elements # in a dictionary by frequency sorted_list = sort_by_freq(tempDict) print sorted_list #print sorted_list for test not to be used for the program for line in sorted_list[0:45]: print "word: %10s freq: %4d" % (line[0],line[1][1]) thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1948235366-1051110175=:27221 Content-Type: text/html; charset=us-ascii
Hi,
I was trying to implement a program that indexes documents and incorporates Document frequency (df): i.e. The number of documents that the term occurs in,the list of documents containing the term, and term frequency (tf): The number of times that the term occurs in each document. I have started something I would appreciate if someone
with information retrievial can give me hint or idea to proceed.....
 
this is what i have developed:
 
def index(file, key):
        """create an index """
 
        stop_list = [
           'about', 'all', 'also', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 
           ...............]
        # A regular expression for extracting all non xml words       
        aword =re.compile (r'<[^<>]*>|\b[\w-]+\b')
        adict = {}
        temp = aword.findall(file.lower())
        i = -1
        #print temp # prints a listfor test  #eliminate all stoplist words
        for word in temp:
            if word[0] != '<' and word not in stop_list:
                   
                   
                    i = i + 1     
                    #add the word tokens and their positions
                    #to dictionary
                    adict.setdefault(word,[]).append(i)
                   
                   
        # used for counting total words
        temp = 0
        test = []
        for word in adict.items():
                test.append( word )
                temp += 1
        print test       
        print temp      
        #-----------------------------------------------------
        print adict #for testing
        print "i = %d" %(i) # for testing
        #print "total = %d" %(total) # for testing
       
        #incoorporate the frequency calculation and remember we started -1      
        nwords = math.log(i + 1)
       
        print "nwords = %d" %(nwords) # for testing
        print "---------------"  #for testing
        #----------------------------------------------------------
       
        #create a dictionary that will be used for updating
        # the initial dictionary created
        tempDict = {}
       
        for word, positions in adict.items():               
            # coumpute the word frequency
            TermFreq = int(100 *len(positions) / nwords)
            #print len(positions), nwords
            #InvDocFreq = int( temp / len(positions))
            #print len(positions), TermFreq , InvDocFreq,temp ,nwords              
            #Inv_Index = int(10 * (TermFreq * InvDocFreq))
           
            # this dictionary puts the keys with multiple variables
            tempDict.setdefault(word,[]).append(key)
            tempDict.setdefault(word,[]).append(TermFreq)
            tempDict.setdefault(word,[]).append(positions)
           
        #print tempDict # for testing purpose
       
       
        #call for function sort_by_freq which sorts the elements
        # in a dictionary by frequency
        sorted_list = sort_by_freq(tempDict)
        print sorted_list      
        #print sorted_list for test not to be used for the program
        for line in sorted_list[0:45]:
                print "word: %10s  freq: %4d" % (line[0],line[1][1])
 
   thanks in advance
         



Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1948235366-1051110175=:27221-- From SWidney@ci.las-vegas.nv.us Wed Apr 23 12:20:03 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Apr 23 11:20:03 2003 Subject: [Tutor] Comparing lines in two files, writing result into a t hird file Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8513@sovereign.ci.las-vegas.nv.us> > I have two files, file1.txt and file 2. txt, each containing > numbers. I want to compare the numbers in the files and put > an asterisk at the end of the numbers that match, writing the > result into a third file > I've tried various combinations of opening the files and 'if' > nests, but I can't seem to get it right. Any hints on what > structure to use. Thanks in advance. Hints? Dictionary! Use a dictionary to record the numbers in the first file. Then compare the numbers in the second file, giving a meaningful value to those that are duplicated and just recording the others. You now have enough information to write your third file. > I have two files, file1 and file2. I want to print the first > line from file1, then the first line from file2, then the second > line from file 1, then the second line from file 2, etc. Not sure if this was yours also, but as another hint: check your version of python. If it's 2.0 or greater, check the Library Reference for the built-in function zip(). Scott From Anish.Mehta@enst-bretagne.fr Wed Apr 23 12:24:02 2003 From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish) Date: Wed Apr 23 11:24:02 2003 Subject: [Tutor] re.compile ?? Message-ID: <3EA6B0D6.1050501@antares.enst-bretagne.fr> Hello ! I am not getting what should be the outcome of this line numberAddedRE = re.compile("(.*)#\d+$") I tried to read it from /usr/lib/python2.2/re.py But i am not getting it properly. Please suggest regarding this. Thanks in advance. Regards, Anish MEHTA From pan@uchicago.edu Wed Apr 23 12:24:12 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Wed Apr 23 11:24:12 2003 Subject: [Tutor] Re: looping through and comparing lists of dictionaries In-Reply-To: <20030423130140.15527.74718.Mailman@mail.python.org> References: <20030423130140.15527.74718.Mailman@mail.python.org> Message-ID: <1051111389.3ea6afdd6f821@webmail-b.uchicago.edu> > Message: 7 > From: "bkd" > To: > Date: Wed, 23 Apr 2003 03:04:07 -0400 > Subject: [Tutor] looping through and comparing lists of dictionaries [snip] > What I have now is this: > > for girl in range(len(redheads)): > if len(redheads)==0: break > else: > for line in range(len(olddata)): > if len(redheads)==0: break > elif olddata[line]['name']<>redheads[girl]: pass > elif olddata[line]['hair']=='Redhead': del redheads[girl] Try this: olddata = [x for x in olddata if x['name'] not in redheads] for i in olddata: print i This gives you: >>> {'hair': 'Brunette', 'role': 'Castaway', 'name': 'Maryann'} {'hair': 'Blond', 'role': 'Genie', 'name': 'Jeanne'} {'hair': 'Brunette', 'role': 'Genie', 'name': 'Serena'} HTH pan From antonmuhin at rambler.ru" References: <3EA6B0D6.1050501@antares.enst-bretagne.fr> Message-ID: <8634037062.20030423201018@rambler.ru> Hello Anish, Wednesday, April 23, 2003, 7:27:18 PM, you wrote: MA> Hello ! MA> I am not getting what should be the outcome of this line MA> numberAddedRE = re.compile("(.*)#\d+$") MA> I tried to read it from /usr/lib/python2.2/re.py MA> But i am not getting it properly. Please suggest regarding this. MA> Thanks in advance. MA> Regards, MA> Anish MEHTA Something like any string that ends with # + sequences of digits: dpwufhuwefbe[#123, etc. -- Best regards, anton mailto:antonmuhin@rambler.ru From jeff@ccvcorp.com Wed Apr 23 13:36:45 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 23 12:36:45 2003 Subject: [Tutor] List element with replace References: <000501c304d4$c547a2d0$0201a8c0@eagle> Message-ID: <3EA6C13C.9040101@ccvcorp.com> Henry Steigerwaldt wrote: >line 1 >>> mexT[0] = "x/n 74| 51 79| 41 60|" >line 2 >>> mexT[0] = mexT[0].split()[1:] >line 3 >>> print mexT[0] >line 4 >>> ['74|', '51', '79|', '55', '79|'] >line 5 >>> mexT[0] = mexT[0].replace("|", "") > >Traceback (most recent call last): > File "", line 1, in ? > mexT[0] = mexT[0].replace("|", "") >AttributeError: 'list' object has no attribute 'replace' > > > >Yet, if I use a variable instead of a list element, say "s" and >use in place of mexT[0], no error occurs. > >Example: s = "74| 51 79| 41 60|" > s = s.replace("|", "") > print s > 74 51 79 41 60 > Ah, but you're using two different data types in your two cases. Your mexT[0] is actually a list, while in your second example s is a string. You can apply the string method replace() to each element of the list at mexT[0], but you need to be explicit about that: mexT[0] = [ item.replace("|", "") for item in mexT[0] ] You may then need to convert the list back into a string: mexT[0] = " ".join(mexT[0]) By the way, simply as a matter of style, I'd prefer to be doing all of this massaging using a temporary name, instead of stuffing each step back into mexT[0]. temp = mexT[0].split()[1:] temp = [ item.replace("|", "") for item in temp ] mexT[0] = " ".join(temp) This makes for a slightly clearer distinction between the intermediate steps and the finished product. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 14:05:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 13:05:02 2003 Subject: [Tutor] Fwd: Please read [bad vibes] In-Reply-To: Message-ID: On Tue, 22 Apr 2003, Cameron Stoner wrote: > I have been kinda out of it with the tutor, but this person sent me an > email and if you would explain what this is all about. Hi Cameron, It was an ugly scene. But if you're really interested, see: http://mail.python.org/pipermail/tutor/2003-April/021887.html If the person had asked interesting questions, I probably wouldn't have gotten so angry, but the questions the person asked were mindless multiple choice parroting phrasebook style questions, the worse kind of questions. And to tell the truth, I'm ashamed for answering so bitterly to the person, and would rather like that thread to die a quiet death... *sigh* In summary, someone asked us to do their homework, and all of us here said no. From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 14:15:23 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 13:15:23 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file In-Reply-To: Message-ID: On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote: > Yes, that's the good news ! The input files will always be sorted. Hi Stuart, Can you talk a little more about why having the input files sorted is a good thing? This is not a silly question, but is meant to help you focus on a particular part of the problem: there's something about the sorting that makes this "merging" problem particularly nice. [By the way, Stuart's problem is similar to the Unix utility 'comm', which also requires that its inputs are in sorted order.] Good luck to you! From lonetwin@yahoo.com Wed Apr 23 14:20:03 2003 From: lonetwin@yahoo.com (lonetwin) Date: Wed Apr 23 13:20:03 2003 Subject: [Tutor] re.compile ?? In-Reply-To: <3EA6B0D6.1050501@antares.enst-bretagne.fr> References: <3EA6B0D6.1050501@antares.enst-bretagne.fr> Message-ID: <200304232303.54642.lonetwin@yahoo.com> Hi Anish, On Wednesday 23 April 2003 08:57 pm, Mehta, Anish wrote: > I am not getting what should be the outcome of this line > numberAddedRE = re.compile("(.*)#\d+$") Re: One of the ways I try to decipher re's is by starting from the innermost re and reading upto the enclosing quotes. It has also helped me a lot when I "spell out" the re. That means when I see a '.*' I say 'any character repeated 0 or more times'. Now to your re ....lets see, the innermost is (.*) ---> any character repeated 0 or more times. # ---> followed by a '#' \d+ ---> followed by *at least one* (that's what the '+' says) digit $ ---> at the end of the line so the above re will match "dsfsd#34213" " #33" "__@#1111111" but will not match (among various other combinations) "# " ---> there should be at least one digit between '#' and the end of the line "DF23#453 " ---> the digits should occur at the end of the line HTH Peace Steve -- Heisengberg might have been here. From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 14:24:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 13:24:01 2003 Subject: [Tutor] re.compile ?? In-Reply-To: <8634037062.20030423201018@rambler.ru> Message-ID: > MA> I am not getting what should be the outcome of this line > > MA> numberAddedRE = re.compile("(.*)#\d+$") > > MA> I tried to read it from /usr/lib/python2.2/re.py > MA> But i am not getting it properly. Please suggest regarding this. > > Something like any string that ends with # + sequences of digits: > dpwufhuwefbe[#123, etc. Hi Anish, Can you explain what you want to get from the regular expression? The main problem here is that we, like Python, don't know what you expect the output to be. *grin* Are you getting an error message from your program, or is it more that the regex isn't detecting the patterns that you want it to detect? If you give us some examples of things you'd like numberAddedRE to recognize, we should be better able to understand the purpose of the regular expression. Best of wishes to you! From alan.gauld@blueyonder.co.uk Wed Apr 23 14:31:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Apr 23 13:31:02 2003 Subject: [Tutor] List element with replace References: <000501c304d4$c547a2d0$0201a8c0@eagle> Message-ID: <002b01c309be$174770e0$6401a8c0@xp> > line 3 >>> print mexT[0] > line 4 >>> ['74|', '51', '79|', '55', '79|'] Notice that mexT[0] is a list. Each element of the list is a string. > line 5 >>> mexT[0] = mexT[0].replace("|", "") > AttributeError: 'list' object has no attribute 'replace' You need to iterate over the list and do the replace on each element, like so: mexT[0] = [ s.replace('|','') for s in mexT[0] ] OR if you prefer map(): mexT[0] = map(lambda s: s.replace('|',''), mexT[0]) HTH, Alan G. From stuart_clemons@us.ibm.com Wed Apr 23 15:12:09 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 23 14:12:09 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file In-Reply-To: Message-ID: This is a multipart message in MIME format. --=_alternative 0064353985256D11_= Content-Type: text/plain; charset="US-ASCII" Hi Danny: Thanks for replying. Let me preface my response by saying I'm basically a Python newbie. I got into Python a little bit about a year ago, but then was pulled away to do other things. I'm now being asked to do some things where I think Python will be very useful. So, I'm trying to learn as I go, but I gotta produce stuff fairly quickly and I don't have a lot of spare time to spend on my learning curve. I do like Python though, and I'm glad I have something to use it for. So, anyway, now that I think about it a little bit, perhaps sorted order doesn't really matter. One responder suggested that I use dictionaries in my code structure. My understanding is that dictionaries are mappings, not sequences, so I guess ordering is not really relevant here. FWIW, It does turn out that the files I'm working with are always ordered sequentially when I get them. Concerning dictionaries, do you think dictionaries is the structure to use ? If so, I'll try to spend some time reading up on dictionaries. I do remember having problems reading a file into a dictionary when I tried it a year ago or so. TIA. - Stuart Danny Yoo 04/23/2003 01:14 PM To: stuart_clemons@us.ibm.com cc: "R. Alan Monroe" , Subject: Re: [Tutor] Comparing lines in two files, writing result into a third file On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote: > Yes, that's the good news ! The input files will always be sorted. Hi Stuart, Can you talk a little more about why having the input files sorted is a good thing? This is not a silly question, but is meant to help you focus on a particular part of the problem: there's something about the sorting that makes this "merging" problem particularly nice. [By the way, Stuart's problem is similar to the Unix utility 'comm', which also requires that its inputs are in sorted order.] Good luck to you! --=_alternative 0064353985256D11_= Content-Type: text/html; charset="US-ASCII"
Hi Danny:

Thanks for replying.  Let me preface my response by saying I'm basically a Python newbie.  I got into Python a little bit about a year ago, but then was pulled away to do other things. I'm now being asked to do some things where I think Python will be very useful.  So, I'm trying to learn as I go, but I gotta produce stuff fairly quickly and I don't have a lot of spare time to spend on my learning curve.  I do like Python though, and I'm glad I have something to use it for.

So, anyway, now that I think about it a little bit, perhaps sorted order doesn't really matter.  One responder suggested that I use dictionaries in my code structure.  My understanding is that dictionaries are mappings, not sequences, so I guess ordering is not really relevant here.  FWIW, It does turn out that the files I'm working with are always ordered sequentially when I get them.

Concerning dictionaries, do you think dictionaries is the structure to use ? If so, I'll try to spend some time reading up on dictionaries.  I do remember having problems reading a file into a dictionary when I tried it a year ago or so.

TIA.  
 
- Stuart
 


Danny Yoo <dyoo@hkn.eecs.berkeley.edu>

04/23/2003 01:14 PM

       
        To:        stuart_clemons@us.ibm.com
        cc:        "R. Alan Monroe" <amonroe@columbus.rr.com>, <tutor@python.org>
        Subject:        Re: [Tutor] Comparing lines in two files, writing result into a third file





On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote:


> Yes, that's the good news !  The input files will always be sorted.

Hi Stuart,


Can you talk a little more about why having the input files sorted is a
good thing?  This is not a silly question, but is meant to help you focus
on a particular part of the problem: there's something about the sorting
that makes this "merging" problem particularly nice.


[By the way, Stuart's problem is similar to the Unix utility 'comm', which
also requires that its inputs are in sorted order.]


Good luck to you!


--=_alternative 0064353985256D11_=-- From pan@uchicago.edu Wed Apr 23 16:05:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Wed Apr 23 15:05:02 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third In-Reply-To: <20030423130140.15527.74718.Mailman@mail.python.org> References: <20030423130140.15527.74718.Mailman@mail.python.org> Message-ID: <1051124678.3ea6e3c61ab04@webmail.uchicago.edu> > I've tried various combinations of opening the files and 'if' nests, but I > can't seem to get it right. Any hints on what structure to use. Thanks in > advance. Try this: ---------------------------------------------- f1=open('c:/py/digest/f1.txt', 'r') f2=open('c:/py/digest/f2.txt', 'r') f3=open('c:/py/digest/f3.txt', 'w') a= [x.strip() for x in f1.readlines()] # a = ['1','3','4'] b= [x.strip() for x in f2.readlines()] # b = ['1','2','3','4','5'] c= [(((x in a) and (x+'*\n')) or (x+'\n')) for x in b] f3.writelines(c) f1.close() f2.close() f3.close() ---------------------------------------------- The main part is: [(((x in a) and (x+'*\n')) or (x+'\n')) for x in b] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ in which (((x in a) and (x+'*\n')) or (x+'\n')) is equivilant to: if x in a: return x + '*\n' else: return x + '\n' if let it be f(x), then it becomes: c= [f(x) for x in b] Note: The example I show here doesn't take the following situation into consideration: f1: 1,3,4,6 <==== f2: 1,2,3,4,5 '6' is not in f2, so it is not included in the f3. Since this situation is not described in your question, so I will just leave it this way. pan From David McDonnell" This is a multi-part message in MIME format. ------=_NextPart_000_009E_01C308E9.F863FB50 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable Hi All, I'm new to the list, been lurking for a week or so now and am completely = new to python script, although i'm faimilar with some other scripting = languages such as MaxScript (for 3DSMax). Anyway i'm trying to do some image manipulation code, which will = basically require me to grab the data from an image, mainipulate the = pixel colours etc in code and then output the resulting image. Basically = one fo the things i want to be able to do is to compare the R,G,B values = of pixels in the image, alter them if certain conditions are met and = then output the results. I've got the image displaying, getting the data = and just setting the data to same thing at this point. Now how do i work = on the actual data? I've tried printing out the Data to try and see how = its presented etc (bad mistake... total gibberish to me and makes my = system speaker beep constantly for about 5 minutes).=20 Any ideas or pointers anyone? The code is below. Also i did have what i = wanted working previously using the wxWindows GetRed, GetBlue, and = GetGreen, comparing them and outputting using SetRGB though the whole = thing seemed too slow (about 10 - 15 seconds for 1 image, although most = of that time seemed to be taken up in the Get Stage) Much appreciated dave class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,-4,title,size=3D(800,600), style=3DwxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self.CreateStatusBar() =20 self.panel =3D wx.wxPanel(self, -1) file =3D 'p_34.bmp' bmp =3D wxImage(opj(file), wxBITMAP_TYPE_BMP).ConvertToBitmap() wxStaticBitmap(self.panel, -1,bmp, (15, 30))#, (bmp.GetWidth(), = bmp.GetHeight())) =20 bmp2 =3D wxImage(opj(file), wxBITMAP_TYPE_BMP) print "Getting Data" data =3D bmp2.GetData() print "Got Data" =20 =20 bmp2.SetData(data) bmp =3D wxBitmapFromImage(bmp2) =20 wxStaticBitmap(self.panel, -1,bmp, (500, 30))#, (bmp.GetWidth(), = bmp.GetHeight())) =20 self.Show(true) ------=_NextPart_000_009E_01C308E9.F863FB50 Content-Type: text/html; charset="Windows-1252" Content-Transfer-Encoding: quoted-printable
Hi All,
 
I'm new to the list, been lurking for a week or so = now and am=20 completely new to python script, although i'm faimilar with some other = scripting=20 languages such as MaxScript (for 3DSMax).
 
Anyway i'm trying to do some image manipulation = code, which=20 will basically require me to grab the data from an image, mainipulate = the pixel=20 colours etc in code and then output the resulting image. Basically one = fo the=20 things i want to be able to do is to compare the R,G,B values of pixels = in the=20 image, alter them if certain conditions are met and then output the = results.=20 I've got the image displaying, getting the data and just setting the = data to=20 same thing at this point. Now how do i work on the actual data? I've = tried=20 printing out the Data to try and see how its presented etc (bad = mistake... total=20 gibberish to me and makes my system speaker beep constantly for about 5=20 minutes).
Any ideas or pointers anyone? The code is below. = Also i did=20 have what i wanted working previously using the wxWindows GetRed, = GetBlue, and=20 GetGreen, comparing them and outputting using SetRGB though the whole = thing=20 seemed too slow (about 10 - 15 seconds for 1 image, although most of = that time=20 seemed to be taken up in the Get Stage)
 
Much appreciated
 
dave
 
 
 
class MainWindow(wxFrame):
 def=20 __init__(self,parent,id,title):
 
  wxFrame.__init__(self,parent,-4,title,size=3D(800,60= 0),
     style=3DwxDEFAULT_FRAME_STYLE|wxNO_F= ULL_REPAINT_ON_RESIZE)
  self.CreateStatusBar()
 &nb= sp;
  self.panel=20 =3D wx.wxPanel(self, -1)
  file =3D = 'p_34.bmp'
  bmp =3D=20 wxImage(opj(file),=20 wxBITMAP_TYPE_BMP).ConvertToBitmap()
  wxStaticBitmap(self.p= anel,=20 -1,bmp, (15, 30))#, (bmp.GetWidth(),=20 bmp.GetHeight()))
   
  bmp2 =3D = wxImage(opj(file),=20 wxBITMAP_TYPE_BMP)
  print "Getting = Data"
  data =3D=20 bmp2.GetData()
  print "Got=20 Data"
  
  
  bmp2.SetData(data)  bmp=20 =3D = wxBitmapFromImage(bmp2)  
  wxStaticBitmap(self.pa= nel,=20 -1,bmp, (500, 30))#, (bmp.GetWidth(), bmp.GetHeight()))
 
 
  self.Show(true)
 
------=_NextPart_000_009E_01C308E9.F863FB50-- From zak_arntson@hotmail.com Wed Apr 23 16:13:11 2003 From: zak_arntson@hotmail.com (Zak Arntson) Date: Wed Apr 23 15:13:11 2003 Subject: [Tutor] IDLE not getting changes to imported module Message-ID: I've got a simple problem, which I'm sure has been answered, but I couldn't find the answer at the Tutor archives. I'll pose the problem as a "bug report" :) Problem: IDLE not picking up changes to an imported module Steps: 1. A module, main.py, imports another module, thing.py 2. From main.py, I "import module" then "run script" -- Things work fine -- 3. Change and save thing.py 4. From main.py, I "run script" Expected: Changes made in thing.py are picked up and reflected in step 4. Actual: Changes made in thing.py are NOT picked up, and the original, unchanged version of thing.py is used. I'm guessing that the original thing.py is stuck in memory, and not updated when main.py imports again (with the second "run script"). The only fix I've found so far is to restart IDLE everytime I want to run any changes to an imported module. But that seems pretty clunky. Is there some way I can get thing.py's changes to be reflected as soon as I save it? Thanks all, Zak Arntson mailto:zak@mimir.net http://www.harlekin-maus.com _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From bgailer@alum.rpi.edu Wed Apr 23 16:45:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 23 15:45:02 2003 Subject: [Tutor] IDLE not getting changes to imported module In-Reply-To: Message-ID: <5.2.0.9.0.20030423134158.01a18bb0@66.28.54.253> --=======74386F73======= Content-Type: text/plain; x-avg-checked=avg-ok-58B519DC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:42 AM 4/23/2003 -0700, Zak Arntson wrote: >I've got a simple problem, which I'm sure has been answered, but I >couldn't find the answer at the Tutor archives. I'll pose the problem as a >"bug report" :) > >Problem: IDLE not picking up changes to an imported module > >Steps: >1. A module, main.py, imports another module, thing.py >2. From main.py, I "import module" then "run script" >-- Things work fine -- >3. Change and save thing.py >4. From main.py, I "run script" > >Expected: Changes made in thing.py are picked up and reflected in step 4. >Actual: Changes made in thing.py are NOT picked up, and the original, >unchanged version of thing.py is used. > >I'm guessing that the original thing.py is stuck in memory, and not >updated when main.py imports again (with the second "run script"). The >only fix I've found so far is to restart IDLE everytime I want to run any >changes to an imported module. But that seems pretty clunky. > >Is there some way I can get thing.py's changes to be reflected as soon as >I save it? After the initial import (I'm assuming it is "import thing") use the reload function to capture changes: reload(thing) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======74386F73======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-58B519DC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======74386F73=======-- From stuart_clemons@us.ibm.com Wed Apr 23 16:48:53 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 23 15:48:53 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file In-Reply-To: Message-ID: This is a multipart message in MIME format. --=_alternative 006CF50885256D11_= Content-Type: text/plain; charset="US-ASCII" Thanks Danny. I appreciate the example. I'll try to apply your example "merging" structure to my problem. This is kind of similiar to the approach I was playing with. I hope to have time to work on it tomorrow morning. We'll see what I come up with. Thanks again. Danny Yoo 04/23/2003 03:32 PM To: stuart_clemons@us.ibm.com cc: "R. Alan Monroe" , Subject: Re: [Tutor] Comparing lines in two files, writing result into a third file On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote: > So, anyway, now that I think about it a little bit, perhaps sorted order > doesn't really matter. One responder suggested that I use dictionaries > in my code structure. My understanding is that dictionaries are > mappings, not sequences, so I guess ordering is not really relevant > here. FWIW, It does turn out that the files I'm working with are always > ordered sequentially when I get them. > > Concerning dictionaries, do you think dictionaries is the structure to > use ? If so, I'll try to spend some time reading up on dictionaries. I > do remember having problems reading a file into a dictionary when I > tried it a year ago or so. Hi Stuart, Yes, dictionaries will work. It's also very possible to do the problem without dictionaries if we use a "merging" method. I'll try describing the idea of the "merge" method in terms of cards and hands; maybe it will appeal to the card game players here. *grin* Imagine that we have two lists in each of our hands: ### left_hand = [1, 3, 5, 7, 9] right_hand = [2, 4, 6, 8, 10] ### And imagine that our task is to bring these two hands together into one big pile, but make sure that the big pile is sorted. If we do this in real life, we'll notice that we'll do something like put down left card (1) put down right card (2) put down left card (3) put down right card (4) ... and so we, in a sense, shuffle the cards into order. Now say that our left and right hands hold something like this instead: ### left_hand = [1, 2, 4, 6] right_hand = [3, 5] ### We'll still assume that each pile in our hands is individually sorted. When we try to merge these lists together, our actions are similar, but we do a little more to figure out which hand we should put down: left = [1, 2, 4, 6], right = [3, 5] put down left card (1) left = [2,4,6], right = [3, 5] put down left card (2) left = [4, 6], right = [3, 5] put down right card (3) left = [4, 6], right = [5] put down left card (4) left = [6], right = [5] put down right card (5) left = [6], right = [] put down left card (6) left = [], right = [] If we do this by hand, we notice that we have to look at the top cards from each hand, and do something based on what we see. But what we do is fairly simple: ### ### pseudocode while we have cards in both left and right hands: if top left card < top right card: put_down top left card else: put_down top right card put any remaining hand cards into large pile. ### The pseudocode above isn't totally correct, because it doesn't take care of the case when the top left card is the same as the top right card. That's where you probably want to flag one of the the card with an asterisk before putting it into the large pile, and discarding the other. This should give some impression of the merging approach; you may need to adjust it so that it works with files rather than left and right hands though. *grin* Good luck! --=_alternative 006CF50885256D11_= Content-Type: text/html; charset="US-ASCII"
Thanks Danny.   I appreciate the example.  I'll try to apply your example "merging" structure to my problem.  This is kind of similiar to the approach I was playing with.  I hope to have time to work on it tomorrow morning.  We'll see what I come up with.  Thanks again.
 


Danny Yoo <dyoo@hkn.eecs.berkeley.edu>

04/23/2003 03:32 PM

       
        To:        stuart_clemons@us.ibm.com
        cc:        "R. Alan Monroe" <amonroe@columbus.rr.com>, <tutor@python.org>
        Subject:        Re: [Tutor] Comparing lines in two files, writing result into a third file





On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote:

> So, anyway, now that I think about it a little bit, perhaps sorted order
> doesn't really matter.  One responder suggested that I use dictionaries
> in my code structure.  My understanding is that dictionaries are
> mappings, not sequences, so I guess ordering is not really relevant
> here.  FWIW, It does turn out that the files I'm working with are always
> ordered sequentially when I get them.
>
> Concerning dictionaries, do you think dictionaries is the structure to
> use ? If so, I'll try to spend some time reading up on dictionaries.  I
> do remember having problems reading a file into a dictionary when I
> tried it a year ago or so.

Hi Stuart,


Yes, dictionaries will work.

It's also very possible to do the problem without dictionaries if we use a
"merging" method.  I'll try describing the idea of the "merge"  method in
terms of cards and hands; maybe it will appeal to the card game players
here.  *grin*


Imagine that we have two lists in each of our hands:

###
left_hand = [1, 3, 5, 7, 9]
right_hand = [2, 4, 6, 8, 10]
###


And imagine that our task is to bring these two hands together into one
big pile, but make sure that the big pile is sorted.  If we do this in
real life, we'll notice that we'll do something like

   put down left card (1)
   put down right card (2)
   put down left card (3)
   put down right card (4)
   ...

and so we, in a sense, shuffle the cards into order.



Now say that our left and right hands hold something like this instead:

###
left_hand = [1, 2, 4, 6]
right_hand = [3, 5]
###

We'll still assume that each pile in our hands is individually sorted.
When we try to merge these lists together, our actions are similar, but we
do a little more to figure out which hand we should put down:

                                left = [1, 2, 4, 6], right = [3, 5]
   put down left card (1)       left = [2,4,6],      right = [3, 5]
   put down left card (2)       left = [4, 6],       right = [3, 5]
   put down right card (3)      left = [4, 6],       right = [5]
   put down left card (4)       left = [6],          right = [5]
   put down right card (5)      left = [6],          right = []
   put down left card (6)       left = [],           right = []

If we do this by hand, we notice that we have to look at the top cards
from each hand, and do something based on what we see.  But what we do is
fairly simple:

###
### pseudocode
while we have cards in both left and right hands:
   if top left card < top right card:
       put_down top left card
   else:
       put_down top right card
put any remaining hand cards into large pile.
###

The pseudocode above isn't totally correct, because it doesn't take care
of the case when the top left card is the same as the top right card.
That's where you probably want to flag one of the the card with an
asterisk before putting it into the large pile, and discarding the other.


This should give some impression of the merging approach; you may need to
adjust it so that it works with files rather than left and right hands
though.  *grin*


Good luck!


--=_alternative 006CF50885256D11_=-- From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 17:07:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 16:07:01 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file In-Reply-To: Message-ID: On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote: > So, anyway, now that I think about it a little bit, perhaps sorted order > doesn't really matter. One responder suggested that I use dictionaries > in my code structure. My understanding is that dictionaries are > mappings, not sequences, so I guess ordering is not really relevant > here. FWIW, It does turn out that the files I'm working with are always > ordered sequentially when I get them. > > Concerning dictionaries, do you think dictionaries is the structure to > use ? If so, I'll try to spend some time reading up on dictionaries. I > do remember having problems reading a file into a dictionary when I > tried it a year ago or so. Hi Stuart, Yes, dictionaries will work. It's also very possible to do the problem without dictionaries if we use a "merging" method. I'll try describing the idea of the "merge" method in terms of cards and hands; maybe it will appeal to the card game players here. *grin* Imagine that we have two lists in each of our hands: ### left_hand = [1, 3, 5, 7, 9] right_hand = [2, 4, 6, 8, 10] ### And imagine that our task is to bring these two hands together into one big pile, but make sure that the big pile is sorted. If we do this in real life, we'll notice that we'll do something like put down left card (1) put down right card (2) put down left card (3) put down right card (4) ... and so we, in a sense, shuffle the cards into order. Now say that our left and right hands hold something like this instead: ### left_hand = [1, 2, 4, 6] right_hand = [3, 5] ### We'll still assume that each pile in our hands is individually sorted. When we try to merge these lists together, our actions are similar, but we do a little more to figure out which hand we should put down: left = [1, 2, 4, 6], right = [3, 5] put down left card (1) left = [2,4,6], right = [3, 5] put down left card (2) left = [4, 6], right = [3, 5] put down right card (3) left = [4, 6], right = [5] put down left card (4) left = [6], right = [5] put down right card (5) left = [6], right = [] put down left card (6) left = [], right = [] If we do this by hand, we notice that we have to look at the top cards from each hand, and do something based on what we see. But what we do is fairly simple: ### ### pseudocode while we have cards in both left and right hands: if top left card < top right card: put_down top left card else: put_down top right card put any remaining hand cards into large pile. ### The pseudocode above isn't totally correct, because it doesn't take care of the case when the top left card is the same as the top right card. That's where you probably want to flag one of the the card with an asterisk before putting it into the large pile, and discarding the other. This should give some impression of the merging approach; you may need to adjust it so that it works with files rather than left and right hands though. *grin* Good luck! From pan@uchicago.edu Wed Apr 23 18:09:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Wed Apr 23 17:09:02 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third In-Reply-To: <20030423194502.17931.33784.Mailman@mail.python.org> References: <20030423194502.17931.33784.Mailman@mail.python.org> Message-ID: <1051132082.3ea700b242b46@webmail.uchicago.edu> Hi Danny and Stuart, IMO, Stuart's question can be solved without worrying about the sort order. To me the following steps are more straightforward: 1. load files into 2 lists (a,b) 2. mix them together into list c 3. build a new list d from list c. When building, check the count of elements in c. If count > 1, then attach * 4. remove duplicate items in d. Put into code: ------------------------------------------------- f1=open('c:/py/digest/f1.txt', 'r') f2=open('c:/py/digest/f2.txt', 'r') f3=open('c:/py/digest/f3.txt', 'w') a= [x.strip() for x in f1.readlines()] # a= ['1','3','4', '6'] b= [x.strip() for x in f2.readlines()] # b= ['1','2','3','4','5'] c = [((a+b).count(x)>1) and (x+'*\n') or (x+'\n') for x in a+b] set ={} d= [set.setdefault(x,x) for x in c if x not in set] # Remove duplicates d.sort() f3.writelines(d) f1.close() f2.close() f3.close() ------------------------------------------------- It takes total only 13 lines of code. The lists a,b,c,d will be: a= ['1', '3', '4', '6'] b= ['1', '2', '3', '4', '5'] c= ['1*\n', '3*\n', '4*\n', '6\n', '1*\n', '2\n', '3*\n', '4*\n', '5\n'] d= ['1*\n', '2\n', '3*\n', '4*\n', '5\n', '6\n'] # The 'duplicate removing code' is from : # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # by Raymond Hettinger, 2002/03/17 HTH pan From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 18:26:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 17:26:01 2003 Subject: [Tutor] re.compile ?? (fwd) Message-ID: Hi Anish: I'm forwarding this to Tutor; let's keep discussion on the list so that all of us here can help. ---------- Forwarded message ---------- Date: Wed, 23 Apr 2003 21:47:43 +0200 From: "Mehta, Anish" To: Danny Yoo Subject: Re: [Tutor] re.compile ?? import sys import os import getopt import re from fontTools.ttLib import TTFont from fontTools import version def usage(): print __doc__ % version sys.exit(2) numberAddedRE = re.compile("(.*)#\d+$") def makeOutputFileName(input, outputDir, extension): dir, file = os.path.split(input) file, ext = os.path.splitext(file) if outputDir: dir = outputDir output = os.path.join(dir, file + extension) m = numberAddedRE.match(file) if m: file = m.group(1) n = 1 while os.path.exists(output): output = os.path.join(dir, file + "#" + repr(n) + extension) n = n + 1 return output I am trying to understand this code. Here dir, file is assigned the directory and file after os.path.split(input) divides the input in two parts of file and directory. Next if the output directory is mentioned then output dir is assigned to dir. Then in the next line it is joined to make the required path having output directory. After that i m not getting what is expected from the next few lines having match and group. Thanks to all for giving their valuable support. Regards, Anish MEHTA. Danny Yoo wrote: > > >>MA> I am not getting what should be the outcome of this line >> >>MA> numberAddedRE = re.compile("(.*)#\d+$") >> >>MA> I tried to read it from /usr/lib/python2.2/re.py >>MA> But i am not getting it properly. Please suggest regarding this. >> >>Something like any string that ends with # + sequences of digits: >>dpwufhuwefbe[#123, etc. >> >> > >Hi Anish, > >Can you explain what you want to get from the regular expression? The main >problem here is that we, like Python, don't know what you expect the >output to be. *grin* > >Are you getting an error message from your program, or is it more that the >regex isn't detecting the patterns that you want it to detect? If you >give us some examples of things you'd like numberAddedRE to recognize, we >should be better able to understand the purpose of the regular expression. > > >Best of wishes to you! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From stuart_clemons@us.ibm.com Wed Apr 23 18:39:43 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 23 17:39:43 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third Message-ID: Hi Pan: Thanks for the detailed response. I hope to have time tomorrow morning to try this out and to further analyze. The steps are very clear, but I need to spend more time fully understanding the code part, though it's definitely not over my head & I think I mostly know what's going on. You make it look very easy. Thanks again. - Stuart pan@uchicago.edu To: tutor@python.org 04/23/03 05:08 PM cc: stuart_clemons@us.ibm.com Subject: Re: Comparing lines in two files, writing result into a third Hi Danny and Stuart, IMO, Stuart's question can be solved without worrying about the sort order. To me the following steps are more straightforward: 1. load files into 2 lists (a,b) 2. mix them together into list c 3. build a new list d from list c. When building, check the count of elements in c. If count > 1, then attach * 4. remove duplicate items in d. Put into code: ------------------------------------------------- f1=open('c:/py/digest/f1.txt', 'r') f2=open('c:/py/digest/f2.txt', 'r') f3=open('c:/py/digest/f3.txt', 'w') a= [x.strip() for x in f1.readlines()] # a= ['1','3','4', '6'] b= [x.strip() for x in f2.readlines()] # b= ['1','2','3','4','5'] c = [((a+b).count(x)>1) and (x+'*\n') or (x+'\n') for x in a+b] set ={} d= [set.setdefault(x,x) for x in c if x not in set] # Remove duplicates d.sort() f3.writelines(d) f1.close() f2.close() f3.close() ------------------------------------------------- It takes total only 13 lines of code. The lists a,b,c,d will be: a= ['1', '3', '4', '6'] b= ['1', '2', '3', '4', '5'] c= ['1*\n', '3*\n', '4*\n', '6\n', '1*\n', '2\n', '3*\n', '4*\n', '5\n'] d= ['1*\n', '2\n', '3*\n', '4*\n', '5\n', '6\n'] # The 'duplicate removing code' is from : # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 # by Raymond Hettinger, 2002/03/17 HTH pan From dyoo@hkn.eecs.berkeley.edu Wed Apr 23 19:03:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 23 18:03:01 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third [measuring an algorithm / using profile] In-Reply-To: <1051132082.3ea700b242b46@webmail.uchicago.edu> Message-ID: On Wed, 23 Apr 2003 pan@uchicago.edu wrote: > IMO, Stuart's question can be solved without worrying about the sort > order. To me the following steps are more straightforward: > > 1. load files into 2 lists (a,b) > 2. mix them together into list c > 3. build a new list d from list c. When building, check > the count of elements in c. If count > 1, then attach * Hi Pan, But step three is what ends up being expensive if we're not careful. In the code: > f1=open('c:/py/digest/f1.txt', 'r') > f2=open('c:/py/digest/f2.txt', 'r') > a= [x.strip() for x in f1.readlines()] # a= ['1','3','4', '6'] > b= [x.strip() for x in f2.readlines()] # b= ['1','2','3','4','5'] > c = [((a+b).count(x)>1) and (x+'*\n') or (x+'\n') for x in a+b] the cost of constructing 'c' can be problematic. To count() in a list, we need to scan through the whole list. Mathematically speaking, the cost of count()ing a list is proportional to the length of the list. On a list of length 'n', if we run 'count' for every element in our list, the total cost of doing this ends up being quadratic. That is, |-----------------| we're doing this 'nC' itself 'n' times cost = nC + nC + .... + nC = n^2 * C where C is a constant of proportionality. C will stand for how expensive doing a count() on something like [1] is. C is actually really darn miniscule, but it's still not zero. *grin* If 'n' gets large, it'll swamp over C. We can test this out empirically using the 'profiling' module. First, let's set up a small framework: ### >>> def makeBigList(n): ... return [0] * n ... >>> def doCounting(L): ## slightly simpler than the original ... return [L.count(x) > 1 for x in L] ... >>> doCounting(makeBigList(10)) [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] >>> import profile >>> profile.run("doCounting(makeBigList(10))") 4 function calls in 0.020 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :1(doCounting) 1 0.000 0.000 0.000 0.000 :1(makeBigList) 1 0.000 0.000 0.000 0.000 :1(?) 1 0.020 0.020 0.020 0.020 profile:0(doCounting(makeBigList(10))) 0 0.000 0.000 profile:0(profiler) ### What we plan to do is test doCounting for larger and larger lists, and see what happens to the CPU seconds. ### >>> test_lists = [makeBigList(n) for n in (1000, 2000, 3000)] >>> test_lists = [makeBigList(n) for n in (1000, 2000, 3000)] >>> for l in test_lists: ... profile.run('doCounting(l)') ... 3 function calls in 0.150 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.150 0.150 0.150 0.150 :1(doCounting) 1 0.000 0.000 0.150 0.150 :1(?) 1 0.000 0.000 0.150 0.150 profile:0(doCounting(l)) 0 0.000 0.000 profile:0(profiler) 3 function calls in 0.580 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.580 0.580 0.580 0.580 :1(doCounting) 1 0.000 0.000 0.580 0.580 :1(?) 1 0.000 0.000 0.580 0.580 profile:0(doCounting(l)) 0 0.000 0.000 profile:0(profiler) 3 function calls in 1.290 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 1.290 1.290 1.290 1.290 :1(doCounting) 1 0.000 0.000 1.290 1.290 :1(?) 1 0.000 0.000 1.290 1.290 profile:0(doCounting(l)) 0 0.000 0.000 profile:0(profiler) ### Notice that, as we make 'n' grow at a steady pace, the time it takes to call doCounting() grows faster than linear. I ran the numbers for n going on range(1000, 10001, 1000), and got times approximate to: n time (sec) ----------- 1000 0.140 2000 0.570 3000 1.280 4000 2.310 5000 3.600 6000 5.180 7000 7.000 8000 9.040 9000 11.560 10000 14.260 This might not seem to be a big deal: it takes about a second to handle a 3000 line input. But if the program is meant to handle large amounts of data, it can be worth it to learn a little more about what's expensive and what we can do to make our programs run faster. Anyway, I hope that clears up why we're recommending dictionaries and merging over the direct approach. From SWidney@ci.las-vegas.nv.us Wed Apr 23 20:19:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Apr 23 19:19:02 2003 Subject: [Tutor] Comparing lines in two files, writing result into a t hird file Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC851B@sovereign.ci.las-vegas.nv.us> > ... So, I'm trying to learn as I go, but I gotta produce stuff > fairly quickly and I don't have a lot of spare time to spend on > my learning curve. I do like Python though, and I'm glad I have > something to use it for. > > So, anyway, now that I think about it a little bit, perhaps sorted > order doesn't really matter. One responder suggested that I use > dictionaries in my code structure. My understanding is that > dictionaries are mappings, not sequences, so I guess ordering is > not really relevant here. FWIW, It does turn out that the files > I'm working with are always ordered sequentially when I get them. > > Concerning dictionaries, do you think dictionaries is the structure > to use ? If so, I'll try to spend some time reading up on > dictionaries. I do remember having problems reading a file into a > dictionary when I tried it a year ago or so. Since you're pressed for time, I can give you a basic script using a dictionary.... ##### d = {} # Start with an empty dictionary f1 = file('file1.txt', 'r') for num in f1.readlines(): num = num.strip() # get rid of any nasty newlines d[num] = 1 # and populate f1.close() f2 = file('file2.txt', 'r') for num in f2.readlines(): num = num.strip() # again with the newlines if d.has_key(num): d[num] += 1 # <- increment value, or else: d[num] = 1 # <- create a new key f2.close() nums = d.keys() nums.sort() f3 = file('file3.txt', 'w') for num in nums: f3.write(num) # Here we put the if d[num] > 1: # newlines back, either f3.write("*\n") # <- with else: # or f3.write("\n") # <- without f3.close() # the asterisk #### Should be fairly quick. And it's certainly easier to flash-parse with the naked eye than a value-packed list comprehension. HTH Scott From zaixia_zhang@yahoo.com Wed Apr 23 21:40:02 2003 From: zaixia_zhang@yahoo.com (Zhang Zaixia) Date: Wed Apr 23 20:40:02 2003 Subject: [Tutor] Chinese text processing Message-ID: <20030424003951.70410.qmail@web12506.mail.yahoo.com> Hi, all, I am a new learner. I met some problem when I did my project using python. Here is my question: Can we set our default encoding to be our favoriate one? For example, if I want to process Chinese, I can set my default encoding to be 'GB_2312-80'. I checked the python2.2 package(windows version), I can not find any encoding name related to Chinese. Any help is appreciated. Thanks. Zaixia __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com From csmith@blakeschool.org Thu Apr 24 00:01:22 2003 From: csmith@blakeschool.org (Christopher Smith) Date: Wed Apr 23 23:01:22 2003 Subject: [Tutor] Re: List element with replace Message-ID: Henry Steigerwaldt hsteiger@comcast.net writes: >What am I doing wrong with this code? For some >reason, I get the error below when trying to remove >the "|" character from an existing line of numbers stored >in a list element. > >First in line 2, I remove the x/n from the numbers that >are stored in the list element by using the "split" method. >Then mexT[0] will contain "74| 51 79| 41 60|" as >verified with the output using the print statement in line 4. >So far so good. > >But in line 5, I attempt to remove the "|" character from the >line of numbers by using the "replace" method, and hopefully >store this result back into mexT[0], but that nasty error >occurs below about "list object has no attribute replace." > >line 1 >>> mexT[0] = "x/n 74| 51 79| 41 60|" >line 2 >>> mexT[0] = mexT[0].split()[1:] While mexT[0] is a string, the result of the split operation is a list. And the complaint that 'lists don't have a replace' method is raised. Without knowing all the manipulations you are going to do to the list it is hard to anticipate the best solution for getting rid of the '|' characters. If all you want to do is get rid of the 'x/n' and the '|' characters then converting the list to a string, doing the replacements, and converting it back to a list might be an option: ### >>> l ['x/n 74| 51| 79| 41 60|', 1] >>> str(_) # convert to a string; the '_' refers to the last output "['x/n 74| 51| 79| 41 60|', 1]" >>> _.replace('x/n','') #do replacements "[' 74| 51| 79| 41 60|', 1]" >>> _.replace('|','') "[' 74 51 79 41 60', 1]" >>> eval(_, {}) # convert back to list, not giving eval() access to anything [' 74 51 79 41 60', 1] ### /c From stuart_clemons@us.ibm.com Thu Apr 24 08:52:02 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Thu Apr 24 07:52:02 2003 Subject: [Tutor] Comparing lines in two files, writing result into a t hird file Message-ID: Hi Scott: Thanks for laying out the dictionary structure for me. I wanted to use dictionaries a year ago for something I was working on, but I couldn't get dictionaries to work for me (it was very frustrating), so I ended up hacking something else together. I think that was about the last time I needed to use Python for anything. Anyway, I'm going to try using this structure to solve the problem I'm working on. I need to produce this "merged" list fairly quickly (like today) and then on a regular basis. To Danny and Pan: Thanks very much for contributing thoughts and code related to this problem. Since it looks like I'll have a need to use Python for the forseeable future, as a learning exercise, I'm going to try each of these approaches to this problem. Most of the work I'll need Python for is similar to this problem. (Next up is formatting a dump of a text log file into a readable report. I think I know how to handle this one, but if not, as Arnold would say, I'll be back !) Thanks again. - Stuart > Concerning dictionaries, do you think dictionaries is the structure > to use ? If so, I'll try to spend some time reading up on > dictionaries. I do remember having problems reading a file into a > dictionary when I tried it a year ago or so. Since you're pressed for time, I can give you a basic script using a dictionary.... ##### d = {} # Start with an empty dictionary f1 = file('file1.txt', 'r') for num in f1.readlines(): num = num.strip() # get rid of any nasty newlines d[num] = 1 # and populate f1.close() f2 = file('file2.txt', 'r') for num in f2.readlines(): num = num.strip() # again with the newlines if d.has_key(num): d[num] += 1 # <- increment value, or else: d[num] = 1 # <- create a new key f2.close() nums = d.keys() nums.sort() f3 = file('file3.txt', 'w') for num in nums: f3.write(num) # Here we put the if d[num] > 1: # newlines back, either f3.write("*\n") # <- with else: # or f3.write("\n") # <- without f3.close() # the asterisk #### Should be fairly quick. And it's certainly easier to flash-parse with the naked eye than a value-packed list comprehension. HTH Scott From wkoorts@mweb.co.za Thu Apr 24 15:46:02 2003 From: wkoorts@mweb.co.za (Wayne Koorts) Date: Thu Apr 24 14:46:02 2003 Subject: [Tutor] Nesting lists? Message-ID:
Hi,
 
= I'd like to have 'an array of arrays'.  Yes, yes I know= it's not an array in python but a list.  What I'd like to= do is something to the effect of:
 
= data =3D [data1[], data2[], data3[]]
 
= but that just gives me an error.  I thought of maybe using= a dictionary?
 
= The idea is that I can have a for: loop that assigns values to= the lists within the main list in order from first to= last.  As in the e.g. data1.assign(x1),= data2.assign(x2).
 
= Regards,
Wayne
From jonathan.schmidt@wartburg.edu Thu Apr 24 16:00:03 2003 From: jonathan.schmidt@wartburg.edu (Jonathan D. Schmidt) Date: Thu Apr 24 15:00:03 2003 Subject: [Tutor] Nesting lists? Message-ID: <200304241358.AA14680160@wartburg.edu> What I've always done is: data = [] data.append([ Message-ID: <3EA846D2.3060209@ccvcorp.com> Christopher Smith wrote: >[...] If all you want to do is >get rid of the 'x/n' and the '|' characters then converting the list >to a string, doing the replacements, and converting it back to a list >might be an option: > >### > > >>>>l >>>> >>>> >['x/n 74| 51| 79| 41 60|', 1] > > >>>>str(_) # convert to a string; the '_' refers to the last output >>>> >>>> >"['x/n 74| 51| 79| 41 60|', 1]" > > >>>>_.replace('x/n','') #do replacements >>>> >>>> >"[' 74| 51| 79| 41 60|', 1]" > > >>>>_.replace('|','') >>>> >>>> >"[' 74 51 79 41 60', 1]" > > >>>>eval(_, {}) # convert back to list, not giving eval() access to >>>> >>>> >anything >[' 74 51 79 41 60', 1] >### > Since it looks like this was only converted to a list as a side-effect of removing the 'x/n', we can avoid a lot of ugly back-and-forth conversions. >>> mexT[0] 'x/n 74| 51 79| 41 60|' >>> temp = mexT[0] >>> temp = temp.replace('x/n', '') >>> temp ' 74| 51 79| 41 60|' >>> temp = temp.replace('|','') >>> temp ' 74 51 79 41 60' >>> temp = temp.strip() >>> temp '74 51 79 41 60' >>> mexT[0] = temp >>> mexT[0] '74 51 79 41 60' >>> If the end result really should leave mexT[0] as a list, then a simple split() will do the trick. This lets us avoid the use of eval(), which is generally a bad idea to use unless there's no other way to accomplish your task (i.e., almost never). Jeff Shannon Technician/Programmer Credit International From pan@uchicago.edu Thu Apr 24 17:53:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Thu Apr 24 16:53:01 2003 Subject: [Tutor] RE: Comparing lines in two files, writing result into a third file In-Reply-To: <20030424160006.5877.49722.Mailman@mail.python.org> References: <20030424160006.5877.49722.Mailman@mail.python.org> Message-ID: <1051217542.3ea84e8688500@webmail.uchicago.edu> Thx Danny for pointing out the rate limiting step in the code I presented earlier. I am heading toward the world of genome/evolution analysis in which the data size could be abnormally huge. This sort of practice -- using profile to detect the rate limiting step -- could be very helpful. pan From dyoo@hkn.eecs.berkeley.edu Thu Apr 24 19:16:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 24 18:16:02 2003 Subject: [Tutor] code efficiency and biological databases In-Reply-To: <1051217542.3ea84e8688500@webmail.uchicago.edu> Message-ID: On Thu, 24 Apr 2003 pan@uchicago.edu wrote: > Thx Danny for pointing out the rate limiting step in the code I > presented earlier. The computer scientist Alan Perlis once quipped: "Lisp programmers know the value of everything, and the cost of nothing." Let's make sure that that generalization doesn't apply so strongly to Python programmers. *grin* > I am heading toward the world of genome/evolution analysis Very cool! Yes, biologists often have to deal with enormous databases, so I think it can be effective to be aware of program efficiency. The Institute of Genomic Research (TIGR) keeps a respository of many genomes available on their FTP site; what's sorta neat is that a lot of their data is in XML. But what sorta sucks is that a lot of their data is in XML. *grin* If you're ever interested in the model organism 'Arabidopsis Thaliana', you can check out a concrete example of a medium-sized dataset: ftp://ftp.tigr.org/pub/data/a_thaliana/ath1/BACS/ I'm using the 'gzip' and 'pulldom' modules to open and parse out individual sections of each "Bacterial Artificial Chromosome" at work. But the library documentation on 'pulldom' is so laughably sparse at the moment --- I'm thinking of writing a small tutorial on it when I get the chance. Sorry for being so off topic; I just like talking about my work... *grin* Talk to you later! From dyoo@hkn.eecs.berkeley.edu Thu Apr 24 20:01:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Apr 24 19:01:00 2003 Subject: [Tutor] re.compile ?? (fwd) In-Reply-To: Message-ID: > def usage(): > print __doc__ % version > sys.exit(2) > > > numberAddedRE = re.compile("(.*)#\d+$") > > def makeOutputFileName(input, outputDir, extension): > dir, file = os.path.split(input) > file, ext = os.path.splitext(file) > if outputDir: > dir = outputDir > output = os.path.join(dir, file + extension) > m = numberAddedRE.match(file) > if m: > file = m.group(1) > n = 1 > while os.path.exists(output): > output = os.path.join(dir, file + "#" + repr(n) + extension) > n = n + 1 > return output > > I am trying to understand this code. Here dir, file is assigned the > directory and file after os.path.split(input) divides the input in two > parts of file and directory. Next if the output directory is mentioned > then output dir is assigned to dir. Then in the next line it is joined > to make the required path having output directory. > > After that i m not getting what is expected from the next few lines > having match and group. Hi Anish, The code: m = numberAddedRE.match(file) if m: file = m.group(1) is a check to see if the 'file' fits the pattern defined in numberAddedRE. If it doesn't match properly, 'm' will have the value None, so we'll skip the next if statment. But if we do match the pattern, we get back a "match" object that can tell us how the match worked. In particular, when we say m.group(1), the regular expression engine gives us the part of the string that matched against the first pair of parentheses in: re.compile("(.*)#\d+$") Here's an example of group() in action: ### >>> import re >>> regex = re.compile('(fo+)bar') >>> m = regex.match('foooooobar!') >>> m.group(0) 'foooooobar' >>> m.group(1) 'foooooo' ### It might also help if we look at the function in context. Let's first pretend that we have a directory structure like: ### /home/anish/src/ python#1.py python#2.py python#3.py python#4.py ### That is, let's say that we have a directory called '/home/anish/src/', with 4 python source files. Try working out what happens if we call: print makeOutputFileName('/home/anish/src/python#1.py', None, '.py') The code, I think, is doing too much work, so that might be what's confusing. It tries to find an available file name, making sure it doesn't take the name of an existing file, and if it sees a name in a particular format --- if that name has a trailing number --- it tries to create a new name with the next ascending number in sequence. From tim@johnsons-web.com Fri Apr 25 00:51:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Apr 24 23:51:01 2003 Subject: [Tutor] List Comprehension (shared references) Message-ID: <20030425034904.GA9074@johnsons-web.com> Hi all: I'm just getting my feet wet with list comprehensions. I need to write a function that returns a nested list of empty lists. It seems simple, but I'm a python newbie and I don't want to leave myself that can bite me later... The following console session seems to fit the bill. x = 7 >>> ml = [[] for row in range(x)] >>> ml [[], [], [], [], [], [], []] # Now that *seems* to be what I'm looking for :-) And furthermore: >>> ml[1].append('test') >>> ml [[], ['test'], [], [], [], [], []] There appears to be no shared references. Am I correct here? Comments appreciated. -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From pan@uchicago.edu Fri Apr 25 01:54:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Fri Apr 25 00:54:02 2003 Subject: [Tutor] Re: List Comprehension (shared references) In-Reply-To: <20030424160006.5877.49722.Mailman@mail.python.org> References: <20030424160006.5877.49722.Mailman@mail.python.org> Message-ID: <1051246428.3ea8bf5cef0b8@webmail.uchicago.edu> > x = 7 > >>> ml = [[] for row in range(x)] > >>> ml > [[], [], [], [], [], [], []] > > # Now that *seems* to be what I'm looking for :-) > And furthermore: > >>> ml[1].append('test') > >>> ml > [[], ['test'], [], [], [], [], []] > > There appears to be no shared references. Try this: >>> x=7 >>> m = [] >>> ml =[ m for i in range(x)] >>> ml [[], [], [], [], [], [], []] >>> ml[1].append('test') >>> ml [['test'], ['test'], ['test'], ['test'], ['test'], ['test'], ['test']] pan From shalehperry@attbi.com Fri Apr 25 02:01:09 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Apr 25 01:01:09 2003 Subject: [Tutor] List Comprehension (shared references) In-Reply-To: <20030425034904.GA9074@johnsons-web.com> References: <20030425034904.GA9074@johnsons-web.com> Message-ID: <200304242200.14238.shalehperry@attbi.com> On Thursday 24 April 2003 20:49, Tim Johnson wrote: > Hi all: > I'm just getting my feet wet with list comprehensions. > I need to write a function that returns a nested list > of empty lists. > > The following console session seems to fit the bill. > x = 7 > > >>> ml = [[] for row in range(x)] > >>> ml > > [[], [], [], [], [], [], []] > [] generates a new list each time, so it is indeed safe. From francois.granger@free.fr Fri Apr 25 10:46:03 2003 From: francois.granger@free.fr (Francois Granger) Date: Fri Apr 25 09:46:03 2003 Subject: [Tutor] Nesting lists? In-Reply-To: References: Message-ID: At 20:46 +0200 24/04/2003, in message [Tutor] Nesting lists?, Wayne Koorts wrote: >Hi, > >I'd like to have 'an array of arrays'. Yes, yes I know it's not an >array in python but a list. What I'd like to do is something to the >effect of: > >data = [data1[], data2[], data3[]] > >but that just gives me an error. I thought of maybe using a dictionary? >>> data1 = ['a'] >>> data2 = ['b'] >>> data3 = ['c'] >>> data = [] >>> data.append(data1) >>> data.append(data2) >>> data.append(data3) >>> data [['a'], ['b'], ['c']] -- Hofstadter's Law : It always takes longer than you expect, even when you take into account Hofstadter's Law. From SWidney@ci.las-vegas.nv.us Fri Apr 25 11:34:01 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Apr 25 10:34:01 2003 Subject: [Tutor] Nesting lists? Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8552@sovereign.ci.las-vegas.nv.us> > > I'd like to have 'an array of arrays'. Yes, yes I know it's not an > > array in python but a list. What I'd like to do is something to the > > effect of: > > > > data = [data1[], data2[], data3[]] > > > > but that just gives me an error. I thought of maybe using a > > dictionary? > > >>> data1 = ['a'] > >>> data2 = ['b'] > >>> data3 = ['c'] > >>> data = [] > >>> data.append(data1) > >>> data.append(data2) > >>> data.append(data3) > >>> data > [['a'], ['b'], ['c']] There's a very subtle trap here for the unwary. After entering the above in the interpreter, try this: >>> data1 = [1] >>> data2 = [2] >>> data3 = [3] >>> data [['a'], ['b'], ['c']] >>> data1 [1] >>> data2 [2] >>> data3 [3] >>> Previously on this list, Danny Yoo gave a wonderful explanation of why this happens (including ASCII graphics!). This is not a bug! But it can bite you. Search the archives if you're interested. Now look at this: >>> data1 = ['a'] >>> data2 = ['b'] >>> data3 = ['c'] >>> data = [] >>> data.append(data1) >>> data.append(data2) >>> data.append(data3) >>> data [['a'], ['b'], ['c']] >>> data1.append(1) >>> data2.append(2) >>> data3.append(3) >>> data [['a', 1], ['b', 2], ['c', 3]] >>> data1.pop(0) 'a' >>> data2.pop(0) 'b' >>> data3.pop(0) 'c' >>> data [[1], [2], [3]] >>> Food for thought.... Scott From zak@harlekin-maus.com Fri Apr 25 12:53:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Apr 25 11:53:02 2003 Subject: [Tutor] __init__ for class instantiation? Message-ID: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> Here's a short history: I'm working on an interactive fiction engine, and I'd like to create a list of verbs dynamically, based on the classes created. My current solution is to define the class, then run a verb-grabber function right after that definition: import wordlist def getActions (thingClass): for m in dir (thingClass): if m [:4] == 'act_': wordlist.addVerb (m [4:]) # Player class, where act_* defines a verb class Player (Thing): def __init__ (self): ... code ... def act_go (self, parsed): ... code ... def act_look (self, parsed): ... code ... getActions (Player) --- My question is: Is there a function I can define in the base Thing class which would run once Player (or any other Thing child) has been fully defined? Or is my current solution as close as I can get? --- Lastly, thanks for the quick answers to my last question! I'm looking forward to being a contributing part of this list. -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From antonmuhin at rambler.ru" References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> Message-ID: <1074601035.20030425201807@rambler.ru> Hello Zak, Friday, April 25, 2003, 7:51:51 PM, you wrote: ZA> Here's a short history: I'm working on an interactive fiction engine, and ZA> I'd like to create a list of verbs dynamically, based on the classes ZA> created. ZA> My current solution is to define the class, then run a verb-grabber ZA> function right after that definition: ZA> import wordlist ZA> def getActions (thingClass): ZA> for m in dir (thingClass): ZA> if m [:4] == 'act_': ZA> wordlist.addVerb (m [4:]) ZA> # Player class, where act_* defines a verb ZA> class Player (Thing): ZA> def __init__ (self): ZA> ... code ... ZA> def act_go (self, parsed): ZA> ... code ... ZA> def act_look (self, parsed): ZA> ... code ... ZA> getActions (Player) ZA> --- ZA> My question is: Is there a function I can define in the base Thing class ZA> which would run once Player (or any other Thing child) has been fully ZA> defined? Or is my current solution as close as I can get? ZA> --- ZA> Lastly, thanks for the quick answers to my last question! I'm looking ZA> forward to being a contributing part of this list. I hope that this example might be of interest for you: class MetaVerbPrinter(type): def __new__(cls, name, bases, dict): print "Verbs of class", name, ">", [m for m in dict if m.startswith("act_")] return type.__new__(cls, name, bases, dict) class Thing: __metaclass__ = MetaVerbPrinter class Player (Thing): def __init__ (self): pass def act_go (self, parsed): pass def act_look (self, parsed): pass *Warning* I'm just playing with metaclasses and I'm not an expert. -- Best regards, anton mailto:antonmuhin@rambler.ru From dana@pixelenvy.ca Fri Apr 25 13:21:16 2003 From: dana@pixelenvy.ca (Dana Larose) Date: Fri Apr 25 12:21:16 2003 Subject: [Tutor] __init__ for class instantiation? In-Reply-To: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> Message-ID: On Fri, 25 Apr 2003, Zak Arntson wrote: > Here's a short history: I'm working on an interactive fiction engine, and > I'd like to create a list of verbs dynamically, based on the classes > created. > > My current solution is to define the class, then run a verb-grabber > function right after that definition: > > import wordlist > > def getActions (thingClass): > for m in dir (thingClass): > if m [:4] == 'act_': > wordlist.addVerb (m [4:]) > > # Player class, where act_* defines a verb > class Player (Thing): > def __init__ (self): > ... code ... > def act_go (self, parsed): > ... code ... > def act_look (self, parsed): > ... code ... > > getActions (Player) > > --- > > My question is: Is there a function I can define in the base Thing class > which would run once Player (or any other Thing child) has been fully > defined? Or is my current solution as close as I can get? > If I understand what you want to do, why not put getActions in the __init__ method of Thing? Then, at the end of __init__ for Player (or other child classes you define), call Thing's constructor: class Thing: def __init(self): ... code .... self.getActions() class Player(Thing): def __init__(self): ... code ... Thing.__init__(self) dana. From aicolburn@yahoo.com Fri Apr 25 13:49:01 2003 From: aicolburn@yahoo.com (Alan Colburn) Date: Fri Apr 25 12:49:01 2003 Subject: [Tutor] Copying registry entries Message-ID: <20030425164809.17411.qmail@web41612.mail.yahoo.com> Hi all -- I'd like to write a script to back up my Outlook Express (WinXP e-mail) data. Most of the information is in files and folders, which I understand how to copy. However, some of the information to back up is stored in registry keys. ... Can anyone help me understand how to copy a registry key? As always, thank you! -- Al C. __________________________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo http://search.yahoo.com From zak@harlekin-maus.com Fri Apr 25 14:01:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Apr 25 13:01:01 2003 Subject: [Tutor] __init__ for class instantiation? In-Reply-To: References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> Message-ID: <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> > On Fri, 25 Apr 2003, Zak Arntson wrote: > >> Here's a short history: I'm working on an interactive fiction engine, >> and I'd like to create a list of verbs dynamically, based on the >> classes created. >> My question is: Is there a function I can define in the base Thing >> class which would run once Player (or any other Thing child) has been >> fully defined? Or is my current solution as close as I can get? >> > > If I understand what you want to do, why not put getActions in the > __init__ method of Thing? Then, at the end of __init__ for Player (or > other child classes you define), call Thing's constructor: > > class Thing: > def __init(self): > ... code .... > self.getActions() > > class Player(Thing): > def __init__(self): > ... code ... > Thing.__init__(self) > > dana. The problem here (as with __new__) is that __init__ will be called with every creation of a Player instance. I just want to getActions once the Player class is defined. Otherwise, I run getActions() _every_ time I create a Player (or any other Thing child). This wouldn't hurt much, considering even with multiplayer, a new player wouldn't be created often. It's just not as elegant as running only when Player is defined. But! Your method is cleaner than my approach. I'll put getActions into Thing's __init__. It seems more elegant than me plonking a getActions after every class definition. That leads me to a side question, though: Does __init__ of a parent only run when explicitly called by the child's __init__? -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From zak@harlekin-maus.com Fri Apr 25 14:19:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Apr 25 13:19:02 2003 Subject: [Tutor] __init__ for class instantiation? In-Reply-To: <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> Message-ID: <1229.192.207.104.231.1051291054.squirrel@mail.harlekin-maus.com> > > That leads me to a side question, though: Does __init__ of a parent only > run when explicitly called by the child's __init__? Nevermind that question. I just answered it myself with some goofing around in the Shell. -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From SWidney@ci.las-vegas.nv.us Fri Apr 25 15:03:21 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Apr 25 14:03:21 2003 Subject: [Tutor] Copying registry entries Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8554@sovereign.ci.las-vegas.nv.us> > I'd like to write a script to back up my Outlook > Express (WinXP e-mail) data. Most of the information > is in files and folders, which I understand how to > copy. However, some of the information to back up is > stored in registry keys. ... Can anyone help me > understand how to copy a registry key? > > As always, thank you! -- Al C. > It's true, the documentation for the Win32 extensions is pretty sparse. And if you're not familiar with the API, it's hard to know where to start looking. But what you want is there, under Win32 API, Modules, win32api in the Python for Win32 Extensions Help. There are 20-or-so functions there specifically for dealing with the registry. Here's an example fresh off the grill: >>> import win32api >>> import win32con >>> key = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Python\\PythonCore\\2.2\\PythonPath', 0, win32con.KEY_QUERY_VALUE) >>> val = win32api.RegQueryValueEx(key, '') >>> val ('C:\\Python22\\Lib;C:\\Python22\\DLLs;C:\\Python22\\Lib\\lib-tk', 1) >>> win32api.RegCloseKey(key) >>> There is more that you'll want to take advantage of, but this should give you a good start. Scott From alan.gauld@blueyonder.co.uk Fri Apr 25 15:10:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 25 14:10:02 2003 Subject: [Tutor] __init__ for class instantiation? References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> Message-ID: <007401c30b55$d26cfeb0$6401a8c0@xp> > def getActions (thingClass): ... > > class Player (Thing): > def __init__ (self): > ... code ... > def act_go (self, parsed): > ... code ... > def act_look (self, parsed): > ... code ... > > My question is: Is there a function I can define in the base Thing class > which would run once Player (or any other Thing child) has been fully > defined? Or is my current solution as close as I can get? The short answer is no I don't believe so, not as such. The definition of a class doesn't (except at a very deep secret level) trigger any action in Python so you can't force it to do anything. You could maybe play some tricks with class constructor functions that return a Thing class after running your magic method. class Thing: def doTheBiz(): # use new static method syntax here ... define rest of Thing here... def makeThing(): t = Thing # note t is a class not an instance! t.doTheBiz() # needs to be a class (ie static) method return t Then in the new class defintions call makeThing: class C(makeThing()): # define C here But I haven't tried this.... Normally you wouyld do it at the instance level, is there any reason why you can't do that? ie. Wait till the class is instantiated... Alan G From alan.gauld@blueyonder.co.uk Fri Apr 25 15:14:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 25 14:14:01 2003 Subject: [Tutor] Nesting lists? References: Message-ID: <007b01c30b56$6a00dbc0$6401a8c0@xp> > >array in python but a list. What I'd like to do is something to the > >effect of: > > > >data = [data1[], data2[], data3[]] > > data1 = [] data2 = [] data3 = [] data = [data1, data2, data3] Or even: data = [ [], [], [] ] data[0].append(1) #-> [ [1], [], [] ] etc. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From malex@tagancha.org Fri Apr 25 15:24:01 2003 From: malex@tagancha.org (Oleksandr Moskalenko) Date: Fri Apr 25 14:24:01 2003 Subject: [Tutor] code efficiency and biological databases In-Reply-To: References: <1051217542.3ea84e8688500@webmail.uchicago.edu> Message-ID: <20030424225454.GA8760@purdue.edu> Danny, * Danny Yoo [2003-04-24 15:15:53 -0700]: > > > On Thu, 24 Apr 2003 pan@uchicago.edu wrote: > > > Thx Danny for pointing out the rate limiting step in the code I > > presented earlier. > > The computer scientist Alan Perlis once quipped: "Lisp programmers know > the value of everything, and the cost of nothing." Let's make sure that > that generalization doesn't apply so strongly to Python programmers. > *grin* > > > > I am heading toward the world of genome/evolution analysis > > Very cool! Yes, biologists often have to deal with enormous databases, so > I think it can be effective to be aware of program efficiency. > > The Institute of Genomic Research (TIGR) keeps a respository of many > genomes available on their FTP site; what's sorta neat is that a lot of > their data is in XML. But what sorta sucks is that a lot of their data is > in XML. *grin* > > If you're ever interested in the model organism 'Arabidopsis Thaliana', > you can check out a concrete example of a medium-sized dataset: > > ftp://ftp.tigr.org/pub/data/a_thaliana/ath1/BACS/ > > I'm using the 'gzip' and 'pulldom' modules to open and parse out > individual sections of each "Bacterial Artificial Chromosome" at work. > But the library documentation on 'pulldom' is so laughably sparse at the > moment --- I'm thinking of writing a small tutorial on it when I get the > chance. > This would be a great tutorial to write! You have a supporting vote from me. > > Sorry for being so off topic; I just like talking about my work... *grin* > Talk to you later! Alex. -- The lyf so short, the craft so long to lerne. -- Chaucer From zak@harlekin-maus.com Fri Apr 25 16:41:21 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Apr 25 15:41:21 2003 Subject: [Tutor] __init__ for class instantiation? In-Reply-To: <007401c30b55$d26cfeb0$6401a8c0@xp> References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <007401c30b55$d26cfeb0$6401a8c0@xp> Message-ID: <1990.192.207.104.231.1051299616.squirrel@mail.harlekin-maus.com> >> >> My question is: Is there a function I can define in the base Thing > class >> which would run once Player (or any other Thing child) has been > fully >> defined? Or is my current solution as close as I can get? > > The short answer is no I don't believe so, not as such. > The definition of a class doesn't (except at a very deep secret > level) trigger any action in Python so you can't force it to > do anything. > > You could maybe play some tricks with class constructor functions > that return a Thing class after running your magic method. > > Normally you wouyld do it at the instance level, is there any reason why > you can't do that? ie. Wait till the class is instantiated... > > Alan G My best current solution is to do just that. I can do it via __init__, but this means the function I want to run once upon the class's definition is actually called with every instance of the class. But I'm not going to stress about the CPU cycles caused by this :) -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From tbrauch@mindless.com Fri Apr 25 16:56:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Fri Apr 25 15:56:02 2003 Subject: [Tutor] Python and Apache (OT) Message-ID: <004a01c30b64$8f266880$6600a8c0@tbrauch> Python seems to be getting a bad rap in a web-based addition to the book "Apache: The Definitive Guide, 3rd ed.", Peter Laurie. He was unfamiliar with Python, but "in an hour or so" he was able to create a cgi script. That makes Python seem rather easy to learn, right? He also complained about the indenting. And, he says it "lack[s] some of the bells and whistles other languages offer." [side note: I have no idea how to write a script in Java or Perl that will ftp into a site, get a specific file, strip all the excess that doesn't interest me, reformat what is left over in the style I need, log into another ftp server and publish the information as an html document. I did this in about 5 minutes with Python the other day]. Anyway, read for yourself and leave a comment or two if you wish. - Tim From hall@ouhep1.nhn.ou.edu Fri Apr 25 18:14:01 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri Apr 25 17:14:01 2003 Subject: [Tutor] Python and Apache (OT) In-Reply-To: <004a01c30b64$8f266880$6600a8c0@tbrauch> Message-ID: >From reading this, it looks like the guy really didnt want to write this piece to begin with. he states something to the effect that he thinks python is not very widely used for cgi scripting, however it is my understanding that python works very well for cgi scripting, and is widely used for that purpose. his rail on indentation seems a bit asinine, but thats just my opinion. I happen to love pythons indentation, and have carried over the use of indentation into my C++ coding, despite not needing it (its much easier to look for an indented block than some damn squiggly brace.) Maybe the concept of indentation over braces ires oldtimers, as it goes a long way into forcing one to write organized code, which is easily read by anyone. (I recently had the very un-fun experience of having to modify someone elses very un-organized C++ code, and it almost drove me mad trying to figure out what the heck the code was doing! Organized C++ is hard enough to understand if you didnt write it...) Anyway, overall I think this guy was writing a piece he really didnt want to have to write in the first place. He obviously didnt put much time into exploring python. Its really a shame that people might read this with no prior knowledge of python and form an opinon based on this piece. Ike On Fri, 25 Apr 2003, Timothy M. Brauch wrote: > Python seems to be getting a bad rap in a web-based addition to the book > "Apache: The Definitive Guide, 3rd ed.", Peter Laurie. > > > He was unfamiliar with Python, but "in an hour or so" he was able to create > a cgi script. That makes Python seem rather easy to learn, right? He also > complained about the indenting. And, he says it "lack[s] some of the bells > and whistles other languages offer." [side note: I have no idea how to > write a script in Java or Perl that will ftp into a site, get a specific > file, strip all the excess that doesn't interest me, reformat what is left > over in the style I need, log into another ftp server and publish the > information as an html document. I did this in about 5 minutes with Python > the other day]. > > Anyway, read for yourself and leave a comment or two if you wish. > > - Tim > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From dyoo@hkn.eecs.berkeley.edu Fri Apr 25 18:33:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Apr 25 17:33:01 2003 Subject: [Tutor] Python and Apache (OT) [use prepared statements!] In-Reply-To: <004a01c30b64$8f266880$6600a8c0@tbrauch> Message-ID: On Fri, 25 Apr 2003, Timothy M. Brauch wrote: > Python seems to be getting a bad rap in a web-based addition to the book > "Apache: The Definitive Guide, 3rd ed.", Peter Laurie. > Hi Timothy, It may just be that he was asked to write the article in a hurry --- a lot of the tone of his article implies that he had not talked with other Python folks while preparing the article. He's making a lot of assumptions about the language that only time and experience will fix. It sounds like he's getting slightly roasted in the feedback section of his article, so we won't get into subjective details: let's concentrate on the objective things he talks about in his article. A few things he complains about are non-issues. For example, here's one complaint he makes about documentation: """(You can also download the manuals. In the world of freeware, where no one is paid to do the tiresome work of presenting user-friendly material, you get over 700 files without, as far as I could see, an index. But, hey!)""" It's true that the documentation still does need some work, but this particular complaint is on pretty shaky ground. There are several indices in the documentation. If we're interested in a list of modules, we can look at: http://www.python.org/doc/current/modindex.html And if we're interested in a function in the Library Reference, there's an extensive index at: http://www.python.org/doc/current/lib/genindex.html His program example uses quite a few deprecated and private modules that should not be imported directly; in particular, he uses '_mysql' and 'regex' --- he should really be using the 'MySQLdb' module frontend, as well as the 're' regular expression module. And it's really odd that he's not using the 'cgi' module to do form parameter parsing. Why do it by hand if the standard library does it better? Let's take a chunk of his code, and rewrite it using MySQLdb so that it's clearer. Hmmm... let's see... ### original code a="select xname,sname from people where xname='"+c+"'" print a,"
" db.query(a) r=db.store_result() while(1): a=r.fetch_row() if(len(a)): print "Christian name:",a[0][0], "Surname:\ ",a[0][1],"
" else: break ### Yikes. There are some major problems with this code, especially on the first line: a="select xname,sname from people where xname='"+c+"'" When we're working with databases, we should always try to use "prepared statement" syntax if it's possible to do so: the database handler should be responsible for doing quotation for us, not us. This is such an important thing to know that we should talk about it more. There's a strong possibility that 'c' can itself contain quotation marks, in which case the xname's contents will leak right into our SQL. One example of such a name is: O'Reilly *cough* For a SELECT statement, it might not be too bad, but if this had been an UPDATE or DELETE, imagine what can happen if we're doing something like: "delete from people where name = '" + c + "' If someone feeds in: c = "' or 1 = 1" the resulting SQL statement will completely fry the 'people' table. This sort of stuff is especially relevant to CGI code, where we do need to be careful how we handle data from the outside world. Here's the rewritten code, using prepared statement syntax: ### Assume 'conn' is a database connection conforming to DB API 2.0 print a, "
" cursor = conn.cursor() cursor.execute("select xname,sname from people where xname=%s", c) for name, surname in cursor.fetchall(): print "Christian name:", name, "Surname:", surname, "
" ### My main impression of the article is that he wrote it in isolation from the rest of the Python community. If he had properly peer reviewed it, the article would have been more accurate. Hope this helps! From alan.gauld@blueyonder.co.uk Fri Apr 25 21:39:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 25 20:39:01 2003 Subject: [Tutor] __init__ for class instantiation? References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <007401c30b55$d26cfeb0$6401a8c0@xp> <1990.192.207.104.231.1051299616.squirrel@mail.harlekin-maus.com> Message-ID: <001c01c30b8c$49b0db00$6401a8c0@xp> > My best current solution is to do just that. I can do it via __init__, but > this means the function I want to run once upon the class's definition is > actually called with every instance of the class. But I'm not going to > stress about the CPU cycles caused by this :) Set a class variable to one the first time def __init__(...): # do the usual stuff if not MyClass.flag: myClsass.flag = 1 self.MySpecialMethod() Then only the first instance calls the method, others just do the if test. OR set it to None def __init__(....): # usual stuff self.MySpecialMethod() self.MySpecialMethod = None # note no parens! First time through it calls it, subsequent times theres nothing to call. You ight need to wrap a try/except round it too... HTH, Alan G. From alan.gauld@blueyonder.co.uk Fri Apr 25 21:44:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Apr 25 20:44:02 2003 Subject: [Tutor] __init__ for class instantiation? References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <007401c30b55$d26cfeb0$6401a8c0@xp> <1990.192.207.104.231.1051299616.squirrel@mail.harlekin-maus.com> Message-ID: <002d01c30b8c$de507e50$6401a8c0@xp> > My best current solution is to do just that. I can do it via __init__, but > this means the function I want to run once upon the class's definition is > actually called with every instance of the class. But I'm not going to > stress about the CPU cycles caused by this :) One other thought. Create a singleton class(ACtionList?) to hold the actions then assign that to a member of your Thing class... Pass it into Thing as a default init parameter even. Then every Thing type object has a reference to the single instance of ActionList. Just a thought. Alan G. From op73418@mail.telepac.pt Fri Apr 25 22:23:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Apr 25 21:23:01 2003 Subject: [Tutor] __init__ for class instantiation? References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <007401c30b55$d26cfeb0$6401a8c0@xp> <1990.192.207.104.231.1051299616.squirrel@mail.harlekin-maus.com> Message-ID: <002d01c30b92$5b9d44b0$9d1a0dd5@violante> ----- Original Message ----- From: "Zak Arntson" To: Sent: Friday, April 25, 2003 8:40 PM Subject: Re: [Tutor] __init__ for class instantiation? > >> > >> My question is: Is there a function I can define in the base Thing > > class > >> which would run once Player (or any other Thing child) has been > > fully > >> defined? Or is my current solution as close as I can get? > > > > The short answer is no I don't believe so, not as such. > > The definition of a class doesn't (except at a very deep secret > > level) trigger any action in Python so you can't force it to > > do anything. > > > > You could maybe play some tricks with class constructor functions > > that return a Thing class after running your magic method. > > > > > Normally you wouyld do it at the instance level, is there any reason why > > you can't do that? ie. Wait till the class is instantiated... > > > > Alan G > > My best current solution is to do just that. I can do it via __init__, but > this means the function I want to run once upon the class's definition is > actually called with every instance of the class. But I'm not going to > stress about the CPU cycles caused by this :) > Just add a class attribute like _was_get_args_called = 0 and in the __init__ something like if not self._was_get_args_called: self._was_get_args_called = 1 But as another poster mentioned what the problem is begging here is really a metaclass. HTH, G. Rodrigues > -- > Zak Arntson > www.harlekin-maus.com - Games - Lots of 'em From magnus@thinkware.se Sat Apr 26 06:11:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Apr 26 05:11:02 2003 Subject: [Tutor] Nesting lists? In-Reply-To: <20030425213301.18611.77423.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030426103930.02644958@www.thinkware.se> At Fri, 25 Apr 2003 19:13:46 +0100, Alan Gauld wrote: > > >array in python but a list. What I'd like to do is something to >the > > >effect of: > > > > > >data = [data1[], data2[], data3[]] > > > >data1 = [] >data2 = [] >data3 = [] >data = [data1, data2, data3] > >Or even: > >data = [ [], [], [] ] > >data[0].append(1) #-> [ [1], [], [] ] If you wan't to use this array of array for numeric values, you might want to have a look at "Numeric", see http://www.pfdubois.com/numpy/ E.g. >>> import Numeric >>> a = Numeric.array([[1,2,3],[4,5,6],[7,8,9]]) >>> b = Numeric.array([[3,2,1],[6,5,4],[9,8,7]]) >>> print a [[1 2 3] [4 5 6] [7 8 9]] >>> print b [[3 2 1] [6 5 4] [9 8 7]] >>> c = a * b >>> print c [[ 3 4 3] [24 25 24] [63 64 63]] >>> # That was just an elementwise multiplication. >>> d = Numeric.matrixmultiply(a, b) >>> print d [[ 42 36 30] [ 96 81 66] [150 126 102]] >>> # Aha, here we have a proper matrix multiplication. >>> Numeric.transpose(d) array([[ 42, 96, 150], [ 36, 81, 126], [ 30, 66, 102]]) # etc... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From allyn.@tardigrade.net Sat Apr 26 07:20:03 2003 From: allyn.@tardigrade.net (Allyn Weaks) Date: Sat Apr 26 06:20:03 2003 Subject: [Tutor] Python and Apache (OT) In-Reply-To: References: Message-ID: On 25/4/2003, Isaac Hall wrote: >he states something to the effect that he thinks >python is not very widely used for cgi scripting, however it is my >understanding that python works very well for cgi scripting, and is >widely used for that purpose. As a python beginner who wants to do some cgi things, I have to agree with the author on this point. Perhaps python is widely used for cgi, but if so, those programmers aren't sharing their work. I'm not talking about frameworks here, I have no desire for frameworks, just simple everyday cgis. Last month I went out looking for examples to study, and while I could easily find thousands of cgis written in perl, the available python cgis were in the tens. Not even the hundreds. Many of those were years old, and badly needed fixing and/or modernization. I realize that most of the thousands of perl cgis are garbage (buggy, no security, etc), and many of the rest are near clones of each other, but for any type of web task (form manager, log analysis, chat room, database, search engine, etc) there seem to be at least three or four excellent ones to choose from. Python has a long way to go to fill in those gaps. A plea for those of you writing cgi scripts, even simple one-offs if they work--submit them to the standard repositories! There isn't even much in the vaults of parnassus, let alone the big indices such as (perl: 3029, python: 13, visual basic: 43). By the way, I'm constantly amused by anyone not liking indentation and lack of braces on first sight. It was largely that that made me want to drop my tussling with perl for python about 30 seconds after accidentally running into some python source. It was only afterwards that I found the even better goodies, such as decent list manipulation. -- Allyn Weaks allyn@tardigrade.net Seattle, WA Sunset zone 5 Pacific NW Native Wildlife Gardening: http://www.tardigrade.org/natives/ "The benefit of even limited monopolies is too doubtful, to be opposed to that of their general suppression." Thomas Jefferson From stuart_clemons@us.ibm.com Sat Apr 26 11:11:02 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Sat Apr 26 10:11:02 2003 Subject: [Tutor] Comparing lines in two files, writing result into a t hird file Message-ID: Hi Scott: I just wanted to say thanks again. I was able to spend time breaking down the code you provided. (Start with a few lines of code snippet, add print out variables, run code, see exactly what was going on, add more code snippet, print out variables, etc.). Wow. Clear, concise and dead-on ! (I'm not worthy !!!). Extremely eloquent in its simplicity. This really clears up the problem I had in the past when I tried to read a file into a dictionary. This structure worked perfectly for my immediate problem and I can see that it will work perfectly for variations of the this merge report that I want to provide. This weekend I hope to look at Danny and Pan's approaches as a learning exercise. Danny got me thinking about code efficiency. I hope to look at some Python code I wrote about a year ago (that's remarkably still being used) when I last worked with Python. I'm still a newbie, but I was a really a newbie then. I know that that code could be done much more efficiently. Anyway, enough rambling. I really feel like I learned a lot just by asking one question. Getting this information (and seeing some success in using it) has really got me psyched about Python. Thanks again. This is a great forum. - Stuart ----- Forwarded by Stuart Clemons/Westford/IBM on 04/26/03 09:37 AM ----- Stuart Clemons To: Scott Widney 04/24/03 07:42 AM cc: tutor@python.org Subject: RE: [Tutor] Comparing lines in two files, writing result into a t hird file (Document link: Stuart Clemons) Hi Scott: Thanks for laying out the dictionary structure for me. I wanted to use dictionaries a year ago for something I was working on, but I couldn't get dictionaries to work for me (it was very frustrating), so I ended up hacking something else together. I think that was about the last time I needed to use Python for anything. Anyway, I'm going to try using this structure to solve the problem I'm working on. I need to produce this "merged" list fairly quickly (like today) and then on a regular basis. To Danny and Pan: Thanks very much for contributing thoughts and code related to this problem. Since it looks like I'll have a need to use Python for the forseeable future, as a learning exercise, I'm going to try each of these approaches to this problem. Most of the work I'll need Python for is similar to this problem. (Next up is formatting a dump of a text log file into a readable report. I think I know how to handle this one, but if not, as Arnold would say, I'll be back !) Thanks again. - Stuart > Concerning dictionaries, do you think dictionaries is the structure > to use ? If so, I'll try to spend some time reading up on > dictionaries. I do remember having problems reading a file into a > dictionary when I tried it a year ago or so. Since you're pressed for time, I can give you a basic script using a dictionary.... ##### d = {} # Start with an empty dictionary f1 = file('file1.txt', 'r') for num in f1.readlines(): num = num.strip() # get rid of any nasty newlines d[num] = 1 # and populate f1.close() f2 = file('file2.txt', 'r') for num in f2.readlines(): num = num.strip() # again with the newlines if d.has_key(num): d[num] += 1 # <- increment value, or else: d[num] = 1 # <- create a new key f2.close() nums = d.keys() nums.sort() f3 = file('file3.txt', 'w') for num in nums: f3.write(num) # Here we put the if d[num] > 1: # newlines back, either f3.write("*\n") # <- with else: # or f3.write("\n") # <- without f3.close() # the asterisk #### Should be fairly quick. And it's certainly easier to flash-parse with the naked eye than a value-packed list comprehension. HTH Scott From antonmuhin at rambler.ru" References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> Message-ID: <1761186205.20030426183113@rambler.ru> Hello Zak, Friday, April 25, 2003, 9:00:54 PM, you wrote: ZA> The problem here (as with __new__) is that __init__ will be called with ZA> every creation of a Player instance. It seems that you are wrong here---__new__ is called only once after class is defined. -- Best regards, anton mailto:antonmuhin@rambler.ru From am@fx.ro Sat Apr 26 13:09:01 2003 From: am@fx.ro (Adrian Maier) Date: Sat Apr 26 12:09:01 2003 Subject: [Tutor] The "No parsers found" error. Message-ID: <20030426183638.A320@coto> Hello! This is a rather long post. The problem is related to a program (called GNUe-forms) that uses xml.sax and is unable to run because it can't find any XML parser. My feeling is that the problem could be caused by some version incompatibility rather than a bug in that program. But I am a newbie and have never used xml.sax, so that i have no clue about how xml.sax is supposed to be used . So: I have come across a development suite called GNUe (GNU Enterprise). It is written in python and has several components: Forms, Reports, Designer. It is able to use several database engines. After installing gnue, i am now trying to see the examples it comes with. The forms are stored in XML ( the file extension is gfd). When trying to run any of the samples it complains about not finding any (xml) parser: $ gnue-form form.gfd DB000: Traceback (most recent call last): [...] DB000: File "/usr/local/gnue/lib/python/gnue/common/GParser.py", line 89, in loadXMLObject DB000: parser = xml.sax.make_parser() DB000: File "/usr/local/lib/python2.2/xml/sax/__init__.py", line 93, in make_parser DB000: raise SAXReaderNotAvailable("No parsers found", None) DB000: xml.sax._exceptions.SAXReaderNotAvailable: No parsers found This is a part of the file that causes the exception: ............. part of GParser.py ............ def loadXMLObject(stream, handler, rootType, xmlFileType, initialize=1, attributes={}, initParameters={}): # Create a parser parser = xml.sax.make_parser() # <-------line 89 # Set up some namespace-related stuff for the parsers parser.setFeature(xml.sax.handler.feature_namespaces, 1) .............................. A (very) quick look in the help() showed me that the function make_parser expects a parameter (the list of the "available parsers"), but i haven't been able to figure out what values should that list contain ( ok: it's the list of the modules that provide parsers. But which are those modules? ) Please tell me if you have any idea about what is wrong. Maybe I have to install some additional modules? I am using Python 2.2 built from sources on a Debian 2.2r5. Thank you in advance for any hint you could provide, Adrian Maier (am@fx.ro) From pan@uchicago.edu Sat Apr 26 14:49:02 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Sat Apr 26 13:49:02 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third file In-Reply-To: <20030426160007.23248.79157.Mailman@mail.python.org> References: <20030426160007.23248.79157.Mailman@mail.python.org> Message-ID: <1051379330.3eaac682b106c@webmail-b.uchicago.edu> Hi Stuart, Scott's example is indeed excellent. So far we've got 3 different approaches: 1) Scott's dictionary 2) Danny's list comparison 3) Pan's list comprehension I believe Scott's approach is the fastest one, but I didn't do any rate test on it. I actually tried to see if I can modify my code to 'beat' Danny's, in terms of speed. But I failed, miserably, hahaha ... I guess my appraoch is the slowest one and can only be used when the data size is < 3000. In my opinion, Scott's code can still be modified to make it even more efficient (or, more eloquent at least): 1) Use the built-in .setdefault() function of a dict for the folloing action: if d.has_key(num): d[num] += 1 # <- increment value, or else: d[num] = 1 # <- create a new key I'll leave this for you to figure out. 2) His dictionary 'dum' looks like: 'a':1, 'b':1, 'd':2, 'f':1, ... By using "d[num] = 1" and "d[num] += 1" it saves the 'counts' as the dictionary values. It is actually better to save the 'keys' instead of 'counts' (d[num] = num + '\n' or + '*\n'): 'a':'a\n', 'b':'b\n', 'd':'d*\n', 'f':'f\n', ... The 'dictionary-saving' steps are exactly the same, but you don't need the final checking (if d[num] > 1:) in the third part of his code. Instead you just go get the d.values() and that's it. This would reduce the code size significantly. The other concern is that when loading the first file: f1 = file('file1.txt', 'r') for num in f1.readlines(): num = num.strip() # get rid of any nasty newlines d[num] = 1 # and populate f1.close() there's no "if d.has_key(num):" checking. That's to assume that in the file1.txt there are no duplicate items. If there are, then Scott's code will miss them. Anyway enough words for now. Enjoy your py diving. pan > Message: 6 > Subject: RE: [Tutor] Comparing lines in two files, writing result into a > t hird file > To: Scott Widney > Cc: tutor@python.org > From: stuart_clemons@us.ibm.com > Date: Sat, 26 Apr 2003 10:00:30 -0400 > > Hi Scott: > > I just wanted to say thanks again. I was able to spend time breaking down > the code you provided. (Start with a few lines of code snippet, add print > out variables, run code, see exactly what was going on, add more code > snippet, print out variables, etc.). > > Wow. Clear, concise and dead-on ! (I'm not worthy !!!). Extremely > eloquent in its simplicity. This really clears up the problem I had in the > past when I tried to read a file into a dictionary. This structure worked > perfectly for my immediate problem and I can see that it will work > perfectly for variations of the this merge report that I want to provide. > > This weekend I hope to look at Danny and Pan's approaches as a learning > exercise. Danny got me thinking about code efficiency. I hope to look at > some Python code I wrote about a year ago (that's remarkably still being > used) when I last worked with Python. I'm still a newbie, but I was a > really a newbie then. I know that that code could be done much more > efficiently. > > Anyway, enough rambling. I really feel like I learned a lot just by asking > one question. Getting this information (and seeing some success in using > it) has really got me psyched about Python. Thanks again. This is a great > forum. > > - Stuart From carroll@tjc.com Sat Apr 26 16:19:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Sat Apr 26 15:19:02 2003 Subject: [Tutor] Comparing lines in two files, writing result into a third file In-Reply-To: Message-ID: On Wed, 23 Apr 2003 stuart_clemons@us.ibm.com wrote: > I have two files, file1.txt and file 2. txt, each containing numbers. I > want to compare the numbers in the files and put an asterisk at the end of > the numbers that match, writing the result into a third file, . If the files are small enough, one of the easiest ways would be to read each file into a sequence, then use difflib.differ() to produce a third sequence that highlights the differences. Then you can write that sequence out to a file, perhaps after reformattnig it from differ()'s format to your own. There's also a filecmp.cmp() method, which compares files, but unfortunately, it only tells you whether they're equal or not, without telling why they're different. Another approach might be to invoke the OS's diff command, and process the output. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From carroll@tjc.com Sat Apr 26 16:21:50 2003 From: carroll@tjc.com (Terry Carroll) Date: Sat Apr 26 15:21:50 2003 Subject: [Tutor] Python/CGI question: multiple-screen interview Message-ID: This is probably as much a CGI question as Python, but I hope it's not too off-topic. I want to write a Python web application (at this point, I'm thinking CGI) that asks the user a series of questions. I don't want to do a one-page form, because a lot of questions will be inapplicable depending on earlier answers.[1] This seems to require saving state in some way between invocations. What's the best approach for this? Cookies? Something else? Would you do this as multiple Python CGI programs, one for each set of questions, or a single program that sets up some sort of dialog? Finally, am I crazy for planning on doing this as CGI? Should I be thinking of doing it some other way, say as a Java servlet with Jython (about which I know nothing)? [1] An example may help. My application is to determine the expiration of a particular work's U.S. copyright. For works published prior to 1978, this is based on the publication date. For works created 1978 or later, it's based on the date of the author's death. So, if the user answers an early question that the work was published in, say, 1964, I don't want to ask if and when the author died; it doesn't matter, and won't affect the outcome. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From tbrauch@mindless.com Sat Apr 26 16:51:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sat Apr 26 15:51:02 2003 Subject: [Tutor] re question Message-ID: <002201c30c2d$1e172200$6600a8c0@tbrauch> I'm working with the re module, doing some file processing. I have a question that maybe someone can explain to me. The re module talks about raw strings and I'm not quite sure I understand what a raw string is and how it differs from a regular string. What is the difference? - Tim From craig@eigentone-solo-collective.net Sat Apr 26 17:25:02 2003 From: craig@eigentone-solo-collective.net (Craig Davey) Date: Sat Apr 26 16:25:02 2003 Subject: [Tutor] SAXReaderNotAvailable - problems using xml.dom in python2.1.3 Message-ID: Greetings I'm quite new to python so I apologize if I've overlooked the obvious. I've just installed python2.1.3 on Mac OS 10.2 and have run into a problem demonstrated by the following: --- snip/ ------------ >>> import xml.dom.minidom >>> dom = xml.dom.minidom.parseString('a little text for show') Traceback (most recent call last): File "", line 1, in ? File "/opt/PYTHON/PYTHON2.1.3/lib/python2.1/xml/dom/minidom.py", line 915, in parseString return _doparse(pulldom.parseString, args, kwargs) File "/opt/PYTHON/PYTHON2.1.3/lib/python2.1/xml/dom/minidom.py", line 901, in _doparse events = apply(func, args, kwargs) File "/opt/PYTHON/PYTHON2.1.3/lib/python2.1/xml/dom/pulldom.py", line 301, in parseString parser = xml.sax.make_parser() File "/opt/PYTHON/PYTHON2.1.3/lib/python2.1/xml/sax/__init__.py", line 88, in make_parser raise SAXReaderNotAvailable("No parsers found", None) xml.sax._exceptions.SAXReaderNotAvailable: No parsers found --- /snip ------------ I'm coming at this from a mostly ECMAScript and Lingo background so I'm afraid most of these errors are lost on me. I do understand that without some way to parse xml into a dom I'm going to have a hard time working with xml in python. Any pointers on how to resolve this problem are most appreciated, I really do not know where to start. - Craig Davey From krier115@student.liu.se Sat Apr 26 17:37:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Sat Apr 26 16:37:02 2003 Subject: [Tutor] re question In-Reply-To: <002201c30c2d$1e172200$6600a8c0@tbrauch> References: <002201c30c2d$1e172200$6600a8c0@tbrauch> Message-ID: <20030426203608.GA10244@n14.ryd.student.liu.se> On Sat, Apr 26, 2003 at 03:50:41PM -0400, Timothy M. Brauch wrote: > I'm working with the re module, doing some file processing. I have a > question that maybe someone can explain to me. The re module talks about > raw strings and I'm not quite sure I understand what a raw string is and how > it differs from a regular string. What is the difference? A raw string doesn't translate escape sequences and such. Raw strings are preceeded by an 'r'. Example: >>> print 'Hello\n' Hello >>> print r'Hello\n' Hello\n >>> 'Hello\n' 'Hello\n' >>> r'Hello\n' 'Hello\\n' In a raw string you can put special characters and likewise how you want without them getting their special meaning, they are just characters. Or you can see it so that Python automatically escapes the special characters so they lose their special meaning. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From tim@johnsons-web.com Sat Apr 26 19:34:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sat Apr 26 18:34:01 2003 Subject: [Tutor] Python/CGI question: multiple-screen interview In-Reply-To: References: Message-ID: <20030426223216.GH23285@johnsons-web.com> Hi Terry: Disclaimer - I pretty much 'earn my bread' with CGI, but I'm only slowly converting to python: * Terry Carroll [030426 11:28]: > This is probably as much a CGI question as Python, but I hope it's not too > off-topic. > > I want to write a Python web application (at this point, I'm thinking CGI) > that asks the user a series of questions. I don't want to do a one-page > form, because a lot of questions will be inapplicable depending on earlier > answers.[1] > > This seems to require saving state in some way between invocations. > What's the best approach for this? Cookies? Something else? I am not seeing anything in your plans that couldn't be solved simply by posting data forward via. Data entered in on page could be posted forward and 'stored' in hidden fields.... > Would you do this as multiple Python CGI programs, one for each set of > questions, or a single program that sets up some sort of dialog? There is no reason why this couldn't be done with one CGI application, really that's kind of up to you, based on the size of the script, etc. > Finally, am I crazy for planning on doing this as CGI? Should I be > thinking of doing it some other way, say as a Java servlet with Jython > (about which I know nothing)? I use MySql a lot, and frequently use mysql to store persistant data when it becomes unwieldly to pass around via 'get' or 'post' methods. My company's philosophy (and that's just our standard operating procedure) is to do as much on the server as possible. We resort to cookies as a last resort and javascript only when desired by the client and/or necessary. - the *KISS* principle - You've really got a lot of options here - it would help you to get 'up to speed' on cgi and find out what it offers you..... in my opinion. > > [1] An example may help. My application is to determine the expiration of > a particular work's U.S. copyright. For works published prior to 1978, > this is based on the publication date. For works created 1978 or later, > it's based on the date of the author's death. So, if the user answers an > early question that the work was published in, say, 1964, I don't want to > ask if and when the author died; it doesn't matter, and won't affect the > outcome. .... so you post the copyright forward to another instance, that instance (cgi program) grabs the copyright from the cgi content, acts based on that date, and stores the date as a hidden field so that the user can't change it at this time, and preserves for the next posting.... HTH -tim- > > > -- > Terry Carroll | "To have this rare opportunity > Santa Clara, CA | is a rare opportunity." > carroll@tjc.com | - Houston Rockets' Yao Ming, on being named > Modell delendus est | starting center for the 2003 NBA All-Star Game > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From dyoo@hkn.eecs.berkeley.edu Sat Apr 26 19:43:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Apr 26 18:43:01 2003 Subject: [Tutor] The "No parsers found" error. In-Reply-To: <20030426183638.A320@coto> Message-ID: > This is a rather long post. The problem is related to a program (called > GNUe-forms) that uses xml.sax and is unable to run because it can't find > any XML parser. Hi Adrian, Ah, I remember that error message! You may need to install a library or two to get a complete XML system. For some reason, Python 2.2 doesn't come with a native parser, and depends on an outside source to provide one. (If you had the 'expat' C library, Python can use that, but it requires a recompile of Python.) To fix the problem, you'll probably want to grab PyXML: http://pyxml.sourceforge.net/ PyXML provides a parser that will plug right into Python. > My feeling is that the problem could be caused by some version > incompatibility rather than a bug in that program. But I am a newbie and > have never used xml.sax, so that i have no clue about how xml.sax is > supposed to be used . No prob; you're in the right place to ask. *grin* The folks on the XML-SIG mailing list may also be a good resource for help on this stuff: http://mail.python.org/mailman/listinfo/xml-sig > DB000: File "/usr/local/gnue/lib/python/gnue/common/GParser.py", > line 89, in loadXMLObject > DB000: parser = xml.sax.make_parser() > DB000: File "/usr/local/lib/python2.2/xml/sax/__init__.py", > line 93, in make_parser > DB000: raise SAXReaderNotAvailable("No parsers found", None) > DB000: xml.sax._exceptions.SAXReaderNotAvailable: No parsers found Yeah, this is a common problem for newcomers to Python and XML. It's a little annoying; I hope that the situation is improved in Python 2.3... Anyway, if you install the PyXML subsystem, that should fix the problem for you. Good luck to you! From am@fx.ro Sun Apr 27 05:26:57 2003 From: am@fx.ro (Adrian Maier) Date: Sun Apr 27 04:26:57 2003 Subject: [Tutor] SAXReaderNotAvailable - problems using xml.dom in python2.1.3 In-Reply-To: ; from craig@eigentone-solo-collective.net on Sat, Apr 26, 2003 at 04:23:27PM -0400 References: Message-ID: <20030427103332.A399@coto> Craig Davey (craig@eigentone-solo-collective.net) a scris : > Greetings > > I'm quite new to python so I apologize if I've overlooked the obvious. > I've just installed python2.1.3 on Mac OS 10.2 and have run into a > problem demonstrated by the following: > > File "/opt/PYTHON/PYTHON2.1.3/lib/python2.1/xml/sax/__init__.py", > line 88, in make_parser > raise SAXReaderNotAvailable("No parsers found", None) > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found > --- /snip ------------ Very recently (a few days ago) i had exactly the same problem. Danny Yoo was kind enough to tell me the solution: you need to install an additional module called PyXML (pyxml.sourceforge.net). Good luck! > I'm coming at this from a mostly ECMAScript and Lingo background so I'm > afraid most of these errors are lost on me. I do understand that > without some way to parse xml into a dom I'm going to have a hard time > working with xml in python. Any pointers on how to resolve this problem > are most appreciated, I really do not know where to start. > > - Craig Davey > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Adrian Maier (am@fx.ro) From am@fx.ro Sun Apr 27 05:27:08 2003 From: am@fx.ro (Adrian Maier) Date: Sun Apr 27 04:27:08 2003 Subject: [Tutor] The "No parsers found" error. In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Sat, Apr 26, 2003 at 03:42:00PM -0700 References: <20030426183638.A320@coto> Message-ID: <20030427104332.B399@coto> Danny Yoo (dyoo@hkn.eecs.berkeley.edu) a scris : > Ah, I remember that error message! > To fix the problem, you'll probably want to grab PyXML: > http://pyxml.sourceforge.net/ I've just installed PyXML. Now, GNUe seems to work perfectly! Thanks, Danny, for the information. ( This was an example of trivial solution that becomes trivial only after you find out what to do... ;-) Best luck! -- Adrian Maier (am@fx.ro) From jjhegde@ncst.ernet.in Sun Apr 27 06:34:02 2003 From: jjhegde@ncst.ernet.in (Jayprasad J. Hegde) Date: Sun Apr 27 05:34:02 2003 Subject: [Tutor] looping through and comparing lists of dictionaries In-Reply-To: References: <01ee01c30966$8c40ff90$5102020a@graphnet.com> Message-ID: <20030427092916.GA312@konark.ncst.ernet.in> On Wed, Apr 23, 2003 at 04:41:46PM +0200, Michael Janssen wrote: Smart solution Michael. Just to share the spoils, I would like to include a solution which uses the list version too and is perhaps a bit more elegant (modesty, modesty, where art thou? ;) ) This solution simply gathers the list of 'oldtimers' having the desired feature -- in this case the hair colour -- and makes a list out of it. It then appends a girl's name to the new list only if she is not there on the old list. I hope you folks finds it useful. Sayonara, - JJH ps - Here it is: redheads = [] oldtimers = [] reqdColour = 'Redhead' for girl in olddata: if girl ['hair'] == reqdColour: oldtimers.append (girl ['name']) ## print oldtimers for girl in newdata: if girl['hair'] == reqdColour: if girl ['name'] not in oldtimers: redheads.append (girl ['name']) print redheads > ------------ Michael's solution ------------------ > olddata={'Betty': {'hair':'Blonde','role':'Student'}, > 'Veronica': {'hair':'Brunette','role':'Student'}, > 'Maryann': {'hair':'Brunette','role':'Castaway'}, > 'Ginger': {'hair':'Redhead','role':'Castaway'}, > 'Jeanne': {'hair':'Blond','role':'Genie'}, > 'Serena': {'hair':'Brunette','role':'Genie'}, > 'Samantha': {'hair':'Blond','role':'Witch'}, > } > > and the same for nowdata > > new_redhead = [] > for name in newdata.keys(): > if newdata[name]['hair'] == 'Redhead' and \ > olddata[name]['hair'] != 'Redhead': > new_redhead.append(name) > > > in case your data comes indeed sorted-by-name and you want maintain the > order with a list, it's even more simple: > > for old, new in zip(olddata, newdata): > if new['hair'] == 'Redhead' and \ > olddata['hair'] != 'Redhead': > new_redhead.append(new['name']) > -- BOFH excuse #262: Our POP server was kidnapped by a weasel. [ Jayprasad J. Hegde, KBCS Division, National Centre for Software Technology, Juhu, Mumbai 400049, India. Tel:+91-22-26201606x373 ] From idiot1@netzero.net Mon Apr 28 00:11:51 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun Apr 27 23:11:51 2003 Subject: [Tutor] form mail script Message-ID: <3EAC9C0A.5050402@netzero.net> I needed a script to accept feedback for a new site, check out the data, and send a letter if it was not bogus. Works, filters out caca I don't need to take time looking at and deleting. Feeds from a form with limited options, but hacking the form is no releif for the cracker, the script is tight. AS soon as I get it wrapped up, I will offer iton the tinylist site. anyone with a need for this sort of thing? Hers's a link to the form to look it over: http://www.listville.net/feedback.shtml -- end Respectfully, Kirk D Bailey Owner HowlerMonkey Email Services Company: http://www.howlermonkey.net/ Inventor of TinyList MLM list server: http://www.tinylist.org/ Consulting Grump: http://www.sacredelectron.org/ Remember: it is an ill wind that blows no minds. Fnord. From zmerch@30below.com Mon Apr 28 01:47:02 2003 From: zmerch@30below.com (Roger Merchberger) Date: Mon Apr 28 00:47:02 2003 Subject: [Tutor] Python and Apache (OT) In-Reply-To: References: < Message-ID: <5.1.0.14.2.20030428001058.0298ade0@mail.30below.com> At 21:05 04/25/2003 -0700, you wrote: >On 25/4/2003, Isaac Hall wrote: > > >he states something to the effect that he thinks > >python is not very widely used for cgi scripting, however it is my > >understanding that python works very well for cgi scripting, and is > >widely used for that purpose. > >As a python beginner who wants to do some cgi things, I have to agree >with the author on this point. Perhaps python is widely used for cgi, >but if so, those programmers aren't sharing their work. I'm not >talking about frameworks here, I have no desire for frameworks, just >simple everyday cgis. Last month I went out looking for examples to >study, and while I could easily find thousands of cgis written in perl, >the available python cgis were in the tens. Not even the hundreds. >Many of those were years old, and badly needed fixing and/or >modernization. I realize that most of the thousands of perl cgis are >garbage (buggy, no security, etc), and many of the rest are near clones >of each other, but for any type of web task (form manager, log >analysis, chat room, database, search engine, etc) there seem to be at >least three or four excellent ones to choose from. Python has a long >way to go to fill in those gaps. At least as far as I can tell, tho, Python as a CGI scripting engine isn't as versatile as Perl. Now, lemme quantify that: I set up mod_python per the instructions, and from everything that I've learned as a beginner at Python & a fairly knowledgeable Linux geek & web admin, Apache's configuration of mod_python only sets a single named script as a viable python CGI program, or if there is a way of having multiple python CGI scripts in one config, there's /no/ documentation as to how to set that up. If you tell Apache that you want script.py as your CGI, that's all you get. If you can tell Apache that *.py should all be run, Google can't find it, and every "wildcard" permutation I've tried in my httpd.conf file resulted in Apache barfing & refusing to start. What do I do when I want a guestbook.py, a forsale.py & wantlist.py? Usually code it in Perl or ColdFusion. Oh, and WRT your mention of lack of security in a lot of perl CGIs out there -- I do agree, but setting up a wildcard *.cgi to run from a non-CGI directory is a big security hole in itself, so that's why I wanted another option. >By the way, I'm constantly amused by anyone not liking indentation and >lack of braces on first sight. It was largely that that made me want >to drop my tussling with perl for python about 30 seconds after >accidentally running into some python source. It was only afterwards >that I found the even better goodies, such as decent list manipulation. To each his own. I'm constantly amused by people who are amazed that not everyone fits into their worldview. I personally much prefer /stated/ loop boundries (while/wend; if/else/endif; for/next) but braces aren't a problem either -- and I'll be the first to admit that the indentation is less difficult than I'd thought to become accustomed to (well, once I reconfiged my editor to quit converting spaces to tabs...) I can honestly say that it took me no less time to start hacking usable proggies in Perl than it did in Python. Admittedly, I had better documentation for Perl, so that's a testament to Python, but I've also got 8 more years of experience under my belt, and hacking an unknown language in many ways has gotten easier... Flip a coin... =-=-=-= I'm not giving up on Python (as I have with PHP...) but personally, I don't think that mod_python is quite ready for prime-time as a CGI scripting mega-powerhouse. I honestly hope that this changes soon, and when it does, I will switch! But until then, I just can't put Perl on the back burner... Just my Python noobie $0.02, Roger "Merch" Merchberger From phthenry@earthlink.net Mon Apr 28 03:10:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Apr 28 02:10:01 2003 Subject: [Tutor] unicode problem Message-ID: <20030428020932.A31959@localhost.localdomain> When I use Sax, I am getting a unicode problem. If I put an "ö" in my file (ö), then sax translates this to a unicode string: u'?' (some value) I then cannot parse the string. If I try to add to it: my_string = my_string + '\n' Then I get this error: File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border line = line + filler + padding + border + "\n" UnicodeError: ASCII decoding error: ordinal not in range(128) The only way to get around this problem is to convert the text to ascii beforehand: for x in my_string: if ord(x) > 127: num = ord(x) x = "&#" + str(num) + ";" new_string = new_string + x I don't want to use entities, though. Since my script converts to text, I need for the text to be represented as characters up to 256. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From Janssen@rz.uni-frankfurt.de Mon Apr 28 05:50:24 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Apr 28 04:50:24 2003 Subject: [Tutor] unicode problem In-Reply-To: <20030428020932.A31959@localhost.localdomain> Message-ID: On Mon, 28 Apr 2003, Paul Tremblay wrote: > When I use Sax, I am getting a unicode problem. > > If I put an "=F6" in my file (ö), then sax translates this to a > unicode string: > > u'?' (some value) > > I then cannot parse the string. If I try to add to it: > > my_string =3D my_string + '\n' > > Then I get this error: > > > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > line =3D line + filler + padding + border + "\n" > UnicodeError: ASCII decoding error: ordinal not in range(128) I don't know, if this is also suitable for your situation, but it can solve errors with "not in range": >>> u =3D u'=E4' >>> u u'\xe4' >>> print u Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) >>> print u.encode("latin-1") =E4 unicode string is converted to string The name of the encoding may also be iso-8859-1. I suppose legal values for encoding are such for that files under /path/to/pathon/lib/encodings are found. encode takes a second parameter controlling how to deal with errors - compare help("".encode). Michael From hemanexp@yahoo.com Mon Apr 28 12:28:02 2003 From: hemanexp@yahoo.com (perl lover) Date: Mon Apr 28 11:28:02 2003 Subject: [Tutor] Getting mouse position interms of canvas unit. Message-ID: <20030428152701.37418.qmail@web41712.mail.yahoo.com> hi, iam new to python and tkinter. I have created a canvas of size 300m * 300m (in millimeter). I bind mouse move method to canvas. when i move the mouse over the canvas the mouse position gets printed in pixel unit. But i want to get mouse position values interms of canvas unit (ie, millimeter). How can i get mouse position values interms of canvas unit? My program is given below. ***************************** from Tkinter import * root = Tk() c = Canvas(root,width="300m",height="300m",background = 'gray') c.pack() def mouseMove(event): print c.canvasx(event.x), c.canvasy(event.y) c.create_rectangle('16m','10.5m','21m','15.5m',fill='blue') c.bind('',mouseMove) root.mainloop() Tnanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From phthenry@earthlink.net Mon Apr 28 12:44:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Apr 28 11:44:02 2003 Subject: [Tutor] unicode problem In-Reply-To: References: <20030428020932.A31959@localhost.localdomain> Message-ID: <20030428114312.C31959@localhost.localdomain> No, this won't fix the problem. I should have been a bit more clear. In my original file, I actually typed 'ö'. When I use Sax, it translates this to unicode. Since I am using a legal entity, I believe that Sax translates it to pure unicode. I did try your solution, I get a similar problem. The code chokes as soon as I try x x.encode("latin-1") I get the same out of range error. Thanks Paul On Mon, Apr 28, 2003 at 10:49:32AM +0200, Michael Janssen wrote: > > On Mon, 28 Apr 2003, Paul Tremblay wrote: > > > When I use Sax, I am getting a unicode problem. > > > > If I put an "ö" in my file (ö), then sax translates this to a > > unicode string: > > > > u'?' (some value) > > > > I then cannot parse the string. If I try to add to it: > > > > my_string = my_string + '\n' > > > > Then I get this error: > > > > > > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > > line = line + filler + padding + border + "\n" > > UnicodeError: ASCII decoding error: ordinal not in range(128) > > I don't know, if this is also suitable for your situation, but it can > solve errors with "not in range": > > >>> u = u'ä' > >>> u > u'\xe4' > >>> print u > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII encoding error: ordinal not in range(128) > >>> print u.encode("latin-1") > ä > > unicode string is converted to string > > The name of the encoding may also be iso-8859-1. I suppose legal values > for encoding are such for that files under /path/to/pathon/lib/encodings > are found. encode takes a second parameter controlling how to deal with > errors - compare help("".encode). > > Michael > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From dyoo@hkn.eecs.berkeley.edu Mon Apr 28 13:57:06 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 28 12:57:06 2003 Subject: [Tutor] unicode problem In-Reply-To: <20030428020932.A31959@localhost.localdomain> Message-ID: On Mon, 28 Apr 2003, Paul Tremblay wrote: > When I use Sax, I am getting a unicode problem. > > If I put an "=F6" in my file (ö), then sax translates this to a > unicode string: > > u'?' (some value) Hi Paul, Sounds ok so far. > I then cannot parse the string. If I try to add to it: > > my_string =3D my_string + '\n' > > Then I get this error: > > > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > line =3D line + filler + padding + border + "\n" > UnicodeError: ASCII decoding error: ordinal not in range(128) Hmm... Let's see: ### >>> from xml.dom.pulldom import parseString >>> for e, n in parseString("elloö"): =2E.. print e =2E.. print n =2E.. START_DOCUMENT START_ELEMENT CHARACTERS CHARACTERS Traceback (most recent call last): File "", line 3, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) ### It looks like the 'print' statement doesn't like high-order bytes. Let's double check: ### >>> print u"\xf6" Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) ### Ok, so we're getting a similar error here. But what I'm still trying to figure out is why doing a string concatenation is making that error pop up for you. Let me play around with this more. ### >>> e_n_pairs =3D list(parseString("elloö")) >>> e_n_pairs [('START_DOCUMENT', ), ('START_ELEMENT', ), ('CHARACTERS', ), ('CHARACTERS', ), ('END_ELEMENT', )] >>> >>> e_n_pairs[3] ('CHARACTERS', ) >>> e_n_pairs[3][1] >>> e_n_pairs[3][1].data u'\xf6' ### I've used pulldom to isolate that umlauted character. Ok, I will try to ellicit your errors by doing the string concatenation by hand. ### >>> weird_char =3D e_n_pairs[3][1].data >>> weird_char + weird_char u'\xf6\xf6' >>> weird_char + weird_char + "foobar" u'\xf6\xf6foobar' ### Odd. I'm having problems getting it to break. *grin* The error message you report: > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > line =3D line + filler + padding + border + "\n" > UnicodeError: ASCII decoding error: ordinal not in range(128) doesn't smell right to me --- for the life of me, I can't imagine why string concatenation would raise that kind of error. Are 'line', 'filler', 'padding' and 'border' all strings? I'd expect something like a 'print', or a file.write(), or a string.encode() sort of thing, but string concatenation should be pretty safe. If your program is short, it might help us see more clearly what Python if you post the program on Tutor. I'm baffled, and I think we need to see some more source code to understand what's happening. By the way, you might find the 'unicode_escape' encodings useful: ### >>> weird_char u'\xf6' >>> weird_char.encode('raw_unicode_escape') '\xf6' >>> print weird_char.encode('raw_unicode_escape') =F6 >>> weird_char.encode('raw_unicode_escape').decode('raw_unicode_escape') u'\xf6' >>> >>> >>> weird_char.encode('unicode_escape') '\\xf6' >>> print weird_char.encode('unicode_escape') \xf6 ### I hope we can help fix this problem fast. Talk to you later! From dyoo@hkn.eecs.berkeley.edu Mon Apr 28 14:14:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Apr 28 13:14:02 2003 Subject: [Tutor] unicode problem In-Reply-To: Message-ID: > The error message you report: > > > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > > line = line + filler + padding + border + "\n" > > UnicodeError: ASCII decoding error: ordinal not in range(128) > > > doesn't smell right to me --- for the life of me, I can't imagine why > string concatenation would raise that kind of error. Oh. Never mind. ### >>> x, y = u'\xf6', '\xf6 >>> x + y Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) ### Well, at least now we have a test case we can work on. *grin* I think that the concatentation causes Python to raise the second string y up as a unicode string. At least, it looks like that unicod()ing a high-byte character can cause the encoding error: ### >>> unicode('\xf6') Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII decoding error: ordinal not in range(128) ### I'm actually not quite sure how to solve this yet; I'm not familiar with Unicode at all, so I think I might need to tinker with this problem a bit. From jeff@ccvcorp.com Mon Apr 28 14:19:10 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Apr 28 13:19:10 2003 Subject: [Tutor] Re: Comparing lines in two files, writing result into a third file References: <20030426160007.23248.79157.Mailman@mail.python.org> <1051379330.3eaac682b106c@webmail-b.uchicago.edu> Message-ID: <3EAD62F4.8070504@ccvcorp.com> pan@uchicago.edu wrote: >1) Use the built-in .setdefault() function of a dict for the folloing action: > > if d.has_key(num): d[num] += 1 # <- increment value, or > else: d[num] = 1 # <- create a new key > Even without using setdefault(), there's a fairly standard simplification of this relatively common idiom: d[key] = d.get(key, 0) + 1 The get() dictionary method returns the value associated with key if it exists, or the second parameter if it doesn't. This effectively gives you a default value for the dictionary. (I suspect that setdefault() would simply reroute all dict retrievals to an appropriately-constructed get() call, or the equivalent thereof...) Jeff Shannon Technician/Programmer Credit International From zak@harlekin-maus.com Mon Apr 28 14:27:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Mon Apr 28 13:27:01 2003 Subject: [Tutor] __init__ for class instantiation? In-Reply-To: <1761186205.20030426183113@rambler.ru> References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> <1761186205.20030426183113@rambler.ru> Message-ID: <1451.192.206.201.86.1051550800.squirrel@mail.harlekin-maus.com> > Hello Zak, > > Friday, April 25, 2003, 9:00:54 PM, you wrote: > > ZA> The problem here (as with __new__) is that __init__ will be called > with ZA> every creation of a Player instance. > > It seems that you are wrong here---__new__ is called only once after > class is defined. > > -- > Best regards, > anton mailto:antonmuhin@rambler.ru I created a new class, and defined __new__, but it doesn't get called from Python, as far as I can tell. Here's my code: class C: def __new__ (cls): print (cls) Even when I create the first instance (d = C()), I don't get any output. From zaixia_zhang@yahoo.com Mon Apr 28 17:05:02 2003 From: zaixia_zhang@yahoo.com (Zhang Zaixia) Date: Mon Apr 28 16:05:02 2003 Subject: [Tutor] encoding problem Message-ID: <20030428200451.63693.qmail@web12503.mail.yahoo.com> I am working on chinese text processing. Does anyone know what the encoding name for Chinese? For European language, we can use 'latin-1', for Japnese, we can use 'shift_JIS'. But I can not find one for simplified Chinese. Does python2.2 support that? Thanks. Zaixia __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From emil@lysator.liu.se Mon Apr 28 18:35:10 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Mon Apr 28 17:35:10 2003 Subject: [Tutor] Python and Apache (OT) In-Reply-To: <5.1.0.14.2.20030428001058.0298ade0@mail.30below.com> (Roger Merchberger's message of "Mon, 28 Apr 2003 00:42:50 -0400") References: < <5.1.0.14.2.20030428001058.0298ade0@mail.30below.com> Message-ID: <87issy2to5.fsf@i110.ryd.student.liu.se> Roger Merchberger writes: > At least as far as I can tell, tho, Python as a CGI scripting engine > isn't as versatile as Perl. > > Now, lemme quantify that: I set up mod_python per the instructions, > and from everything that I've learned as a beginner at Python & a > fairly knowledgeable Linux geek & web admin, Apache's configuration of > mod_python only sets a single named script as a viable python CGI > program, or if there is a way of having multiple python CGI scripts in > one config, there's /no/ documentation as to how to set that up. Actually, there is. It might look a little cryptic to those used to regular CGI:s though, due to the fact that mod_python isn't really meant for CGI:s at all. Take a look at http://www.modpython.org/live/mod_python-2.7.8/doc-html/hand-cgi.html for how to use mod_python for CGI:s. You might also be interested in http://www.modpython.org/FAQ/faqw.py?req=show&file=faq03.004.htp If you just want different handlers in different directories, you can create .htaccess files or use sections in your apache config. > If you tell Apache that you want script.py as your CGI, that's all you > get. If you can tell Apache that *.py should all be run, Google can't > find it, and every "wildcard" permutation I've tried in my httpd.conf > file resulted in Apache barfing & refusing to start. > What do I do when I want a guestbook.py, a forsale.py & wantlist.py? > Usually code it in Perl or ColdFusion. I've never used mod_perl, but after a quick look in the docs, I can't really see the difference between the two. You can still only have one script per directory, designated by the "PerlResponseHandler" directive. Using the ModPerl::Registry handler is the equivalent of mod_python.cgihandler. /Emil From anderson@nkbj.co.jp Tue Apr 29 02:29:02 2003 From: anderson@nkbj.co.jp (Robert M. Anderson) Date: Tue Apr 29 01:29:02 2003 Subject: [Tutor] encoding problem (asian text) References: <20030428200451.63693.qmail@web12503.mail.yahoo.com> Message-ID: <001f01c30e10$8bccdb70$840ca8c0@eanderson> PiBJIGFtIHdvcmtpbmcgb24gY2hpbmVzZSB0ZXh0IHByb2Nlc3NpbmcuIERvZXMgYW55b25lDQo+ IGtub3cgd2hhdCB0aGUgZW5jb2RpbmcgbmFtZSBmb3IgQ2hpbmVzZT8gRm9yIEV1cm9wZWFuDQo+ IGxhbmd1YWdlLCB3ZSBjYW4gdXNlICdsYXRpbi0xJywgZm9yIEphcG5lc2UsIHdlIGNhbg0KPiB1 c2UgJ3NoaWZ0X0pJUycuIEJ1dCBJIGNhbiBub3QgZmluZCBvbmUgZm9yIHNpbXBsaWZpZWQNCj4g Q2hpbmVzZS4gRG9lcyBweXRob24yLjIgc3VwcG9ydCB0aGF0Pw0KDQpFbmNvZGluZyBmaWxlcyBh cmUgZm91bmQgaW4gdGhlIHB5dGhvbi9MaWIvZW5jb2RpbmdzIGRpcmVjdG9yeSwgYW5kIHlvdSBj YW4gZmluZCBtb3N0IG5hbWVzIGluIHRoZSAiYWxpYXNlcy5weSIgZmlsZS4gQnV0IGxpa2UgeW91 IHNheSwgQ2hpbmVzZSBpc24ndCBsaXN0ZWQuDQoNCkkndmUgYmVlbiBhYmxlIHRvIHRyYWNrIGRv d24gc29tZSBfcG9zc2libGVfIGVuY29kaW5nIG5hbWVzLCBsaWtlIHRoZSBmb2xsb3dpbmcgKGJv dGggU2ltcGxpZmllZCBhbmQgVHJhZGl0aW9uYWwpOg0KDQpFVUMtQ04NCkVVQy1UVw0KSFoNCklT Ty0yMDIyLUNODQpJU08tMjAyMi1DTi1FWFQNCiJHQiAxODAzMCINCkJpZzUNCkhLU0NTDQoNClVu Zm9ydHVuYXRlbHksIEkgaGF2ZSBub3QgYmVlbiBhYmxlIHRvIGdldCBhbnkgYWN0dWFsIGNvZGVj cy4NCg0KSSB3b3JrIGF0IGEgcHJpbnRpbmcgY29tcGFueSBhbmQgd2UgaGFuZGxlIHR5cGVzZXR0 aW5nIGluIDIwIGRpZmZlcmVudCBsYW5ndWFnZXMgaGVyZSwgYW5kIEknbSBkeWluZyB0byBoYXZl IGNvZGVjcyBmb3IgQXJhYmljLCBDaGluZXNlIChTaW1wbGlmaWVkIGFuZCBUcmFkaXRpb25hbCks IGFuZCBLb3JlYW4uIFB5dGhvbiBvYnZpb3VzbHkgaGFzIGdyZWF0IHN1cHBvcnQgZm9yIExhdGlu LWJhc2VkIGxhbmd1YWdlcyBhbmQgSmFwYW5lc2UsIGJ1dCB0aGUgYWJvdmUgdGhyZWUgKCJGb3Vy LCBzaXJlISIpIGdpdmUgbWUgZW5kbGVzcyBoZWFkYWNoZXMuDQoNCldoYXQgSSdkIGxpa2UgdG8g a25vdyBpcywgaG93IGRvIEkgZ28gYWJvdXQgZ2V0dGluZyBvdGhlciBjb2RlY3MsIG9yIGlmIHRo ZXkncmUgbm90IGF2YWlsYWJsZSwgaG93IGNhbiBJIGJ1aWxkIHRoZW0/IEkgZG9uJ3QgbmVlZCB0 byBhY3R1YWxseSBkaXNwbGF5IGFueXRoaW5nLCBidXQgSSBuZWVkIHRvIGJlIGFibGUgdG8gcHJl LXByb2Nlc3MgdGhlIHRleHQgZm9yIGltcG9ydCBpbnRvIEZyYW1lLCBRdWFyaywgUGFnZW1ha2Vy LCBldGMuDQoNCkFsc28sIEkndmUgYWN0dWFsbHkgaGFkIGVuY29kaW5nIGVycm9ycyB3aXRoIEZy ZW5jaCBhbmQgdGhlIHN0YW5kYXJkICJsYXRpbi0xIiBjb2RlYy4gKFdlIGhhdmUgdG8gY29udmVy dCBiZXR3ZWVuIE1hYyBhbmQgV2luZG93cyB0ZXh0IGZvciB0aGUgYXBwbGljYXRpb25zIHdlJ3Jl IHVzaW5nLikgSSdsbCBoYXZlIHRvIGxvb2sgaXQgdXAsIGJ1dCBJIHRoaW5rIG9uZSBvZiB0aGUg b2ZmZW5kaW5nIGNoYXJhY3RlciBjb2RlcyB3YXMgZGVjaW1hbCAxNTkuIEluIHRoZSBlbmQsIGl0 IHdhcyBzbyBjb21tb24gdGhhdCBJIGhhZCB0byBhYmFuZG9uIHRoYXQgc2NyaXB0LiBIb3cgd291 bGQgb25lIGxvb2sgaW50byBmaXhpbmcgc29tZXRoaW5nIGxpa2UgdGhpcz8NCg0KU2lnaC4uLiBz byBjbG9zZSBhbmQgeWV0IHNvIGZhci4NCg0KUmVnYXJkcywNCg0KUm9iZXJ0IE0uIEFuZGVyc29u DQpTaGl6dW9rYSwgSmFwYW4NCg== From rmangaliag@slu.edu.ph Tue Apr 29 03:00:02 2003 From: rmangaliag@slu.edu.ph (x) Date: Tue Apr 29 02:00:02 2003 Subject: [Tutor] declaring private attributes... Message-ID: <001701c30e7a$1ab25680$3f1ea8c0@slu.edu.ph> This is a multi-part message in MIME format. ------=_NextPart_000_0014_01C30EBD.28B404C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable is there a way for me to declare private, protected or static class = attributes (like java)??? ------=_NextPart_000_0014_01C30EBD.28B404C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
is there a way for me to declare = private, protected=20 or static class attributes (like java)???
------=_NextPart_000_0014_01C30EBD.28B404C0-- From norvell@houseofspearman.org Tue Apr 29 04:38:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Tue Apr 29 03:38:02 2003 Subject: [Tutor] nested function definition Message-ID: <20030429073754.GA10529@houseofspearman.org> In the Python tutorial, section 5.1.3, ``Functional Programming Tools,'' is the following code: >>> def sum(seq): ... def add(x,y): return x+y ... return reduce(add, seq, 0) ... >>> sum(range(1, 11)) 55 >>> sum([]) 0 Which are the advantages or disadvantages (if any) of defining one function in the definition of another? Defining add(x, y) outside the definition of sum(seq) doesn't appear to change the behavior of either. Thanks for any answers. -- Norvell Spearman From mico@intermatik.co.id Tue Apr 29 04:54:02 2003 From: mico@intermatik.co.id (Mico Siahaan) Date: Tue Apr 29 03:54:02 2003 Subject: [Tutor] Newbie: CGI Message-ID: <3EAE2F65.00000A.03688@siahaan> I tried to make a simple CGI script with python.=0D =0D But I got this error: (copied from Apache's log):=0D =0D [error] [client 202.146.238.5] malformed header from script. Bad header=3DPIPELINING: /var/www/html/sites/ullysigar/cgi-bin/ullyform.cgi=0D =0D What does this error mean? And how to correct it?=0D =0D Thanks From rmangaliag@slu.edu.ph Tue Apr 29 05:10:03 2003 From: rmangaliag@slu.edu.ph (ali mangaliag) Date: Tue Apr 29 04:10:03 2003 Subject: [Tutor] my problem with ** Message-ID: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C30ECF.516B1FE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable what does the ** and * mean in a function parameter?? ex... def foo(*bar, **kwargs): ..... ------=_NextPart_000_0009_01C30ECF.516B1FE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
what does the ** and * mean in a = function=20 parameter??
 
ex...
 
def foo(*bar, **kwargs):
    = .....
------=_NextPart_000_0009_01C30ECF.516B1FE0-- From krier115@student.liu.se Tue Apr 29 05:16:01 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 29 04:16:01 2003 Subject: [Tutor] declaring private attributes... In-Reply-To: <001701c30e7a$1ab25680$3f1ea8c0@slu.edu.ph> References: <001701c30e7a$1ab25680$3f1ea8c0@slu.edu.ph> Message-ID: <20030429081413.GA16835@n14.ryd.student.liu.se> On Wed, Apr 30, 2003 at 02:06:49AM +0800, x wrote: > is there a way for me to declare private, protected or static class attributes (like java)??? Private, yes (sort of). See http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000 for more info. You can not create protected attributes in Python. Everything is public or private. Static attributes (class attributes) are created by putting them immideately after the "class ": >>> class A: ... sa = 1 ... >>> a = A() >>> A.sa 1 >>> a.sa 1 >>> A.sa += 1 >>> A.sa 2 >>> a.sa 2 I'm not very familiar with java, but I'm guessing static attributes work similar to this there. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From krier115@student.liu.se Tue Apr 29 05:30:07 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 29 04:30:07 2003 Subject: [Tutor] my problem with ** In-Reply-To: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> References: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> Message-ID: <20030429082810.GB16835@n14.ryd.student.liu.se> On Wed, Apr 30, 2003 at 04:16:48AM +0800, ali mangaliag wrote: > what does the ** and * mean in a function parameter?? > > ex... > > def foo(*bar, **kwargs): > ..... When using one '*' that argument accepts any excess arguments and wraps them up in a tuple. When using '**' all excess keyword arguments are wrapped up in that argument using a dictionary. Using an example to make it clearer: >>> def foo(*args1, **args2): ... print args1 ... print args2 ... >>> foo() () {} >>> foo(1,2,3) (1, 2, 3) {} >>> foo(mip='meep', mop='mooop') () {'mip': 'meep', 'mop': 'mooop'} >>> foo(1,2,3, mip='meep', mop='moop') (1, 2, 3) {'mip': 'meep', 'mop': 'moop'} If you want you can have a number of ordinary arguments before the ones with the *:s, these work like usual then and the *:ed ones catch the excess arguments. Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From krier115@student.liu.se Tue Apr 29 05:40:02 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 29 04:40:02 2003 Subject: [Tutor] nested function definition In-Reply-To: <20030429073754.GA10529@houseofspearman.org> References: <20030429073754.GA10529@houseofspearman.org> Message-ID: <20030429083918.GC16835@n14.ryd.student.liu.se> On Tue, Apr 29, 2003 at 02:37:54AM -0500, Norvell Spearman wrote: > In the Python tutorial, section 5.1.3, ``Functional Programming Tools,'' > is the following code: > > >>> def sum(seq): > ... def add(x,y): return x+y > ... return reduce(add, seq, 0) > ... > >>> sum(range(1, 11)) > 55 > >>> sum([]) > 0 > > Which are the advantages or disadvantages (if any) of defining one > function in the definition of another? Defining add(x, y) outside the > definition of sum(seq) doesn't appear to change the behavior of either. > Thanks for any answers. When you are using nested function definitions you define the nested function in the other function's scope. That is in the example above the function add is defined in the function sum's local scope. This means that the function add only can be used inside sum. It is not visible at all outside sum. The most obvious uses for this is to define small "fire and forget" functions that you use once inside an other function. For example as above when you need one function argument to a function. If you plan to use the function add in an other function you should declare it globally so it can be used everywhere, otherwise you will have to rewrite your code for that function. The advantages of this is that if you need a function somewhere (for example as argument to an other function) you can easily define it locally, use it and forget about it and you don't have to clutter the global namespace. The disadvantage (if you can call it that) is that the function isn't usable or visible outside the enclosing function. Hope my rambling helps :) Regards, Kristoffer -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From mico@intermatik.co.id Tue Apr 29 06:12:02 2003 From: mico@intermatik.co.id (Mico Siahaan) Date: Tue Apr 29 05:12:02 2003 Subject: [Tutor] my problem with ** References: <000c01c30e8c$43f8e060$3f1ea8c0@slu.edu.ph> Message-ID: <3EAE4167.000011.03688@siahaan> --------------Boundary-00=_NGL3IA11VA4000000000 Content-Type: Multipart/Alternative; boundary="------------Boundary-00=_NGL3DL51VA4000000000" --------------Boundary-00=_NGL3DL51VA4000000000 Content-Type: Text/Plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable * means "matches remaining positional arguments (in a tuple) =0D ** means "matches remaining keywords arguments (in a dictionary) =0D =0D if define function: =0D def foo(*bar, **kwargs): =0D print "positional arguments:" =0D for arg in bar: =0D print arg =0D print "keyword arguments (kwargs):" =0D for kwarg in kwargs.keys(): =0D print kwarg + ":" + kwargs[kwarg] =0D =0D then you can call it by foo('spam','eggs','toast',kwarg1=3D'scam',kwarg2=3D= 'slam=0D ). You will get result: =0D positional arguments: =0D spam =0D eggs =0D toast =0D keyword arguments (kwargs): =0D kwarg2:slam =0D kwarg1:scam =0D =0D -mico- =0D =0D -------Original Message------- =0D =0D From: ali mangaliag =0D Date: Tuesday, April 29, 2003 3:11:35 PM =0D To: Tutor@python.org =0D Subject: [Tutor] my problem with ** =0D =0D what does the ** and * mean in a function parameter?? =0D =0D ex... =0D =0D def foo(*bar, **kwargs): =0D =2E=20 --------------Boundary-00=_NGL3DL51VA4000000000 Content-Type: Text/HTML; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
* means "matches remaining positional argume= nts (in a tuple)
** means "matches remaining keywords arguments (in a= dictionary)

if define function:
def foo(*bar, **kwargs): print "positional arguments:"
for arg in bar:
print arg
prin= t "keyword arguments (kwargs):"
for kwarg in kwargs.keys():
print= kwarg + ":" + kwargs[kwarg]

then you can call it by foo('spam','= eggs','toast',kwarg1=3D'scam',kwarg2=3D'slam
). You will get result: <= BR>positional arguments:
spam
eggs
toast
keyword argument= s (kwargs):
kwarg2:slam
kwarg1:scam

-mico-

------= -Original Message-------

From: ali mangaliag
Date: Tuesday, A= pril 29, 2003 3:11:35 PM
To: Tuto= r@python.org
Subject: [Tutor] my problem with **

what doe= s the ** and * mean in a function parameter??

ex...

def f= oo(*bar, **kwargs):
.
___________________________________= _________________
3D""=  IncrediMail - Email has finally evol= ved - Click Her= e
--------------Boundary-00=_NGL3DL51VA4000000000-- --------------Boundary-00=_NGL3IA11VA4000000000 Content-Type: image/gif; name="IMSTP.gif" Content-Transfer-Encoding: base64 Content-ID: <4505EDD3-C6FE-4691-90F6-6E3D4CEF526F> R0lGODlhFAAPALMIAP9gAM9gAM8vAM9gL/+QL5AvAGAvAP9gL////wAAAAAAAAAAAAAAAAAAAAAA AAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQJFAAIACwAAAAAFAAPAAAEVRDJSaudJuudrxlEKI6B URlCUYyjKpgYAKSgOBSCDEuGDKgrAtC3Q/R+hkPJEDgYCjpKr5A8WK9OaPFZwHoPqm3366VKyeRt E30tVVRscMHDqV/u+AgAIfkEBWQACAAsAAAAABQADwAABBIQyUmrvTjrzbv/YCiOZGmeaAQAIfkE CRQACAAsAgABABAADQAABEoQIUOrpXIOwrsPxiQUheeRAgUA49YNhbCqK1kS9grQhXGAhsDBUJgZ AL2Dcqkk7ogFpvRAokSn0p4PO6UIuUsQggSmFjKXdAgRAQAh+QQFCgAIACwAAAAAFAAPAAAEEhDJ Sau9OOvNu/9gKI5kaZ5oBAAh+QQJFAAIACwCAAEAEAANAAAEShAhQ6ulcg7Cuw/GJBSF55ECBQDj 1g2FsKorWRL2CtCFcYCGwMFQmBkAvYNyqSTuiAWm9ECiRKfSng87pQi5SxCCBKYWMpd0CBEBACH5 BAVkAAgALAAAAAAUAA8AAAQSEMlJq7046827/2AojmRpnmgEADs= --------------Boundary-00=_NGL3IA11VA4000000000-- From Anish.Mehta@enst-bretagne.fr Tue Apr 29 06:40:03 2003 From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish) Date: Tue Apr 29 05:40:03 2003 Subject: [Tutor] ttList-module problem Message-ID: <3EAE499D.9000202@antares.enst-bretagne.fr> Hello ! I am having some problem in understanding this code. Firstly i am not finding TTFont which is being imported with the command from fontTools.ttLib import TTFont I have searched in the ttLib directory but i am unable to find TTFont so that i can read about it. As far as i am getting is that this module is taking input and then some information about tags( ? ) and then printing out the format in the form of checksum, length and offset. Please elaborate this a bit more. def ttList(input, output, options): ttf = TTFont(input) reader = ttf.reader tags = reader.keys() tags.sort() print 'Listing table info for "%s":' % input format = " %4s %10s %7s %7s" print format % ("tag ", " checksum", " length", " offset") print format % ("----", "----------", "-------", "-------") for tag in tags: entry = reader.tables[tag] checksum = "0x" + hex(entry.checkSum)[2:].zfill(8) print format % (tag, checksum, entry.length, entry.offset) print ttf.close() I'll be waiting for your response. Thanks in advance. Regards, Anish MEHTA From magnus@thinkware.se Tue Apr 29 06:51:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 05:51:02 2003 Subject: [Tutor] Newbie: CGI In-Reply-To: <3EAE2F65.00000A.03688@siahaan> Message-ID: <5.2.1.1.0.20030429101850.00b57178@www.thinkware.se> Selamat Datang Mico, At 14:53 2003-04-29 +0700, Mico Siahaan wrote: > I tried to make a simple CGI script with python. > >But I got this error: (copied from Apache's log): >[error] [client 202.146.238.5] malformed header from script. Bad >header=PIPELINING: /var/www/html/sites/ullysigar/cgi-bin/ullyform.cgi > >What does this error mean? And how to correct it? It's much easier to debug programs if we can see the code. :) When you run into a problem, it's a good thing to try to reduce the problem. Try do construct a really small program that exhibits that error. Having said that, I can tell you about this one... Each CGI program must first present a header, which describes the content of the data to come. A naive CGI script like this... #!/usr/bin/env python -u print "Hello World" ...will not work. It will actually assume that the first line(s) contain the header, and it obviously won't recognize that string of HTML as a proper header. Thus the error message: Malformed header. See http://www.ietf.org/rfc/rfc2068.txt Both types of message[*] consist of a start-line, one or more header fields (also known as "headers"), an empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields, and an optional message-body. [*] Request and response How these headers look is defined in the MIME standards (RFC2045-2047), and the registered types are shown inftp://ftp.isi.edu/in-notes/iana/assignments/media-types/media-types So, lets add an appropriate header and an empty line, and see what happens: #!/usr/bin/python -u print "Content-type: text/html" print print "Hello World" Does it work now? Remember that you must always print an empty line between the header and the page content. The header might consist of more than one line, and the empty line acts as the separator. In this case, with content starting with , the browsers I checked will actually display HTML regardless of what content-type you set, but the following two examples will display differently. #!/usr/bin/python -u print "Content-type: text/html" print print "Hello World!" #!/usr/bin/python -u print "Content-type: text/plain" print print "Hello World!" See? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Tue Apr 29 06:59:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 05:59:03 2003 Subject: [Tutor] ttList-module problem In-Reply-To: <3EAE499D.9000202@antares.enst-bretagne.fr> Message-ID: <5.2.1.1.0.20030429115715.026e3210@www.thinkware.se> At 11:45 2003-04-29 +0200, Mehta, Anish wrote: >Hello ! > >I am having some problem in understanding this code. Firstly i am not >finding TTFont which is being imported with the command > >from fontTools.ttLib import TTFont It's even worse for me... >>> import fontTools Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fontTools fontTools is not a standard library. It's probably helpful to explain what python packages you are working with. This might also be a question which is too specific for this mailing list. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From magnus@thinkware.se Tue Apr 29 07:25:06 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 06:25:06 2003 Subject: [Tutor] declaring private attributes... In-Reply-To: <20030429081413.GA16835@n14.ryd.student.liu.se> References: <001701c30e7a$1ab25680$3f1ea8c0@slu.edu.ph> <001701c30e7a$1ab25680$3f1ea8c0@slu.edu.ph> Message-ID: <5.2.1.1.0.20030429120050.00b40978@www.thinkware.se> At 10:14 2003-04-29 +0200, Kristoffer Erlandsson wrote: >On Wed, Apr 30, 2003 at 02:06:49AM +0800, x wrote: > > is there a way for me to declare private, protected or static class > attributes (like java)??? > >Private, yes (sort of). See >http://www.python.org/doc/current/tut/node11.html#SECTION0011600000000000000000 >for more info. > >You can not create protected attributes in Python. Everything is public or >private. But people often use a single underscore to denote protected, like this: x.public x._protected x.__private This is not enforced by python, but you can easily write a code scanner that will warn you if an attribute which starts with a single underscore is preceeded by something other than "self". That would probably find almost all violations. Another option is to have that "code scanner" in your head... But there is no consensus among python programmers to do this. If I remember correctly, "from x import *" won't import anything that starts with _, so there is some kind of underlying support for the notion of _ as protected or internal also in the implementation. It is common that modules intended purely for internal use in a package have names that start with _, such as _sqlite and sqlite, where you import sqlite and program against that, and _sqlite is a shared object (or dll) which is used by sqlite to implement the database. Python is a high level language, and it doesn't provide access to low level manipulation like C and C++ does, but other than that, the python approach is more to make it easy to do the right thing, than to make it difficult to do bad things. In general, it's up to the programmer to make a program correct and maintainable, but it's good if the language doesn't encourage bad coding. On the other hand, it's good if it doesn't make it too difficult to "cheat" when you have to do that. Putting up artificial hinders will often lead to even worse code than the one it was supposed to prevent. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From Anish.Mehta@enst-bretagne.fr Tue Apr 29 09:37:03 2003 From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish) Date: Tue Apr 29 08:37:03 2003 Subject: [Tutor] ttList-module problem References: <5.2.1.1.0.20030429115715.026e3210@www.thinkware.se> Message-ID: <3EAE7344.3020607@antares.enst-bretagne.fr> This is a multi-part message in MIME format. --------------080901060205070506050205 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by laposte.enst-bretagne.fr id h3TCaPO13272 I just replied to the message. I was not aware that it will not go the=20 list. Sorry for the inconvenience. Now i will take care of that i always=20 post to the list. I am attaching the ttx.py program. Please help me in understanding the=20 code. I am trying to understand it step by step and also learning python as=20 well. But still i am a beginner in python. The first module=20 makeoutputdir in this is doing like this according to me: It tries to find an available file name, making sure it doesn't take the = name of an existing file, and if it sees a name in a particular format --= - if that name has a trailing number --- it tries to create a new name wi= th the next ascending number in sequence. I am struck up with the module ttList. Not getting it properly. Roughly i= think that it will print the information about some table in truetype fo= nts in the form of format, checksum etc.. Thanks for responding. Regards Magnus Lyck=E5 wrote: > At 11:45 2003-04-29 +0200, Mehta, Anish wrote: > >> Hello ! >> >> I am having some problem in understanding this code. Firstly i am not=20 >> finding TTFont which is being imported with the command >> >> from fontTools.ttLib import TTFont > > > It's even worse for me... > > >>> import fontTools > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named fontTools > > fontTools is not a standard library. It's probably helpful to > explain what python packages you are working with. This might > also be a question which is too specific for this mailing list. > > > --=20 > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > --------------080901060205070506050205 Content-Type: text/plain; name="ttx.py" Content-Disposition: inline; filename="ttx.py" Content-Transfer-Encoding: 7bit #! /usr/bin/env python """\ usage: ttx [options] inputfile1 [... inputfileN] TTX %s -- From OpenType To XML And Back If an input file is a TrueType or OpenType font file, it will be dumped to an TTX file (an XML-based text format). If an input file is a TTX file, it will be compiled to a TrueType or OpenType font file. Output files are created so they are unique: an existing file is never overwrritten. General options: -h Help: print this message -d Specify a directory where the output files are to be created. -v Verbose: more messages will be written to stdout about what is being done. Dump options: -l List table info: instead of dumping to a TTX file, list some minimal info about each table. -t Specify a table to dump. Multiple -t options are allowed. When no -t option is specified, all tables will be dumped. -x
Specify a table to exclude from the dump. Multiple -x options are allowed. -t and -x are mutually exclusive. -s Split tables: save the TTX data into separate TTX files per table and write one small TTX file that contains references to the individual table dumps. This file can be used as input to ttx, as long as the table files are in the same directory. -i Do NOT disassemble TT instructions: when this option is given, all TrueType programs (glyph programs, the font program and the pre-program) will be written to the TTX file as hex data instead of assembly. This saves some time and makes the TTX file smaller. Compile options: -m Merge with TrueType-input-file: specify a TrueType or OpenType font file to be merged with the TTX file. This option is only valid when at most one TTX file is specified. -b Don't recalc glyph boundig boxes: use the values in the TTX file as-is. """ import sys import os import getopt import re from fontTools.ttLib import TTFont from fontTools import version def usage(): print __doc__ % version sys.exit(2) numberAddedRE = re.compile("(.*)#\d+$") def makeOutputFileName(input, outputDir, extension): dir, file = os.path.split(input) file, ext = os.path.splitext(file) if outputDir: dir = outputDir output = os.path.join(dir, file + extension) m = numberAddedRE.match(file) if m: file = m.group(1) n = 1 while os.path.exists(output): output = os.path.join(dir, file + "#" + repr(n) + extension) n = n + 1 return output class Options: listTables = 0 outputDir = None verbose = 0 splitTables = 0 disassembleInstructions = 1 mergeFile = None recalcBBoxes = 1 def __init__(self, rawOptions, numFiles): self.onlyTables = [] self.skipTables = [] for option, value in rawOptions: # general options if option == "-h": print __doc__ % version sys.exit(0) elif option == "-d": if not os.path.isdir(value): print "The -d option value must be an existing directory" sys.exit(2) self.outputDir = value elif option == "-v": self.verbose = 1 # dump options elif option == "-l": self.listTables = 1 elif option == "-t": self.onlyTables.append(value) elif option == "-x": self.skipTables.append(value) elif option == "-s": self.splitTables = 1 elif option == "-i": self.disassembleInstructions = 0 # compile options elif option == "-m": self.mergeFile = value elif option == "-b": self.recalcBBoxes = 0 if self.onlyTables and self.skipTables: print "-t and -x options are mutually exlusive" sys.exit(2) if self.mergeFile and numFiles > 1: print "Must specify exactly one TTX source file when using -i" sys.exit(2) def ttList(input, output, options): ttf = TTFont(input) reader = ttf.reader tags = reader.keys() tags.sort() print 'Listing table info for "%s":' % input format = " %4s %10s %7s %7s" print format % ("tag ", " checksum", " length", " offset") print format % ("----", "----------", "-------", "-------") for tag in tags: entry = reader.tables[tag] checksum = "0x" + hex(entry.checkSum)[2:].zfill(8) print format % (tag, checksum, entry.length, entry.offset) print ttf.close() def ttDump(input, output, options): print 'Dumping "%s" to "%s"...' % (input, output) ttf = TTFont(input, 0, verbose=options.verbose) ttf.saveXML(output, tables=options.onlyTables, skipTables=options.skipTables, splitTables=options.splitTables, disassembleInstructions=options.disassembleInstructions) ttf.close() def ttCompile(input, output, options): print 'Compiling "%s" to "%s"...' % (input, output) ttf = TTFont(options.mergeFile, recalcBBoxes=options.recalcBBoxes, verbose=options.verbose) ttf.importXML(input) ttf.save(output) if options.verbose: import time print "finished at", time.strftime("%H:%M:%S", time.localtime(time.time())) def guessFileType(fileName): try: f = open(fileName, "rb") except IOError: return None try: import macfs except ImportError: pass else: cr, tp = macfs.FSSpec(fileName).GetCreatorType() if tp == "FFIL": return "TTF" header = f.read(256) head = header[:4] if head == "OTTO": return "OTF" elif head in ("\0\1\0\0", "true"): return "TTF" elif head.lower() == " 0: return "OTX" else: return "TTX" return None def parseOptions(args): try: rawOptions, files = getopt.getopt(args, "ld:vht:x:sim:b") except getopt.GetoptError: usage() if not files: usage() options = Options(rawOptions, len(files)) jobs = [] for input in files: tp = guessFileType(input) if tp in ("OTF", "TTF"): extension = ".ttx" if options.listTables: action = ttList else: action = ttDump elif tp == "TTX": extension = ".ttf" action = ttCompile elif tp == "OTX": extension = ".otf" action = ttCompile else: print 'Unknown file type: "%s"' % input continue output = makeOutputFileName(input, options.outputDir, extension) jobs.append((action, input, output)) return jobs, options def process(jobs, options): for action, input, output in jobs: action(input, output, options) def waitForKeyPress(): """Force the DOS Prompt window to stay open so the user gets a chance to see what's wrong.""" import msvcrt print '(Hit any key to exit)' while not msvcrt.kbhit(): pass def main(args): jobs, options = parseOptions(args) try: process(jobs, options) except KeyboardInterrupt: print "(Cancelled.)" except SystemExit: if sys.platform == "win32": waitForKeyPress() else: raise except: if sys.platform == "win32": import traceback traceback.print_exc() waitForKeyPress() else: raise if __name__ == "__main__": main(sys.argv[1:]) --------------080901060205070506050205-- From a_abdi406@yahoo.com Tue Apr 29 10:11:51 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue Apr 29 09:11:51 2003 Subject: [Tutor] about an error message Message-ID: <20030429131022.50693.qmail@web14512.mail.yahoo.com> --0-1738528055-1051621822=:50152 Content-Type: text/plain; charset=us-ascii Hi I was runing an old version of python program for indexing, I tried to runthe program but it is giving me an error message which is not recognising a certain module, can anyone with experience in previous python versions have a look at this code, and give me what is going onit gives me an error from this line: os.symlink(file, os.path.join(dir, filename)) Also the code had an import statement of module called posix and apparantly it also doesn't recognise that. the above code is from this function: jumper = random.Random() jumper.seed() serial = 0 def linkfileinto(dir, file): while 1: global serial serial = serial + 1 filename = str(serial) try: # XXX assumes symlink() is atomic os.symlink(file, os.path.join(dir, filename)) <--- the problem i return filename except OSError, err: err_errno, msg = err if err_errno == errno.EEXIST: serial = serial + 10**jumper.randrange(3) else: raise --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1738528055-1051621822=:50152 Content-Type: text/html; charset=us-ascii
Hi
 
I was runing an old version of python program for indexing, I tried to run
the program but it is giving me an error message which is not recognising a certain module, can anyone with experience in previous python versions have a look at this code, and give me what is going on
it gives me an error from this line:
 os.symlink(file, os.path.join(dir, filename))
 
 Also the code had an import statement of module called posix and apparantly it also doesn't recognise that.
 
 the above code is from this function:
 
jumper = random.Random()
jumper.seed()
serial = 0
def linkfileinto(dir, file):
    while 1:
        global serial
        serial = serial + 1
        filename = str(serial)
        try:
            # XXX assumes symlink() is atomic
            os.symlink(file, os.path.join(dir, filename)) <--- the problem i
            return filename
        except OSError, err:
            err_errno, msg = err
            if err_errno == errno.EEXIST:
                serial = serial + 10**jumper.randrange(3)
            else:
                raise


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1738528055-1051621822=:50152-- From a_abdi406@yahoo.com Tue Apr 29 10:40:25 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Tue Apr 29 09:40:25 2003 Subject: [Tutor] about counting files Message-ID: <20030429043307.80090.qmail@web14512.mail.yahoo.com> --0-1171494775-1051590787=:79765 Content-Type: text/plain; charset=us-ascii Hi, can ayone help me with this program, I am reading multiple files and I want to count each of these files, I tried different things but I couldn't get it right. here is the program: mport glob, getopt import fileinput,re,shelve,linecache,sys #from TextSplitter import TextSplitter aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') #using xml as well. index={} # Generate an index in file indexFileNamedef genIndex(indexFileName, extension): fname='*.'+extension for line in fileinput.input(glob.glob(fname)): location = fileinput.filename(), fileinput.filelineno() for word in aword.findall(line.lower()): if word[0] != '<': index.setdefault(word,[]).append(location) print index # for testing shelf = shelve.open(indexFileName,'n') for word in index: shelf[word] = index[word] shelf.close() if __name__ == '__main__': import sys for arg in sys.argv[1:]: genIndex(arg,'txt') thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-1171494775-1051590787=:79765 Content-Type: text/html; charset=us-ascii
Hi,
 
can ayone help me with this program, I am reading multiple files and I want to count each of these files, I tried different things but I couldn't get it right.
 
here is the program:
 
 
mport glob, getopt
import fileinput,re,shelve,linecache,sys
#from TextSplitter import TextSplitter
 
aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') #using xml as well.
index={}
 
# Generate an index in file indexFileName
def genIndex(indexFileName, extension):
   
   fname='*.'+extension
    
   for line in fileinput.input(glob.glob(fname)):
      location = fileinput.filename(), fileinput.filelineno()
      for word in aword.findall(line.lower()):
         if word[0] != '<':
            index.setdefault(word,[]).append(location)

   print index  # for testing
  
   shelf = shelve.open(indexFileName,'n')
   for word in index:
      shelf[word] = index[word]
   shelf.close()

if __name__ == '__main__':
    import sys
    for arg in sys.argv[1:]:
           genIndex(arg,'txt')
 
 
thanks in advance

 


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-1171494775-1051590787=:79765-- From norvell@houseofspearman.org Tue Apr 29 11:05:07 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Tue Apr 29 10:05:07 2003 Subject: [Tutor] nested function definition In-Reply-To: <20030429083918.GC16835@n14.ryd.student.liu.se> References: <20030429073754.GA10529@houseofspearman.org> <20030429083918.GC16835@n14.ryd.student.liu.se> Message-ID: <20030429140358.GA13381@houseofspearman.org> On Tuesday, 2003.04.29, 10:39:18 +0200, Kristoffer Erlandsson wrote: > > The most obvious uses for this is to define small "fire and forget" functions > that you use once inside an other function. ... > The advantages of this is that if you need a function somewhere (for example as > argument to an other function) you can easily define it locally, use it and > forget about it and you don't have to clutter the global namespace. The > disadvantage (if you can call it that) is that the function isn't usable or > visible outside the enclosing function. Does this also mean that garbage collection will take out a locally-defined function earlier than a globally-defined one? -- Norvell Spearman From krier115@student.liu.se Tue Apr 29 11:33:09 2003 From: krier115@student.liu.se (Kristoffer Erlandsson) Date: Tue Apr 29 10:33:09 2003 Subject: [Tutor] nested function definition In-Reply-To: <20030429140358.GA13381@houseofspearman.org> References: <20030429073754.GA10529@houseofspearman.org> <20030429083918.GC16835@n14.ryd.student.liu.se> <20030429140358.GA13381@houseofspearman.org> Message-ID: <20030429143219.GA2012@n14.ryd.student.liu.se> On Tue, Apr 29, 2003 at 09:03:58AM -0500, Norvell Spearman wrote: > On Tuesday, 2003.04.29, 10:39:18 +0200, Kristoffer Erlandsson wrote: > > > > The most obvious uses for this is to define small "fire and forget" functions > > that you use once inside an other function. > ... > > The advantages of this is that if you need a function somewhere (for example as > > argument to an other function) you can easily define it locally, use it and > > forget about it and you don't have to clutter the global namespace. The > > disadvantage (if you can call it that) is that the function isn't usable or > > visible outside the enclosing function. > > Does this also mean that garbage collection will take out a > locally-defined function earlier than a globally-defined one? I don't exactly know how the garbage collection in Python works, but if it works as I think it does the function is garbed sometime after the call to the outer function is finished. You have nothing referring to the function then and hence no reason to keep it. This is assuming you haven't returned the function and are referencing it from outside the function in any way. That is, the answer is yes if everything works like I think it does (and as I've seen in other languages) and nothing fishy is going on :) -- Kristoffer Erlandsson E-mail: krier115@student.liu.se ICQ#: 378225 From magnus@thinkware.se Tue Apr 29 11:45:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 10:45:03 2003 Subject: [Tutor] encoding problem (asian text) In-Reply-To: <001f01c30e10$8bccdb70$840ca8c0@eanderson> References: <20030428200451.63693.qmail@web12503.mail.yahoo.com> Message-ID: <5.2.1.1.0.20030429164455.026c6008@www.thinkware.se> At 14:30 2003-04-29 +0900, Robert M. Anderson wrote: > > I am working on chinese text processing. Does anyone > > know what the encoding name for Chinese? For European > > language, we can use 'latin-1', for Japnese, we can > > use 'shift_JIS'. But I can not find one for simplified > > Chinese. Does python2.2 support that? Have a look at http://sourceforge.net/projects/python-codecs/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From bgailer@alum.rpi.edu Tue Apr 29 13:18:25 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue Apr 29 12:18:25 2003 Subject: [Tutor] about counting files In-Reply-To: <20030429043307.80090.qmail@web14512.mail.yahoo.com> Message-ID: <5.2.0.9.0.20030429100927.01a187a8@66.28.54.253> --=======1E297A1E======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-7CB65F26; boundary="=====================_6848697==.ALT" --=====================_6848697==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-7CB65F26; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:33 PM 4/28/2003 -0700, Abdirizak abdi wrote: >[snip]mport glob, getopt >import fileinput,re,shelve,linecache,sys >#from TextSplitter import TextSplitter > >aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') #using xml as well. >index={} > ># Generate an index in file indexFileName >def genIndex(indexFileName, extension): > > fname='*.'+extension > > for line in fileinput.input(glob.glob(fname)): > location = fileinput.filename(), fileinput.filelineno() > for word in aword.findall(line.lower()): > if word[0] != '<': > index.setdefault(word,[]).append(location) > > print index # for testing > > shelf = shelve.open(indexFileName,'n') > for word in index: > shelf[word] = index[word] > shelf.close() > >if __name__ == '__main__': > import sys > for arg in sys.argv[1:]: > genIndex(arg,'txt') From the manual for the fileinput module: "input([files[, inplace[, backup]]]) Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class. The following functions use the global state created by input()" To apply this to your program: fileinputInstance = fileinput.input(glob.glob(fname)) for line in fileinputInstance : location = fileinputInstance .filename(), fileinputInstance .filelineno() Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_6848697==.ALT Content-Type: text/html; x-avg-checked=avg-ok-7CB65F26; charset=us-ascii Content-Transfer-Encoding: 8bit At 09:33 PM 4/28/2003 -0700, Abdirizak abdi wrote:
[snip]mport glob, getopt
import fileinput,re,shelve,linecache,sys
#from TextSplitter import TextSplitter
 
aword =re.compile (r'<[^<>]*>|\b[\w-]+\b') #using xml as well.
index={}
 
# Generate an index in file indexFileName
def genIndex(indexFileName, extension):
  
   fname='*.'+extension
   
   for line in fileinput.input(glob.glob(fname)):
      location = fileinput.filename(), fileinput.filelineno()
      for word in aword.findall(line.lower()):
         if word[0] != '<':
            index.setdefault(word,[]).append(location)

   print index  # for testing
  
   shelf = shelve.open(indexFileName,'n')
   for word in index:
      shelf[word] = index[word]
   shelf.close()

if __name__ == '__main__':
    import sys
    for arg in sys.argv[1:]:
           genIndex(arg,'txt')

From the manual for the fileinput module:

"input([files[, inplace[, backup]]])
Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class.
The following functions use the global state created by input()"

To apply this to your program:
   fileinputInstance = fileinput.input(glob.glob(fname))
   for line in fileinputInstance :
      location = fileinputInstance .filename(), fileinputInstance .filelineno()

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_6848697==.ALT-- --=======1E297A1E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-7CB65F26 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======1E297A1E=======-- From llazarre@yahoo.com Tue Apr 29 13:40:03 2003 From: llazarre@yahoo.com (Levy Lazarre) Date: Tue Apr 29 12:40:03 2003 Subject: [Tutor] pyXML DOM 2.0 Traversal and filters Message-ID: <20030429163854.83209.qmail@web40406.mail.yahoo.com> Hi Fellow Listers, Given the following sample file ('appliances.xml'), I am trying to write a TreeWalker that would print out the element nodes, while a filter would prevent the nodes with a status of "broken" from displaying. cuckoo black and white I am getting some exceptions, making me think that I am calling the filter the wrong way or I am missing something. Can somebody please point me to the right direction? Here is the sample code: ########### SNIP #################### from xml.dom.ext.reader import Sax2 from xml.dom.NodeFilter import NodeFilter # Rejects element nodes with a "status" attribute of "broken": def filterbroken(thisNode): if (thisNode.nodeType == thisNode.ELEMENT_NODE and thisNode.getAttribute("status") == "broken"): return NodeFilter.FILTER_REJECT return NodeFilter.FILTER_ACCEPT # else, accept the node # create Reader object reader = Sax2.Reader() input_file = file("appliances.xml") doc = reader.fromStream(input_file) # Parse the input file, get a DOM tree. walker = doc.createTreeWalker(doc.documentElement, NodeFilter.SHOW_ALL, filterbroken, 0) while 1: print walker.currentNode.nodeName, ': ', walker.currentNode.nodeValue next = walker.nextNode() if next is None: break input_file.close() reader.releaseNode(doc) ########################################## Here are the exceptions I am getting: >>> appliances : None Traceback (most recent call last): File "C:\Python22\Lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\temp\Listing4.14.py", line 21, in ? next = walker.nextNode() File "C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py", line 128, in nextNode next_node = self.__advance() File "C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py", line 141, in __advance if self.firstChild(): File "C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py", line 85, in firstChild if self.__checkFilter(self.__dict__['__currentNode']) != NodeFilter.FILTER_REJECT: File "C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py", line 168, in __checkFilter return self.__dict__['__filter'].acceptNode(node) AttributeError: 'function' object has no attribute 'acceptNode' There are no exceptions when the filter is replaced by None in the 'walker =' statement. Thanks in advance, Levy Lazarre Information Systems Winter Haven Hospital llazarre@yahoo.com __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From dyoo@hkn.eecs.berkeley.edu Tue Apr 29 15:29:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 29 14:29:01 2003 Subject: [Tutor] encoding problem (asian text) In-Reply-To: <001f01c30e10$8bccdb70$840ca8c0@eanderson> Message-ID: > I work at a printing company and we handle typesetting in 20 different > languages here, and I'm dying to have codecs for Arabic, Chinese > (Simplified and Traditional), and Korean. Python obviously has great > support for Latin-based languages and Japanese, but the above three > ("Four, sire!") give me endless headaches. Hi Robert, The i18n-sig folks could probably help us out here; we may want to chat with them for more details. Korean codecs can be found here: http://sourceforge.net/projects/koco And Chinese codecs are part of the python-codecs project: http://sourceforge.net/projects/python-codecs/ (Actually, it looks like the KoreanCodecs have been folded into python-codecs tree too...) Although there isn't a formal release yet, their CVS tree does have source code: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python-codecs/practicecodecs/ChineseCodecs/ > What I'd like to know is, how do I go about getting other codecs, or if > they're not available, how can I build them? I don't need to actually > display anything, but I need to be able to pre-process the text for > import into Frame, Quark, Pagemaker, etc. > > Also, I've actually had encoding errors with French and the standard > "latin-1" codec. (We have to convert between Mac and Windows text for > the applications we're using.) I'll have to look it up, but I think one > of the offending character codes was decimal 159. In the end, it was so > common that I had to abandon that script. How would one look into fixing > something like this? > > Sigh... so close and yet so far. Unforunately, I don't think many of us on Tutor have too much experience with handling regional stuff yet. Because of our inexperience, I'd recommend chatting with the i18n group for answers: the folks there have been grappling with Unicode and encoding issues, and can probably help you with those encoding issues. http://www.python.org/sigs/i18n-sig/ Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue Apr 29 15:51:56 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 29 14:51:56 2003 Subject: [Tutor] about an error message In-Reply-To: <20030429131022.50693.qmail@web14512.mail.yahoo.com> Message-ID: On Tue, 29 Apr 2003, Abdirizak abdi wrote: > Hi I was runing an old version of python program for indexing, I tried > to runthe program but it is giving me an error message which is not > recognising a certain module, can anyone with experience in previous > python versions have a look at this code, and give me what is going onit > gives me an error from this line: os.symlink(file, os.path.join(dir, > filename)) Hi Abdirizak, Can you also tell us what the error message says? You don't have to paraphrase it; it's actually preferable if you copy and paste the error lines verbatim. Giving us the line number is helpful, but it's often not enough: the error message itself and its traceback often give subtle hints that give us more details. Showing us the error message will help us pinpoint exactly where Python is getting confused. *grin* The functions os.symlink() and os.path.join() did exist back in the Python 1.52 days, http://www.python.org/doc/1.5.2p2/lib/os-file-dir.html#l2h-892 http://www.python.org/doc/1.5.2p2/lib/module-os.path.html#l2h-955 So we may not be able to confirm that it's a Python version problem until we see the literal error message. > Also the code had an import statement of module called posix and > apparantly it also doesn't recognise that. Odd! Can you show us the error message that occurs if you try 'import posix'? This is really weird, as 'posix' is also in 1.5.2: http://www.python.org/doc/1.5.2p2/lib/module-posix.html as well as 1.4, http://www.python.org/doc/1.4/lib/node74.html#SECTION00910000000000000000 So as far as we're concerned, posix has been there forever. *grin* You need to show us the error message, so that we can limit the number of hypotheses we need to test to diagnose the problem. I don't think it's a versioning problem, but it may be an installation or library problem on your system. Tell us more about what happens with that import statement. Let's take a look at the code a little more. > jumper = random.Random() > jumper.seed() > serial = 0 > def linkfileinto(dir, file): > while 1: > global serial > serial = serial + 1 > filename = str(serial) > try: > # XXX assumes symlink() is atomic > os.symlink(file, os.path.join(dir, filename)) <--- the problem i So there are some possibilities here. If we assume that os.syslink() and os.path.join() are working if we give them good values, we still have a few things here to check that we've given them good values. What values do 'file', 'dir' and 'filename' contain when the code breaks? > return filename > except OSError, err: > err_errno, msg = err > if err_errno == errno.EEXIST: > serial = serial + 10**jumper.randrange(3) > else: > raise ^^^^^ That last line looks a little suspicious. The code here is raising something, but raising.... what? *grin* There seems to be something missing here --- the raise statement needs to raise a specific class or instance as an exception: we can't just leave it hanging like that: ### >>> raise ValueError Traceback (most recent call last): File "", line 1, in ? ValueError >>> >>> >>> raise Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be strings, classes, or instances, not NoneType ### ... well, we _could_, but the exception that gets raised will mumble about "exceptions must be strings...", and that obscures the real problem about the unrecognized OSError. So the code should probably say something like: ### except OSError, err: err_errno, msg = err if err_errno == errno.EEXIST: serial = serial + 10**jumper.randrange(3) else: raise OSError, err ## raise the error again for ## outside world to check. ### so that we get better debugging information. Good luck to you! From fant@pobox.com Tue Apr 29 16:11:03 2003 From: fant@pobox.com (Andrew Fant) Date: Tue Apr 29 15:11:03 2003 Subject: [Tutor] [off-topic] Python Training Classes? Message-ID: <20030429150337.K21319-100000@net.bluemoon.net> I know this is kind of tangential to the list, but I thought that there would likely be a good answer found here. Does anyone know a source of Python classes akin to what LearningTree and SkillPath offer for Perl (4-5 day lecture/lab)? Being in the Northeastern US would be a decided plus. Thanks Andy Andrew Fant | This | "If I could walk THAT way... Molecular Geek | Space | I wouldn't need the talcum powder!" fant@pobox.com | For | G. Marx (apropos of Aerosmith) Boston, MA USA | Hire | http://www.pharmawulf.com From dyoo@hkn.eecs.berkeley.edu Tue Apr 29 16:11:15 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 29 15:11:15 2003 Subject: [Tutor] pyXML DOM 2.0 Traversal and filters In-Reply-To: <20030429163854.83209.qmail@web40406.mail.yahoo.com> Message-ID: On Tue, 29 Apr 2003, Levy Lazarre wrote: > Given the following sample file ('appliances.xml'), I > am trying to write a TreeWalker that would print out > the element > nodes, while a filter would prevent the nodes with a > status of "broken" from displaying. > > > > cuckoo > black and > white > > > I am getting some exceptions, making me think that I > am calling the filter the wrong way or I am missing > something. > Can somebody please point me to the right direction? > Here is the sample code: Hi Levy, I haven't played with the filtering stuff yet (I'm more into xml.dom.pulldom), but let's give it a shot! *grin* Let's take a look at the code: > from xml.dom.ext.reader import Sax2 > from xml.dom.NodeFilter import NodeFilter > > def filterbroken(thisNode): > if (thisNode.nodeType == thisNode.ELEMENT_NODE and > thisNode.getAttribute("status") == "broken"): > return NodeFilter.FILTER_REJECT > return NodeFilter.FILTER_ACCEPT > > reader = Sax2.Reader() > > input_file = file("appliances.xml") > doc = reader.fromStream(input_file) > walker = doc.createTreeWalker(doc.documentElement, > NodeFilter.SHOW_ALL, filterbroken, 0) Ok, let's stop at this point. The error message we're getting: > AttributeError: 'function' object has no attribute > 'acceptNode' is implying that the walker is thinking that filterbroken is some kind of class instance: it may be trying to do something like: filterbroken.acceptNode() to call the filter. But let's double check the documentation on createTreeWalker() and see what it expects: http://pyxml.sourceforge.net/topics/howto/node22.html Odd! According to the docs, it expects a function. But according to the error message, > "C:\Python22\Lib\site-packages\_xmlplus\dom\TreeWalker.py", > line 168, in __checkFilter > return self.__dict__['__filter'].acceptNode(node) > AttributeError: 'function' object has no attribute > 'acceptNode' ... it's trying to call an acceptNode() method. So something here is definitly wrong. Either the code is wrong, or the documentation is wrong. *grin* And I expect it's the documentation. Published code that uses createTreeWalker() does appear to pass in NodeFilter instances, and not functions: ### # (part of: # http://aspn.activestate.com/ASPN/Mail/Message/XML-checkins/954448) def checkWalkerOnlyTextNodesParentNodeFirstChildFilterSkipB(self): class SkipBFilter(NodeFilter): def acceptNode(self, node): if node.nodeValue == 'B': return self.FILTER_SKIP else: return self.FILTER_ACCEPT walker = self.document.createTreeWalker(self.document, NodeFilter.SHOW_TEXT, SkipBFilter(), 0) ### So you may find that this will work: ### class FilterBroken(NodeFilter): def acceptNode(self, thisNode): if (thisNode.nodeType == thisNode.ELEMENT_NODE and thisNode.getAttribute("status") == "broken"): return NodeFilter.FILTER_REJECT return NodeFilter.FILTER_ACCEPT reader = Sax2.Reader() input_file = file("appliances.xml") doc = reader.fromStream(input_file) walker = doc.createTreeWalker(doc.documentElement, NodeFilter.SHOW_ALL, FilterBroken(), 0) ### If this does do the trick, let's send a holler to the pyxml documentation maintainers and get them to fix their documentation. *grin* Hope this helps! From dyoo@hkn.eecs.berkeley.edu Tue Apr 29 16:25:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 29 15:25:02 2003 Subject: [Tutor] about counting files In-Reply-To: <20030429043307.80090.qmail@web14512.mail.yahoo.com> Message-ID: On Mon, 28 Apr 2003, Abdirizak abdi wrote: > Hi, can ayone help me with this program, I am reading multiple files and > I want to count each of these files, I tried different things but I > couldn't get it right. Hi Abdirizak, Can you tell us in more detail what you expect, and what things look ok? Have you been able to get the counting working with a single file first? The main loop that you've written, ### if __name__ == '__main__': import sys for arg in sys.argv[1:]: genIndex(arg,'txt') ### looks somewhat ok, but the code doesn't tell us what it will do with all these file arguments. The file opening code in genIndex() looks a little odd: ### def genIndex(indexFileName, extension): fname='*.'+extension for line in fileinput.input(glob.glob(fname)): ## [cut] ### Where does indexFileName get used? I see that it's used to control the name of the shelf we open, > shelf = shelve.open(indexFileName,'n') But if we give the program a set of parameters, like 'a b c', I think the code will trying to write three duplicate index files of all the text files in the current directory. Is this what you want? Talk to you later! From magnus@thinkware.se Tue Apr 29 17:38:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 16:38:01 2003 Subject: [Tutor] [off-topic] Python Training Classes? In-Reply-To: <20030429150337.K21319-100000@net.bluemoon.net> Message-ID: <5.2.1.1.0.20030429222549.00b41800@www.thinkware.se> At 15:10 2003-04-29 -0400, Andrew Fant wrote: >Does anyone know a source of Python classes akin to what LearningTree and >SkillPath offer for Perl (4-5 day lecture/lab)? Being in the Northeastern >US would be a decided plus. As far as I know, both Wesley Chun (author of Core Python) and Mark Lutz (author of Programming Python etc) run courses. Chun is in California and Lutz in Colorado? Then you have Patrick O'Brien in St Louis. He's also a well know pythonista. See http://starship.python.net/crew/wesc/cpp/ http://www.rmi.net/~lutz/mytrain.html http://www.orbtech.com/web/training/ -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From dyoo@hkn.eecs.berkeley.edu Tue Apr 29 18:48:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Apr 29 17:48:02 2003 Subject: [Tutor] [off-topic] Python Training Classes? In-Reply-To: <5.2.1.1.0.20030429222549.00b41800@www.thinkware.se> Message-ID: On Tue, 29 Apr 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > >Does anyone know a source of Python classes akin to what LearningTree > >and SkillPath offer for Perl (4-5 day lecture/lab)? Being in the > >Northeastern US would be a decided plus. > > As far as I know, both Wesley Chun (author of Core Python) and Mark Lutz > (author of Programming Python etc) run courses. Chun is in California > and Lutz in Colorado? Then you have Patrick O'Brien in St Louis. He's > also a well know pythonista. Hi Andrew, The Association of C and C++ users (ACCU) also holds some Python classes, so you might be able to do some learning online: http://www.cix.co.uk/~jimh/python/ So if location is a problem, you might want to talk with the ACCU folks and see when their next online class starts up. Good luck! From cdsomerl@murray-ky.net Tue Apr 29 21:12:01 2003 From: cdsomerl@murray-ky.net (Chris Somerlot) Date: Tue Apr 29 20:12:01 2003 Subject: [Tutor] updating module Message-ID: <001401c30eac$90912160$e612953f@www> How can I go about updating the library my zlib module uses? I'm running windows Thanks Chris From hemanexp@yahoo.com Tue Apr 29 21:15:06 2003 From: hemanexp@yahoo.com (perl lover) Date: Tue Apr 29 20:15:06 2003 Subject: [Tutor] Problem in scalling............ Message-ID: <20030430001311.16008.qmail@web41702.mail.yahoo.com> hi, i have a problem in scalling a canvas widget in tkinter. I have created a canvas of size 1000 * 1000. When i move the mouse over canvas the x,y values of mouse pointer are showned in status bar. It is working fine with normal canvas(ie, before scalling). I got 762*477 as bottom right pixel value. When i scallled the canvas stil i got the same value (762*477) if the mouse is placed at bottom right of the canvas. Since i used 2 as scalling factor for both x,y, I expect bottom right value is as half as normal canvas (ie, 381,248). How can i get it? My program is given below. from Tkinter import * class App: def __init__(self,parent): self.myparent = parent self.canvas = Canvas(parent,width="1000m",height="1000m") self.canvas.create_rectangle(100,100,200,200,fill='blue') self.canvas.bind('',self.ZoomIn) self.canvas.bind('',self.mm) self.canvas.pack() def ZoomIn(self,event): self.canvas.scale(ALL,2,2,1.5,1.5) def mm(self,event): print self.canvas.canvasx(event.x),self.canvas.canvasy(event.y) root = Tk() myapp = App(root) root.mainloop() Thanx __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From zak@harlekin-maus.com Tue Apr 29 22:10:03 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Tue Apr 29 21:10:03 2003 Subject: [Tutor] reloading all modules? Message-ID: <3827.192.206.201.86.1051664959.squirrel@mail.harlekin-maus.com> I'm working on a project in IDLE, and I often modify several modules at once. When I change a module, I've got to save it and reload () it. This can be a pain with reloading 3 modules every time I want to rerun my program! Is there a way to reload all imported modules in memory? Or del them all? -- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From p.hartley@spitech.com Tue Apr 29 22:18:12 2003 From: p.hartley@spitech.com (Paul Hartley) Date: Tue Apr 29 21:18:12 2003 Subject: [Tutor] Reading text file written by another application Message-ID: <00ba01c30eb8$ddebdf20$ebe710ac@pc7345> This is a multi-part message in MIME format. ------=_NextPart_000_00B7_01C30EFB.EBFE5640 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I am sending data between two applications using ascii text files. What = I would like to know is how can I have one application check that the = other application has finished writing the text file before starting to = read it? Application one starts to write to the file Application two detects the file has been created - but must not start = reading it yet Application one finishes writing to the file Application two is sure that the file is complete can now read the file, = then delete it. The application is Windows so setting file attributes I don't think = would work. There can be buffering problems two - I tried getting application one to = write another file when it had finished - a sort of flag, but the = buffering meant that the first file had still not been written = completely to disc! Kind regards Paul ------=_NextPart_000_00B7_01C30EFB.EBFE5640 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi,
 
I am sending data between two = applications using=20 ascii text files. What I would like to know is how can I have one = application=20 check that the other application has finished writing the text file = before=20 starting to read it?
 
Application one starts to write to the=20 file
Application two detects the file has = been created -=20 but must not start reading it yet
Application one finishes writing to the = file
Application two is sure that the file = is complete=20 can now read the file, then delete it.
 
The application is Windows so setting = file=20 attributes I don't think would work.
There can be buffering problems two - I = tried=20 getting application one to write another file when it had finished = - a sort=20 of flag, but the buffering meant that the first file had still not been = written=20 completely to disc!
 
Kind regards
 
Paul
------=_NextPart_000_00B7_01C30EFB.EBFE5640-- From magnus@thinkware.se Tue Apr 29 23:28:04 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Apr 29 22:28:04 2003 Subject: [Tutor] reloading all modules? In-Reply-To: <3827.192.206.201.86.1051664959.squirrel@mail.harlekin-maus .com> Message-ID: <5.2.1.1.0.20030430042337.00b55690@www.thinkware.se> At 18:09 2003-04-29 -0700, Zak Arntson wrote: >I'm working on a project in IDLE, and I often modify several modules at >once. When I change a module, I've got to save it and reload () it. This >can be a pain with reloading 3 modules every time I want to rerun my >program! > >Is there a way to reload all imported modules in memory? Or del them all? In IDLE? Don't think so... My suggestion is to just edit filed in IDLE (or PythonWin or whatever) and then run them from the command line. Then you get a fresh start every time, and your running program isn't "disturbed" by all the modules in IDLE etc. Printing will be much faster, there are no problem with GUI event loops messing things up for each other--as well as the load problem. I guess using an IDE which always run the code in a separate process helps. Try IDLE-fork for the most convenient way to get that feature. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From Don Arnold" Message-ID: <050c01c30ec4$28983b30$d510ba3f@defaultcomp> ----- Original Message ----- From: "Magnus Lyckå" To: "Zak Arntson" ; Sent: Tuesday, April 29, 2003 9:28 PM Subject: Re: [Tutor] reloading all modules? > At 18:09 2003-04-29 -0700, Zak Arntson wrote: > >I'm working on a project in IDLE, and I often modify several modules at > >once. When I change a module, I've got to save it and reload () it. This > >can be a pain with reloading 3 modules every time I want to rerun my > >program! > > > >Is there a way to reload all imported modules in memory? Or del them all? > > In IDLE? Don't think so... > > My suggestion is to just edit filed in IDLE (or PythonWin or > whatever) and then run them from the command line. Then you > get a fresh start every time, and your running program isn't > "disturbed" by all the modules in IDLE etc. Printing will be > much faster, there are no problem with GUI event loops messing > things up for each other--as well as the load problem. > > I guess using an IDE which always run the code in a separate > process helps. Try IDLE-fork for the most convenient way to > get that feature. > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The shortest path from thought to working program What I've done before instead of using a plain vanilla import in my modules is wrapping the reload in a try block and importing on the exception: try: reload(mymodule) except NameError: import mymodule Of course, if you're working directly from the interpreter prompt, it's admittedly not too useful. HTH, Don From j.ezequiel@spitech.com Wed Apr 30 00:53:05 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Tue Apr 29 23:53:05 2003 Subject: [Tutor] Entity to UTF-8 Message-ID: <0F757892D113D611BD2E0002559C1FF4035C2BCF@email.spitech.com> Greetings. I need to convert entities (α) in an XML file to the actual UTF-8 characters (?). Currently, I am using this bit of code (prototype to see if I can actually do it). This seems to work just fine but I was wondering if there are other ways of doing this. ##-------------------------------------------------- import codecs import re (utf8_encode, utf8_decode, utf8_reader, utf8_writer) = codecs.lookup("utf-8") patt = '&#([^;]+);' def ToUTF8(matchobj): return unichr(long(matchobj.group(1))) def GetUTF8(pth): infile = utf8_reader(open(pth)) readstr = infile.read() infile.close() return readstr def WriteUTF8(pth, str): outf = utf8_writer(open(pth, 'w')) outf.write(str) outf.close() ustr = GetUTF8('input.htm') ustr = re.sub(patt, ToUTF8, ustr) WriteUTF8('output.htm', ustr) ##-------------------------------------------------- sample input file (actual production files would be XML): TESTING

 я ж щ ю ф й б ⋨ ⌣ > ☎ α

 я ж щ ю ф й б ⋨ ⌣ > ☎ α

sample output file: TESTING

? ? ? ? ? ? ? ? ? ? > ? ?

? ? ? ? ? ? ? ? ? ? > ? ?

Can you point me to resources/tutorials if any for this? Is there a HowTo for the codecs module? Maybe there are other modules I should look at (XML?). Actual (production) input files would most likely have α instead of α but α is also possible. BTW, is there a built-in method to convert a Hex string ('3B1') to a long (945)? I am currently using my own function (am too embarrassed to post it here). From Simon.Wittber@perth.maptek.com.au Wed Apr 30 00:57:01 2003 From: Simon.Wittber@perth.maptek.com.au (Simon Wittber (Maptek)) Date: Tue Apr 29 23:57:01 2003 Subject: [Tutor] profiler question Message-ID: <10F0E58C0018054484E329DC494C4D7F9490D9@mexper1> This is a multi-part message in MIME format. --------------InterScan_NT_MIME_Boundary Content-Type: multipart/alternative; boundary="----_=_NextPart_001_01C30ECC.4347F110" ------_=_NextPart_001_01C30ECC.4347F110 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hello people! =20 Can anyone tell me what the line: =20 1 0.000 0.000 4.772 4.772 :1(?) =20 means in the below profiler output? =20 =20 318 function calls in 4.775 CPU seconds =20 Ordered by: standard name =20 ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 4.772 4.772 :1(?) 1 0.000 0.000 0.001 0.001 jestur.py:162(match) 8 0.001 0.000 0.001 0.000 jestur.py:179(match) 1 0.000 0.000 0.001 0.001 jestur.py:41(recognize) 1 0.000 0.000 0.000 0.000 jestur.py:52(startCapture) 1 0.000 0.000 0.000 0.000 jestur.py:61(finishCapture) 301 0.005 0.000 0.005 0.000 jestur.py:68(addPoint) 1 0.000 0.000 0.000 0.000 jestur.py:76(getPoints) 1 0.001 0.001 0.001 0.001 jestur.py:96(normalisePoints) 1 0.003 0.003 4.775 4.775 profile:0(main()) 0 0.000 0.000 profile:0(profiler) 1 4.765 4.765 4.772 4.772 testjestur.py:28(main) ------_=_NextPart_001_01C30ECC.4347F110 Content-Type: text/html; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Message
Hello=20 people!
 
Can = anyone tell me=20 what the line:
 
       =20 1    0.000    0.000   =20 4.772    4.772 <string>:1(?)
 
means = in the below=20 profiler output?

 
 
        =20 318 function calls in 4.775 CPU seconds
 
   Ordered by: standard = name
 
   ncalls  tottime  = percall  cumtime  percall=20 filename:lineno(function)
       =20 1    0.000    0.000   =20 4.772    4.772=20 <string>:1(?)
       =20 1    0.000    0.000   =20 0.001    0.001=20 jestur.py:162(match)
       =20 8    0.001    0.000   =20 0.001    0.000=20 jestur.py:179(match)
       =20 1    0.000    0.000   =20 0.001    0.001=20 jestur.py:41(recognize)
       =20 1    0.000    0.000   =20 0.000    0.000=20 jestur.py:52(startCapture)
        = 1    0.000    0.000   =20 0.000    0.000=20 jestur.py:61(finishCapture)
     =20 301    0.005    0.000   =20 0.005    0.000=20 jestur.py:68(addPoint)
       =20 1    0.000    0.000   =20 0.000    0.000=20 jestur.py:76(getPoints)
       =20 1    0.001    0.001   =20 0.001    0.001=20 jestur.py:96(normalisePoints)
      &nbs= p;=20 1    0.003    0.003   =20 4.775    4.775=20 profile:0(main())
       =20 0   =20 0.000           &n= bsp;=20 0.000         =20 profile:0(profiler)
       =20 1    4.765    4.765   =20 4.772    4.772=20 testjestur.py:28(main)
=00 ------_=_NextPart_001_01C30ECC.4347F110-- --------------InterScan_NT_MIME_Boundary-- From j.ezequiel@spitech.com Wed Apr 30 02:21:01 2003 From: j.ezequiel@spitech.com (Ezequiel, Justin) Date: Wed Apr 30 01:21:01 2003 Subject: [Tutor] Entity to UTF-8 Message-ID: <0F757892D113D611BD2E0002559C1FF4035DF0D9@email.spitech.com> Full text of my previous mail is at http://www.sps-spitech.com/wap/utf8.txt MS Outlook messed up my mail. Thanks in advance. From antonmuhin at rambler.ru" References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> <1761186205.20030426183113@rambler.ru> <1451.192.206.201.86.1051550800.squirrel@mail.harlekin-maus.com> Message-ID: <682578317.20030430105530@rambler.ru> Hello Zak, Monday, April 28, 2003, 9:26:40 PM, you wrote: ZA> I created a new class, and defined __new__, but it doesn't get called from ZA> Python, as far as I can tell. Here's my code: ZA> class C: ZA> def __new__ (cls): ZA> print (cls) ZA> Even when I create the first instance (d = C()), I don't get any output. Yes, except for cases (if I'm correct) when you inherit from immutable classes: class Foo(tuple): def __new__(self): print "new" Foo() should print "new". However, I might miss the point: method __new__ should be defined not in the class, but in the metaclass. In this case it gets called only once after the class declaration is over. -- Best regards, anton mailto:antonmuhin@rambler.ru From magnus@thinkware.se Wed Apr 30 06:06:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 30 05:06:02 2003 Subject: [Tutor] reloading all modules? In-Reply-To: <050c01c30ec4$28983b30$d510ba3f@defaultcomp> References: <5.2.1.1.0.20030430042337.00b55690@www.thinkware.se> Message-ID: <5.2.1.1.0.20030430094427.026e6510@www.thinkware.se> At 21:56 2003-04-29 -0500, Don Arnold wrote: >What I've done before instead of using a plain vanilla import in my modules >is wrapping the reload in a try block and importing on the exception: > >try: > reload(mymodule) >except NameError: > import mymodule In my opinion this is not an ideal solution. First of all, every import in every module you work with will have this awkward fourliner for every module you import. That will make "import os, sys, time, string" into 16 lines of code. :( Secondly, I think you will eventually run in to situations where you would need to get fresh reloads also of moduls you didn't write. There might be code which is run in import to set things up in a module loaded by a third party module you don't control. The more I work with python (and computers in general), the more I appreciate working with a good commad line prompt or shell. The old DOS shell command.com used in Windows 98 and Me is crappy, but the shell in W2k / XP, cmd.exe, isn't too bad if you enable autocomplete (a registry setting). (I think it's not written by Microsoft, but aquired from a company that made Windows emulators for Unix and Mac). Unix shells like bash are even better, and freely available for all recent Windows versions. Also, in Windows, he seqence Ctrl-S, Alt-Tab, ArrowUp, Enter is certainly fast enough. It's not quite as fast as Ctrl-S, F5, but certainly much faster than the mouse-waving most command line challenged people tend to use. ;) It's always faster if the program you actually want to run is not a program you are currently editing. At least with the current state of IDLE and similar competitors. I'm open for the concepts of IDEs, but I don't think they are good enough to skip the command line today, even if they have their string points. For instance, a graphical debugger or class browser is often better than any command line counter part. With unit tests and python, the use for a debugger is fairly small though. Beyond that, using the command line give access to a wide array of powerful tools, like the cygwin tools with just a few key- presses--often just a few ArrowUp followed by Enter. The Unix tool "grep" from the command line is much more effective than any GUI search tool I've ever seen. Add "find" to the mix and it's eons away. Finally, the unix tool chain, which is now available on almost all computers, is as useful regardless of whether you are programming Python or doing other productive things like working with web sites, producing documentation or what ever. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From bgailer@alum.rpi.edu Wed Apr 30 07:01:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 30 06:01:02 2003 Subject: [Tutor] reloading all modules? In-Reply-To: <3827.192.206.201.86.1051664959.squirrel@mail.harlekin-maus .com> Message-ID: <5.2.0.9.0.20030430035120.03000648@66.28.54.253> --=======25EC4A41======= Content-Type: text/plain; x-avg-checked=avg-ok-497732D7; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:09 PM 4/29/2003 -0700, Zak Arntson wrote: >I'm working on a project in IDLE, and I often modify several modules at >once. When I change a module, I've got to save it and reload () it. This >can be a pain with reloading 3 modules every time I want to rerun my >program! > >Is there a way to reload all imported modules in memory? Or del them all? 2 ideas: import sys for module in sys.modules.values(): try:reload(module) except:pass I use PythonWin. There are a lot of PythonWin-related things in sys.modules, and at least one of them won't reload; that's the reason for the try. 1st improvement: keep a list of the modules you want to reload and iterate over that list instead on sys.modules. 2nd idea: I wrote a module manager that makes certain checks to see if a reload is needed; my main program uses the module manager to import/reload as needed and to run the module's code. If interested let me know. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======25EC4A41======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-497732D7 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======25EC4A41=======-- From kuros@sbcglobal.net Wed Apr 30 07:15:02 2003 From: kuros@sbcglobal.net (Kuros) Date: Wed Apr 30 06:15:02 2003 Subject: [Tutor] Asyncore Problem Message-ID: <005801c30f01$42758d90$9801a8c0@Malkil> This is a multi-part message in MIME format. ------=_NextPart_000_0055_01C30ED7.5664CCF0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hiya, I am using asyncore to build a MUD-like game. I am having one problem = though. I have \n set as the terminator. In the def found_terminator function, I = have it set to do this.. check to see if the socket's state is "logedIn". If its not, it sends = data (the input from the socket) to process input, where I have this... def processLogin(ch, data): if ch.state =3D=3D dConst.getName: gName(ch, data) data =3D None if ch.state =3D=3D dConst.getNewName: write_to_self(ch, 'Please choose a name: ') gNewName(ch, data) if ch.state =3D=3D dConst.getPassword: write_to_self(ch, 'Enter your password: ') gPassword(ch, data) if ch.state =3D=3D dConst.getNewPassword: write_to_self(ch, 'Choose a password: ') gNewPassword(ch, data) ch is the socket, data is the input.=20 Now, each of those functions (gName, etc) work ok, except for this. I = want to get new input for each function, but it is passing the first = input to every one of those. So when ased for a name, it passes what = they typed in to every one of those functions, without getting new input = for each function. Anyone have a solution for this? Thanks, Kuros ------=_NextPart_000_0055_01C30ED7.5664CCF0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hiya,
 
I am using asyncore to build a MUD-like = game. I am=20 having one problem though.
 
I have \n set as the terminator. In the = def=20 found_terminator function, I have it set to do this..
 
check to see if the socket's state is = "logedIn". If=20 its not, it sends data (the input from the socket) to process input, = where I=20 have this...
 
def processLogin(ch,=20 data):
     if ch.state =3D=3D=20 dConst.getName:
         = =20 gName(ch, = data)
          data =3D = None
     if ch.state =3D=3D=20 dConst.getNewName:
        &nb= sp;=20 write_to_self(ch, 'Please choose a name:=20 ')
          = gNewName(ch,=20 data)
     if ch.state =3D=3D=20 dConst.getPassword:
   write_to_self(ch, 'Enter your = password:=20 ')
          = gPassword(ch,=20 data)
     if ch.state =3D=3D=20 dConst.getNewPassword:
        = ; =20 write_to_self(ch, 'Choose a password:=20 ')
          = gNewPassword(ch,=20 data)
 
ch is the socket, data is the input. =
 
Now, each of those functions (gName, = etc) work ok,=20 except for this. I want to get new input for each function, but it is = passing=20 the first input to every one of those. So when ased for a name, it = passes what=20 they typed in to every one of those functions, without getting new input = for=20 each function.
 
Anyone have a solution for = this?
 
Thanks,
Kuros
------=_NextPart_000_0055_01C30ED7.5664CCF0-- From kuros@sbcglobal.net Wed Apr 30 07:24:05 2003 From: kuros@sbcglobal.net (Kuros) Date: Wed Apr 30 06:24:05 2003 Subject: [Tutor] Asyncore Problem References: <005801c30f01$42758d90$9801a8c0@Malkil> Message-ID: <009401c30f02$8ac95f30$9801a8c0@Malkil> This is a multi-part message in MIME format. ------=_NextPart_000_0091_01C30ED8.A18CF440 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Oh, ignore the "data =3D None" part in my snippet. That was one way I = was trying to fix it. it didn't work. =3DP ----- Original Message -----=20 From: Kuros=20 To: tutor@python.org=20 Sent: Wednesday, April 30, 2003 5:14 AM Subject: [Tutor] Asyncore Problem Hiya, I am using asyncore to build a MUD-like game. I am having one problem = though. I have \n set as the terminator. In the def found_terminator function, = I have it set to do this.. check to see if the socket's state is "logedIn". If its not, it sends = data (the input from the socket) to process input, where I have this... def processLogin(ch, data): if ch.state =3D=3D dConst.getName: gName(ch, data) data =3D None if ch.state =3D=3D dConst.getNewName: write_to_self(ch, 'Please choose a name: ') gNewName(ch, data) if ch.state =3D=3D dConst.getPassword: write_to_self(ch, 'Enter your password: ') gPassword(ch, data) if ch.state =3D=3D dConst.getNewPassword: write_to_self(ch, 'Choose a password: ') gNewPassword(ch, data) ch is the socket, data is the input.=20 Now, each of those functions (gName, etc) work ok, except for this. I = want to get new input for each function, but it is passing the first = input to every one of those. So when ased for a name, it passes what = they typed in to every one of those functions, without getting new input = for each function. Anyone have a solution for this? Thanks, Kuros ------=_NextPart_000_0091_01C30ED8.A18CF440 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Oh, ignore the "data =3D None" part in = my snippet.=20 That was one way I was trying to fix it. it didn't work. = =3DP
----- Original Message -----
From:=20 Kuros=20
Sent: Wednesday, April 30, 2003 = 5:14=20 AM
Subject: [Tutor] Asyncore = Problem

Hiya,
 
I am using asyncore to build a = MUD-like game. I=20 am having one problem though.
 
I have \n set as the terminator. In = the def=20 found_terminator function, I have it set to do this..
 
check to see if the socket's state is = "logedIn".=20 If its not, it sends data (the input from the socket) to process = input, where=20 I have this...
 
def processLogin(ch,=20 data):
     if ch.state =3D=3D=20 = dConst.getName:
         = =20 gName(ch, = data)
          data=20 =3D None
     if ch.state =3D=3D=20 = dConst.getNewName:
        &nb= sp;=20 write_to_self(ch, 'Please choose a name:=20 ')
          = gNewName(ch,=20 data)
     if ch.state =3D=3D=20 dConst.getPassword:
   write_to_self(ch, 'Enter your = password:=20 ')
          = gPassword(ch,=20 data)
     if ch.state =3D=3D=20 = dConst.getNewPassword:
        = ; =20 write_to_self(ch, 'Choose a password:=20 ')
          = gNewPassword(ch,=20 data)
 
ch is the socket, data is the input.=20
 
Now, each of those functions (gName, = etc) work=20 ok, except for this. I want to get new input for each function, but it = is=20 passing the first input to every one of those. So when ased for a = name, it=20 passes what they typed in to every one of those functions, without = getting new=20 input for each function.
 
Anyone have a solution for = this?
 
Thanks,
Kuros
------=_NextPart_000_0091_01C30ED8.A18CF440-- From emil@lysator.liu.se Wed Apr 30 10:22:38 2003 From: emil@lysator.liu.se (Emil Styrke) Date: Wed Apr 30 09:22:38 2003 Subject: [Tutor] Problem in scalling............ In-Reply-To: <20030430001311.16008.qmail@web41702.mail.yahoo.com> (perl lover's message of "Tue, 29 Apr 2003 17:13:11 -0700 (PDT)") References: <20030430001311.16008.qmail@web41702.mail.yahoo.com> Message-ID: <877k9cdsvk.fsf@i110.ryd.student.liu.se> perl lover writes: > hi, > i have a problem in scalling a canvas widget in > tkinter. I have created a canvas of size 1000 * 1000. > When i move the mouse over canvas the x,y values of > mouse pointer are showned in status bar. It is working > fine with normal canvas(ie, before scalling). I got > 762*477 as bottom right pixel value. When i scallled > the canvas stil i got the same value (762*477) if the > mouse is placed at bottom right of the canvas. Since i > used 2 as scalling factor for both x,y, I expect > bottom right value is as half as normal canvas (ie, > 381,248). How can i get it? My program is given below. I'm not an expert at Tkinter, but my impression is that what you get is the desired behavior. If you want the real x,y coordinates, you could either manually divide by the scaling factor, or use the event.x,event.y values instead, possibly subtracting the coordinates of the top left corner of the canvas widget. Now that I read a little more careful, I'm not sure I understand what your problem is, probably due to my lack of knowledge about the canvas widget. I'll have to experiment a little with this. /Emil > > > from Tkinter import * > > class App: > def __init__(self,parent): > self.myparent = parent > self.canvas = > Canvas(parent,width="1000m",height="1000m") > > self.canvas.create_rectangle(100,100,200,200,fill='blue') > self.canvas.bind('',self.ZoomIn) > self.canvas.bind('',self.mm) > self.canvas.pack() > > def ZoomIn(self,event): > self.canvas.scale(ALL,2,2,1.5,1.5) > > def mm(self,event): > print > self.canvas.canvasx(event.x),self.canvas.canvasy(event.y) > > > > root = Tk() > myapp = App(root) > root.mainloop() > > Thanx > > > > __________________________________ > Do you Yahoo!? > The New Yahoo! Search - Faster. Easier. Bingo. > http://search.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From stuart_clemons@us.ibm.com Wed Apr 30 10:27:39 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 30 09:27:39 2003 Subject: [Tutor] Question about nested FOR looping Message-ID: Hi all: I'm a newbie playing around with nested FOR loops using readlines or a defined list. I noticed the looping action of the nested FOR is different depending on if the input data is coming from a file (readlines) or a defined list. Note, that only the nested FOR input source makes a difference in the output results. The data source of the top level FOR loop doesn't seem to affect the looping action of the nested FOR. Below are the program and results. Can anyone explain why the looping action is different depending on the nested FOR input source (readlines vs defined list) ? Please let me know if this not clear. (It doesn't look all that clear to me !) Here's the text file, subitems.txt: 1 3 5 Nested looping from a defined list: ###### Start Program ####### import string mF = file('g:\python22\sctest\\master.txt', 'r') # This file contains the same data as the master list (below) #sF = file('g:\python22\sctest\\subitems.txt', 'r') # This file contains the same data as the subitems list (below) #master = ['1', '2', '3', '4', '5'] # This list = Master.txt (above) subitems = ['1', '3', '5'] # This list = subitems.txt (above) for m in mF.readlines(): # Read data from master.txt file #for m in master: # Or, read data for master list m = m.strip() #for s in sF.readlines(): # Read data from subitems.txt file for s in subitems: # Or, read data from subitems list s = s.strip() if s == m: print "this num is duplicate: ", m break if s <> m: print "this num is unique: ", m ###### End Program ######### The result of running the program is this: this num is duplicate: 1 this num is unique: 2 this num is duplicate: 3 this num is unique: 4 this num is duplicate: 5 If the nested loop uses readlines to input data from subitems.txt, the result is this: this num is duplicate: 1 this num is unique: 2 this num is unique: 3 this num is unique: 4 this num is unique: 5 Why are they different ? TIA From bgailer@alum.rpi.edu Wed Apr 30 11:18:58 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Apr 30 10:18:58 2003 Subject: [Tutor] Question about nested FOR looping In-Reply-To: Message-ID: <5.2.0.9.0.20030430081500.02fff698@66.28.54.253> --=======59A4E44======= Content-Type: text/plain; x-avg-checked=avg-ok-497732D7; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:17 AM 4/30/2003 -0400, stuart_clemons@us.ibm.com wrote: >I'm a newbie playing around with nested FOR loops using readlines or a >defined list. I noticed the looping action of the nested FOR is different >depending on if the input data is coming from a file (readlines) or a >defined list. Note, that only the nested FOR input source makes a >difference in the output results. The data source of the top level FOR >loop doesn't seem to affect the looping action of the nested FOR. > >Below are the program and results. Can anyone explain why the looping >action is different depending on the nested FOR input source (readlines vs >defined list) ? > >Please let me know if this not clear. (It doesn't look all that clear to >me !) > >Here's the text file, subitems.txt: >1 >3 >5 > >Nested looping from a defined list: > >###### Start Program ####### > >import string >mF = file('g:\python22\sctest\\master.txt', 'r') # This file contains the >same data as the master list (below) >#sF = file('g:\python22\sctest\\subitems.txt', 'r') # This file contains >the same data as the subitems list (below) > >#master = ['1', '2', '3', '4', '5'] # This list = Master.txt (above) >subitems = ['1', '3', '5'] # This list = subitems.txt >(above) > >for m in mF.readlines(): # Read data from master.txt file >#for m in master: # Or, read data for master list > m = m.strip() > > #for s in sF.readlines(): # Read data from subitems.txt file > for s in subitems: # Or, read data from subitems list > s = s.strip() > if s == m: > print "this num is duplicate: ", m > break > if s <> m: > print "this num is unique: ", m > >###### End Program ######### > >The result of running the program is this: > >this num is duplicate: 1 >this num is unique: 2 >this num is duplicate: 3 >this num is unique: 4 >this num is duplicate: 5 > > >If the nested loop uses readlines to input data from subitems.txt, the >result is this: > >this num is duplicate: 1 >this num is unique: 2 >this num is unique: 3 >this num is unique: 4 >this num is unique: 5 > >Why are they different ? Repeating "for s in subitems:" reuses the list each time The first call to "for s in sF.readlines():" reads to end of file. Subsequent calls do NOT move to start of file; just return ''. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======59A4E44======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-497732D7 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.474 / Virus Database: 272 - Release Date: 4/18/2003 --=======59A4E44=======-- From llazarre@yahoo.com Wed Apr 30 12:07:02 2003 From: llazarre@yahoo.com (Levy Lazarre) Date: Wed Apr 30 11:07:02 2003 Subject: [Tutor] pyXML DOM 2.0 Traversal and filters In-Reply-To: Message-ID: <20030430150530.70491.qmail@web40412.mail.yahoo.com> --- Danny Yoo wrote: > So you may find that this will work: > > ### > class FilterBroken(NodeFilter): > def acceptNode(self, thisNode): > if (thisNode.nodeType == > thisNode.ELEMENT_NODE and > thisNode.getAttribute("status") == > "broken"): > return NodeFilter.FILTER_REJECT > return NodeFilter.FILTER_ACCEPT > > reader = Sax2.Reader() > input_file = file("appliances.xml") > doc = reader.fromStream(input_file) > walker = doc.createTreeWalker(doc.documentElement, > NodeFilter.SHOW_ALL, > FilterBroken(), 0) > ### > > > If this does do the trick, let's send a holler to > the pyxml documentation > maintainers and get them to fix their documentation. > *grin* > > > Hope this helps! > Thanks Danny. Great insight.It did the trick! As you said, the documentation is wrong and createTreeWalker() expects a class instance, not a function. This is the same in Java. Interestingly, I did some more research after I sent my message to the List. I found an article that showed me how to do the same thing without using a TreeWalker, but with generators. The resulting code is shorter and faster, and actually uses a function as filter. Here it is: from __future__ import generators from xml.dom import Node from xml.dom import minidom # doc_order_iter_filter iterates over non-attribute nodes, returning those that pass a filter def doc_order_iter_filter(node, filter_func): if filter_func(node): yield node for child in node.childNodes: for cn in doc_order_iter_filter(child, filter_func): yield cn return # This filter function rejects element nodes with a "status" attribute of "broken": elem_filter = lambda n: n.nodeType == Node.ELEMENT_NODE and n.getAttribute("status") != "broken" ##### main program doc = minidom.parse('appliances.xml') for node in doc_order_iter_filter(doc, elem_filter): print node __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From llazarre@yahoo.com Wed Apr 30 12:18:01 2003 From: llazarre@yahoo.com (Levy Lazarre) Date: Wed Apr 30 11:18:01 2003 Subject: [Tutor] getElementById() in XML 4DOM implementation Message-ID: <20030430151642.18361.qmail@web40405.mail.yahoo.com> Hi all, I am having some difficulties with the getElementById() method processing an XML file. It seems to work fine in the minidom implementation, but not the 4DOM implementation. Could somebody shed some light? Here is some testing: >>> from xml.dom import minidom >>> xmldoc = minidom.parse('school.xml') >>> xmldoc.getElementById("L2") But the same code doesn't seem to work with the 4DOM implementation, where the method is also provided: >>> from xml.dom.ext.reader import Sax2 >>> reader = Sax2.Reader() >>> doc = reader.fromStream(file('school.xml')) >>> doc.getElementById("L2") >>> The test file('school.xml') is like: ]> Algebra I Gentle introduction to Algebra! 4.30.03 20 Trigonometry I Learn the science of angles. 4.29.03 18 Lecture Hall I 25 Open Lecture Hall II 3 Open Thanks, Levy Lazarre Winter Haven Hospital llazarre@yahoo.com __________________________________ Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. http://search.yahoo.com From magnus@thinkware.se Wed Apr 30 13:24:07 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 30 12:24:07 2003 Subject: [Tutor] Question about nested FOR looping In-Reply-To: <5.2.0.9.0.20030430081500.02fff698@66.28.54.253> References: Message-ID: <5.2.1.1.0.20030430181627.02655ad8@www.thinkware.se> Bob Gailer wrote in response to Stuart's: >>Why are they different ? > >Repeating "for s in subitems:" reuses the list each time >The first call to "for s in sF.readlines():" reads to end of file. >Subsequent calls do NOT move to start of file; just return ''. if you do "sF.seek(0)" before "for s in sF.readlines():", i.e. reset the current file position to the beginning, it will work as you expect. BTW, with a modern python you can simply write "for s in sF:". Calling .readlines() is implied in that context. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From BAlmond@russreid.com Wed Apr 30 13:32:01 2003 From: BAlmond@russreid.com (Brian Almond) Date: Wed Apr 30 12:32:01 2003 Subject: [Tutor] __init__ for class instantiation? Message-ID: >> ZA> The problem here (as with __new__) is that __init__ will be called >> with ZA> every creation of a Player instance. >> >> It seems that you are wrong here---__new__ is called only once after >> class is defined. >I created a new class, and defined __new__, but it doesn't get called from >Python, as far as I can tell. Here's my code: > >class C: > def __new__ (cls): > print (cls) > >Even when I create the first instance (d = C()), I don't get any output. I didn't see a response to this yet, so let me chime in. The __new__ magic method is a feature of new-style Python classes. As far as I know, a __new__ method defined in an old-style class is just like any other method. (Except for the funny name :) Try this: class C(object): count = 0 def __new__(cls): C.count += 1 return object.__new__(cls) >>> c1 = C() >>> c1 <__main__.C object at 0x00923668> >>> C.count 1 >>> c2 = C() >>> c2 <__main__.C object at 0x00933A50> >>> C.count 2 This perhaps is an odd way to use __new__ - I made this only to demonstrate that __new__ is called for every instantiation of a new-style class. PS: Although there's nothing wrong with the Python docs, I really liked the section on classes in Alex Martelli's book "Python in a Nutshell" - it's a good reference. From jeff@ccvcorp.com Wed Apr 30 13:48:06 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Apr 30 12:48:06 2003 Subject: [Tutor] __init__ for class instantiation? References: <4569.192.207.104.231.1051285911.squirrel@mail.harlekin-maus.com> <1155.192.207.104.231.1051290054.squirrel@mail.harlekin-maus.com> <1761186205.20030426183113@rambler.ru> <1451.192.206.201.86.1051550800.squirrel@mail.harlekin-maus.com> <682578317.20030430105530@rambler.ru> Message-ID: <3EAFFE16.1060606@ccvcorp.com> > > >Monday, April 28, 2003, 9:26:40 PM, Zak Arntson wrote: > > I created a new class, and defined __new__, but it doesn't get called from > Python, as far as I can tell. Here's my code: > > class C: > def __new__ (cls): > print (cls) > > > > Even when I create the first instance (d = C()), I don't get any output. > I may be mistaken here, but I believe that __new__ would only apply to new-style classes, not old-style ones. This means that in Python 2.2, you need to derive your class from object: class C(object): [...] I'm not sure if new-style classes are the default in 2.3 or not, but explicitly deriving from object shouldn't be a problem there. Jeff Shannon Technician/Programmer Credit International From guillermo.fernandez@epfl.ch Wed Apr 30 14:39:02 2003 From: guillermo.fernandez@epfl.ch (guillermo.fernandez@epfl.ch) Date: Wed Apr 30 13:39:02 2003 Subject: [Tutor] IMAP library In-Reply-To: <20030430160006.15344.15121.Mailman@mail.python.org> References: <20030430160006.15344.15121.Mailman@mail.python.org> Message-ID: <1051724081.3eb009317a398@imapwww.epfl.ch> Hi! I'm trying to understand how the IMAP library works. For that I've copied this program and modified it a little bit: import getpass, imaplib, string M = imaplib.IMAP4('mailbox.site.com') M.login(getpass.getuser(), getpass.getpass()) M.select('INBOX',1) typ, data = M.search(None, "FROM \"a.friend@site.com\"") for num in string.split(data[0]): typ, data = M.fetch(num, '(RFC822)') print 'Message %s\n%s\n' % (num, data[0][1]) M.logout() I recieve this error: $ python test.py Password: Traceback (most recent call last): File "test.py", line 8, in ? typ, data = M.search(None, "FROM \"a.friend@site.com\"") File "/usr/lib/python2.1/imaplib.py", line 468, in search typ, dat = apply(self._simple_command, (name, charset) + criteria) File "/usr/lib/python2.1/imaplib.py", line 844, in _simple_command return self._command_complete(name, apply(self._command, (name,) + args)) File "/usr/lib/python2.1/imaplib.py", line 681, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: SEARCH command error: BAD ['Invalid Search criteria'] I've checked the RFC3501 and they say for the search command: FROM Messages that contain the specified string in the envelope structure's FROM field. As I put a string with the e-mail address I'm looking for, I don't get what I've done wrong. If someone could give me a hand or has any idea of where I could look for an answer... Thanks! Guille From Janssen@rz.uni-frankfurt.de Wed Apr 30 15:10:05 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Apr 30 14:10:05 2003 Subject: [Tutor] IMAP library In-Reply-To: <1051724081.3eb009317a398@imapwww.epfl.ch> Message-ID: On Wed, 30 Apr 2003 guillermo.fernandez@epfl.ch wrote: > Hi! > > I'm trying to understand how the IMAP library works. For that I've copied this program and modified it a little bit: > > import getpass, imaplib, string > > M = imaplib.IMAP4('mailbox.site.com') > M.login(getpass.getuser(), getpass.getpass()) > M.select('INBOX',1) > typ, data = M.search(None, "FROM \"a.friend@site.com\"") the docs say, you have two possibilities how to write the search criterium: """ msgnums = M.search(None, 'FROM', '"LDJ"') # or: msgnums = M.search(None, '(FROM "LDJ")') """ it seems, that the type of quote (single/ dubble) matters: >>> M.search(None, "(FROM 'Janssen@rz.uni-frankfurt.de')") ('OK', ['']) >>> M.search(None, '(FROM "Janssen@rz.uni-frankfurt.de")') ('OK', ['1 2 3 4 14 18 21 25 26 40 42']) [i post a lot of messages to myself ;-)] does anyone know how to search for X-Header Values (Like "X-BeenThere: tutor@python.org")? Michael From Janssen@rz.uni-frankfurt.de Wed Apr 30 15:23:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Apr 30 14:23:01 2003 Subject: [Tutor] IMAP library In-Reply-To: Message-ID: On Wed, 30 Apr 2003, Michael Janssen wrote: > does anyone know how to search for X-Header Values (Like "X-BeenThere: > tutor@python.org")? to answere myself: >>> M.search(None, '(HEADER "X-BeenThere" "tutor@python.org")') ('OK', ['1 2 3 ..... rfc3501 section 6.4.4 lists all possibilities Michael From stuart_clemons@us.ibm.com Wed Apr 30 15:23:19 2003 From: stuart_clemons@us.ibm.com (stuart_clemons@us.ibm.com) Date: Wed Apr 30 14:23:19 2003 Subject: [Tutor] Question about nested FOR looping In-Reply-To: <5.2.1.1.0.20030430181627.02655ad8@www.thinkware.se> Message-ID: This is a multipart message in MIME format. --=_alternative 0065138C85256D18_= Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: quoted-printable Thanks Bob and Magnus. You've expanded my Python knowledge ! So, as a follow-up out of curiosity, which is the most efficient: 1) Read the two files into lists and then process the lists, or 2) Process directly from the file reads, using seek in the nested FOR, or 3) Read one file into a list and process during the read of the second=20 file ? As some added info, Scott Widney from tutor@python.org, provided a=20 dictionary construct for this same problem, ie, compare two lists,=20 identifying the duplicates. I would guess that the dictionary construct=20 would be the most efficient method, based on random vs sequential=20 ordering. Is this right ? (BTW, I used the dictionary construct to provide a report I needed to=20 produce quickly. As a learning exercise, I've now gone back to look at my = original approach to the problem, which I couldn't get to work at the=20 time.) Thanks again for your responses. - Stuart =20 Magnus Lyck=E5 04/30/2003 12:22 PM =20 To: Bob Gailer ,=20 stuart=5Fclemons@us.ibm.com, tutor@python.org cc:=20 Subject: Re: [Tutor] Question about nested FOR looping Bob Gailer wrote in response to Stuart's: >>Why are they different ? > >Repeating "for s in subitems:" reuses the list each time >The first call to "for s in sF.readlines():" reads to end of file.=20 >Subsequent calls do NOT move to start of file; just return ''. if you do "sF.seek(0)" before "for s in sF.readlines():", i.e. reset the current file position to the beginning, it will work as you expect. BTW, with a modern python you can simply write "for s in sF:". Calling .readlines() is implied in that context. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program=20 --=_alternative 0065138C85256D18_= Content-Type: text/html; charset="ISO-8859-1" Content-Transfer-Encoding: quoted-printable
Thanks Bob and Magnus.  You've expanded my Python knowledge !

So, as a follow-up out of curiosity, which is the most efficient:

1) Read the two files into lists and then process the lists, or

2) Process directly from the file re= ads, using seek in the nested FOR, or

3) Read one file into a list and pro= cess during the read of the second file ?

As some added info, Scott Widney from tutor@python.org, provided a dictionary construct for this same problem, ie, compare two lists, identifying the duplicates.   I would guess that the dictionary construct would be the most efficient method, based on random vs sequential ordering.  Is this right ?

(BTW, I used the dictionary construct to provide a report I needed to produce quickly.  As a learning exerci= se, I've now gone back to look at my original approach to the problem, which I couldn't get to work at the time.)

Thanks again for your responses.

- Stuart
 


Magnus Lyck=E5 <magnus@thinkwa= re.se>

04/30/2003 12:22 PM

       
        To:        Bob Gailer <bgailer@alum.rpi.edu>, stuart=5Fclemons@us.ibm.com, tutor@python.org
        cc:        
        Subject:        Re: [Tutor] Question about nested FOR looping



Bob Gailer wrote in response to Stuart's:
>>Why are they different ?
>
>Repeating "for s in subitems:" reuses the list each time
>The first call to "for s in sF.readlines():" reads to end of file.
>Subsequent calls do NOT move to start of file; just return ''.

if you do "sF.seek(0)" before "for s in sF.readlines():"= ;, i.e.
reset the current file position to the beginning, it will work
as you expect.

BTW, with a modern python you can simply write "for s in sF:".
Calling .readlines() is implied in that context.


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program


--=_alternative 0065138C85256D18_=-- From Janssen@rz.uni-frankfurt.de Wed Apr 30 16:25:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Apr 30 15:25:02 2003 Subject: [Tutor] Question about nested FOR looping In-Reply-To: Message-ID: On Wed, 30 Apr 2003 stuart_clemons@us.ibm.com wrote: > So, as a follow-up out of curiosity, which is the most efficient: > > 1) Read the two files into lists and then process the lists, or with (vary) large files this is forbidden because of memory-consumption. With reasonable small files it can be handy espessially if you need random access (not looping line-by-line). > 2) Process directly from the file reads, using seek in the nested FOR, or *can* be good for memory. NB: "for line in fo.readlines():" build a (possibly) huge list of lines within memory. fo.xreadlines() is better or recent-version-of-python "for line in fo:" > 3) Read one file into a list and process during the read of the second > file ? depends on wich is the big file. The problem with all these approaches is, that it iter over len(list1) x len(list2). With large lists you will have many comparisions (comparing e.g. 10,000 x 10,000 entries *this way* can easily last for some minutes). Since dictinary lookup is fast it is much better to store the lines of first file in a dictionary and look for each line of the second file if the dictionary "has_key(line)" and report the duplicates. > As some added info, Scott Widney from tutor@python.org, provided a > dictionary construct for this same problem, ie, compare two lists, > identifying the duplicates. I would guess that the dictionary construct > would be the most efficient method, based on random vs sequential > ordering. Is this right ? Yes, because dictionary lookup is fast because of random ordering. say len(list1) --> 10 len(list2) --> 20 for line in list1: # iters 10 times for line2 in list2: # iters 10 x 20 times if line == line2: # 200 comparisions pass dict1 = dict([(x, 1) for x in list1]) # builds a dictionary from list1 for line in list2: # iters 20 times if dict1.has_key(line): # 20 lookups pass NB: for line in list1: # iters 10 times if line in list1: # 10 lookups pass is possibly slower since looups in lists are slow. Could well be that this is as slow as the dubble-for-loop solution in case the "if line in list1" lookup works internally as a iteration through each element. Michael From magnus@thinkware.se Wed Apr 30 17:43:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Apr 30 16:43:02 2003 Subject: [Tutor] Question about nested FOR looping In-Reply-To: References: <5.2.1.1.0.20030430181627.02655ad8@www.thinkware.se> Message-ID: <5.2.1.1.0.20030430214437.026bcf40@www.thinkware.se> At 14:11 2003-04-30 -0400, stuart_clemons@us.ibm.com wrote: >So, as a follow-up out of curiosity, which is the most efficient: > >1) Read the two files into lists and then process the lists, or > >2) Process directly from the file reads, using seek in the nested FOR, or > >3) Read one file into a list and process during the read of the second file ? I can only suggest that you measure with reasonable data sets. It might be a good thing to measure with different sizes of the files to see how the timing changes as a function of the file sizes. import profile profile.run('myFunction()') I'm not sure either of these are optimal though. :) If the sizes of of your files are M and N respectively, you will have a runtime which is roughly proportional to M*N. That's pretty lousy from a performance point of view. It's the first logical approach, and unless performance id really an issue, I wouldn't bother going any further, but you're the one who asked about performance. >As some added info, Scott Widney from tutor@python.org, provided a >dictionary construct for this same problem, ie, compare two lists, >identifying the duplicates. I would guess that the dictionary construct >would be the most efficient method, based on random vs sequential >ordering. Is this right ? This should be faster, more like proportional to M+N in runtime. I.e., of both and M and N gets five times bigger, runtime will increase five times, not twenty five times as with the nested list. In practice, performance figures don't usually follow the simplistic theories we apply. For instance, most functions will drop significantly in performance when RAM is exhausted, so if solution A is faster than solution B both when N=10000 (all in RAM) and when N=1000000 (both A and B swapping badly) there might be an intermediate value where B is much faster than A if it uses less memory (A is swapping but B isn't). Whether and when this will happen will depend on how loaded the machine is with other jobs etc, so it's not trivial to know performance beforehand... There are other solutions too... If you have two sorted lists without duplicates, you could imagine working like this untested code: m = s = l_m, l_s = len(m), len(s) m_pos = s_pos = 0 while m_pos < l_m and s_pos < l_s: m_val, s_val = m[m_pos].strip(), s[s_pos].strip() if m_val == s_val: print "this num is duplicate: ", m_val m_pos += 1 s_pos += 1 elif m_val < s_val: m_pos += 1 else: s_pos += 1 I'm not sure about the exit condition. Maybe it should be or instead of and? You figure it out... Anyway, this algorithm should also be O(N+M), and I don't think you can beat that for any solution where you need to read the files. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The shortest path from thought to working program From a_abdi406@yahoo.com Wed Apr 30 18:08:13 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Apr 30 17:08:13 2003 Subject: [Tutor] about Regular Expression in Class function Message-ID: <20030430130859.32894.qmail@web14506.mail.yahoo.com> --0-717062632-1051708139=:32655 Content-Type: text/plain; charset=us-ascii hi, I have a class that indexes some text,this class has a function calledreadline() it reads a line from a file, what I need to do is to pass RE(regular expression) so that only normal words are extracted because the input file(i.e file to be read ) has some XML tags so for e.g. the file has this Similarity-Based Estimation of Word Cooccurrence Probabilities and want to extract ['Similarity based', 'Estimation'.....] I think the problem is it doesn't accept the class instances such as : aword =re.compile (r'([^<]+)')self.line = aword.findall(self.line) Can anyone help me to suggest how I can incorporate this RE.Here is the function:Class text_word_iterator......def readline(self): #aword =re.compile (r'<[^<>]*>|\b[\w-]+\b')#|([^<]+)') #added now aword =re.compile (r'([^<]+)') #added now self.line = self.file.readline() #already there self.line = aword.findall(self.line) #added now for xml--should work self.line = ' '.join(self.line) #this is a extra lin added -- works print self.line if self.line == '': self.words = None else: self.words = filter(None, re.split(r'\W+', self.line))#mod form \W ->\s+ thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-717062632-1051708139=:32655 Content-Type: text/html; charset=us-ascii
hi,
 
I have a class that indexes some text,this class has a function called
readline() it reads a line from a file, what I need to do is to pass
RE(regular expression) so that only normal words are extracted because the input file(i.e file to be read ) has some XML tags so for e.g. the file has this
<S ID='S-0'> <W>Similarity-Based</W> <W>Estimation</W> <W>of</W> <W>Word</W> <W>Cooccurrence</W> <W>Probabilities</W> </S>
 
and want to extract ['Similarity based', 'Estimation'.....]    I think the problem is it doesn't accept the class instances such as :
 
aword =re.compile (r'<W>([^<]+)</W>')
self.line = aword.findall(self.line)
 
Can anyone help me to suggest how I can incorporate this RE.
Here is the function:
Class text_word_iterator
......
def readline(self):
  #aword =re.compile (r'<[^<>]*>|\b[\w-]+\b')#|<W>([^<]+)</W>') #added now
        aword =re.compile (r'<W>([^<]+)</W>') #added now
        self.line = self.file.readline() #already there
        self.line = aword.findall(self.line) #added now for xml--should work
        self.line = ' '.join(self.line) #this is a extra lin added -- works
        print self.line
       
        if self.line == '': self.words = None
        else: self.words = filter(None, re.split(r'\W+', self.line))#mod form \W ->\s+
       
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-717062632-1051708139=:32655-- From a_abdi406@yahoo.com Wed Apr 30 18:09:51 2003 From: a_abdi406@yahoo.com (Abdirizak abdi) Date: Wed Apr 30 17:09:51 2003 Subject: [Tutor] about Regular Expression in Class function Message-ID: <20030430143834.65357.qmail@web14512.mail.yahoo.com> --0-379051222-1051713514=:64128 Content-Type: text/plain; charset=us-ascii hi, I have a class that indexes some text,this class has a function calledreadline() it reads a line from a file, what I need to do is to pass RE(regular _expression) so that only normal words are extracted because the input file(i.e file to be read ) has some XML tags so for e.g. the file has this Similarity-Based Estimation of Word Cooccurrence Probabilities and want to extract ['Similarity based', 'Estimation'.....] I think the problem is it doesn't accept the class instances such as : aword =re.compile (r'([^<]+)')self.line = aword.findall(self.line) Can anyone help me to suggest how I can incorporate this RE.Here is the function:Class text_word_iterator......def readline(self): #aword =re.compile (r'<[^<>]*>|\b[\w-]+\b')#|([^<]+)') #added now aword =re.compile (r'([^<]+)') #added now self.line = self.file.readline() #already there self.line = aword.findall(self.line) #added now for xml--should work self.line = ' '.join(self.line) #this is a extra lin added -- works print self.line if self.line == '': self.words = None else: self.words = filter(None, re.split(r'\W+', self.line))#mod form \W ->\s+ thanks in advance --------------------------------- Do you Yahoo!? The New Yahoo! Search - Faster. Easier. Bingo. --0-379051222-1051713514=:64128 Content-Type: text/html; charset=us-ascii
hi,
 
I have a class that indexes some text,this class has a function called
readline() it reads a line from a file, what I need to do is to pass
RE(regular _expression) so that only normal words are extracted because the input file(i.e file to be read ) has some XML tags so for e.g. the file has this
<S ID='S-0'> <W>Similarity-Based</W> <W>Estimation</W> <W>of</W> <W>Word</W> <W>Cooccurrence</W> <W>Probabilities</W> </S>
 
and want to extract ['Similarity based', 'Estimation'.....]    I think the problem is it doesn't accept the class instances such as :
 
aword =re.compile (r'<W>([^<]+)</W>')
self.line = aword.findall(self.line)
 
Can anyone help me to suggest how I can incorporate this RE.
Here is the function:
Class text_word_iterator
......
def readline(self):
  #aword =re.compile (r'<[^<>]*>|\b[\w-]+\b')#|<W>([^<]+)</W>') #added now
        aword =re.compile (r'<W>([^<]+)</W>') #added now
        self.line = self.file.readline() #already there
        self.line = aword.findall(self.line) #added now for xml--should work
        self.line = ' '.join(self.line) #this is a extra lin added -- works
        print self.line
       
        if self.line == '': self.words = None
        else: self.words = filter(None, re.split(r'\W+', self.line))#mod form \W ->\s+
       
 
thanks in advance


Do you Yahoo!?
The New Yahoo! Search - Faster. Easier. Bingo. --0-379051222-1051713514=:64128-- From dyoo@hkn.eecs.berkeley.edu Wed Apr 30 18:45:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 30 17:45:02 2003 Subject: [Tutor] Question about nested FOR looping [an implementation of a 'mergeiter' merging iterator function] In-Reply-To: Message-ID: On Wed, 30 Apr 2003, Michael Janssen wrote: > On Wed, 30 Apr 2003 stuart_clemons@us.ibm.com wrote: > > > So, as a follow-up out of curiosity, which is the most efficient: > > > > 1) Read the two files into lists and then process the lists, or > > with (vary) large files this is forbidden because of memory-consumption. > With reasonable small files it can be handy espessially if you need random > access (not looping line-by-line). > > > 2) Process directly from the file reads, using seek in the nested FOR, or > > *can* be good for memory. NB: "for line in fo.readlines():" build a > (possibly) huge list of lines within memory. fo.xreadlines() is better or > recent-version-of-python "for line in fo:" Hi everyone, But just to mention: using seek() is not necessary. If we're doing a merge between two sequences, and if the two sequences are themselves already sorted, we can do a simulaneous linear pass through both sequences just once, and avoid the multiple scan. Since you already have a good dictionary solution to your problem, I feel it should be ok to post an implementation of merging for you. Here's a module that applies a merging between two iteratable objects, using that left-hand/right-hand process we talked about earlier: ### #!/usr/bin/env python """mergeiter.py: An extended example of generators in action. Provides a function called mergeiter that merges two iterators together. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ from __future__ import generators def mergeiter(i1, i2, cmp=cmp): """Returns the "merge" of i1 and i2. i1 and i2 must be iteratable objects, and we assume that i1 and i2 are both individually sorted. """ left, right = ExtendedIter(i1), ExtendedIter(i2) while 1: if not left.has_next(): while 1: yield ('r', right.next()) if not right.has_next(): while 1: yield ('l', left.next()) comparison = cmp(left.peek(), right.peek()) if comparison < 0: yield ('l', left.next()) elif comparison == 0: right.next() ; yield ('=', left.next()) else: yield ('r', right.next()) class ExtendedIter: """An extended iterator that wraps around an existing iterators. It provides extra methods: has_next(): checks if we can still yield items. peek(): returns the next element of our iterator, but doesn't pass by it.""" def __init__(self, i): self._myiter = iter(i) self._next_element = None self._has_next = 0 self._prime() def has_next(self): """Returns true if we can call next() without raising a StopException.""" return self._has_next def peek(self): """Nonexhaustively returns the next element in our iterator.""" assert self.has_next() return self._next_element def next(self): """Returns the next element in our iterator.""" if not self._has_next: raise StopIteration result = self._next_element self._prime() return result def _prime(self): """Private function to initialize the states of self._next_element and self._has_next. We poke our self._myiter to see if it's still alive and kicking.""" try: self._next_element = self._myiter.next() self._has_next = 1 except StopIteration: self.next_element = None self._has_next = 0 def _test(): for item in mergeiter([2, 4, 6, 8], [1, 3, 4, 7, 9, 10]): print item if __name__ == '__main__': ## _test() f1, f2 = open(sys.argv[1], sys.argv[2]) for item in mergeiter(f1, f2): print item ### Here's a sample of it in action: ### >>> import mergeiter >>> mergeiter._test() ('r', 1) ('l', 2) ('r', 3) ('=', 4) ('l', 6) ('r', 7) ('l', 8) ('r', 9) ('r', 10) ### The program uses a constant amount of memory, regardless of the size of the files, and should run in linear time since the code does a single pass through both files. The code might seem a little mysterious because of the generators stuff. Generators are a new feature in Python 2.2, and I've been having way too much fun with them. *grin* You can find out more about generators here: http://www.python.org/peps/pep-0255.html If this mergeiter() function is useful enough, and if speed is a real concern, we can show how one can recode this as a C extension. *grin* I hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Apr 30 18:51:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Apr 30 17:51:02 2003 Subject: [Tutor] Question about nested FOR looping [an implementation of a 'mergeiter' merging iterator function] In-Reply-To: Message-ID: Doh. There's a bug in the 'if __name__ == "__main__"' part of the code. > if __name__ == '__main__': > ## _test() > f1, f2 = open(sys.argv[1], sys.argv[2]) > for item in mergeiter(f1, f2): > print item > ### That's totally wrong. I knew I should have tested it earlier... This should really be: ### if __name__ == '__main__': ## _test() import sys f1, f2 = open(sys.argv[1]), open(sys.argv[2]) for item in mergeiter(f1, f2): print item ### My apologies for being careless! I was too excited seeing it work as a module, that I had forgotten to test it as a standalone program... *grin* From phthenry@earthlink.net Wed Apr 30 21:01:16 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed Apr 30 20:01:16 2003 Subject: [Tutor] Entity to UTF-8 In-Reply-To: <0F757892D113D611BD2E0002559C1FF4035C2BCF@email.spitech.com> References: <0F757892D113D611BD2E0002559C1FF4035C2BCF@email.spitech.com> Message-ID: <20030430150054.K31959@localhost.localdomain> You probably already know this already, but I thought I'd offer it anyway. Your code has the lines: patt = '&#([^;]+);' ustr = re.sub(patt, ToUTF8, ustr) I believe this is ineffecient, because python has to compile the regular expression each time. This code should be more effecient: patt = re.compile(r'&#[^;];') ustr = re.sub(patt, ToUTF8, ustr) I am struggling with unicode myself, so I am going to test out your code and see if it helps me. Paul On Wed, Apr 30, 2003 at 11:53:10AM +0800, Ezequiel, Justin wrote: > From: "Ezequiel, Justin" > To: "'tutor@python. org' (E-mail)" > Subject: [Tutor] Entity to UTF-8 > Date: Wed, 30 Apr 2003 11:53:10 +0800 > > Greetings. > > I need to convert entities (α) in an XML file to the actual UTF-8 characters (?). > Currently, I am using this bit of code (prototype to see if I can actually do it). > This seems to work just fine but I was wondering if there are other ways of doing this. > > ##-------------------------------------------------- > import codecs > import re > > (utf8_encode, utf8_decode, utf8_reader, utf8_writer) = codecs.lookup("utf-8") > patt = '&#([^;]+);' > > def ToUTF8(matchobj): > return unichr(long(matchobj.group(1))) > > def GetUTF8(pth): > infile = utf8_reader(open(pth)) > readstr = infile.read() > infile.close() > return readstr > > def WriteUTF8(pth, str): > outf = utf8_writer(open(pth, 'w')) > outf.write(str) > outf.close() > > ustr = GetUTF8('input.htm') > > ustr = re.sub(patt, ToUTF8, ustr) > > WriteUTF8('output.htm', ustr) > ##-------------------------------------------------- > > sample input file (actual production files would be XML): > > > > TESTING > > >

 я ж щ ю ф й б ⋨ ⌣ > ☎ α

>

 я ж щ ю ф й б ⋨ ⌣ > ☎ α

> > > > sample output file: > > > > TESTING > > >

? ? ? ? ? ? ? ? ? ? > ? ?

>

? ? ? ? ? ? ? ? ? ? > ? ?

> > > > Can you point me to resources/tutorials if any for this? > Is there a HowTo for the codecs module? > Maybe there are other modules I should look at (XML?). > > Actual (production) input files would most likely have α instead of α but α is also possible. > > BTW, is there a built-in method to convert a Hex string ('3B1') to a long (945)? > I am currently using my own function (am too embarrassed to post it here). > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Wed Apr 30 21:01:32 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Wed Apr 30 20:01:32 2003 Subject: [Tutor] unicode problem In-Reply-To: References: Message-ID: <20030430161739.L31959@localhost.localdomain> Now I can't reproduce my problem! I have played around a bit with unicode. As you discovered below (but which I am just realizing), you can concatenate any string with utf-8 as long as both strings ar utf-8, or one string is utf-8 and the other string has values below 128. My code should not have broken. Sax translates everything to utf-8. The module that broke the string tries to add stuff to the string Sax passed to it (utf-8), but this stuff has a range below 128. I think I'll try this in my code, just to make sure: try: line = line + filler + padding + border + "\n" except UnicodeError: filler = convert_to_utf_8_func(filler) padding = convert_to_utf_8_func(padding) border = convert_to_utf_8_func(border) line = line + filler + padding + border + '\n' def conver_to_utf_8_func(my_string): # fill in code. I can read one character at a time, get the # the value and use unichr(num), but that another thread a few # days later has a better way to do this pass Thanks Paul On Mon, Apr 28, 2003 at 10:13:30AM -0700, Danny Yoo wrote: > > > > > The error message you report: > > > > > File "/home/paul/lib/python/paul/format_txt.py", line 159, in r_border > > > line = line + filler + padding + border + "\n" > > > UnicodeError: ASCII decoding error: ordinal not in range(128) > > > > > > doesn't smell right to me --- for the life of me, I can't imagine why > > string concatenation would raise that kind of error. > > > Oh. Never mind. > > ### > >>> x, y = u'\xf6', '\xf6 > >>> x + y > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII decoding error: ordinal not in range(128) > ### > > > Well, at least now we have a test case we can work on. *grin* > > > > I think that the concatentation causes Python to raise the second string y > up as a unicode string. At least, it looks like that unicod()ing a > high-byte character can cause the encoding error: > > ### > >>> unicode('\xf6') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeError: ASCII decoding error: ordinal not in range(128) > ### > > > I'm actually not quite sure how to solve this yet; I'm not familiar with > Unicode at all, so I think I might need to tinker with this problem a bit. -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************