From mhoneyfield@xtra.co.nz Tue Jul 1 04:48:02 2003 From: mhoneyfield@xtra.co.nz (Michael Honeyfield) Date: Tue Jul 1 03:48:02 2003 Subject: [Tutor] compiling python apps Message-ID: <3F013C6F.20202@xtra.co.nz> Hello python users, I have set myself the task of learning python. I learn best in the deep end (sometimes) and thought I would give pysol a hack and see what I can do with it. Perhaps port the UI to the QT python UI. Anyways, I am confussed on the two pysol packages that one can download. One of them is a "ready to run" package (3301Kb) and the other is the source (151Kb). I figured the source package is there for customizing (which is what I wish to do) but I dont know how to "compile" it like the "ready to run" package is. Anyone following this list understand me or am I making a public fool of myself? :) If a am not making much sense I will try to clarifiy further. But to sum it up, How do I get my modified pysol source compile like the ready to run package? I have emailed the maintainer, but not had any reply (I suspect he is busy in the next cool release of pysol :) ) Many many thanks in advance Mike -- Ok, there's no way to do this gracefully, so I won't even try. I'm going to just hunker down for some really impressive extended flaming, and my asbestos underwear is firmly in place, and extremely uncomfortable. -- Linus Trovalds From glingl@mail.rg16.asn-wien.ac.at Tue Jul 1 06:16:03 2003 From: glingl@mail.rg16.asn-wien.ac.at (glingl) Date: Tue Jul 1 05:16:03 2003 Subject: [Tutor] finding factorials - hmm..., gcd Message-ID: <200307010915.h619FGc02559@ada.rg16.asn-wien.ac.at> --- Payal Rathod schrieb: > > Sorry Danny I am still not getting it. Now I am so confused that I think > I don't know what exactly a function does and what is it it returns. > > I have posted my code below with some comments regarding issues I don't > get. > > #!/usr/local/bin/python > > def euclid(a,b): > while b != 0: > c = a > a = b > b = c % a > print 'A = ', a > print 'B = ', b > return euclid(a,b) > # What will this return exactly? > else: > return a > > x = 100 > y = 20 > > result = euclid(x, y) > > # Why do we define x and y here seperately? > # Can't we have result = euclid(100,20) > # This apparently is not working. > > print x > print y > > # This always prints 100 and 20. I think it should print the present values > # of x and y which are not 100 and 20 always. > > print result > > # The result is given as 20 which I think is wrong. Is there anything > # wrong with my mathematical logic or my function? > > With warm regards, > -Payal > Your code is ok and gives the right result! e.g change: x, y = 25, 15 and you will get: >>> A = 15 B = 10 A = 10 B = 5 A = 5 B = 0 25 15 5 hmmm..., o.k., it's not perfektly ok, because ... def euclid(a,b): while b != 0: c = a a = b b = c % a # (1) normally it's not considered good practice to pu # print-statements in a function which aims at calculating # a numerical rsult. - # But here let's use it for getting insight in the working # of euclid print 'A = ', a print 'B = ', b # (2) here you use an uncoditional return - so the body of # the while-loop will be exited after the first run. # Consequently it will never work as a loop and you could # (a) use an if instead of while or # (b) drop the return and recursive call of euclid - # recursion also accomplishes some sort of iteration # and should/need/(must?) not be done in addition # to the while-iteration return euclid(a,b) else: return a x = 25 y = 15 result = euclid(x, y) print x print y print result ################################ # If you decide for the use of while you arrive at: def euclid(a,b): while b != 0: c = a a = b b = c % a print 'A = ', a print 'B = ', b # return euclid(a,b) # else: return a x = 25 y = 15 result = euclid(x, y) print x print y print result ######################################## an alternative is to decide for the use of recursion, in which case you arrive at: def euclid(a,b): if b != 0: c = a a = b b = c % a print 'A = ', a print 'B = ', b return euclid(a,b) else: return a x = 198 y = 94 result = euclid(x, y) print x print y print result # (3) here you can leave out the three statements # # c = a # a = b # b = c % a # # if think carefully about which values are to be # inserted as arguments in the recursive function # call. # What are the values of a and b respectively after # execution of these 3 statements. (Remember: ist is # perfectly right to insert arithmetic expressions like # a / b, a+b etc as arguments - in which case they # will be computed (evaluated( before the results are # "bound" to the parameters.) Finally you should delete (or comment out) the print statements! Hmmm, will this help? Regards, Gregor P.S.: Maybe http://www.ibiblio.org/obp/thinkCSpy/ , especially chapters 4 to 6, contains material, which could be helpful for you. From marta_andrea@libero.it Tue Jul 1 06:43:04 2003 From: marta_andrea@libero.it (=?iso-8859-1?Q?marta=5Fandrea?=) Date: Tue Jul 1 05:43:04 2003 Subject: [Tutor] =?iso-8859-1?Q?audiofile_manipulation?= Message-ID: Hi to all,=0D=0AI'd like to manipulate directly audiosamples. The idea is= to algorithmically calculate each sample value and then write it to fil= e (I know it's a huge task: but it can produce really interesting results= ).=0D=0A=0D=0AI cheked the docs but I am got a bit confused on audiofiles= manipulation.=0D=0A=0D=0ACould anyone (no hurry) post an exemple to do t= his?=0D=0A=0D=0AThanks a lot as usual for any hint!=0D=0A=0D=0A-a-=0D=0A=0D= =0A=0D=0A=0D=0AAndrea Valle From magnus@thinkware.se Tue Jul 1 08:49:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 1 07:49:01 2003 Subject: [Tutor] encodings In-Reply-To: <001f01c33d14$25a9ef80$224c70dc@homeu0a59ztmqs> References: <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se> <5.2.1.1.0.20030613225247.01ef45c0@www.thinkware.se> <5.2.1.1.0.20030614225808.01fb3a48@www.thinkware.se> Message-ID: <5.2.1.1.0.20030701133808.01f51230@www.thinkware.se> I suppose you meant for this to go to the mailing list. You seem to have sent it to me. It seems to me that GB2312 is a 16-bit encoding. As far as I know, Python handles 8-bit strings and Unicode. I don't know how to handle non-Unicode multi-byte strings in Python. Perhaps it can't be done? You will probably find more help at comp.lang.python or in the i18n-sig mailing list. See http://mail.python.org/mailman/listinfo/i18n-sig At 09:25 2003-06-28 +0800, you wrote: >the new problem >i'm in default chinese gb2312 charset >in ./python23/lib/encoding/ no found gb2312 encode/decode >so i get gb2312 charset map from >ftp://ftp.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/GB/GB2312.TXT >exec /Python23/Tools/Scripts/gencodec.py get gb2312.py >put gb2312.py into /python23/lib/encoding/ >in IDLE 0.8 > >>> import codecs > >>> codecs.lookup('gb2312') >(0x01A073F0>>, instance at 0x01A07FD0>>, 0x010F04E0>, ) > >look fine! > >>> text='???' #chinese char > >>> text.decode('gb2312') >Traceback (most recent call last): > File "", line 1, in ? > text.decode('gb2312') > File "C:\Python23\lib\encodings\gb2312.py", line 22, in decode > return codecs.charmap_decode(input,errors,decoding_map) >UnicodeDecodeError: 'charmap' codec can't decode byte 0xbd in position 0: >character maps to > >why? >other > >>> text=u'abcd' > >>> text.encode('gb2312') >Traceback (most recent call last): > File "", line 1, in ? > text.encode('gb2312') > File "C:\Python23\lib\encodings\gb2312.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) >UnicodeEncodeError: 'charmap' codec can't encode characters in position >0-3: character maps to > >What should I do ? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From DORSEY_EDMUND_K@LILLY.COM Tue Jul 1 11:29:02 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Tue Jul 1 10:29:02 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) Message-ID: This is a multipart message in MIME format. --Boundary_(ID_lGig0Ad/t17kN9QAmb93eA) Content-type: text/plain; charset="us-ascii" I need to initialize an array with sizes greater than 10 million indices. The reason for this is because I then proceed to fill in the array but jumping around. (The array is used to store binary medical image data) I tried using a for loop like so for i in range(0, arraySize): #arraySize being over 10 million myArray.append(0) #just use zero as a place holder WHen arraySize is small under 200,000 or so it works okay (though very very slow) Anything larger than this and it just crashes. I have 2 gigs of memory so I'm not running out of memory. Two Questions... 1) Why does this crash? 2) Is there a faster, stable way to do what I want to do Thank you for all the help ~Edmund Dorsey --Boundary_(ID_lGig0Ad/t17kN9QAmb93eA)-- From speno@isc.upenn.edu Tue Jul 1 11:37:03 2003 From: speno@isc.upenn.edu (John P Speno) Date: Tue Jul 1 10:37:03 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) In-Reply-To: References: Message-ID: <20030701143601.GA13464@isc.upenn.edu> > for i in range(0, arraySize): #arraySize being over 10 million > myArray.append(0) #just use zero as a place holder How about? myArray = [0] * arraySize From ATrautman@perryjudds.com Tue Jul 1 11:52:01 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Tue Jul 1 10:52:01 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) Message-ID: <06738462136C054B8F8872D69DA140DB010825@corp-exch-1.pjinet.com> Edmund, An array as large as you want will require quite large computing power unless the stored data is binary. Questions: What are you storing (generic description) in each array position? Large amounts of data will require completely different structures. What can't the image be broken up into smaller regions? This is the way graphics are normally handled. By breaking images into squares (triangles for 3D graphics) the computer only has to deal with smaller regions at a time. If you can work on smaller regions the test will be a few choices: Sort the incoming file, pick a regional small array and extract its' data from the larger file, and/or take each data element as it comes and locate the smaller array, store and move to the next element. These are a few methods I can think of, I'm sure the list can come up with others. HTH Alan I need to initialize an array with sizes greater than 10 million indices. The reason for this is because I then proceed to fill in the array but jumping around. (The array is used to store binary medical image data) I tried using a for loop like so for i in range(0, arraySize): #arraySize being over 10 million myArray.append(0) #just use zero as a place holder WHen arraySize is small under 200,000 or so it works okay (though very very slow) Anything larger than this and it just crashes. I have 2 gigs of memory so I'm not running out of memory. Two Questions... 1) Why does this crash? 2) Is there a faster, stable way to do what I want to do Thank you for all the help ~Edmund Dorsey From zak@harlekin-maus.com Tue Jul 1 12:22:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Tue Jul 1 11:22:01 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) In-Reply-To: <06738462136C054B8F8872D69DA140DB010825@corp-exch-1.pjinet.com> References: <06738462136C054B8F8872D69DA140DB010825@corp-exch-1.pjinet.com> Message-ID: <1255.192.207.104.220.1057072895.squirrel@mail.harlekin-maus.com> > WHen arraySize is small under 200,000 or so it works okay (though very > very slow) Anything larger than this and it just crashes. I have 2 > gigs of memory so I'm not running out of memory. > ~Edmund Dorsey How is the data arranged? If there are many places where the value is 0, you could try storing the data in a dictionary, where the key is the 'index'. >>> def get_at(myDict, i): if myDict.has_key(i): return myDict[i] return 0 Or ... if you know there will be large spans of equal values, you could store the value as a dictionary key, and the key's value as a list or range. >>> d = {} # We have the value 12 from index 34 to 102 >>> d[34] = (34,102) Like Edmund said, it all depends on how the data's arranged. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From DORSEY_EDMUND_K@LILLY.COM Tue Jul 1 12:24:01 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Tue Jul 1 11:24:01 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) Message-ID: This is a multipart message in MIME format. --Boundary_(ID_qTGNmyN8K8F3RpyBLuyTCQ) Content-type: text/plain; charset="us-ascii" The data is stored as binary 16bit short to be precise. I'm writing some software to increase the resolution of ct images using a subvoxel processing algorithm. I've read the original binary file sans the header into an array and then created a larger empty array to place the new image data that will be created based on the algorithm I'm working with. Since I'm not doing any rendering breaking the image into smaller pieces wouldn't help (I think) because I'd still have to process each piece of data. Since it's voxel data (3d) I have to convert the 3d coordinates to a 1d array index. Thus splitting the data up would be a huge headache and start to become conceptually very difficult. In addition I'm jumping around the array (due to the fact that I'm placing 3d data in a 1d array) so the whole thing needs to be initialized at once. Using the following worked and reasonably fast (about 5 seconds to initialize an array with close to 100 million indices) myArray = [0] * arraySize Thanks for the help! ~Edmund Alan Trautman 07/01/2003 09:50 AM To: "'DORSEY_EDMUND_K@LILLY.COM'" , tutor@python.org cc: Subject: RE: [Tutor] Problems creating very large arrays (over 10 million indices) Edmund, An array as large as you want will require quite large computing power unless the stored data is binary. Questions: What are you storing (generic description) in each array position? Large amounts of data will require completely different structures. What can't the image be broken up into smaller regions? This is the way graphics are normally handled. By breaking images into squares (triangles for 3D graphics) the computer only has to deal with smaller regions at a time. If you can work on smaller regions the test will be a few choices: Sort the incoming file, pick a regional small array and extract its' data from the larger file, and/or take each data element as it comes and locate the smaller array, store and move to the next element. These are a few methods I can think of, I'm sure the list can come up with others. HTH Alan I need to initialize an array with sizes greater than 10 million indices. The reason for this is because I then proceed to fill in the array but jumping around. (The array is used to store binary medical image data) I tried using a for loop like so for i in range(0, arraySize): #arraySize being over 10 million myArray.append(0) #just use zero as a place holder WHen arraySize is small under 200,000 or so it works okay (though very very slow) Anything larger than this and it just crashes. I have 2 gigs of memory so I'm not running out of memory. Two Questions... 1) Why does this crash? 2) Is there a faster, stable way to do what I want to do Thank you for all the help ~Edmund Dorsey --Boundary_(ID_qTGNmyN8K8F3RpyBLuyTCQ)-- From camartin@snet.net Tue Jul 1 12:36:15 2003 From: camartin@snet.net (Cliff Martin) Date: Tue Jul 1 11:36:15 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2559 - 14 msgs Readline code References: <20030701094304.20150.86113.Mailman@mail.python.org> Message-ID: <3F01AAAD.60309@snet.net> --------------020509010608030901030803 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Rick, Thanks for your response. I see that, at least for the print statement this is true but if I run the code of your second example and ask for the len(words) I only get the word length of the words in the last line. Why aren''t all the elements in the assignment words? I'm sure this is trivial but I'm certainly missing it. Thanks again. Cliff Martin tutor-request@python.org wrote: >Send Tutor mailing list submissions to > tutor@python.org > >To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor >or, via email, send a message with subject or body 'help' to > tutor-request@python.org > >You can reach the person managing the list at > tutor-admin@python.org > >When replying, please edit your Subject line so it is more specific >than "Re: Contents of Tutor digest..." > > >Today's Topics: > > 1. Re: newbie 'while' question (Zak Arntson) > 2. Re: newbie 'while' question (Danny Yoo) > 3. Re: newbie 'while' question (Danny Yoo) > 4. Re: Re: Convert list to literal string. (Derrick 'dman' Hudson) > 5. Re: newbie 'while' question (Matthew Richardson) > 6. Re: newbie 'while' question (Zak Arntson) > 7. readlines code (Cliff Martin) > 8. writing a search engine (Kyle Babich) > 9. Re: readlines code (Rick Pasotto) > 10. Re: writing a search engine (Sean 'Shaleh' Perry) > 11. Re: finding factorials (Payal Rathod) > 12. compiling python apps (Michael Honeyfield) > 13. Re: finding factorials - hmm..., gcd (glingl) > 14. =?iso-8859-1?Q?audiofile_manipulation?= (=?iso-8859-1?Q?marta=5Fandrea?=) > >--__--__-- > >Message: 1 >Date: Mon, 30 Jun 2003 15:41:40 -0700 (PDT) >Subject: Re: [Tutor] newbie 'while' question >From: "Zak Arntson" >To: > > > >>Which works great. I'm still stuck on how to do Zak's method of >>manipulating the string, but starting to feel better about 'while' now. >> >>Thanks, >>Matt >> >> > >Here's some code, missing stuff: > >s = raw_input('>') >while s: # when will the while loop be done? > print s[??] # ?? is some value > s = ?? # you want to change s > >--- >Zak Arntson >www.harlekin-maus.com - Games - Lots of 'em > > > > >--__--__-- > >Message: 2 >Date: Mon, 30 Jun 2003 15:43:37 -0700 (PDT) >From: Danny Yoo >To: Matthew Richardson >cc: Python Tutor >Subject: Re: [Tutor] newbie 'while' question > > > > > >>>In mathematical terms, we'd say that we'd like a half-open range, >>> >>> >>> 0 <= x < length of "Matthew Ricahrdson" >>> >>> >>>And we'll find that the equivalent expression in Python is very similar to >>>this. *grin* >>> >>> >>>I hope this gives some hints on how to correct the while 'condition' >>>expression. Good luck! >>> >>> >>I knew I should have paid more attention in math... >> >> > > >You did have the right approach. That is, you approached it from the >left: > > while x >= 0: # 0 <= x > >You just had to have the right approach. *grin* > > while x < len(s): # x < len(s) > > > > > >By the way, it turns out that we can do both directions at the same time: > > while 0 <= x < len(s): # 0 <= x and x < len(s) > > >which is a safe way to go about it. Of course, only a few programmers I >know will ever write the condition like this. *grin* Most will just >write: > > x < len(s) > >and just assume that x is nonnegative. Crazy programmers. *grin* > > > >Good luck to you! > > > >--__--__-- > >Message: 3 >Date: Mon, 30 Jun 2003 15:53:24 -0700 (PDT) >From: Danny Yoo >To: Eric L Howard >cc: Python Tutor >Subject: Re: [Tutor] newbie 'while' question > > > > > >>>This is very close to the correct solution. You get the number of >>>characters in the string with the len() built-in function. But >>> >>> s = raw_input('Enter a name: ') >>> x = 0 >>> while x <= len(s): >>> print s[x] >>> x += 1 >>> >>>will still result in an IndexError (even though it's close to being >>>correct). Do you see why? >>> >>> >>[newbie swing ;-)] >> >>I know it works, but would it be bad to do something like >> >>s = raw_input('Enter a name: ') >> for x in range(0, len(s)): >> print s[x] >> >>There's no need to initialize x, or declare our math statement in the >>code. Thoughts, corrections? >> >> > > >Hi Eric, > > >Sure, this works great, and you're right: the 'for' loop is the more >appropriate looping construct here, since we're going along the letters of >the name. > > >We can even do: > >### >s = raw_input('Enter a name: ') >for ch in s: > print ch >### > >and skip the manual indicing altogether. *grin* > > >Strings are like Lists --- they are both "sequences" --- and the 'for' >loop can deal with them uniformly. Matt's question asked to do it with >'while', but in real life code, the 'for' loop is usually easier to >construct because it's less open-ended than 'while'. > > >Good luck! > > > >--__--__-- > >Message: 4 >Date: Mon, 30 Jun 2003 18:53:37 -0400 >From: "Derrick 'dman' Hudson" >To: tutor@python.org >Subject: Re: [Tutor] Re: Convert list to literal string. > > >--vEao7xgI/oilGqZ+ >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline >Content-Transfer-Encoding: quoted-printable > >On Sat, Jun 28, 2003 at 10:00:04AM -0500, David wrote: > >| I can make a loop and process the info. > >Dealing with the list of data is certainly doable. You still didn't >provide the code that shows how you ended up with a list (how!? >command line arguments are strings until you parse them into something >else) so I can't explain what you are doing wrong. > >Abel already reminded you of > ','.join( ['IBM', 'EK', 'MO', 'UTX'] ) > >(if this helps you, then I suspect you called .split() on the command >line argument, and that's where your list came from) > >[... lots and lots of snip ...] >| --addstocks IBM,EK,MO,UTX > >This is easy. See sample (but untested) code below : > > >import sys >import getopt > >try: > opts, args =3D getopt.getopt(sys.argv[1:], "", ["addstocks=3D"]) >except getopt.GetoptError: > # print help information and exit: > usage() # Note: you have to define this function! > sys.exit(2) > >stock_labels =3D None >for o, a in opts: > if o =3D=3D "--addstocks" : > stock_labels =3D a > >if not stock_labels : > usage() > sys.exit(3) > >print stock_labels >print type(stock_labels) >print stock_labels.__class__ # use this with python >=3D 2.2 >addstock( stock_labels ) > > >-D > >--=20 >A violent man entices his neighbor >and leads him down a path that is not good. > Proverbs 16:29 >=20 >http://dman13.dyndns.org/~dman/ > >--vEao7xgI/oilGqZ+ >Content-Type: application/pgp-signature >Content-Disposition: inline > >-----BEGIN PGP SIGNATURE----- >Version: GnuPG v1.0.6 (GNU/Linux) >Comment: For info see http://www.gnupg.org > >iEYEARECAAYFAj8Av3EACgkQiB6vp1xAVUAiuwCeNkrIAAt2rnOS68eJ7w4Y92h2 >MIoAnjnLumBlZlLlNUqGY6BCZeprMnBu >=7tgh >-----END PGP SIGNATURE----- > >--vEao7xgI/oilGqZ+-- > > >--__--__-- > >Message: 5 >Date: Mon, 30 Jun 2003 16:04:14 -0700 >From: Matthew Richardson >Subject: Re: [Tutor] newbie 'while' question >To: Danny Yoo >Cc: Eric L Howard , Python Tutor >Organization: > >On Mon, 2003-06-30 at 15:53, Danny Yoo wrote: > > >>>>This is very close to the correct solution. You get the number of >>>>characters in the string with the len() built-in function. But >>>> >>>> s = raw_input('Enter a name: ') >>>> x = 0 >>>> while x <= len(s): >>>> print s[x] >>>> x += 1 >>>> >>>>will still result in an IndexError (even though it's close to being >>>>correct). Do you see why? >>>> >>>> >>>[newbie swing ;-)] >>> >>>I know it works, but would it be bad to do something like >>> >>>s = raw_input('Enter a name: ') >>> for x in range(0, len(s)): >>> print s[x] >>> >>>There's no need to initialize x, or declare our math statement in the >>>code. Thoughts, corrections? >>> >>> >>Hi Eric, >> >> >>Sure, this works great, and you're right: the 'for' loop is the more >>appropriate looping construct here, since we're going along the letters of >>the name. >> >> >>We can even do: >> >>### >>s = raw_input('Enter a name: ') >>for ch in s: >> print ch >>### >> >>and skip the manual indicing altogether. *grin* >> >> >>Strings are like Lists --- they are both "sequences" --- and the 'for' >>loop can deal with them uniformly. Matt's question asked to do it with >>'while', but in real life code, the 'for' loop is usually easier to >>construct because it's less open-ended than 'while'. >> >> >>Good luck! >> >> >> > >The exercise is out of Wesley Chun's 'Core Python Programming.' The for >loop was far easier for me, but the exercise was to perform the same >task both ways. No point in skipping over the 'hard' material in the >name of expediency. I want to get a firm grip on this and ploughing >through all of the examples is the only way I'll get it. > >Now for Zak's string manipulation.... > >Matt > > > --------------020509010608030901030803 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Rick,

Thanks for your response. I see that, at least for the print statement this is true but if I run the code of  your second example and ask for the len(words) I only get the word length of the words in the last line.  Why aren''t all the elements in the assignment words? I'm sure this is trivial but I'm certainly missing it.  Thanks again.

Cliff Martin

tutor-request@python.org wrote:
Send Tutor mailing list submissions to
	tutor@python.org

To subscribe or unsubscribe via the World Wide Web, visit
	http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
	tutor-request@python.org

You can reach the person managing the list at
	tutor-admin@python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

   1. Re: newbie 'while' question (Zak Arntson)
   2. Re: newbie 'while' question (Danny Yoo)
   3. Re: newbie 'while' question (Danny Yoo)
   4. Re: Re: Convert list to literal string. (Derrick 'dman' Hudson)
   5. Re: newbie 'while' question (Matthew Richardson)
   6. Re: newbie 'while' question (Zak Arntson)
   7. readlines code (Cliff Martin)
   8. writing a search engine (Kyle Babich)
   9. Re: readlines code (Rick Pasotto)
  10. Re: writing a search engine (Sean 'Shaleh' Perry)
  11. Re: finding factorials (Payal Rathod)
  12. compiling python apps (Michael Honeyfield)
  13. Re: finding factorials - hmm..., gcd (glingl)
  14. =?iso-8859-1?Q?audiofile_manipulation?= (=?iso-8859-1?Q?marta=5Fandrea?=)

--__--__--

Message: 1
Date: Mon, 30 Jun 2003 15:41:40 -0700 (PDT)
Subject: Re: [Tutor] newbie 'while' question
From: "Zak Arntson" <zak@harlekin-maus.com>
To: <tutor@python.org>

  
Which works great.  I'm still stuck on how to do Zak's method of
manipulating the string, but starting to feel better about 'while' now.

Thanks,
Matt
    

Here's some code, missing stuff:

s = raw_input('>')
while s:    # when will the while loop be done?
    print s[??]   # ?? is some value
    s = ?? # you want to change s

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em




--__--__--

Message: 2
Date: Mon, 30 Jun 2003 15:43:37 -0700 (PDT)
From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
To: Matthew Richardson <marichar@csusb.edu>
cc: Python Tutor <tutor@python.org>
Subject: Re: [Tutor] newbie 'while' question



  
In mathematical terms, we'd say that we'd like a half-open range,


         0  <=  x   < length of "Matthew Ricahrdson"


And we'll find that the equivalent expression in Python is very similar to
this.  *grin*


I hope this gives some hints on how to correct the while 'condition'
expression.  Good luck!
      
I knew I should have paid more attention in math...
    


You did have the right approach.  That is, you approached it from the
left:

    while x >= 0:                   #  0 <= x

You just had to have the right approach.  *grin*

    while x < len(s):               #  x < len(s)





By the way, it turns out that we can do both directions at the same time:

    while 0 <= x < len(s):          #  0 <= x and x < len(s)


which is a safe way to go about it.  Of course, only a few programmers I
know will ever write the condition like this.  *grin* Most will just
write:

    x < len(s)

and just assume that x is nonnegative.  Crazy programmers.  *grin*



Good luck to you!



--__--__--

Message: 3
Date: Mon, 30 Jun 2003 15:53:24 -0700 (PDT)
From: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
To: Eric L Howard <elh@outreachnetworks.com>
cc: Python Tutor <tutor@python.org>
Subject: Re: [Tutor] newbie 'while' question



  
This is very close to the correct solution.  You get the number of
characters in the string with the len() built-in function.  But

  s = raw_input('Enter a name: ')
  x = 0
  while x <= len(s):
      print s[x]
      x += 1

will still result in an IndexError (even though it's close to being
correct).  Do you see why?
      
[newbie swing ;-)]

I know it works, but would it be bad to do something like

s = raw_input('Enter a name: ')
    for x in range(0, len(s)):
    print s[x]

There's no need to initialize x, or declare our math statement in the
code. Thoughts, corrections?
    


Hi Eric,


Sure, this works great, and you're right: the 'for' loop is the more
appropriate looping construct here, since we're going along the letters of
the name.


We can even do:

###
s = raw_input('Enter a name: ')
for ch in s:
    print ch
###

and skip the manual indicing altogether.  *grin*


Strings are like Lists --- they are both "sequences" --- and the 'for'
loop can deal with them uniformly.  Matt's question asked to do it with
'while', but in real life code, the 'for' loop is usually easier to
construct because it's less open-ended than 'while'.


Good luck!



--__--__--

Message: 4
Date: Mon, 30 Jun 2003 18:53:37 -0400
From: "Derrick 'dman' Hudson" <dman@dman13.dyndns.org>
To: tutor@python.org
Subject: Re: [Tutor] Re: Convert list to literal string.


--vEao7xgI/oilGqZ+
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Sat, Jun 28, 2003 at 10:00:04AM -0500, David wrote:

| I can make a loop and process the info.

Dealing with the list of data is certainly doable.  You still didn't
provide the code that shows how you ended up with a list (how!?
command line arguments are strings until you parse them into something
else) so I can't explain what you are doing wrong.

Abel already reminded you of
    ','.join( ['IBM', 'EK', 'MO', 'UTX'] )

(if this helps you, then I suspect you called .split() on the command
line argument, and that's where your list came from)

[... lots and lots of snip ...]
| --addstocks  IBM,EK,MO,UTX

This is easy.  See sample (but untested) code below :


import sys
import getopt

try:
    opts, args =3D getopt.getopt(sys.argv[1:], "", ["addstocks=3D"])
except getopt.GetoptError:
    # print help information and exit:
    usage()     # Note: you have to define this function!
    sys.exit(2)

stock_labels =3D None
for o, a in opts:
    if o =3D=3D "--addstocks" :
        stock_labels =3D a

if not stock_labels :
    usage()
    sys.exit(3)

print stock_labels
print type(stock_labels)
print stock_labels.__class__  # use this with python >=3D 2.2
addstock( stock_labels )


-D

--=20
A violent man entices his neighbor
and leads him down a path that is not good.
        Proverbs 16:29
=20
http://dman13.dyndns.org/~dman/

--vEao7xgI/oilGqZ+
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj8Av3EACgkQiB6vp1xAVUAiuwCeNkrIAAt2rnOS68eJ7w4Y92h2
MIoAnjnLumBlZlLlNUqGY6BCZeprMnBu
=7tgh
-----END PGP SIGNATURE-----

--vEao7xgI/oilGqZ+--


--__--__--

Message: 5
Date: Mon, 30 Jun 2003 16:04:14 -0700
From: Matthew Richardson <marichar@csusb.edu>
Subject: Re: [Tutor] newbie 'while' question
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
Cc: Eric L Howard <elh@outreachnetworks.com>, Python Tutor <tutor@python.org>
Organization:

On Mon, 2003-06-30 at 15:53, Danny Yoo wrote:
  
This is very close to the correct solution.  You get the number of
characters in the string with the len() built-in function.  But

  s = raw_input('Enter a name: ')
  x = 0
  while x <= len(s):
      print s[x]
      x += 1

will still result in an IndexError (even though it's close to being
correct).  Do you see why?
        
[newbie swing ;-)]

I know it works, but would it be bad to do something like

s = raw_input('Enter a name: ')
    for x in range(0, len(s)):
    print s[x]

There's no need to initialize x, or declare our math statement in the
code. Thoughts, corrections?
      
Hi Eric,


Sure, this works great, and you're right: the 'for' loop is the more
appropriate looping construct here, since we're going along the letters of
the name.


We can even do:

###
s = raw_input('Enter a name: ')
for ch in s:
    print ch
###

and skip the manual indicing altogether.  *grin*


Strings are like Lists --- they are both "sequences" --- and the 'for'
loop can deal with them uniformly.  Matt's question asked to do it with
'while', but in real life code, the 'for' loop is usually easier to
construct because it's less open-ended than 'while'.


Good luck!

    

The exercise is out of Wesley Chun's 'Core Python Programming.'  The for
loop was far easier for me, but the exercise was to perform the same
task both ways.  No point in skipping over the 'hard' material in the
name of expediency.  I want to get a firm grip on this and ploughing
through all of the examples is the only way I'll get it.

Now for Zak's string manipulation....

Matt

  

--------------020509010608030901030803-- From tpc@csua.berkeley.edu Tue Jul 1 12:52:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Jul 1 11:52:01 2003 Subject: [Tutor] writing a search engine In-Reply-To: <20030701014813.3D7166BDCD@smtp.us2.messagingengine.com> Message-ID: <20030701084357.X55683-100000@localhost.name> this site hosts a (no longer maintained) quick and dirty search engine: http://www.melbpc.org.au/pcupdate/2012/2012article10.htm it's ok for getting a working example up, although it only indexes from the virtual index apache creates or an index.html file in a given directory. Also, its stop words list doesn't seem to work at all, and it doesn't do phrase searching or highlighted terms in results. It also is not a Google type of index, which ranks results by how many links point to the page as well as keyword matching. On Mon, 30 Jun 2003, Kyle Babich wrote: > Any suggestions on where to start? I plan on writing one for a small > site of mine. It will basically be "google-style"- simple and > functional. The item being searched will be text files, where users can > search based on title, contents, or both. I was reading through some > books but I'm stumped on where to begin. I've never tried writing > something even similar to a search engine and I guess I'm little > confused/overwhelmed/bewildered. :) You guys always come to the rescue > for me, so how about one more time? > -- > Kyle > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen@rz.uni-frankfurt.de Tue Jul 1 13:13:03 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Jul 1 12:13:03 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) In-Reply-To: References: Message-ID: On Tue, 1 Jul 2003 DORSEY_EDMUND_K@LILLY.COM wrote: > Using the following worked and reasonably fast (about 5 seconds to > initialize an array with close to 100 million indices) > > myArray = [0] * arraySize your first testcase: for i in range(0, arraySize): #arraySize being over 10 million myArray.append(0) #just use zero as a place holder builds both a "range" list fom 0 till arraySize as also myArray. Beside the time for the append operation (and subsequents efforts to aquire more memory) you will need twice the time of "consuming memory". "xrange" is better with for-loops over wide ranges: it doesn't build the list but just iterate trough the items (doing some behind-the-scene-magic). k = range(10000000) consumes 150 MB (from 512 RAM) on my Computer (linux i686 glibc?). "del k" frees just 40 MB. Exiting the python interpreter releases memory until former state (measured with "free -m". Just one testrun). This is much - but not enough to freeze a machine. Michael > > Thanks for the help! > > ~Edmund > > > > > > > Alan Trautman > 07/01/2003 09:50 AM > > > To: "'DORSEY_EDMUND_K@LILLY.COM'" , > tutor@python.org > cc: > Subject: RE: [Tutor] Problems creating very large arrays (over 10 million indices) > > > Edmund, > > An array as large as you want will require quite large computing power > unless the stored data is binary. > > Questions: > What are you storing (generic description) in each array position? Large > amounts of data will require completely different structures. > > What can't the image be broken up into smaller regions? This is the way > graphics are normally handled. By breaking images into squares (triangles > for 3D graphics) the computer only has to deal with smaller regions at a > time. > > > If you can work on smaller regions the test will be a few choices: Sort > the > incoming file, pick a regional small array and extract its' data from the > larger file, and/or take each data element as it comes and locate the > smaller array, store and move to the next element. These are a few methods > I > can think of, I'm sure the list can come up with others. > > > HTH > Alan > > > I need to initialize an array with sizes greater than 10 million indices. > The reason for this is because I then proceed to fill in the array but > jumping around. (The array is used to store binary medical image data) I > > tried using a for loop like so > > > for i in range(0, arraySize): #arraySize being over 10 million > myArray.append(0) #just use zero as a place holder > > WHen arraySize is small under 200,000 or so it works okay (though very > very slow) Anything larger than this and it just crashes. I have 2 gigs > of memory so I'm not running out of memory. > > Two Questions... > > 1) Why does this crash? > 2) Is there a faster, stable way to do what I want to do > > Thank you for all the help > > ~Edmund Dorsey > > > > From Zabelkind@web.de Tue Jul 1 13:20:02 2003 From: Zabelkind@web.de (Mathias Mamsch) Date: Tue Jul 1 12:20:02 2003 Subject: [Tutor] writing a search engine References: <20030701014813.3D7166BDCD@smtp.us2.messagingengine.com> Message-ID: <007601c33fec$d5d00f40$0500a8c0@nias> > Any suggestions on where to start? I plan on writing one for a small > site of mine. It will basically be "google-style"- simple and > functional. The item being searched will be text files, where users can > search based on title, contents, or both. I was reading through some > books but I'm stumped on where to begin. I've never tried writing > something even similar to a search engine and I guess I'm little > confused/overwhelmed/bewildered. :) You guys always come to the rescue > for me, so how about one more time? > -- > Kyle > So the problem is you cannot search all your documents, after the user entered the text. Its clear that you have to do some "hashing", that means search the documents offline and create a list of keywords and their corresponding references. An easy example would be, to store every word, which appears in your documents as a key in a dictionary and the value could be the file the word appeared in and the position of the word in the file. So when you get a search query from the user, you search your list and have all occurences of the word. Modern search engines like google use complex algorithms for hashing the keywords in the documents, that is why they are so fast. Greetings Mathias Mamsch From highrik@ntlworld.com Tue Jul 1 14:12:02 2003 From: highrik@ntlworld.com (Rick Thomas) Date: Tue Jul 1 13:12:02 2003 Subject: [Tutor] Shebang problem In-Reply-To: <20030627163402.GA3949@hooloovoo> References: <200306271715.59089.highrik@ntlworld.com> <20030627163402.GA3949@hooloovoo> Message-ID: <200307011818.55845.highrik@ntlworld.com> On Friday 27 June 2003 17:34, Abel Daniel wrote: > Rick Thomas wrote: > > Hi, > > > > I'm very new to programming and am plodding my way through Alan Gauld's > > book 'Learn to Program Using Python'. At present I can't get my programs > > to execute using the Shebang trick. > > > > #!/usr/bin/python > > > > My scripts ran fine when I was using SuSE 7.3 but I've recently upgraded > > to 8.3 and wondered if this is somehow the problem. My scripts run ok > > if I type for example 'python foo.py' in a terminal. > > > > Any advice would be much appreciated. Abel Daniel advised > Pasting the exact error message would have helped to narrow the problem, > but here are some ideas: > > - try 'which python' to find out which program runs when you do > 'python foo.py'. That way you can be sure that you are trying to use the > same interpreter in both cases. > > - you could try using a '#!/usr/bin/env python' shebang line, which will > more-or-less ensure that you get the same interpreter. (I guess this > won't help if the idea above didn't.) > > - check that you have executable permissions on the file. > > Abel Daniel The exact error message I get is 'bash: foo.py: command not found'. When I type in 'which python' at a terminal I get /usr/bin/python which is the correct path for my scripts. I've tried changing the shebang line to #!/usr/bin/env python but I got the same error message as above. I know all my scripts are executable as I've always used the 'chmod' u+x command after creating a script file. further advice would be much appriciated. Rick Thomas. ______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From marichar@csusb.edu Tue Jul 1 14:16:03 2003 From: marichar@csusb.edu (Matthew Richardson) Date: Tue Jul 1 13:16:03 2003 Subject: [Tutor] Shebang problem In-Reply-To: <200307011818.55845.highrik@ntlworld.com> References: <200306271715.59089.highrik@ntlworld.com> <20030627163402.GA3949@hooloovoo> <200307011818.55845.highrik@ntlworld.com> Message-ID: <1057079698.567.5.camel@matthew-richardsons-computer.local> On Tue, 2003-07-01 at 10:18, Rick Thomas wrote: > On Friday 27 June 2003 17:34, Abel Daniel wrote: > > Rick Thomas wrote: > > > Hi, > > > > > > I'm very new to programming and am plodding my way through Alan Gauld's > > > book 'Learn to Program Using Python'. At present I can't get my programs > > > to execute using the Shebang trick. > > > > > > #!/usr/bin/python > > > > > > My scripts ran fine when I was using SuSE 7.3 but I've recently upgraded > > > to 8.3 and wondered if this is somehow the problem. My scripts run ok > > > if I type for example 'python foo.py' in a terminal. > > > > > > Any advice would be much appreciated. > > Abel Daniel advised > > > Pasting the exact error message would have helped to narrow the problem, > > but here are some ideas: > > > > - try 'which python' to find out which program runs when you do > > 'python foo.py'. That way you can be sure that you are trying to use the > > same interpreter in both cases. > > > > - you could try using a '#!/usr/bin/env python' shebang line, which will > > more-or-less ensure that you get the same interpreter. (I guess this > > won't help if the idea above didn't.) > > > > - check that you have executable permissions on the file. > > > > Abel Daniel > > The exact error message I get is 'bash: foo.py: command not found'. When I > type in 'which python' at a terminal I get /usr/bin/python which is the > correct path for my scripts. I've tried changing the shebang line to > #!/usr/bin/env python but I got the same error message as above. I know all > my scripts are executable as I've always used the 'chmod' u+x command after > creating a script file. > > further advice would be much appriciated. > > Rick Thomas. > Have you tried executing the script with the full path name or changing to the directory it is in and executing it with ./foo.py? --Matt -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino From DORSEY_EDMUND_K@LILLY.COM Tue Jul 1 15:22:02 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Tue Jul 1 14:22:02 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) Message-ID: This is a multipart message in MIME format. --Boundary_(ID_RCFIgHm6ndEwQkUSS7kpmA) Content-type: text/plain; charset="us-ascii" I tried creating a Numeric array but I couldn't get the binary data into it. The array module was so great cause I could just use readfile to read in the entire file at once. I tried this ... a = Numeric.ones((xsize, ysize, zsize), Numeric.Int16) #create 3d numeric array of type short filled with ones (placeholders) a[0][0][0] = file.read(2) #read in two bytes and stick it in the array Of course it says the that the array 'a' needs an int as input. Plus if I do this method I need to use 3 nested for loops and it is significantly slower than using a normal 1d array. Is this how I would have to do it with the Numeric module? Thanks for all the input you've given. ~Edmund Edmund, Given the size of your arrays and that they are 3 dimensional, you may want to take a look at the Numeric package or the relatively new numarray package. They can handle multi-dimensional data in a very efficient manner. They both can be found on sourceforge at http://sourceforge.net/projects/numpy/ ------------------------- original message ----------------------------------- The data is stored as binary 16bit short to be precise. I'm writing some software to increase the resolution of ct images using a subvoxel processing algorithm. I've read the original binary file sans the header into an array and then created a larger empty array to place the new image data that will be created based on the algorithm I'm working with. Since I'm not doing any rendering breaking the image into smaller pieces wouldn't help (I think) because I'd still have to process each piece of data. Since it's voxel data (3d) I have to convert the 3d coordinates to a 1d array index. Thus splitting the data up would be a huge headache and start to become conceptually very difficult. In addition I'm jumping around the array (due to the fact that I'm placing 3d data in a 1d array) so the whole thing needs to be initialized at once. Using the following worked and reasonably fast (about 5 seconds to initialize an array with close to 100 million indices) myArray = [0] * arraySize Thanks for the help! ~Edmund ------------------------------------------------------------------------------- HTH, -Reggie --Boundary_(ID_RCFIgHm6ndEwQkUSS7kpmA)-- From rick@niof.net Tue Jul 1 15:23:09 2003 From: rick@niof.net (Rick Pasotto) Date: Tue Jul 1 14:23:09 2003 Subject: [Tutor] Shebang problem In-Reply-To: <200307011818.55845.highrik@ntlworld.com> References: <200306271715.59089.highrik@ntlworld.com> <20030627163402.GA3949@hooloovoo> <200307011818.55845.highrik@ntlworld.com> Message-ID: <20030701175450.GC5712@niof.net> On Tue, Jul 01, 2003 at 06:18:55PM +0100, Rick Thomas wrote: > > The exact error message I get is 'bash: foo.py: command not found'. When I > type in 'which python' at a terminal I get /usr/bin/python which is the > correct path for my scripts. I've tried changing the shebang line to > #!/usr/bin/env python but I got the same error message as above. I know all > my scripts are executable as I've always used the 'chmod' u+x command after > creating a script file. > > further advice would be much appriciated. Did M$ get involved? I've encountered that error message when the lines ended in '\r\n' instead of just '\n'. -- "Of all the sexual aberrations, perhaps the most peculiar is chastity." -- Remy de Gourmont Rick Pasotto rick@niof.net http://www.niof.net From payal-python@staticky.com Tue Jul 1 15:58:02 2003 From: payal-python@staticky.com (Payal Rathod) Date: Tue Jul 1 14:58:02 2003 Subject: [Tutor] finding factorials - hmm..., gcd In-Reply-To: <200307010915.h619FGc02559@ada.rg16.asn-wien.ac.at> References: <200307010915.h619FGc02559@ada.rg16.asn-wien.ac.at> Message-ID: <20030701185705.GA4607@linux.local> On Tue, Jul 01, 2003 at 11:15:01AM +0100, glingl wrote: > Your code is ok and gives the right result! > e.g change: x, y = 25, 15 and you will get: Are you sure? I mean I don't get what a common factor means? Can you tell? > # (1) normally it's not considered good practice to pu > # print-statements in a function which aims at calculating > # a numerical rsult. - Why??? I mean it is good for troubleshooting/debugging. > # (2) here you use an uncoditional return - so the body of > # the while-loop will be exited after the first run. I don't get this. You mean to say that once I type return euclid(a,b), the while loop stops? Why? Also, if it does not get executed how am I getting right answers as you say? > # Consequently it will never work as a loop and you could > # (a) use an if instead of while or Can you point a small example in *this* context using an if statement? > # (b) drop the return and recursive call of euclid - > # recursion also accomplishes some sort of iteration > # and should/need/(must?) not be done in addition > # to the while-iteration I didn't get your meaning on this too, please. > # (3) here you can leave out the three statements > # > # c = a > # a = b > # b = c % a > # > # if think carefully about which values are to be > # inserted as arguments in the recursive function > # call. > # What are the values of a and b respectively after > # execution of these 3 statements. (Remember: ist is > # perfectly right to insert arithmetic expressions like > # a / b, a+b etc as arguments - in which case they > # will be computed (evaluated( before the results are > # "bound" to the parameters.) Ahh! Sorry again, I didn't get you. I don't understand much programmers jargon. The whole paragraph looks greek to me. > P.S.: Maybe http://www.ibiblio.org/obp/thinkCSpy/ , > especially chapters 4 to 6, > contains material, which could be helpful for you. I had read them 2 days back. Maybe I should read them again. Thanks a lot for the time and patience. With warm regards, -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. From glingl@aon.at Tue Jul 1 16:11:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 1 15:11:02 2003 Subject: [Tutor] finding factorials References: <20030630141707.GA1882@linux.local> <20030701023901.GA1603@linux.local> Message-ID: <3F01DD02.4080002@aon.at> Payal Rathod schrieb: Hello Payal! I think I should have made some comments on your comments -- >On Mon, Jun 30, 2003 at 10:33:36AM -0700, Danny Yoo wrote: > > >>Same mistake as last time. *grin* The code is simply dropping the value >>that you're calculating from doing euclid(). We need to capture that >>value: >> >> > >Sorry Danny I am still not getting it. Now I am so confused that I think >I don't know what exactly a function does and what is it it returns. > >I have posted my code below with some comments regarding issues I don't >get. > >#!/usr/local/bin/python > >def euclid(a,b): > while b != 0: > c = a > a = b > b = c % a > print 'A = ', a > print 'B = ', b > return euclid(a,b) ># What will this return exactly? > #- this will return the gcd of b and the rest when a is divided by b > else: > return a > >x = 100 >y = 20 > >result = euclid(x, y) > ># Why do we define x and y here seperately? ># Can't we have result = euclid(100,20) ># This apparently is not working. > #-- I tried it out and it - not surprisingly - worked! > >print x >print y > ># This always prints 100 and 20. I think it should print the present values ># of x and y which are not 100 and 20 always. > > #-- These remain 100 and 20 respectively, because your code doesn't contain #-- statements, which change the values of x and y. #-- Only the values of a and b (and c) are changed, but these are entirely different #-- variables, local to the function euclid and not globally visible. The change of #-- their values is revealed by your print-statements. >print result > ># The result is given as 20 which I think is wrong. > #-- Why do you think this is wrong? What do you think is the greatest #-- common divisor of 100 and 20? ># Is there anything ># wrong with my mathematical logic or my function? > > #-- Hmm ??? See my previous posting. Best wishes, Gregor >With warm regards, >-Payal > > > > From reggie@merfinllc.com Tue Jul 1 16:17:01 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Tue Jul 1 15:17:01 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) In-Reply-To: References: Message-ID: <1057086956.24474.19.camel@pika> Edmund, Assuming that fp is a file object opened for reading your file and that you've already read past the header, maybe one of these will work for you: a = Numeric.fromstring(fp.read(), Numeric.Int16) Numeric.reshape(a, (xsize, ysize, zsize)) OR a = numarray.fromfile(fp, numarray.Int16, (xsize, ysize, zsize)) I don't have much experience reading in data from outside sources, so I can't say that I've tested these, but I hope they steer you in the right direction. On Tue, 2003-07-01 at 11:20, DORSEY_EDMUND_K@LILLY.COM wrote: > I tried creating a Numeric array but I couldn't get the binary data into > it. The array module was so great cause I could just use readfile to read > in the entire file at once. > > I tried this ... > > a = Numeric.ones((xsize, ysize, zsize), Numeric.Int16) #create 3d numeric > array of type short filled with ones (placeholders) > a[0][0][0] = file.read(2) #read in two bytes and stick it in the array > > Of course it says the that the array 'a' needs an int as input. Plus if I > do this method I need to use 3 nested for loops and it is significantly > slower than using a normal 1d array. Is this how I would have to do it > with the Numeric module? Thanks for all the input you've given. > > ~Edmund > > > > > > Edmund, > > Given the size of your arrays and that they are 3 dimensional, you may > want > to take a look at the Numeric package or the relatively new numarray > package. They can handle multi-dimensional data in a very efficient > manner. > They both can be found on sourceforge at > > http://sourceforge.net/projects/numpy/ > -- Reggie From reggie@merfinllc.com Tue Jul 1 16:23:01 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Tue Jul 1 15:23:01 2003 Subject: [Tutor] Problems creating very large arrays (over 10 million indices) In-Reply-To: <1057086956.24474.19.camel@pika> References: <1057086956.24474.19.camel@pika> Message-ID: <1057087331.24474.25.camel@pika> Sorry, I was a little too fast on the send button on that last message. The first example should read: a = Numeric.fromstring(fp.read(), Numeric.Int16) a = Numeric.reshape(a, (xsize, ysize, zsize)) On Tue, 2003-07-01 at 12:15, Reggie Dugard wrote: > Edmund, > > Assuming that fp is a file object opened for reading your file and that > you've already read past the header, maybe one of these will work for > you: > > a = Numeric.fromstring(fp.read(), Numeric.Int16) > Numeric.reshape(a, (xsize, ysize, zsize)) > > OR > > a = numarray.fromfile(fp, numarray.Int16, (xsize, ysize, zsize)) > > I don't have much experience reading in data from outside sources, so I > can't say that I've tested these, but I hope they steer you in the right > direction. > > > On Tue, 2003-07-01 at 11:20, DORSEY_EDMUND_K@LILLY.COM wrote: > > I tried creating a Numeric array but I couldn't get the binary data into > > it. The array module was so great cause I could just use readfile to read > > in the entire file at once. > > > > I tried this ... > > > > a = Numeric.ones((xsize, ysize, zsize), Numeric.Int16) #create 3d numeric > > array of type short filled with ones (placeholders) > > a[0][0][0] = file.read(2) #read in two bytes and stick it in the array > > > > Of course it says the that the array 'a' needs an int as input. Plus if I > > do this method I need to use 3 nested for loops and it is significantly > > slower than using a normal 1d array. Is this how I would have to do it > > with the Numeric module? Thanks for all the input you've given. > > > > ~Edmund > > > > > > > > > > > > Edmund, > > > > Given the size of your arrays and that they are 3 dimensional, you may > > want > > to take a look at the Numeric package or the relatively new numarray > > package. They can handle multi-dimensional data in a very efficient > > manner. > > They both can be found on sourceforge at > > > > http://sourceforge.net/projects/numpy/ > > -- Reggie From dyoo@hkn.eecs.berkeley.edu Tue Jul 1 16:31:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 1 15:31:09 2003 Subject: [Tutor] writing a search engine [quicky intro to vector search engines] In-Reply-To: <007601c33fec$d5d00f40$0500a8c0@nias> Message-ID: On Tue, 1 Jul 2003, Mathias Mamsch wrote: > > Any suggestions on where to start? I plan on writing one for a small > > site of mine. It will basically be "google-style"- simple and > > functional. Hi Mathias, If you're ambitious, you can try writing a vector search engine. *grin* The general idea is to turn each document in our collection into a vector in N-dimensional space. And N can be potentially really large: it's the number of unique words in our whole document collection. No wimpy 3d space here! For example, let's say we had the following documents: ### docs = ["This is a test of the emergency broadcast system", "This is neat, what kind of system is it?"] ### Given a set of documents, we can map each unique word to some kind of numeric identifier. Perhaps we can use some kind of dictionary, like this: ### d = { 'this' : 0, 'is' : 1, 'a' : 2, 'test' : 3, 'of' : 4, 'the' : 5, 'emergency' : 6, 'broadcast' : 7, 'system' : 8, 'neat' : 9, 'what' : 10, 'kind' : 11, 'it' : 12 } ### With this numbering, we can now transform our documents into vectors in 13-dimensional space. ### >>> def transformIntoVector(words): ... vector = [0] * 13 ... for w in words: ... vector[d[w]] = 1 ... return vector ... >>> doc_vectors = [transformIntoVector(doc.split()) for doc in docs] >>> doc_vectors[0] [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0] >>> doc_vectors[1] [1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1] ### And now we store our library of document vectors somewhere handy on disk, or perhaps just keep it in memory. A query search, then, becomes a math problem: we take our query, transform it into a "query vector", ### >>> query = transformIntoVector(["emergency"]) ## I want all documents >>> ## that have "emergency". >>> query [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0] ### And once we do this, then we can do a search by finding the vectors in our document collection that are most "similar" to our query vector. One cute way to do a simliarity check is to simply "multiply" a query vector, componentwise, against our document vectors. ### >>> def v_multiply(v1, v2): ... sum = 0 ... for x, y in zip(v1, v2): ... sum += x * y ... return sum ... >>> query [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0] >>> doc_vectors [[1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1]] >>> >>> v_multiply(query, doc_vectors[0]) 1 >>> v_multiply(query, doc_vectors[1]) 0 ### Shades of linear algebra! *grin* Since our query was the word "emergency", we matched against our first document, but got no hits in our second document. The explanation about is oversimplified, but I hope it makes some sense. *grin* I've taken some of the ideas of the code from, http://www.perl.com/lpt/a/2003/02/19/engine.html and written them as concept code in Python. My code is so rough at the moment that I really don't want to show it to anyone... *grin* But here's a small sample of what it looks like: ### class Engine: def search(self, query_text, threshold=0.5): query_vector = self.vectorizer.makeVector(query_text) result_vector = Numeric.zeros(self.matrix.shape[1], typecode='d') self.matrix.matvec_transp(query_vector, result_vector) return map(self.mapToDocId, Numeric.nonzero(Numeric.greater(result_vector, threshold))) ### self.matrix is a 'pysparse' matrix of all my document vectors, using some libraries from the PySparse project, http://www.python.org/pycon/papers/pysparse.html That being said, the code is UGLY. I promise I'll clean up the code when I get the chance... and I have to admit that my linear algebra is weak, so there are some parts of the code that might be suboptimal. I really want to learn more about linear algebra now, now that I see that there's something I can apply it with! (The real reason I'm working on this code is to do document clustering for a digital library, but I haven't yet found a fast way to do a matrix multiply on a 10000x60000 matrix without running out of memory. Perhaps I should learn about eigenvectors.) If you're interested, you can download a tarball of it here: http://hkn.eecs.berkeley.edu/~dyoo/python/vector_search.tar.gz But I am not linking it on my website until I add documentation and good comments into the code. *grin* Anyway, I hope this helps! From glingl@aon.at Tue Jul 1 16:50:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 1 15:50:02 2003 Subject: [Tutor] finding factorials - hmm..., gcd References: <200307010915.h619FGc02559@ada.rg16.asn-wien.ac.at> <20030701185705.GA4607@linux.local> Message-ID: <3F01E629.5080805@aon.at> Payal Rathod schrieb: >On Tue, Jul 01, 2003 at 11:15:01AM +0100, glingl wrote: > > >>Your code is ok and gives the right result! >>e.g change: x, y = 25, 15 and you will get: >> >> > >Are you sure? I mean I don't get what a common factor means? Can you >tell? > > > >># (1) normally it's not considered good practice to pu >># print-statements in a function which aims at calculating >># a numerical rsult. - >> >> > > >Why??? I mean it is good for troubleshooting/debugging. > Yes! (But didn't I say that?) > > > >># (2) here you use an uncoditional return - so the body of >># the while-loop will be exited after the first run. >> >> > >I don't get this. You mean to say that once I type return euclid(a,b), >the while loop stops? > Not only the while-loop stops but the execution of the program leaves the (code of the) function and continues with finishing the statement, which contains the function call - in your case an assignment, which assigns the returned value to the variable result. >Why? > This is the purpose the return-statement is intended for >Also, if it does not get executed > I didn't say, that the body of the while loop doesn't get executed. I said that it *invariably* is executed *only_once*, which is not was a loop is normally meant for. >how am I >getting right answers as you say? > > Because it does the same as the code of the recursive correction (that is the second one) in my posting. > > >># Consequently it will never work as a loop and you could >># (a) use an if instead of while or >> >> > >Can you point a small example in *this* context using an if statement? > I think, I gave you two "small" examples exactly in *your_context*, namely two different possible modifications of your code - (a) the first one resulting in a euclid-function using a while loop (BUT NO RECURSION) and (b) the second one using recursion (BUT NO WHILE-LOOP) >># (b) drop the return and recursive call of euclid - >># recursion also accomplishes some sort of iteration >># and should/need/(must?) not be done in addition >># to the while-iteration >> >> > >I didn't get your meaning on this too, please. > > A recursive functions calls itself (again, several times, until the stop-condition is reached), so its code is executed repeatedly. >># (3) here you can leave out the three statements >># >># c = a >># a = b >># b = c % a >># >># if think carefully about which values are to be >># inserted as arguments in the recursive function >># call. >># What are the values of a and b respectively after >># execution of these 3 statements. (Remember: ist is >># perfectly right to insert arithmetic expressions like >># a / b, a+b etc as arguments - in which case they >># will be computed (evaluated( before the results are >># "bound" to the parameters.) >> >> I fear, my crude English is responsible, that you don't understand what I mean. Although just this maybe really hard to grasp. I wont't give an explanation, more gifted people exist on this list. Just try the following code and think about it: print "WHAT'S GOING ON?" x =4 y=10 z = 0 print "x =",x,"y =",y,"z =",z def look(a,b): print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b a=2*a b=2*b c=a*b print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c return c c = c*c # ;-) print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c # or: :-( ? print "x =",x,"y =",y,"z =",z z = look(x,y) # this will execute 2 (!) print-statements # you won't be able to print a,b,c here print "x =",x,"y =",y,"z =",z Regards, Gregor >Ahh! Sorry again, I didn't get you. I don't understand much programmers >jargon. The whole paragraph looks greek to me. > > > >>P.S.: Maybe http://www.ibiblio.org/obp/thinkCSpy/ , >>especially chapters 4 to 6, >>contains material, which could be helpful for you. >> >> > >I had read them 2 days back. Maybe I should read them again. > > >Thanks a lot for the time and patience. >With warm regards, >-Payal > > > From patterner@rocketmail.com Tue Jul 1 17:38:02 2003 From: patterner@rocketmail.com (Chris Readle) Date: Tue Jul 1 16:38:02 2003 Subject: [Tutor] Hello and a (probably) stupid question Message-ID: <20030701203712.15927.qmail@web40612.mail.yahoo.com> Hi all, My name is Chris and I've just started learning Python. I'm working through the tutorial and I've come upon a difficult thing. One of the sample pieces of code works fine when typed interactively into the interpreter, but doesn't seem to work when I type it up in gvim. Here are the two bits of code: Bit that works: for n in range(2,10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # Loop fell through without finding factor print n, 'is a prime number' This bit returns: 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 Which the tutorial indicates is correct. Bit that doesn't work: # Testing to see if there is some funny starting value in the variables causing this to fail n, x = 0, 0 print n, x for n in range(2,10): for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break else: # Loop fell through without finding a factor print n, 'is a prime number' This bit returns: 0 0 3 is a prime number 4 equals 2 * 2 5 is a prime number 5 is a prime number 5 is a prime number 6 equals 2 * 3 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 7 is a prime number 8 equals 2 * 4 9 is a prime number 9 equals 3 * 3 Which is a little messed. Now, the only thing I see that's different is that they're indented differently. However, both are indented consistently, which is my understanding of how that should work. To add some kick to the sauce, if I take the former example and paste it into a text file and run THAT through the interpreter, it works as well. Any thoughts from the python experts out there? chris __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From dyoo@hkn.eecs.berkeley.edu Tue Jul 1 17:47:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 1 16:47:01 2003 Subject: [Tutor] finding factorials In-Reply-To: <20030701023901.GA1603@linux.local> Message-ID: On Tue, 1 Jul 2003, Payal Rathod wrote: > > I have posted my code below with some comments regarding issues I don't > get. Hi Payal, Sure, no problem. Let's take a look: > #!/usr/local/bin/python > > def euclid(a,b): > while b != 0: > c = a > a = b > b = c % a > print 'A = ', a > print 'B = ', b > return euclid(a,b) > # What will this return exactly? > else: > return a I'll skip your first question for a moment. We'll try to come back to it later. > x = 100 > y = 20 > > result = euclid(x, y) > > # Why do we define x and y here seperately? > # Can't we have result = euclid(100,20) > # This apparently is not working. Hmmm! You're right: that should work too! There was no need to do: ### x = 100 y = 20 ### but I thought that your original code had done the same, so I didn't want to change it. Can you show us what happens when you try doing euclid(100, 20)? It should work. > print x > print y > > # This always prints 100 and 20. I think it should print the present > # values of x and y which are not 100 and 20 always. Let's try another experiment for a moment. Take a look: ### >>> def square(x): ... return x * x ... >>> x = 3 >>> y = 4 >>> z = square(x) + square(y) ### At this point, what do you expect to see if we check up on the value of x, y, and z? (Your question touches on the idea of "local" scope. We can talk about it a little later when you feel more comfortable about functions.) What happens if we do something like this: ### >>> x = 42 >>> y = 42 >>> x = x + 1 ### Check with the interactive interpreter to see what the values of 'x' and 'y' are after we do those statement, just to make sure they're consistent with what you expect. The conceptual problem you might be running into is seeing '=' and thinking it means math equality. If so, be careful: it's not! If this is what you're running into when you see something like: x = 42 then you need to think of it more like x <---------------- 42 That is, imagine a big honking arrow that pushes a value into a name, squeezing out the old value in the process. The technical term for this is "assignment". Some folks are too dignified to use the big honking arrow, and will write it out on paper like this: x <- 42 And some computer languages do allow this kind of notation, which more clearly shows that what we're doing isn't symmetric at all: we're pushing stuff from the right hand side into the left hand side. Unfortunately, Python only uses the '=' notation to assign values to variable names, so you have to use '=', even though it might look visually disturbing. I don't know if this is the assignment issue is the thing that you're getting caught on, but if so, I hope the explanation helps a little. > print result > > # The result is given as 20 which I think is wrong. Is there anything > # wrong with my mathematical logic or my function? Math logic. *grin* The GCD of 100 and 20 is supposed to be 20. GCD(a,b) is the greatest number that will divide both 'a' and 'b' evenly, and 20 fits that criteria perfectly. Hope this helps! From jsoons@juilliard.edu Tue Jul 1 18:00:06 2003 From: jsoons@juilliard.edu (Jonathan Soons) Date: Tue Jul 1 17:00:06 2003 Subject: [Tutor] Shebang problem Message-ID: <33E101AC5AFF78419F466954A9685420BCF029@mailbox.juilliard.edu> For security reasons your profile prevents you executing a file in your = CWD. So try './foo.py' jonathan soons -Message: 3 From: Rick Thomas To: Tutor@python.org Subject: Re: [Tutor] Shebang problem Date: Tue, 1 Jul 2003 18:18:55 +0100 On Friday 27 June 2003 17:34, Abel Daniel wrote: > Rick Thomas wrote: > > Hi, > > > > I'm very new to programming and am plodding my way through Alan = Gauld's > > book 'Learn to Program Using Python'. At present I can't get my = programs > > to execute using the Shebang trick. > > > > #!/usr/bin/python > > > > My scripts ran fine when I was using SuSE 7.3 but I've recently = upgraded > > to 8.3 and wondered if this is somehow the problem. My scripts run = ok=20 > > if I type for example 'python foo.py' in a terminal. > > > > Any advice would be much appreciated. =20 From reggie@merfinllc.com Tue Jul 1 18:19:01 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Tue Jul 1 17:19:01 2003 Subject: [Tutor] Hello and a (probably) stupid question In-Reply-To: <20030701203712.15927.qmail@web40612.mail.yahoo.com> References: <20030701203712.15927.qmail@web40612.mail.yahoo.com> Message-ID: <1057094315.24474.33.camel@pika> Chris, Hi, glad to hear you're interested in Python! Your problem illustrates the importance of indentation in Python. In your interactive example, you'll notice that the else clause is indented to the same level as the for statement. This means that the statements in the else block will be executed if the for loop is allowed to run to completion (no break is encountered). In the example you entered in gvim, the else clause is indented to the level of the if statement so it will be executed whenever the if test fails during a pass through the loop - giving you incorrect results. I hope this explanation is somewhat clear. Good luck with the rest of the tutorial! On Tue, 2003-07-01 at 13:37, Chris Readle wrote: > Hi all, > > My name is Chris and I've just started learning Python. I'm working > through the tutorial and I've come upon a difficult thing. One of the > sample pieces of code works fine when typed interactively into the > interpreter, but doesn't seem to work when I type it up in gvim. Here are > the two bits of code: > > Bit that works: > for n in range(2,10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # Loop fell through without finding factor > print n, 'is a prime number' > > This bit returns: > 2 is a prime number > 3 is a prime number > 4 equals 2 * 2 > 5 is a prime number > 6 equals 2 * 3 > 7 is a prime number > 8 equals 2 * 4 > 9 equals 3 * 3 > > Which the tutorial indicates is correct. > > > Bit that doesn't work: > # Testing to see if there is some funny starting value in the variables > causing this to fail > n, x = 0, 0 > print n, x > > for n in range(2,10): > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > else: > # Loop fell through without finding a factor > print n, 'is a prime number' > > This bit returns: > 0 0 > 3 is a prime number > 4 equals 2 * 2 > 5 is a prime number > 5 is a prime number > 5 is a prime number > 6 equals 2 * 3 > 7 is a prime number > 7 is a prime number > 7 is a prime number > 7 is a prime number > 7 is a prime number > 8 equals 2 * 4 > 9 is a prime number > 9 equals 3 * 3 > > Which is a little messed. > > Now, the only thing I see that's different is that they're indented > differently. However, both are indented consistently, which is my > understanding of how that should work. To add some kick to the sauce, if > I take the former example and paste it into a text file and run THAT > through the interpreter, it works as well. > > Any thoughts from the python experts out there? > > chris > > > __________________________________ > Do you Yahoo!? > SBC Yahoo! DSL - Now only $29.95 per month! > http://sbc.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Reggie From patterner@rocketmail.com Tue Jul 1 18:39:02 2003 From: patterner@rocketmail.com (Chris Readle) Date: Tue Jul 1 17:39:02 2003 Subject: [Tutor] Hello and a (probably) stupid question In-Reply-To: <1057094315.24474.33.camel@pika> Message-ID: <20030701213806.92884.qmail@web40608.mail.yahoo.com> Reggie, Aha, that sure enough did it. I was looking at the code, and comparing them to each other, but I never thought about comparing the whitespace....this is one of those things that will take me awhile to wrap my head around I think. :) Thanks for the quick response! chris --- Reggie Dugard wrote: > Chris, > > Hi, glad to hear you're interested in Python! Your problem illustrates > the importance of indentation in Python. In your interactive example, > you'll notice that the else clause is indented to the same level as the > for statement. This means that the statements in the else block will be > executed if the for loop is allowed to run to completion (no break is > encountered). > > In the example you entered in gvim, the else clause is indented to the > level of the if statement so it will be executed whenever the if test > fails during a pass through the loop - giving you incorrect results. > > I hope this explanation is somewhat clear. Good luck with the rest of > the tutorial! > > On Tue, 2003-07-01 at 13:37, Chris Readle wrote: > > Hi all, > > > > My name is Chris and I've just started learning Python. I'm working > > through the tutorial and I've come upon a difficult thing. One of the > > sample pieces of code works fine when typed interactively into the > > interpreter, but doesn't seem to work when I type it up in gvim. Here > are > > the two bits of code: > > > > Bit that works: > > for n in range(2,10): > > for x in range(2, n): > > if n % x == 0: > > print n, 'equals', x, '*', n/x > > break > > else: > > # Loop fell through without finding factor > > print n, 'is a prime number' > > > > This bit returns: > > 2 is a prime number > > 3 is a prime number > > 4 equals 2 * 2 > > 5 is a prime number > > 6 equals 2 * 3 > > 7 is a prime number > > 8 equals 2 * 4 > > 9 equals 3 * 3 > > > > Which the tutorial indicates is correct. > > > > > > Bit that doesn't work: > > # Testing to see if there is some funny starting value in the > variables > > causing this to fail > > n, x = 0, 0 > > print n, x > > > > for n in range(2,10): > > for x in range(2, n): > > if n % x == 0: > > print n, 'equals', x, '*', n/x > > break > > else: > > # Loop fell through without finding a factor > > print n, 'is a prime number' > > > > This bit returns: > > 0 0 > > 3 is a prime number > > 4 equals 2 * 2 > > 5 is a prime number > > 5 is a prime number > > 5 is a prime number > > 6 equals 2 * 3 > > 7 is a prime number > > 7 is a prime number > > 7 is a prime number > > 7 is a prime number > > 7 is a prime number > > 8 equals 2 * 4 > > 9 is a prime number > > 9 equals 3 * 3 > > > > Which is a little messed. > > > > Now, the only thing I see that's different is that they're indented > > differently. However, both are indented consistently, which is my > > understanding of how that should work. To add some kick to the sauce, > if > > I take the former example and paste it into a text file and run THAT > > through the interpreter, it works as well. > > > > Any thoughts from the python experts out there? > > > > chris > > > > > > __________________________________ > > Do you Yahoo!? > > SBC Yahoo! DSL - Now only $29.95 per month! > > http://sbc.yahoo.com > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > -- > Reggie > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From glingl@aon.at Tue Jul 1 18:49:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 1 17:49:01 2003 Subject: [Tutor] finding factorials References: Message-ID: <3F020238.4040004@aon.at> Danny Yoo schrieb: > >The conceptual problem you might be running into is seeing '=' and >thinking it means math equality. If so, be careful: it's not! > >If this is what you're running into when you see something like: > > x = 42 > > >then you need to think of it more like > > x <---------------- 42 > > > Hi, Danny! I have a different model in my mind, when I see something like this. I think of a name attached to, or pointing to some object. In this case the object is the number 42. So I think more like x -----------------> 42 Now, when I see x, I know I have to think of the object behind x, the object which is named x. >>> a = 25001 >>> b = a >>> b is a 1 # (or, in Python 2.3: True) So this, for me, means: the object named a is the same as the one named b. This lets me better understand, what's going on, if I start to change objects, (which of course is not possible with a number). I prefer - from the beginning - to use a model , which I don't need to change when new things appear or have to be done. These are simply two different points of view, I think ... Best regards, Gregor >That is, imagine a big honking arrow that pushes a value into a name, > So my big honking arrow pushes a name onto an object (for instance a value) taking this name off another object, if it incidentally has been used for one earlier. Moreover I can easily think of attaching two (or more) names to an object; much easier than pushing an object (a value) into two (ore more) names >squeezing out the old value in the process. The technical term for this >is "assignment". Some folks are too dignified to use the big honking >arrow, and will write it out on paper like this: > > x <- 42 > > >And some computer languages do allow this kind of notation, which more >clearly shows that what we're doing isn't symmetric at all: we're pushing >stuff from the right hand side into the left hand side. Unfortunately, >Python only uses the '=' notation to assign values to variable names, so >you have to use '=', even though it might look visually disturbing. > >I don't know if this is the assignment issue is the thing that you're >getting caught on, but if so, I hope the explanation helps a little. > > > > > > >>print result >> >># The result is given as 20 which I think is wrong. Is there anything >># wrong with my mathematical logic or my function? >> >> > >Math logic. *grin* > >The GCD of 100 and 20 is supposed to be 20. GCD(a,b) is the greatest >number that will divide both 'a' and 'b' evenly, and 20 fits that criteria >perfectly. > > >Hope this helps! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From project5@redrival.net Tue Jul 1 21:29:01 2003 From: project5@redrival.net (Andrei) Date: Tue Jul 1 20:29:01 2003 Subject: [Tutor] Re: compiling python apps In-Reply-To: <3F013C6F.20202@xtra.co.nz> References: <3F013C6F.20202@xtra.co.nz> Message-ID: Michael Honeyfield wrote: > I have set myself the task of learning python. I learn best in the > deep end (sometimes) and thought I would give pysol a hack and see what > I can do with it. Perhaps port the UI to the QT python UI. That's one way of doing it :). > Anyways, I am confussed on the two pysol packages that one can download. > One of them is a "ready to run" package (3301Kb) and the other is the > source (151Kb). I figured the source package is there for customizing > (which is what I wish to do) but I dont know how to "compile" it like > the "ready to run" package is. Anyone following this list understand me > or am I making a public fool of myself? :) If a am not making much sense > I will try to clarifiy further. I've never looked specifically at PySol, but Python doesn't get "compiled" in the classic sense of the word. The ready to run package most likely contains a Python interpreter and whatever other third party libraries PySol employs, but *also* the source code. > But to sum it up, How do I get my modified pysol source compile like the > ready to run package? I have emailed the maintainer, but not had any > reply (I suspect he is busy in the next cool release of pysol :) ) Install all required third-party packages as well as Python on your machine en just start the application using "python appname.py" (where appname is the name of the main python file). Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5@redrival.net Tue Jul 1 21:36:01 2003 From: project5@redrival.net (Andrei) Date: Tue Jul 1 20:36:01 2003 Subject: [Tutor] Re: Hello and a (probably) stupid question In-Reply-To: <20030701213806.92884.qmail@web40608.mail.yahoo.com> References: <1057094315.24474.33.camel@pika> <20030701213806.92884.qmail@web40608.mail.yahoo.com> Message-ID: Chris Readle wrote: > Aha, that sure enough did it. I was looking at the code, and comparing > them to each other, but I never thought about comparing the > whitespace....this is one of those things that will take me awhile to wrap > my head around I think. :) Thanks for the quick response! It's really not that hard :). If it looks like a block, it IS a block. Having a good editor will help you a lot with whitespace (auto-indenting and the likes), so you won't have to bother at all. Also make sure your editor converts Tabs to 4 spaces when working on Python code, otherwise you might mix real tabs and spaces so things might *seem* to have the same indentation, but in reality they're different. I suppose Gvim should be able to do this (I use Scite myself). Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From camartin@snet.net Tue Jul 1 22:45:02 2003 From: camartin@snet.net (Cliff Martin) Date: Tue Jul 1 21:45:02 2003 Subject: [Tutor] Re: Readlines code. Message-ID: <3F023956.9030301@snet.net> --------------030006060102080807010402 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Rick, Thanks for the help. I understand what you did and this wraps up the file for printing but once the stuff is printed it no longer exists in the assignment words. I want to manipulate and calculate (once I've converted the strings into numbers) and I need this split and extracted \n file to exist. I can't use a standard function because once the return statement is executed the data is written to file. What am I still not understanding. Cliff Martin On Mon, Jun 30, 2003 at 09:43:37PM -0400, Cliff Martin wrote: >> Hi, >> >> I'm trying to read in an ASCII file of a fairly large set of data with >> data separated by spaces and each line ending with a linefeed. If I use >> readlines() I get all the data but each line still has a \n tacked on. >> If I use: >> >> f=open("c:/transfer/filename") >> for line in f.readlines(): >> words=line.rstrip().split() >> >> I get only the last line of the file in words. Could someone explain >> why this is happening? There is something about the use of Python here >> that I'm not understanding. Thanks for any help. > > I suspect you're only *doing* something to the last line. Consider the following two programs: f = open("c:/transfer/filename") for line in f.readlines(): words=line.rstrip().split() print words f = open("c:/transfer/filename") for line in f.readlines(): words=line.rstrip().split() print words Both process all the lines in the file but the first only prints out the last line while the second prints out all the lines. Indentation is *critical* in python. -- "Damn all expurgated books; the dirtiest book of all is the expurgated book." -- Walt Whitman Rick Pasotto rick@niof.net http://www.niof.net --------------030006060102080807010402 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Rick,

Thanks for the help. I understand what you did and this wraps up the file for printing but once the stuff is printed it no longer exists in the assignment words.  I want to manipulate and calculate (once I've converted the strings into numbers) and I need this split and extracted \n file to exist. I can't use a standard function because once the return statement is executed the data is written to file. What am I still not understanding.

Cliff Martin

On Mon, Jun 30, 2003 at 09:43:37PM -0400, Cliff Martin wrote:
> Hi,
> 
> I'm trying to read in an ASCII file of a fairly large set of data with 
> data separated by spaces and each line ending with a linefeed.  If I use 
> readlines() I get all the data but each line still has a \n tacked on. 
> If I use:
> 
> f=open("c:/transfer/filename")
> for line in f.readlines():
>        words=line.rstrip().split()
> 
> I get only the last line of the file in words.  Could someone explain 
> why this is happening?  There is something about the use of Python here 
> that I'm not understanding.  Thanks for any help.
  

I suspect you're only *doing* something to the last line.

Consider the following two programs:

f = open("c:/transfer/filename")
for line in f.readlines():
	words=line.rstrip().split()
print words

f = open("c:/transfer/filename")
for line in f.readlines():
	words=line.rstrip().split()
	print words

Both process all the lines in the file but the first only prints out the
last line while the second prints out all the lines.

Indentation is *critical* in python.

-- "Damn all expurgated books; the dirtiest book of all is the expurgated book." -- Walt Whitman Rick Pasotto rick@niof.net http://www.niof.net

--------------030006060102080807010402-- From dman@dman13.dyndns.org Tue Jul 1 23:08:02 2003 From: dman@dman13.dyndns.org (Derrick 'dman' Hudson) Date: Tue Jul 1 22:08:02 2003 Subject: [Tutor] Re: Readlines code. In-Reply-To: <3F023956.9030301@snet.net> References: <20030701015523.GB5712@niof.net> <3F023956.9030301@snet.net> Message-ID: <20030702020737.GA18206@dman13.dyndns.org> --fdj2RfSjLxBAspz7 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Jul 01, 2003 at 09:45:58PM -0400, Cliff Martin wrote: | Rick, |=20 | Thanks for the help. I understand what you did and this wraps up the=20 | file for printing but once the stuff is printed it no longer exists in=20 | the assignment words. Think about the scope of your variable 'words', when it exists and when it is changed. | f=3Dopen("c:/transfer/filename") | for line in f.readlines(): | words=3Dline.rstrip().split() The variable is assigned to inside the loop. That means that each time through the loop it refers to a different object. Once the loop terminates, the variable still exists as it did in the last iteration of the loop. There are a few different ways of solving your problem, depending on what you want to do and what your constraints are. One possibility is this : words =3D [s.rstrip().split() for s in f.readlines()] With this, the variable 'words' will be a list with each element representing a line in the file. Each element of that list is a list containing the separate strings yielded by split(). Note that this stores the entire file in memory at once. If the file is large then this isn't suitable. (note that your code, using readlines(), has the same problem anyways) Another option is to process each line, one at a time, in the loop. This way you never have the entire file in memory at once, you only have the line currently being processed. (this can lead to DoS problems too if the file has excessively long lines) f=3Dopen("c:/transfer/filename") for line in f.xreadlines(): # note: use xreadlines() instead words=3Dline.rstrip().split() ... do something with 'words' here ... =2E.. here we're all done, we don't have the data in memory, ... =2E.. but we don't need it because we already processed all of it ... HTH, -D --=20 Microsoft is to operating systems & security .... .... what McDonald's is to gourmet coo= king =20 http://dman13.dyndns.org/~dman/ --fdj2RfSjLxBAspz7 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj8CPmkACgkQiB6vp1xAVUBGigCeJ5CzMZVXSSK2RugnsvLO9obF G/0An1xwJCAnVKrQAib46elNp/tvuH+X =C+RI -----END PGP SIGNATURE----- --fdj2RfSjLxBAspz7-- From rick@niof.net Tue Jul 1 23:17:01 2003 From: rick@niof.net (Rick Pasotto) Date: Tue Jul 1 22:17:01 2003 Subject: [Tutor] Re: Readlines code. In-Reply-To: <3F023956.9030301@snet.net> References: <3F023956.9030301@snet.net> Message-ID: <20030702021716.GF5712@niof.net> On Tue, Jul 01, 2003 at 09:45:58PM -0400, Cliff Martin wrote: > Rick, > > Thanks for the help. I understand what you did and this wraps up the > file for printing but once the stuff is printed it no longer exists in > the assignment words. I want to manipulate and calculate (once I've > converted the strings into numbers) and I need this split and extracted > \n file to exist. I can't use a standard function because once the > return statement is executed the data is written to file. What am I > still not understanding. Are you sure you can't do everything you need to do to each line as you encounter it? Why do you need to process the entire set of lines a second time? If you really need to do multiple passes through the file then perhaps the best thing would be: myfile = file("c:/transfer/filename") # 'file' is the new 'open' Now 'myfile' is a list of all the lines in the disk file which you can go through as many times as you want. for i in range(len(myfile)): myfile[i] = myfile[i].strip().split() for i in range(len(myfile)): # do something else to every line I really suspect that if you re-think what you're doing you'll find that you can do everything in one pass. [And please don't put your reply at the top of the message. Replies logically come *after* what they are replying to, not before.] > On Mon, Jun 30, 2003 at 09:43:37PM -0400, Cliff Martin wrote: > > >>Hi, > >> > >>I'm trying to read in an ASCII file of a fairly large set of data with > >>data separated by spaces and each line ending with a linefeed. If I use > >>readlines() I get all the data but each line still has a \n tacked on. > >>If I use: > >> > >>f=open("c:/transfer/filename") > >>for line in f.readlines(): > >> words=line.rstrip().split() > >> > >>I get only the last line of the file in words. Could someone explain > >>why this is happening? There is something about the use of Python here > >>that I'm not understanding. Thanks for any help. > > I suspect you're only *doing* something to the last line. > > Consider the following two programs: > > f = open("c:/transfer/filename") > for line in f.readlines(): > words=line.rstrip().split() > print words > > f = open("c:/transfer/filename") > for line in f.readlines(): > words=line.rstrip().split() > print words > > Both process all the lines in the file but the first only prints out the > last line while the second prints out all the lines. > > Indentation is *critical* in python. -- "It will be of little avail to the people that the laws are made by men of their own choice, if the laws be so voluminous that they cannot be read, or so incoherent that they cannot be understood; if they be repealed or revised before they are promulged, or undergo such incessant changes that no man who knows what the law is to-day can guess what it will be tomorrow. Law is defined to be a rule of action; but how can that be a rule, which is little known and less fixed?" -- James Madison, Federalist #62 (27-Feb-1788) Rick Pasotto rick@niof.net http://www.niof.net From rick@niof.net Tue Jul 1 23:20:02 2003 From: rick@niof.net (Rick Pasotto) Date: Tue Jul 1 22:20:02 2003 Subject: [Tutor] Re: Readlines code. In-Reply-To: <20030702020737.GA18206@dman13.dyndns.org> References: <20030701015523.GB5712@niof.net> <3F023956.9030301@snet.net> <20030702020737.GA18206@dman13.dyndns.org> Message-ID: <20030702022008.GG5712@niof.net> On Tue, Jul 01, 2003 at 10:07:37PM -0400, Derrick 'dman' Hudson wrote: > > There are a few different ways of solving your problem, depending on > what you want to do and what your constraints are. One possibility is > this : > > words = [s.rstrip().split() for s in f.readlines()] Much better than what I suggested (though the result is the same). I need to get used to list comprehensions. -- "Life's too short for chess." -- H. J. Byron Rick Pasotto rick@niof.net http://www.niof.net From payal-python@staticky.com Wed Jul 2 00:18:03 2003 From: payal-python@staticky.com (Payal Rathod) Date: Tue Jul 1 23:18:03 2003 Subject: [Tutor] program flow Message-ID: <20030702031014.GB1637@linux.local> Hi, Gregor example on "magic" funtions has set me thinking. I am wondering how a program flow really is now. Consider a small example. #!/usr/bin/python x = 1 y = 2 def sum1(a,b): ..... ..... ..... return a return b print "Magic Functins! Hello World!" z = sum1(x,y) How does python flow works. It works out 1st 3 lines and then when it comes to def sum1(a,b): what happens or it jumps that part and goes directly to "Magic Functins! Hello World!" and then to z = sum1(x,y) from where it jumps to def sum1(a,b): What is the flow here? With warm regards, -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. From payal-python@staticky.com Wed Jul 2 00:18:09 2003 From: payal-python@staticky.com (Payal Rathod) Date: Tue Jul 1 23:18:09 2003 Subject: [Tutor] finding factorials - hmm..., gcd In-Reply-To: <3F01E629.5080805@aon.at> References: <200307010915.h619FGc02559@ada.rg16.asn-wien.ac.at> <20030701185705.GA4607@linux.local> <3F01E629.5080805@aon.at> Message-ID: <20030702030305.GA1637@linux.local> On Tue, Jul 01, 2003 at 09:51:05PM +0200, Gregor Lingl wrote: Thanks for the mails all of you and thanks for the "magic" example. Please clear my doubt below. Commented example below. Print statements are now numbered. print "WHAT'S GOING ON?" x =4 y=10 z = 0 print "x =",x,"y =",y,"z =",z # -------> (1) def look(a,b): print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b # --------> (2) a=2*a b=2*b c=a*b print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c # ------> (3) return c c = c*c # ;-) print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c # -----> (4) print "x =",x,"y =",y,"z =",z # ------------> (5) z = look(x,y) # this will execute 2 (!) print-statements # you won't be able to print a,b,c here print "x =",x,"y =",y,"z =",z # ---------> (6) The output is, WHAT'S GOING ON? x = 4 y = 10 z = 0 # This comes from print statement (1) x = 4 y = 10 z = 0 # This comes from print statement (5) x = 4 y = 10 z = 0 a = 4 b = 10 # Where the world this comes from? a and b are never defined anywhere, # nor are they assigned values of x and y. Where did python get the # idea that a = 4 and b = 10? x = 4 y = 10 z = 0 a = 8 b = 20 c = 160 x = 4 y = 10 z = 160 # Once the above question is answered I think this will have the same # logic. Thanks a lot for this "magic" example. With warm regards, -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. From p.hartley@spitech.com Wed Jul 2 00:48:02 2003 From: p.hartley@spitech.com (Paul Hartley) Date: Tue Jul 1 23:48:02 2003 Subject: [Tutor] Linux versions Message-ID: <004401c3404c$9ccd53a0$ebe710ac@paul> This is a multi-part message in MIME format. ------=_NextPart_000_0041_01C3408F.AAA5CF00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I currently work almost exclusively with Windows 98 and XP. But I am = becoming increasingly annoyed at the bully tactics of Microsoft so I = would like to switch to Linux. I have made a couple of half-hearted = atempts in the past but never stuck with it. This time I am serious!! So I need a recommendation. I recently saw questions where some python = packages were being downloaded and would not work because the Linux was = Mandrake and not Red Hat. I must say all the marketing hype of Mandrake = had me looking at that version of Linux - as most of my time is spent = with email, wordprocessing and spreadsheets - not programming. I am not = on OS techie and I guess I would want to dual boot if only so I could = play Railroad Tycoon sometimes. Any suggestions or experiences that Windows users have had switching to = Linux would be most appretiated and what are the complications for using = Python on the different systems. Kind regards Paul ------=_NextPart_000_0041_01C3408F.AAA5CF00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I currently work almost exclusively = with Windows 98=20 and XP. But I am becoming increasingly annoyed at the bully tactics of = Microsoft=20 so I would like to switch to Linux. I have made a couple of half-hearted = atempts=20 in the past but never stuck with it. This time I am = serious!!
 
So I need a recommendation. I recently = saw=20 questions where some python packages were being downloaded and would not = work=20 because the Linux was Mandrake and not Red Hat. I must say all the = marketing=20 hype of Mandrake had me looking at that version of Linux - as most of my = time is=20 spent with email, wordprocessing and spreadsheets - not programming. I = am not on=20 OS techie and I guess I would want to dual boot if only so I could play = Railroad=20 Tycoon sometimes.
 
Any suggestions or experiences that = Windows users=20 have had switching to Linux would be most appretiated and what are the=20 complications for using Python on the different systems.
 
Kind regards
 
Paul
------=_NextPart_000_0041_01C3408F.AAA5CF00-- From tutor@python.org Wed Jul 2 01:48:02 2003 From: tutor@python.org (/dev/rob0) Date: Wed Jul 2 00:48:02 2003 Subject: [Tutor] Linux versions In-Reply-To: <004401c3404c$9ccd53a0$ebe710ac@paul> References: <004401c3404c$9ccd53a0$ebe710ac@paul> Message-ID: <20030702044752.GJ1814@obrien.1984.lan> On Wed, Jul 02, 2003 at 11:47:08AM +0800, Paul Hartley wrote: > I currently work almost exclusively with Windows 98 and XP. But I am becoming increasingly annoyed at the bully tactics of Microsoft so I would like to switch to Linux. I have made a couple of half-hearted atempts in the past but never stuck with it. This time I am serious!! > So I need a recommendation. I recently saw questions where some python > packages were being downloaded and would not work because the Linux > was Mandrake and not Red Hat. Whilst GNU/Linux is GNU/Linux is GNU/Linux, subtle differences in the versions of crucial components such as the C libraries and compiler can make binaries built on/for one distro (and version) incompatible with another. Perhaps that's what you saw. GNU/Linux truly is one OS in that anything which will run on one distro can be built to run on any other. (((Free|Open|Net)BSD)|'Mac OS X') is similarly one underlying OS (but there are some incompatibilities with Linux and differing hardware support.) > I am not on OS techie and I guess I would want to dual boot if only Multi-booting is not a problem with any GNU/Linux. You can even boot from a floppy or CD (often necessary when dealing with DOS-based Windows which may overwrite your master boot record without permission.) > Any suggestions or experiences that Windows users have had switching > to Linux would be most appretiated I made the complete switch in Dec. 1999 because my Windows machine (its hard drive) failed. The transition didn't seem that difficult for me, but then, I *am* an OS techie. :) I use Slackware exclusively, both in server deployments and for my own workstation. I would recommend it to anyone who is seeking an in-depth understanding of GNU/Linux, but since you say you're not an OS techie, it may not be for you. Slackware is built by and for hard-core geeks (and professional sysadmins). SuSE, Red Hat and Mandrake have all set their sights on your part of the "market": refugees from Windows. I think I'd recommend them in that order, too, but don't put a lot of faith in that. It's possible that you would find any of these to be as easy or easier to install and use than Windows.[1] Debian isn't a "market", it is a community. It might be worth a look. Most notable about Debian is their extreme devotion to Free Software principles[2] and probably the most sophisticated package management tools. It's another one by-and-for geeks, but I've known some lesser- to-non-geeks who find it quite to their liking. > and what are the complications for using Python on the different > systems. OOTC! :) Good. I'm not aware of any problems with Python. Some distros may not install it by default, and they may not include all parts of it as you might get from the Python source. HTH, although I suppose some URL's would help too ... I don't know of any, but I know you're one of millions wanting to make the change, so Google about and you will undoubtedly find some advice. Rob - /dev/rob0 [1] One impressive benefit, as I recently discovered by setting up a Windows system, is that far more comes with your GNU/Linux CD than with Windows. Even a relatively minimal distro like Slackware gives you a wide selection of user software. [2] And a fanatical devotion to the Pope![3] [3] I'll bet you didn't expect the Spanish Inquisition.[4] [4] NOBODY expects the Spanish Inquisition! From glingl@mail.rg16.asn-wien.ac.at Wed Jul 2 04:15:03 2003 From: glingl@mail.rg16.asn-wien.ac.at (glingl) Date: Wed Jul 2 03:15:03 2003 Subject: [Tutor] finding factorials - hmm..., gcd Message-ID: <200307020714.h627E2c05951@ada.rg16.asn-wien.ac.at> --- Payal Rathod schrieb: .. > Commented example below. Print statements are now numbered. > > print "WHAT'S GOING ON?" > x =4 > y=10 > z = 0 > print "x =",x,"y =",y,"z =",z # -------> (1) > > def look(a,b): > print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b # --------> (2) > a=2*a > b=2*b > c=a*b > print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c # ------> (3) > return c > c = c*c # ;-) > print "x =",x,"y =",y,"z =",z,"a =",a,"b =",b,"c =",c # -----> (4) > > print "x =",x,"y =",y,"z =",z # ------------> (5) > z = look(x,y) # this will execute 2 (!) print-statements > # you won't be able to print a,b,c here > print "x =",x,"y =",y,"z =",z # ---------> (6) > > > The output is, > > WHAT'S GOING ON? > x = 4 y = 10 z = 0 # This comes from print statement (1) right! > x = 4 y = 10 z = 0 # This comes from print statement (5) right! > x = 4 y = 10 z = 0 a = 4 b = 10 > # Where the world this comes from? from print statement (2), which gets executed whenever the function look is called > # a and b are never defined anywhere, the are! in the first line of the definition of look: def look(a,b) a and b get created, every time you call look - an destroyed every time the execution of look has ceased. > # nor are they assigned values of x and y. They are! When look(x,y) is called, a gets the value of x and b gets the value of y. (Think of: a and b are substituted by x and y). You can substitute other values, e.g. by calling look(1001,-1) > # Where did python get the > # idea that a = 4 and b = 10? When look(x,y) is called, a gets the value of x and b gets the value of y. (Think of: a and b are substituted by x and y). You can substitute other values, e.g. by calling look(1001,-1) > x = 4 y = 10 z = 0 a = 8 b = 20 c = 160 While the values of a and b change during the execution of look, the variables x and y retain their old values. > x = 4 y = 10 z = 160 > # Once the above question is answered I think this will have the same > # logic. I've tried my best Regards, Gregor > > Thanks a lot for this "magic" example. > With warm regards, > -Payal > > -- > "Visit GNU/Linux Success Stories" > http://payal.staticky.com > Guest-Book Section Updated. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From yduppen@xs4all.nl Wed Jul 2 04:59:08 2003 From: yduppen@xs4all.nl (Yigal Duppen) Date: Wed Jul 2 03:59:08 2003 Subject: [Tutor] Linux versions In-Reply-To: <20030702044752.GJ1814@obrien.1984.lan> References: <004401c3404c$9ccd53a0$ebe710ac@paul> <20030702044752.GJ1814@obrien.1984.lan> Message-ID: <200307020958.01491.yduppen@xs4all.nl> > > and what are the complications for using Python on the different > > systems. > > OOTC! :) Good. I'm not aware of any problems with Python. I do! :-) There is one important caveat with most linux distros -- they allow (and often have) multiple versions of python to be installed simultaneously. So you can have 'python1.5', 'python2.1' and 'python2.2' on your system at the same time. Usually, there is also a 'python' executable which points to one of these versions. But here is the catch -- not on all systems does 'python' point to the latest version! For example, on my Debian system, 'python' points to 'python1.5'. I know RedHat systems suffer (or suffered?) from the same problem. This means that if your program 'myprogram.py' uses any newish features, and you say python myprogram.py you will get annoying, and at first incomprehensible, errors. So on my system I should say python2.2 myprogram.py Not a major issue, but you have to be aware of it. If you don't want any of this hassle, just use SuSE. It's the most userfriendly distro I've seen so far. And it only contains the latest Python version. YDD From mhoneyfield@xtra.co.nz Wed Jul 2 06:37:02 2003 From: mhoneyfield@xtra.co.nz (Michael Honeyfield) Date: Wed Jul 2 05:37:02 2003 Subject: [Tutor] Re: compiling python apps In-Reply-To: References: <3F013C6F.20202@xtra.co.nz> Message-ID: <3F02A77E.2040801@xtra.co.nz> > I've never looked specifically at PySol, but Python doesn't get > "compiled" in the classic sense of the word. The ready to run package > most likely contains a Python interpreter and whatever other third party > libraries PySol employs, but *also* the source code. hmm... the ready to run contains 3 1MB pysol_xx.pyc files. The xx being some numbers. I understand that its not "compiel" but more a byte code. What I dont get is that when I run the src, which is only .py's, a .pyc is made for each .py, so how come pysol only contains 3 of these .pyc's and they are much larger than the .pyc's I get when I run the scripts. Is there some way to "group" scripts together into a single .pyc and then using python to run the .pyc? >> But to sum it up, How do I get my modified pysol source compile like >> the ready to run package? I have emailed the maintainer, but not had >> any reply (I suspect he is busy in the next cool release of pysol :) ) > > > Install all required third-party packages as well as Python on your > machine en just start the application using "python appname.py" (where > appname is the name of the main python file). its only python 2.2.x and tcl :) Cheers Mike -- Ok, there's no way to do this gracefully, so I won't even try. I'm going to just hunker down for some really impressive extended flaming, and my asbestos underwear is firmly in place, and extremely uncomfortable. -- Linus Trovalds From tbstep@tampabay.rr.com Wed Jul 2 07:57:03 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Wed Jul 2 06:57:03 2003 Subject: OT: Re: [Tutor] Linux versions In-Reply-To: <20030702044752.GJ1814@obrien.1984.lan> References: <004401c3404c$9ccd53a0$ebe710ac@paul> <20030702044752.GJ1814@obrien.1984.lan> Message-ID: <200307020654.22247.tbstep@tampabay.rr.com> On Wednesday 02 July 2003 12:47 am, /dev/rob0 wrote: > I use Slackware exclusively, both in server deployments and for my own > workstation. I would recommend it to anyone who is seeking an in-depth > understanding of GNU/Linux, but since you say you're not an OS techie, > it may not be for you. Slackware is built by and for hard-core geeks > (and professional sysadmins). I know that is the general perception, but I would have to disagree. I have tried Mandrake, SuSE, Red Hat and Slackware (in that order). I found Slackware to be the most user-friendly of all of them. Oh, I used FreeBSD in between RH and Slack and I still use it from time to time. I put FBSD up there with Slack in terms of ease of use as well. Though, I suppose SuSE and company are easier if you get a 100% clean install (which I have never had on any distro) and you don't plan on doing any kind of customizing. So, maybe I do agree just a bit. -- Todd Stephens From op73418@mail.telepac.pt Wed Jul 2 08:32:01 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Wed Jul 2 07:32:01 2003 Subject: [Tutor] program flow In-Reply-To: <20030702031014.GB1637@linux.local> Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Payal Rathod > Sent: quarta-feira, 2 de Julho de 2003 4:10 > To: Python Tutor ML > Subject: [Tutor] program flow > > > Hi, > Gregor example on "magic" funtions has set me thinking. I > am wondering > how a program flow really is now. Consider a small example. > > #!/usr/bin/python > x = 1 > y = 2 > > def sum1(a,b): > ..... > ..... > ..... > return a > return b > Note that return b will never be executed since the function returns before it gets there! Maybe you want: return a, b > print "Magic Functins! Hello World!" > > > z = sum1(x,y) > > > How does python flow works. It works out 1st 3 lines and > then when it > comes to def sum1(a,b): what happens or it jumps that part and goes > directly to "Magic Functins! Hello World!" and then to z = sum1(x,y) > from where it jumps to def sum1(a,b): > > What is the flow here? > the def statement is a statement of sorts, but it *is* executed, *not* jumped over. What happens is that the function body is "compiled" into a function object and this object is bounded to the name sum1. Then Python continues to the other statements. The same thing for a class statement. The following gives some info on function objects: >>> def sum1(a, b): ... return a ... >>> print sum1 >>> help(sum1) Help on function sum1 in module __main__: sum1(a, b) >>> for elem in dir(sum1): ... print elem ... __call__ __class__ __delattr__ __dict__ __doc__ __get__ __getattribute__ __hash__ __init__ __name__ __new__ __reduce__ __repr__ __setattr__ __str__ > With warm regards, > -Payal > With my best regards, G. Rodrigues From thomi@thomi.imail.net.nz Wed Jul 2 08:40:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed Jul 2 07:40:02 2003 Subject: [Tutor] checking for class version info. Message-ID: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> Hey, I have the following problem: I have developed a small program which saves (using the pickle module) some classes, and loads them at a later date. The trouble is, the program is under active development, and the contents of the classes are changing constantly. What i would like to do, is invent some way so that as the classes are loaded, they automatically detect if they are the save "version" as the current class in the program source file. If they are not, they somehow "re-initialise" themselves in the new class. does that make sense? the first way i thought i would do it is generate some sort of unique identifier for the source code file each class is in (the code is such that every class is in a separate file - this cannot be changed); the size of the file in bytes would probably be enough for this (or perhaps the last modification time?). However, that would mean that simple adding a comment to the class would cause the class to reload, and that wouldn't be too good. then i thought about having a variable in each class called "version", or something similar, so that when a developer updates a class significantly, he can change the version number, and the classes would reload themselves, if their version number didn't match that in the class source code file. The trouble with that is that developers are lazy, and would probably forget. Also, i have no idea how to go about doing this "reloading". It may be that the objects will have to be re-created every time the class changes, or that I'll have to make a conversion script, but there you go, any ideas? where should i go from here? thanks, -- Thomi Richards, thomi@thomi.imail.net.nz From payal-python@staticky.com Wed Jul 2 08:54:02 2003 From: payal-python@staticky.com (Payal Rathod) Date: Wed Jul 2 07:54:02 2003 Subject: [Tutor] finding factorials - hmm..., gcd In-Reply-To: <200307020714.h627E2c05951@ada.rg16.asn-wien.ac.at> References: <200307020714.h627E2c05951@ada.rg16.asn-wien.ac.at> Message-ID: <20030702115152.GC2509@linux.local> Hi, Thanks for the mail and the explanation. It was splendid. Along with another offlist explanation by a member I got it fitted in quite ok. I have written my own recursive function (a function calling itself). Just have a look please. Before you shudder with the thought of answering it, I say just look and if you feel like it comment. It is an infinite function. It goes on repetatively. #!/usr/bin/python def rec_fun(): print a rec_fun() a = 10 rec_fun() BTW OT, if I want to redirect the errors an output to a file why does this not work? $ python rec1.py 2>&1 > temp Is it writting on some different file handle? Thanks a lot and bye -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. From magnus@thinkware.se Wed Jul 2 10:18:07 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 2 09:18:07 2003 Subject: [Tutor] Linux versions In-Reply-To: <200307020958.01491.yduppen@xs4all.nl> References: <20030702044752.GJ1814@obrien.1984.lan> <004401c3404c$9ccd53a0$ebe710ac@paul> <20030702044752.GJ1814@obrien.1984.lan> Message-ID: <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> At 09:58 2003-07-02 +0200, Yigal Duppen wrote: >But here is the catch -- not on all systems does 'python' point to the >latest version! For example, on my Debian system, 'python' points to >'python1.5'. I know RedHat systems suffer (or suffered?) from the same >problem. Redhat no longer relies on Python 1.5.2. As long as you use Red Hat 8.x, you should have no problem with this. Don't know much about Debian, but I do think that both Mandrake, RedHat and SuSE are easier to get started with than Debian if you are a newbie. Debian suppsedly runs very well once it's installed, but to get there takes a while. I haven't used Slackware since version 2.3... I think you will be fine with Mandrake. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From ATrautman@perryjudds.com Wed Jul 2 11:30:26 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed Jul 2 10:30:26 2003 Subject: [Tutor] Linux versions Message-ID: <06738462136C054B8F8872D69DA140DB010827@corp-exch-1.pjinet.com> My recent experience is that Mandrake is the best for new LINUX users. It can install on a base system in right around 20 keystrokes. I recently installed it on a devil system (SCSI, multi-NIC, odd ball video) and it took first try and so far 1 weeks limited usage it seems fine. My last experience with Redhat 8.1 was that the install was only slightly harder to install but was harder to configure as it still needed a combination of X based and console based adjustments to work. Mandrakes HardDrake (X-configure) is really slick. As far as Python Mandrake will install Python 2.2 and TCL 8.? by default so I've never had any Python problems. I don't know what the current Redhat install is. I have had some troubles with Mandrakes SDL RPM which is disappointing as it is an essential? library, at least for me. I also haven't had time to really dig into it. HTH, Alan -----Original Message----- From: Paul Hartley [mailto:p.hartley@spitech.com] Sent: Tuesday, July 01, 2003 10:47 PM To: tutor@python.org Subject: [Tutor] Linux versions I currently work almost exclusively with Windows 98 and XP. But I am becoming increasingly annoyed at the bully tactics of Microsoft so I would like to switch to Linux. I have made a couple of half-hearted atempts in the past but never stuck with it. This time I am serious!! So I need a recommendation. I recently saw questions where some python packages were being downloaded and would not work because the Linux was Mandrake and not Red Hat. I must say all the marketing hype of Mandrake had me looking at that version of Linux - as most of my time is spent with email, wordprocessing and spreadsheets - not programming. I am not on OS techie and I guess I would want to dual boot if only so I could play Railroad Tycoon sometimes. Any suggestions or experiences that Windows users have had switching to Linux would be most appretiated and what are the complications for using Python on the different systems. Kind regards Paul From DORSEY_EDMUND_K@LILLY.COM Wed Jul 2 13:17:01 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Wed Jul 2 12:17:01 2003 Subject: [Tutor] Passing arguments Message-ID: This is a multipart message in MIME format. --=_alternative 0059423305256D57_= Content-Type: text/plain; charset="us-ascii" I have a class called GUI which draws my GUI. I then have another class called Calc which does all the calculations. One of the GUI objects I'm using is a progressMeter (pmw) The progressMeter is declared in GUI and it has an update function called updateProgress. So you can have a loop and keep calling updateProgress and increment your progress. This works fine and dandy if I call updateProgress in the GUI class. The problem is I can't monitor the progress in the GUI class because the calculation is being done in the Calc class. Ideally, I want to called updateProgress in the loop of Calc Class. I thought for a second since python passes stuff by reference I could just pass a reference to the progressMeter to Calc and then do the update there but that doesn't work. Do I need to make the progressMeter global? I read that's not very elegant. How would I go about letting the Calc class update progressMeter. Thank you for your help. ~Ed --=_alternative 0059423305256D57_= Content-Type: text/html; charset="us-ascii"
I have a class called GUI which draws my GUI.  I then have another class called Calc which does all the calculations.

One of the GUI objects I'm using is a progressMeter (pmw)

The progressMeter is declared in GUI and it has an update function called updateProgress.  So you can have a loop and keep calling updateProgress and increment your progress.
This works fine and dandy if I call updateProgress in the GUI class.  The problem is I can't monitor the progress in the GUI class because the calculation is being done in the Calc class.

Ideally, I want to called updateProgress in the loop of Calc Class.

I thought for a second since python passes stuff by reference I could just pass a reference to the progressMeter to Calc and then do the update there but that doesn't work.

Do I need to make the progressMeter global?  I read that's not very elegant.

How would I go about letting the Calc class update progressMeter.  Thank you for your help.

~Ed

--=_alternative 0059423305256D57_=-- From magnus@thinkware.se Wed Jul 2 13:30:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 2 12:30:02 2003 Subject: [Tutor] Passing arguments In-Reply-To: Message-ID: <5.2.1.1.0.20030702183224.01fd1cb0@www.thinkware.se> At 11:14 2003-07-02 -0500, DORSEY_EDMUND_K@LILLY.COM wrote: >I thought for a second since python passes stuff by reference I could just >pass a reference to the progressMeter to Calc and then do the update there >but that doesn't work. This should work. You are doing it wrong I guess. Show some code please. We can't debug prose. ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From Suresh Kumar" Hi, Iam using python2.2/tkinter/windows. My doubt is regarding how to convert tkiner canvas as a PNG file? I have drawn some rectangles in my canvas. The canvas size is larger than the screen. Initially i used "ImageGrab" to grab the entire canvas. But the ImageGrab approach doesn't work in my case, since it copies pixels from the display, i couldn't able to grab the entire canvas. To overcome this problem i used Postscript generation mechanisms provided by the Canvas widget and coverted the canvas to a postscript file. In this case i converted entire canvas into a postscript file. The problem with Postscript format is, we need Ghostscript viewer to view the Postcript image which we have to install separately. Since most of the systems running under Windows OS will have "Microsoft Photo Editor", it would be nice to have a PNG file rather than PostScript file. Is there any way to store the entire canvas as a PNG file? Otherwise how can i convert a postscript file to PNG or BMP file in Python? Is it possible to convert postscript file to PNG file in python? Anyother solution.......? I need the solution urgently. Earlier replies are welcome. With Regards, V.Suresh Kumar ___________________________________________________ Click below to experience Sooraj R Barjatya's latest offering 'Main Prem Ki Diwani Hoon' starring Hrithik, Abhishek & Kareena http://www.mpkdh.com From reggie@merfinllc.com Wed Jul 2 13:36:02 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Wed Jul 2 12:36:02 2003 Subject: [Tutor] Passing arguments In-Reply-To: References: Message-ID: <1057163744.29479.8.camel@pika> Edmund, You have the right idea about passing a reference to the progressMeter method to the Calc class instance, either in its constructor or when you call the method that does the calculation. For example gui = GUI(...) c = Calc(...) c.do_loop(..., gui.updateProgress) and in the do_loop method: def do_loop(self, ..., progress=None): ... while calculate: ... if progress: percent_done = ... progress(percent_done) Hopefully this will put you on the right track. On Wed, 2003-07-02 at 09:14, DORSEY_EDMUND_K@LILLY.COM wrote: > I have a class called GUI which draws my GUI. I then have another > class called Calc which does all the calculations. > > One of the GUI objects I'm using is a progressMeter (pmw) > > The progressMeter is declared in GUI and it has an update function > called updateProgress. So you can have a loop and keep calling > updateProgress and increment your progress. > This works fine and dandy if I call updateProgress in the GUI class. > The problem is I can't monitor the progress in the GUI class because > the calculation is being done in the Calc class. > > Ideally, I want to called updateProgress in the loop of Calc Class. > > I thought for a second since python passes stuff by reference I could > just pass a reference to the progressMeter to Calc and then do the > update there but that doesn't work. > > Do I need to make the progressMeter global? I read that's not very > elegant. > > How would I go about letting the Calc class update progressMeter. > Thank you for your help. > > ~Ed -- Reggie From project5@redrival.net Wed Jul 2 14:33:02 2003 From: project5@redrival.net (Andrei) Date: Wed Jul 2 13:33:02 2003 Subject: [Tutor] Re: compiling python apps In-Reply-To: <3F02A77E.2040801@xtra.co.nz> References: <3F013C6F.20202@xtra.co.nz> <3F02A77E.2040801@xtra.co.nz> Message-ID: Michael Honeyfield wrote: > hmm... the ready to run contains 3 1MB pysol_xx.pyc files. The xx being > some numbers. I understand that its not "compiel" but more a byte code. Indeed. > What I dont get is that when I run the src, which is only .py's, a .pyc > is made for each .py, so how come pysol only contains 3 of these .pyc's > and they are much larger than the .pyc's I get when I run the scripts. > Is there some way to "group" scripts together into a single .pyc and > then using python to run the .pyc? A .pyc is made when the program is executed for *every* .py file except the main one (the one you actually execute). In so far what you get sounds like quite normal behaviour. I don't know what PySol is doing, but considering the size difference (and I'm just guessing here) the "binary" modules might include some resources (or even modules) which are somehow unpacked and used/executed at runtime. There's a Python decompyler somewhere on the net, perhaps you could use it on the "binary" distro and see what you find out. I've never used the decompyler, but I've read its output can be reasonably readable. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From =?iso-8859-1?B?dHV0b3IucHl0aG9uLm9yZw==?=" --_b22c13855f2e96190b7c70f4dc2055326 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: base64 SSBoYXZlIGEgc2VyaWVzIG9mIGxpc3RzIGNhbGxlZCAibGluZTEiLCAibGluZTIiLCAibGluZTMi LCBldGMuLi4gd2hpY2ggSSBjb21iaW5lIGludG8gb25lIGxpc3QgdGhpcyB3YXk6DQoNCmM0ID0g W10NCmZvciBpIGluIHJhbmdlKDQ2KToNCiAgICBleGVjKCdjNC5leHRlbmQobGluZScgKyBzdHIo aSsxKSArICcpJykNCg0KVGhlIGxpc3QgYXJlIGp1c3QgZGVjbGFyZWQgaW4gdGhlIHNjcmlwdCBh bmQgbGlzdCBuYW1lcyBhcmUgbm90IHN0b3JlZCBpbiBhbnl0aGluZyBiZXNpZGVzIFB5dGhvbidz IGRlZmF1bHQgZGF0YSBzdHJ1Y3R1cmVzLiAgQ2FuIGFueW9uZSB0ZWxsIG1lIGhvdyBJIGNhbiBk byB0aGlzIHdpdGhvdXQgdXNpbmcgZXhlYz8NCg0KUG9vciBZb3JpY2sNCnR1dG9yLnB5dGhvbi5v cmdAcG9vcnlvcmljay5jb20K --_b22c13855f2e96190b7c70f4dc2055326 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1pc28tODg1OS0xIj4KPC9oZWFkPgo8Ym9keT4KSSBoYXZlIGEgc2Vy aWVzIG9mIGxpc3RzIGNhbGxlZCAibGluZTEiLCAibGluZTIiLCAibGluZTMiLCBldGMuLi4gd2hp Y2ggSSBjb21iaW5lIGludG8gb25lIGxpc3QgdGhpcyB3YXk6DTxicj4KDTxicj4KYzQgPSBbXQ08 YnI+CmZvciBpIGluIHJhbmdlKDQ2KToNPGJyPgogICAgZXhlYygnYzQuZXh0ZW5kKGxpbmUnICsg c3RyKGkrMSkgKyAnKScpDTxicj4KDTxicj4KVGhlIGxpc3QgYXJlIGp1c3QgZGVjbGFyZWQgaW4g dGhlIHNjcmlwdCBhbmQgbGlzdCBuYW1lcyBhcmUgbm90IHN0b3JlZCBpbiBhbnl0aGluZyBiZXNp ZGVzIFB5dGhvbidzIGRlZmF1bHQgZGF0YSBzdHJ1Y3R1cmVzLiAgQ2FuIGFueW9uZSB0ZWxsIG1l IGhvdyBJIGNhbiBkbyB0aGlzIHdpdGhvdXQgdXNpbmcgZXhlYz8NPGJyPgoNPGJyPgpQb29yIFlv cmljaw08YnI+CnR1dG9yLnB5dGhvbi5vcmdAcG9vcnlvcmljay5jb208YnI+CjwvYm9keT48L2h0 bWw+Cg== --_b22c13855f2e96190b7c70f4dc2055326-- From magnus@thinkware.se Wed Jul 2 16:49:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 2 15:49:02 2003 Subject: [Tutor] extending a series of lists In-Reply-To: <20030702173329.27540.qmail@station198.com> Message-ID: <5.2.1.1.0.20030702214659.01fc3ed0@www.thinkware.se> At 17:33 2003-07-02 +0000, tutor.python.org wrote: >I have a series of lists called "line1", "line2", "line3", etc... which I >combine into one list this way: > >c4 = [] >for i in range(46): >exec('c4.extend(line' + str(i+1) + ')') Ouch! Don't use "list1", "list2" etc. Use a list of lists. I'd say that as soon as you write variable names with numbers like that, you are just trying to implement a list very poorly. ;) I.e. instead of having: list1 = [...] list2 = [...] ... you should have: lists = [] lists.append([...]) lists.append([...]) ... so in a place where you would use "list0" today, you use "lists[0]" instead. Where you want to iterate over the lists, simply use something like: c4 = [] for l in lists: c4.extend(l) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dman@dman13.dyndns.org Wed Jul 2 17:43:01 2003 From: dman@dman13.dyndns.org (Derrick 'dman' Hudson) Date: Wed Jul 2 16:43:01 2003 Subject: [Tutor] Re: Linux versions In-Reply-To: <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> References: <20030702044752.GJ1814@obrien.1984.lan> <004401c3404c$9ccd53a0$ebe710ac@paul> <20030702044752.GJ1814@obrien.1984.lan> <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> Message-ID: <20030702204156.GA30172@dman13.dyndns.org> --9jxsPFA5p3P2qPhR Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Wed, Jul 02, 2003 at 03:22:33PM +0200, Magnus Lyck=E5 wrote: | At 09:58 2003-07-02 +0200, Yigal Duppen wrote: | >But here is the catch -- not on all systems does 'python' point to the | >latest version! For example, on my Debian system, 'python' points to | >'python1.5'. Old debian systems have 1.5.2 as the default python. Newer ones (running a current 'testing' or 'unstable') have either 2.2.2 or 2.2.3 as the default python. All "current" debian systems have the option of installing more than one python simultaneously. (I have 2.1, 2.2 and 2.3 installed right now) | Don't know much about Debian, but I do think that both Mandrake, | RedHat and SuSE are easier to get started with than Debian if you | are a newbie. I agree. | Debian suppsedly runs very well once it's installed, It does. (which is why I use it) | but to get there takes a while. This depends on several factors. For someone wholly inexperienced with unix then it certainly will take a while, particularly if you are unfamiliar with your hardware and details needed to configure it. As your familiarity increases, the time to get a new system going will vastly decrease. As a first recommendation, try Knoppix. It is entirely cd-based. You put the CD in the drive, boot, and there's the system. It doesn't affect your hard drive. It is a good way to try out a linux system or to use linux on a machine that you don't have permission/authority to alter the OS on. It just so happens that knoppix is based on debian, so transitioning from one to the other is quite easy, but once you get some familiarity with linux in general working with any other system will be easier. -D --=20 Misfortune pursues the sinner, but prosperity is the reward for the righteous. Proverbs 13:21 =20 http://dman13.dyndns.org/~dman/ --9jxsPFA5p3P2qPhR Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj8DQ5MACgkQiB6vp1xAVUDCJgCfUByuypMy6ja1ehW6y3vDG9Mh gyoAnj/vao1ogfYKNGFLb4QzHBt110l3 =UyFj -----END PGP SIGNATURE----- --9jxsPFA5p3P2qPhR-- From Michael Montagne Wed Jul 2 19:58:02 2003 From: Michael Montagne (Michael Montagne) Date: Wed Jul 2 18:58:02 2003 Subject: [Tutor] Exchange Public Folders Message-ID: <20030702225727.GB22128@boora.com> #!/bin/python import getpass, imaplib from mx.DateTime import * import smtplib cnt=0 host="webmail" address="montagne@boora.com" faddress="fax@boora.com" msg="Subject: Incoming Fax" M = imaplib.IMAP4('mailserver') M.login('FAX', 'faxpass') cnt=M.select('INBOX') print cnt #print M.list() typ, data = M.search(None, 'ALL') for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') M.append("Public Folders/FAX INBOX",None,None,num) M.copy(num,"Public Folders/FAX INBOX") # M.store(num,'+FLAGS','\Deleted') print ('%s' % (num)) #M.expunge() M.logout() if cnt: msg="Subject: Incoming Fax\n\n" + cnt[1][0] + " faxes just arrived" s=smtplib.SMTP(host) s.sendmail(faddress,address,msg) -- Michael Montagne http://www.themontagnes.com 503.226.1575 -- From jeff@ccvcorp.com Wed Jul 2 20:33:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 2 19:33:02 2003 Subject: [Tutor] program flow References: <20030702031014.GB1637@linux.local> Message-ID: <3F036B79.2000500@ccvcorp.com> Payal Rathod wrote: >Hi, >Gregor example on "magic" funtions has set me thinking. I am wondering >how a program flow really is now. Consider a small example. > >#!/usr/bin/python >x = 1 >y = 2 > >def sum1(a,b): > ..... > return a > return b > >print "Magic Functins! Hello World!" > >z = sum1(x,y) > > >How does python flow works. It works out 1st 3 lines and then when it >comes to def sum1(a,b): what happens or it jumps that part and goes >directly to "Magic Functins! Hello World!" and then to z = sum1(x,y) >from where it jumps to def sum1(a,b): > When it gets to 'def sum(...)', it does just that -- it creates that function object, and binds it to the name 'sum'. It then proceeds to the print statement, and finally calls the just-created function object and binds the result of that call to the name 'z'. The key here is that 'def' is a statement, just like any other; it creates an object and binds that object to a name, at the time that the statement is executed. Jeff Shannon Technician/Programmer Credit International From as1116522@sapo.pt Wed Jul 2 21:30:02 2003 From: as1116522@sapo.pt (Paulo Baptista) Date: Wed Jul 2 20:30:02 2003 Subject: [Tutor] Anyone know about Anygui Message-ID: <1057195734.2549.3.camel@localhost.localdomain> Hi guys, Do you know if anygui is being maintained, development seems to have stopped for the reasons described on the project page, but do you know if the project's going to develop? Best regards, Paulo Baptista From python@kyle.sent.com Wed Jul 2 22:49:12 2003 From: python@kyle.sent.com (Kyle Babich) Date: Wed Jul 2 21:49:12 2003 Subject: [Tutor] FYI Message-ID: <20030703014802.A9DBB6BC69@smtp.us2.messagingengine.com> I just launched pyBoards.com, please check it out. It's a community for Python programmers. -- Kyle From thomi@thomi.imail.net.nz Wed Jul 2 22:53:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed Jul 2 21:53:01 2003 Subject: [Tutor] FYI In-Reply-To: <20030703014802.A9DBB6BC69@smtp.us2.messagingengine.com> References: <20030703014802.A9DBB6BC69@smtp.us2.messagingengine.com> Message-ID: <20030703135200.69d31314.thomi@thomi.imail.net.nz> > I just launched pyBoards.com, please check it out. It's a community > for Python programmers. it uses PHP!! what happened to python ;) -- Thomi Richards, thomi@thomi.imail.net.nz From payal-python@staticky.com Wed Jul 2 23:44:01 2003 From: payal-python@staticky.com (Payal Rathod) Date: Wed Jul 2 22:44:01 2003 Subject: [Tutor] is it a right choice? Message-ID: <20030703024420.GA1522@linux.local> Hi, Before I venture in the python infested world, I want to ask whether I am making a right choice by taking python as my first programming language. I cannot program in C, C++ or Java etc. I can *just* do little shell scripting. My objective in learning a better language is that I have huge log files in my office and get many logs files from friends who are sytem admins. I love to analyse those files and find out browing habits of my compnay (from squid logs), most number of mails sent to a domain ( like hotmail), number of bytes data transferred thru' http, pop3 and smtp etc. I prefer to write my own programs to do these things. With rudimentary shell scripting knowledge analysing log files which are many times over 200Mb is difficult so I was seeking a language which can do these tasks beautifully without getting too much involved in underlying concepts. Am I looking for Python? Is Perl easier to learn for a newbie than python? Is it OK to continue with Python? Also can Python produce binary programs like perl (perlcc)? Thanks, With warm regards, -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. From tbstep@tampabay.rr.com Thu Jul 3 00:23:02 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Wed Jul 2 23:23:02 2003 Subject: [Tutor] is it a right choice? Message-ID: <200307022320.37240.tbstep@tampabay.rr.com> Forgot to CC this to the list: On Wednesday 02 July 2003 10:44 pm, Payal Rathod wrote: > Am I looking for Python? Is Perl easier to learn for a newbie than > python? Is it OK to continue with Python? I would say that Python is the correct place to look. I haven't found a good Perl book for learning to program in general. While Python is very rich, you can do exactly what you are trying to do without dipping into the advanced features. I, like you, know some shell scripting and decided to learn a 'programming' language. I tried C, then Perl. I finally came to Python and found everything so much easier to put into practice. A great place to look to learn not only the ins and outs of Python, but of programming in general, is the free book "How to Think Like a Computer Scientist". It can be found at: http://www.ibiblio.org/obp/thinkCSpy/ You can also buy it in hardcopy at your favorite online book seller. It is also available in Java and (I think) C versions, but neither one of those is really as suited to your purpose as Python is. -- Todd Stephens From Suresh Kumar" Hi, In Tkinter, how to convert canvas coordinates to window coordinates? To convert window coordinates to canvas coordinates we are using "canvasx,canvasy". But how to do vice-versa? Iam using a canvas whose size is larger than screen size and drawn a rectagnle in the middle of canvas. When i select the rectangle i got its coordinates in terms of canvas coordinates. But i need it in window coordinate. How can i do it? With Regards, V.Suresh Kumar. ___________________________________________________ Click below to experience Sooraj R Barjatya's latest offering 'Main Prem Ki Diwani Hoon' starring Hrithik, Abhishek & Kareena http://www.mpkdh.com From lonetwin@yahoo.com Thu Jul 3 05:11:03 2003 From: lonetwin@yahoo.com (lonetwin) Date: Thu Jul 3 04:11:03 2003 Subject: [Tutor] is it a right choice? In-Reply-To: <200307022320.37240.tbstep@tampabay.rr.com> References: <200307022320.37240.tbstep@tampabay.rr.com> Message-ID: <200307031349.03024.lonetwin@yahoo.com> Hi Payal, On Thursday 03 Jul 2003 8:50 am, Todd Stephens wrote: > Forgot to CC this to the list: [ ... ] > You can also buy it in hardcopy at your favorite online book seller. It is > also available in Java and (I think) C versions, but neither one of those > is really as suited to your purpose as Python is. Just want to add to whatever Todd said. What I personally appreciate about Python is that it is a 'general purpose' language. You can hack up a quick and dirty script that 'does-the-job' as easily as a full blown application. However, one thing you ought to remember. Try and grok the concepts that you are introduced to instead of *how* those are implemented in the language, because those transcend the language that you choose to code in. Just like any *nix, once you know what the '-rwxr-xr-x' mean, you know about file permissions irrespective of what flavor of *nix you choose to use. A tip - one of the more effective ways to learn a new language (at least for me) is to tinker around with some existing code written by someone else. Fortunately for Python, there is a place where even newbies can find something that is simple enough to tinker around with (like the "Hello world !" program). I'm speaking of Useless Python http://www.uselesspython.com/ This is maintained my a group of volunteers from this list. You will also find links to other demo/example pages on the "Source links" page. Hope this gives you a itch to write at least one script worthy to be called Useless. :) Happy hacking Peace Steve -- printk("Penguin %d is stuck in the bottle.\n", i); 2.0.38 /usr/src/linux/arch/sparc/kernel/smp.c From python@kyle.sent.com Thu Jul 3 07:16:02 2003 From: python@kyle.sent.com (Kyle Babich) Date: Thu Jul 3 06:16:02 2003 Subject: [Tutor] Re: FYI In-Reply-To: <20030703032302.29897.15436.Mailman@mail.python.org> References: <20030703032302.29897.15436.Mailman@mail.python.org> Message-ID: <20030703101518.096F371133@smtp.us2.messagingengine.com> Heh... there aren't exactly any good boards out yet written in python. I did realize the irony of a python community written in php and I was looking for hours for a good python discussion board, but without luck. I do plan to switch it over when one does come out though. Hmm... Date: Thu, 3 Jul 2003 13:52:00 +1200 From: Thomas CLive Richards To: tutor@python.org Subject: Re: [Tutor] FYI > I just launched pyBoards.com, please check it out. It's a community > for Python programmers. it uses PHP!! what happened to python ;) -- Thomi Richards, thomi@thomi.imail.net.nz -- Kyle pyBoards.com :: A community for Python programmers From thomi@thomi.imail.net.nz Thu Jul 3 07:19:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 3 06:19:01 2003 Subject: [Tutor] Re: FYI In-Reply-To: <20030703101518.096F371133@smtp.us2.messagingengine.com> References: <20030703032302.29897.15436.Mailman@mail.python.org> <20030703101518.096F371133@smtp.us2.messagingengine.com> Message-ID: <20030703221824.61bf4044.thomi@thomi.imail.net.nz> > Heh... there aren't exactly any good boards out yet written in python. > I > did realize the irony of a python community written in php and I was > looking for hours for a good python discussion board, but without > luck. I do plan to switch it over when one does come out though. > Hmm... I started writing one, but stopped. Maybe i should finish it.... bleh... -- Thomi Richards, thomi@thomi.imail.net.nz From magnus@thinkware.se Thu Jul 3 10:33:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 3 09:33:01 2003 Subject: [Tutor] Re: Linux versions In-Reply-To: <20030702204156.GA30172@dman13.dyndns.org> References: <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> <20030702044752.GJ1814@obrien.1984.lan> <004401c3404c$9ccd53a0$ebe710ac@paul> <20030702044752.GJ1814@obrien.1984.lan> <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> Message-ID: <5.2.1.1.0.20030703140058.01fd1df8@www.thinkware.se> As noted, modern Python versions come with most modern Linux distros. If you want to run a different Python version than you get with the Linux distro, that's no big problem either. Actually, Alex Martelli talked about Python 2.3 at Europython last week, and strongly encourage people to use the beta. It has fewer known bugs than 2.2.3, it's faster, and it has a number of new and useful packages. http://www.europython.org/Talks/Slides/ep03_py23.ppt will tell you more. If you do want to run e.g. python 2.3b2 on your linux box--it's not a big thing. Just download the source, build it and install it under /usr/local. I think this is the default of you just go to the newly downloaded Python directory and do... ./configure make make install ...but don't take my word for it, it's some time since I did that. Read the README. In general it will be much simpler than on Windows, and you don't need to install things like Visual Studio etc. You will typically have all you need. Your new executable will be in /usr/local/bin/python, and it will not interfere with any executable in the linux standard location, which is /usr/bin/python. By placing /usr/local/bin first in the PATH for your user account, you will run your Python 2.3 version if you type "python myfile.py" or if your files start with "#!/usr/bin/env python". If you have system admin tools etc that rely on using /usr/bin/python, that should work as before unless the Linux distributor made some serious mistake. Of course, if you build your own Python, you will probably have to build extension modules as well, but that's typically not more difficult on linux than downloading source an doing "python setup.py install" in the main directory of the downloaded file tree. I guess the rest of this mail is a bit off topic, since we seem to have established that it's quite possible to run Python well on most modern Linux distros. Still, I hope you can live with my further comments and questions about Debian. At 16:41 2003-07-02 -0400, Derrick 'dman' Hudson wrote about Debian installation: >For someone wholly inexperienced >with unix then it certainly will take a while, particularly if you are >unfamiliar with your hardware and details needed to configure it. I don't quite agree. Regardless of prior Unix experience, Debian is not nearly as easy to get started with as the other major Linux distributions. I'd say it's easier to complete a full Mandrake installation than it is to figure out what to download to just get your Debian installation started. Being an expert in korn shell scripting and knowing all the innards of awk, find and sys V init files doesn't change that. I have used Unix since the late 80's as a user and admin of SunOS/Solaris, Apollo Domain, HP/UX, AIX etc. I've used Linux since kernel version 1.2.8 (1994?). I've used Slackware, SuSE, RedHat and Mandrake, as well as some FreeBSD. I've tried to get started with Debian a few times, but I always gave up before I had a running system. I have several laptops without CDs (one doesn't even have a built in floppy--it's external) and it's trivial to get Mandrake running on them, with support for the touch screen on the smaller one etc. I just make a net installation floppy, and reply to some trivial questions. As far as I remember, there's just this single floppy image to get, and I can use rawrite in Windows or the Linux dd command to write that to a floppy. That part is identical for almost all floppy based linux installs. I've done that when I gor tired trying to navigate the Debian site. With Debian I've tried CDs I got in a bundle some years ago, and at that time, it was hopelessly cumbersome to select what software to install. I'm sure it's better now, but the problem seems to be that the Debian project is run by people who are all very involved in Debian and most things are trivial once you know them. I bet 90% of all Debian users got on-site assistance from someone with prior Debian assistance the first time they installed it. I surf to www.debian.org, I rather quickly reach something like http://www.dk.debian.org/distrib/floppyinst to get instructions on what to do next since I want to do a network install with floppys. Then the confusion starts. The link to the files just lead me to a list of mirrors full of files, and it's not clear what I need. I'm referred to five different manuals, and the manual describing what files I need, "Installing Debian GNU/Linux 3.0 For Intel x86 Chapter 11 - Appendix" list almost 100 different files, and refers me to yet another manual to understand just what I need. All these files are for "current", whatever that means. As far as I understand, Debian always have three versions: "stable", "testing" and "unstable". The currently stable version is called "woody", the current testing version is "sarge", and the currently unstable version is called "sid". I assume they also have numbers. But which does "current" point to? I know, most Debian people, who have struggled to get the hang of this will have a gut reaction to say, "Hang on, this is very simple." Well, let me tell you: It isn't. It's confusing. All this is just for the x86 files... I'm sure I only need a few of all these files, but I certainly get the impression that the Debian team is trying to scare people away, rather than to attract new users. I currently have an old IBM 760LD laptop with a P90, 48MB RAM, 810 MB disk, a floppy but no CD and a Netgear FA411 PCMCIA NIC that I'd be interested in running Debian on. No X, just a simple text based system with reasonable security where I can run some Python stuff via ssh etc across the net. Anyone who thinks he or she can guide me through this process is very welcome to try. It seems many Python developers use Debian as their development platform, so it's probably a good platform once you've got it running. >As a first recommendation, try Knoppix. It is entirely cd-based. Can I upgrade this to a current Debian version in a simple way, or am I limited to debs made for Knoppix? I'd really only be interested to use Knoppix as a more convenient installer for Debian. Is there a way to use Knoppix on machines lacking a CD? Would that be easier than other ways to get Debian running. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From jim_938@hotmail.com Thu Jul 3 10:54:01 2003 From: jim_938@hotmail.com (Jimmy verma) Date: Thu Jul 3 09:54:01 2003 Subject: [Tutor] range of int Message-ID: Hello *.*, Can some please tell me the range of interger variables in python. Like in C we have -32768-32767. Thanks in advance. Regards.. _________________________________________________________________ HCL Beanstalk PCs. You could win one. http://server1.msn.co.in/sp03/hclbeanstalktour/index.asp Interested? From magnus@thinkware.se Thu Jul 3 11:15:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 3 10:15:02 2003 Subject: [Tutor] range of int In-Reply-To: Message-ID: <5.2.1.1.0.20030703160719.01fa1c50@www.thinkware.se> At 19:22 2003-07-03 +0530, Jimmy verma wrote: >Can some please tell me the range of interger variables in python. Like >in C we have -32768-32767. A normal Python int is 32 bits on a 32 bit computer. You can find the limits in the sys module. >>> import sys >>> print sys.maxint 2147483647 On a 64 bit system such as an Alpha, Itanium or Ultra Sparc, this would probably be 4611686018427387903, but it depends on the underlying C library. The largest possible int is sys.maxint, and the smallest possible is -1-sys.maxint. But note that modern Python versions will silently convert to long integers when calculation results no longer fit in an int. Thus int + int will return int or long depending on values. From version 2.3 the builtin int type/factory function will return longs if fed with a value that doesn't fit in the int type. With 2.2 you still get an overflow. >>> sys.maxint 2147483647 >>> sys.maxint+1 2147483648L >>> int(sys.maxint) 2147483647 >>> int(sys.maxint+1) Traceback (most recent call last): File "", line 1, in ? OverflowError: long int too large to convert to int In Python 2.3, int(sys.maxint+1) will return a long. This is a part of an ongoing merge of the long and int types. Eventually, Python will only have one integer type, and it's up to the implementation, not to the language standard to handle small integers in an effective way. Python's long integers can be as large as you like, as long as your computer doesn't run out of memory... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From Michael Montagne Thu Jul 3 14:00:02 2003 From: Michael Montagne (Michael Montagne) Date: Thu Jul 3 13:00:02 2003 Subject: [Tutor] Exchange Public Folders In-Reply-To: <20030702225727.GB22128@boora.com> References: <20030702225727.GB22128@boora.com> Message-ID: <20030703165921.GA25275@boora.com> Hey!! There's no message with that code!! Sorry bout that.What is supposed to happen is that all the items from the FAX user's inbox are going to be moved to a Public Folder called 'FAX INBOX'. I am running this from a Linux box so I don't have access to any of the win32 extensions, although I could if I must. I can effectively iterate through the messages but they won't copy. I'm sure the rights are OK. I can also effectively iterate the 'Public folders/FAX INBOX' folder. Is this even possible to do? >Displaying tremendous intelligence on 02/07/03, Michael Montagne wrote: > #!/bin/python > > import getpass, imaplib > from mx.DateTime import * > import smtplib > cnt=0 > host="webmail" > address="montagne@boora.com" > faddress="fax@boora.com" > msg="Subject: Incoming Fax" > > > M = imaplib.IMAP4('mailserver') > M.login('FAX', 'faxpass') > cnt=M.select('INBOX') > print cnt > #print M.list() > typ, data = M.search(None, 'ALL') > > > for num in data[0].split(): > typ, data = M.fetch(num, '(RFC822)') > M.append("Public Folders/FAX INBOX",None,None,num) > M.copy(num,"Public Folders/FAX INBOX") > # M.store(num,'+FLAGS','\Deleted') > print ('%s' % (num)) > #M.expunge() > M.logout() > if cnt: > msg="Subject: Incoming Fax\n\n" + cnt[1][0] + " faxes just arrived" > s=smtplib.SMTP(host) > s.sendmail(faddress,address,msg) -- Michael Montagne http://www.themontagnes.com 503.226.1575 -- From jeff@ccvcorp.com Thu Jul 3 14:37:04 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 3 13:37:04 2003 Subject: [Tutor] is it a right choice? References: <20030703024420.GA1522@linux.local> Message-ID: <3F0469C4.9080200@ccvcorp.com> Payal Rathod wrote: >Hi, >Before I venture in the python infested world, I want to ask whether I >am making a right choice by taking python as my first programming >language. I cannot program in C, C++ or Java etc. I can *just* do little >shell scripting. > Opinions vary, of course, and since you're asking in a Python form it should hardly be surprising that replies you get will be favorable towards Python ;) Still, Python was designed from the start to be a language that would be easy for *everyone* to learn, even nonprogrammers, and there's a growing trend of using Python as a first language for teaching programming. So it seems reasonable to assume that it's a good choice for you. :) >My objective in learning a better language is that I have huge log files >in my office and get many logs files from friends who are sytem admins. >I love to analyse those files and find out browing habits of my compnay >(from squid logs), most number of mails sent to a domain ( like >hotmail), number of bytes data transferred thru' http, pop3 and smtp >etc. I prefer to write my own programs to do these things. >With rudimentary shell scripting knowledge analysing log files which are >many times over 200Mb is difficult so I was seeking a language which can >do these tasks beautifully without getting too much involved in >underlying concepts. >Am I looking for Python? Is Perl easier to learn for a newbie than >python? Is it OK to continue with Python? > For this sort of thing, I think Python is perfect. The interactive interpreter lets you play with your data, without needing a write/compile/run cycle, and there's lots of standard library modules that help you to handle standard protocols like http and pop3. (I've used the Python interpreter and poplib to check my home email from work without bothering to set up a profile in my email client.) Python has powerful string-handling capabilities, too, though there's a few minor tricks that should be kept in mind to keep large-scale string- and file-handling efficient. Perl, in contrast, may arguably be a bit stronger on the string-handling, but its syntax is very complex and confusing. It's much harder to figure out what's going on in a Perl program than it is to figure out a Python program -- this readability of Python is a *very* big advantage when it comes to learning, since it makes it much easier to pick up techniques from other programmers, not to mention a lot easier to see how that program you wrote last month works. (Trust me, after a month or two have passed since you wrote a program, you'll need to figure out how it works all over again, almost as much as if someone else had written it to begine with...) >Also can Python produce binary programs like perl (perlcc)? > > No, Python doesn't compile to binary, but that's not necessarily much of a disadvantage. Since Python is interpreted in a (relatively) platform-neutral way, it's easy to write scripts that run equally well on Windows and Unix, without needing to compile a version for each platform. And Python's dynamic nature (which is a large part of what makes it very difficult to compile to binary) has at least as many benefits as compiling to binary does -- the main advantage of binary code is speed, but that is not often an issue. (And when it is, you can always write a Python extension in C, which does the speed-critical parts of your calculations in a compiled library while letting you handle the overall architecture in Python.) If the motivation for binaries is to have a single self-contained executable to distribute, there's several utilities (Py2exe, McMillan Installer) that will package up a set of Python scripts with an interpreter into a single executable archive. This is not as space-efficient as a true compiled file, since it requires a new copy of the Python interpreter with each program, but it will allow your programs to run on computers that don't already have Python installed. Jeff Shannon Technician/Programmer Credit International From ATrautman@perryjudds.com Thu Jul 3 14:39:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu Jul 3 13:39:02 2003 Subject: [Tutor] is it a right choice? Message-ID: <06738462136C054B8F8872D69DA140DB01082B@corp-exch-1.pjinet.com> Payal, I was in your shoes a few years ago and knew I had to learn a scripting language. After looking at the functionality of both and writing test programs in both I made a few observations: 1. I never learned awk and *NIX shell scripting so all of Perl's symbols were new to me and very frustrating. Especially the multiuse $ sign. Python reads in English which I loved. 2. Perl had a lot more libraries and already configured apps, libraries and app plug ins. This is changing but I think it is still true. 3. They both have objects and object oriented methods so you can learn, demonstrate, and test any items that can be done in C,C++ or JAVA. In most (possibly all) cases you can write them faster in Python. I chose Python because it didn't feel like a lot of work to learn and I haven't found anything else I can't do with Python (I do use C++ for some work still). I'm sure the Perl people can tell you many things they can do and Python can't but the task you outline is the first business application task I used Python for and it is really good at that type of file parsing. In you case I certainly can't recommend C or C++ (to in-depth for no gain) but could recommend JAVA if you have in house/friends who are JAVA programmers to consult with. Personally Python would be my choice for the least headache most gain in the scenario you outlined. HTH, Alan -----Original Message----- From: Payal Rathod [mailto:payal-python@staticky.com] Sent: Wednesday, July 02, 2003 9:44 PM To: Python Tutor ML Subject: [Tutor] is it a right choice? Hi, Before I venture in the python infested world, I want to ask whether I am making a right choice by taking python as my first programming language. I cannot program in C, C++ or Java etc. I can *just* do little shell scripting. My objective in learning a better language is that I have huge log files in my office and get many logs files from friends who are sytem admins. I love to analyse those files and find out browing habits of my compnay (from squid logs), most number of mails sent to a domain ( like hotmail), number of bytes data transferred thru' http, pop3 and smtp etc. I prefer to write my own programs to do these things. With rudimentary shell scripting knowledge analysing log files which are many times over 200Mb is difficult so I was seeking a language which can do these tasks beautifully without getting too much involved in underlying concepts. Am I looking for Python? Is Perl easier to learn for a newbie than python? Is it OK to continue with Python? Also can Python produce binary programs like perl (perlcc)? Thanks, With warm regards, -Payal -- "Visit GNU/Linux Success Stories" http://payal.staticky.com Guest-Book Section Updated. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jmillr@umich.edu Thu Jul 3 15:10:02 2003 From: jmillr@umich.edu (John Miller) Date: Thu Jul 3 14:10:02 2003 Subject: [Tutor] tBoard In-Reply-To: <20030703032302.29897.15436.Mailman@mail.python.org> Message-ID: <6C7AF721-AD81-11D7-9FF6-00039303967A@umich.edu> On Wednesday, July 2, 2003, at 11:23 PM, Kyle Babich wrote: > I just launched pyBoards.com, please check it out. It's a community > for > Python programmers. You may want to check out a fairly recent project: http://tboard.sourceforge.net/ Perhaps a bit of encouragement offered to the developer (Tiberius Teng) would be worthwhile (Taiwanese high school student...) The download site is http://sourceforge.net/projects/tboard John Miller From Desai.Dinakar@mayo.edu Thu Jul 3 15:26:01 2003 From: Desai.Dinakar@mayo.edu (Dinakar) Date: Thu Jul 3 14:26:01 2003 Subject: [Tutor] ldap access from Python Help Message-ID: <3F047655.1050204@mayo.edu> Hello: I would like to use Python to access LDAP server to get email address and other info from our local ldap server. Can someone suggest what all the things I need to do to access. Do I need to install any modules or some other software. I am running Debian (testing) GNU/Linux and Python 2.2.3 Thank you very much. /dinakar From dyoo@hkn.eecs.berkeley.edu Thu Jul 3 15:53:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 3 14:53:02 2003 Subject: [Tutor] is it a right choice? [secondary languages besides Python] In-Reply-To: <06738462136C054B8F8872D69DA140DB01082B@corp-exch-1.pjinet.com> Message-ID: On Thu, 3 Jul 2003, Alan Trautman wrote: > In you case I certainly can't recommend C or C++ (to in-depth for no > gain) but could recommend JAVA if you have in house/friends who are JAVA > programmers to consult with. Hello! I can't recommend C as a first language. But I feel it's a good secondary language, particularly because it exposes a lot of the stupidity that goes on in a computer's hardware. *grin* C encourages putting oneself more into a low-level mindset, where we have to deal with gory details like memory management and pointer arithmetic and integer overflows. Learning C helps one to appreciate the features in a high-level language like Python, and will make you a better programmer. Java, too, will pose little problem once you learn Python: Java's very much like Python in a very rigid, concrete-reinforced straightjacket. The book "The C Programming Language", http://cm.bell-labs.com/cm/cs/cbook/ is well known for its brevity and depth, so if you're going to do C soon, look into K&R. Python's a very good first choice, not just because it is itself a great language, but because, when you want to branch out, it serves as a gateway to the other more "mainstream" languages. > Before I venture in the python infested world, ^^^^^^^^ Infested? This makes it sounds like Python is some sort of disease or something. *grin* Anyway, you can't really go too wrong with Python (or Perl). *grin* Just make sure it's not the only language you look at, if you're serious about learning how to program well. > I want to ask whether I am making a right choice by taking python as my > first programming language. I cannot program in C, C++ or Java etc. I > can *just* do little shell scripting. One other alternative beginners language you might want to check is Scheme. There's a good implementation of Scheme from the PLT Scheme folks: http://www.plt-scheme.org/ Scheme is definitely not mainstream. But it does have a good get of libraries, and quite a few good books both on paper and online: http://www.cs.berkeley.edu/~bh/simply-toc.html http://mitpress.mit.edu/sicp/ http://www.htdp.org/ The Scheme community appears to be much more academically oriented than others --- this may be a good thing or a bad thing, depending on your background. Good luck to you! From DORSEY_EDMUND_K@LILLY.COM Thu Jul 3 17:39:04 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Thu Jul 3 16:39:04 2003 Subject: [Tutor] Memory Problem Message-ID: This is a multipart message in MIME format. --=_alternative 0071495E05256D58_= Content-Type: text/plain; charset="us-ascii" My python crashes on large datasets and works fine with small ones. When it crashes it just tells me it's a memory error. What's odd is that I have 2 GB of memory and the dataset I am loading is only 35 MB. The process I am running on the data creates a file 8 times larger. So that would be 280 MB which still seems to leave plenty of memory. It says the problem is with this line of code return x + (y*self._newXsize) + z * (self._newXY) Here the value returned ranges from 0 to about 100 million I have a function which runs a loop do I need to delete anything to free up space? For example, if you have a function foo def foo(self): x = 1 y = 2 z = 3 return x*y*z and call it a million times from another function ie. def callFoo(self): for i in range(0, 1000000000): self.foo() Do the x,y,z variables in foo get deleted or does it need to be done manually? Thank you. ~Ed --=_alternative 0071495E05256D58_= Content-Type: text/html; charset="us-ascii"
My python crashes on large datasets and works fine with small ones. When it crashes it just tells me it's a memory error.

What's odd is that I have 2 GB of memory and the dataset I am loading is only 35 MB.  The process I am running on the data creates a file 8 times larger.  So that would be 280 MB which still seems to leave plenty of memory.

It says the problem is with this line of code

return x + (y*self._newXsize) + z * (self._newXY)

Here the value returned ranges from 0 to about 100 million

I have a  function which runs a loop do I need to delete anything to free up space?  For example, if you have a function foo

def foo(self):
    x = 1
    y = 2
    z = 3
    return x*y*z

and call it a million times from another function ie.

def callFoo(self):
    for i in range(0, 1000000000):
        self.foo()

Do the x,y,z variables in foo get deleted or does it need to be done manually?  

Thank you. ~Ed

--=_alternative 0071495E05256D58_=-- From thomi@thomi.imail.net.nz Thu Jul 3 20:24:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 3 19:24:01 2003 Subject: [Tutor] checking for class version info. In-Reply-To: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> References: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> Message-ID: <20030704112303.66bb8f6b.thomi@thomi.imail.net.nz> i guess that from the HUGE non-reply this thread has gotten that it's not possible, correct? ahh well... -- Thomi Richards, thomi@thomi.imail.net.nz From magnus@thinkware.se Thu Jul 3 22:41:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 3 21:41:02 2003 Subject: [Tutor] Memory Problem In-Reply-To: Message-ID: <5.2.1.1.0.20030704033042.01efca50@www.thinkware.se> At 15:37 2003-07-03 -0500, DORSEY_EDMUND_K@LILLY.COM wrote: >def callFoo(self): > for i in range(0, 1000000000): > self.foo() Ouch! The range function builds a list of integers, so you allocate space both for the list object, and for the integer objects in the list. Each integer object takes up four bytes, and I think each list item (which is a pointer) takes up four bytes as well. That would mean that you allocate 8 GB of memory when you do range(0, 1000000000). (BTW, range(0,x) is the same as range(x).) If you just use xrange() instead of range(), you won't create any list, but I don't know if Python will actually release the memory used for integers, since they are interned. (That integers are interned means that if you use 42 in several different places in your code, it will always use the same integer object.) If your memory usage doesn't go down to something much, much smaller with def callFoo(self): for i in xrange(1000000000): self.foo() you could try: def callFoo(self): for i in xrange(1000): for j in xrange(1000): for k in xrange(1000): self.foo() Now, you will only use roughly 4kB, instead of 8GB. That's much less memory, right? :) All integers from 0 to 999 will be created (and interned). The same integers will be used in the three loops. No list objects will be created, xrange will just return a new value for each turn in the loop. >Do the x,y,z variables in foo get deleted or does it need to be done >manually? x, y, z are deleted just fine. That's not your problem. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Thu Jul 3 22:47:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 3 21:47:02 2003 Subject: [Tutor] checking for class version info. In-Reply-To: <20030704112303.66bb8f6b.thomi@thomi.imail.net.nz> References: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030704035018.01efffe8@www.thinkware.se> At 11:23 2003-07-04 +1200, Thomas CLive Richards wrote: >i guess that from the HUGE non-reply this thread has gotten that it's >not possible, correct? I'm not sure I ever saw the original posting. Can you give a pointer to where it is in the archives? (Or post again.) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From thomi@thomi.imail.net.nz Thu Jul 3 22:50:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 3 21:50:01 2003 Subject: [Tutor] checking for class version info. In-Reply-To: <5.2.1.1.0.20030704035018.01efffe8@www.thinkware.se> References: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> <5.2.1.1.0.20030704035018.01efffe8@www.thinkware.se> Message-ID: <20030704134907.2cc934ca.thomi@thomi.imail.net.nz> hmmm.. maybe my email stuffed up. It wouldn't be the first time... Hey, I have the following problem: I have developed a small program which saves (using the pickle module) some classes, and loads them at a later date. The trouble is, the program is under active development, and the contents of the classes are changing constantly. What i would like to do, is invent some way so that as the classes are loaded, they automatically detect if they are the save "version" as the current class in the program source file. If they are not, they somehow "re-initialise" themselves in the new class. does that make sense? the first way i thought i would do it is generate some sort of unique identifier for the source code file each class is in (the code is such that every class is in a separate file - this cannot be changed); the size of the file in bytes would probably be enough for this (or perhaps the last modification time?). However, that would mean that simple adding a comment to the class would cause the class to reload, and that wouldn't be too good. then i thought about having a variable in each class called "version", or something similar, so that when a developer updates a class significantly, he can change the version number, and the classes would reload themselves, if their version number didn't match that in the class source code file. The trouble with that is that developers are lazy, and would probably forget. Also, i have no idea how to go about doing this "reloading". It may be that the objects will have to be re-created every time the class changes, or that I'll have to make a conversion script, but there you go, any ideas? where should i go from here? thanks, -- Thomi Richards, thomi@thomi.imail.net.nz From bgailer@alum.rpi.edu Thu Jul 3 23:04:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Thu Jul 3 22:04:01 2003 Subject: [Tutor] checking for class version info. In-Reply-To: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030703190342.074b0a38@66.28.54.253> --=======4B2D47A0======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-7B3454B; boundary="=====================_44158977==.ALT" --=====================_44158977==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-7B3454B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:23 AM 7/4/2003 +1200, you wrote: >i guess that from the HUGE non-reply this thread has gotten that it's >not possible, correct? OK, I'll take a shot at it. At 11:39 PM 7/2/2003 +1200, Thomas CLive Richards wrote: >I have developed a small program which saves (using the pickle module) >some classes, and loads them at a later date. The trouble is, the >program is under active development, and the contents of the classes are >changing constantly. What i would like to do, is invent some way so that >as the classes are loaded, they automatically detect if they are the >save "version" as the current class in the program source file. If they >are not, they somehow "re-initialise" themselves in the new class. does >that make sense? It does, but you may be confusing classes and instances. The instances are what you'd need to re-initialise, no? >the first way i thought i would do it is generate some sort of unique >identifier for the source code file each class is in (the code is such >that every class is in a separate file - this cannot be changed); the >size of the file in bytes would probably be enough for this (or perhaps >the last modification time?). However, that would mean that simple >adding a comment to the class would cause the class to reload, and that >wouldn't be too good. > >then i thought about having a variable in each class called "version", >or something similar, so that when a developer updates a class >significantly, he can change the version number, and the classes would >reload themselves, if their version number didn't match that in the >class source code file. The trouble with that is that developers are >lazy, and would probably forget. > >Also, i have no idea how to go about doing this "reloading". It may be >that the objects will have to be re-created every time the class >changes, or that I'll have to make a conversion script, but there you go Here is how pickle handles re-initialising. From the pickle docs: "When a pickled class instance is unpickled, its __init__() method is normally not invoked. If it is desirable that the __init__() method be called on unpickling, a class can define a method __getinitargs__(), which should return a tuple containing the arguments to be passed to the class constructor (i.e. __init__()). The __getinitargs__() method is called at pickle time; the tuple it returns is incorporated in the pickle for the instance. Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the return state is pickled as the contents for the instance, instead of the contents of the instance's dictionary. If there is no __getstate__() method, the instance's __dict__ is pickled. Upon unpickling, if the class also defines the method __setstate__(), it is called with the unpickled state. If there is no __setstate__() method, the pickled object must be a dictionary and its items are assigned to the new instance's dictionary. If a class defines both __getstate__() and __setstate__(), the state object needn't be a dictionary and these methods can do what they want." Based on this you could accomplish the mechanics by using __getinitargs__ or __setstate__. Here's how __getinitargs__ could work: design __init__ to take a version # as an argument. Save the old version number (class property) using __getinitargs__ and have __init__ compare that to the current version number to decide if things needed to be re-initialised. class Foo: def __init__(self, version): if version != self.version: reinitialise code goes here self.version = '0.9.1' def __getinitargs__(): return (self.version, ) The issue of HOW to recognize changes or enforce developers to maintain version #s is of course a different topic. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_44158977==.ALT Content-Type: text/html; x-avg-checked=avg-ok-7B3454B; charset=us-ascii Content-Transfer-Encoding: 8bit At 11:23 AM 7/4/2003 +1200, you wrote:

i guess that from the HUGE non-reply this thread has gotten that it's
not possible, correct?

OK, I'll take a shot at it.

At 11:39 PM 7/2/2003 +1200, Thomas CLive Richards wrote:
I have developed a small program which saves (using the pickle module)
some classes, and loads them at a later date. The trouble is, the
program is under active development, and the contents of the classes are
changing constantly. What i would like to do, is invent some way so that
as the classes are loaded, they automatically detect if they are the
save "version" as the current class in the program source file. If they
are not, they somehow "re-initialise" themselves in the new class. does
that make sense?

It does, but you may be confusing classes and instances. The instances are what you'd need to re-initialise, no?

the first way i thought i would do it is generate some sort of unique
identifier for the source code file each class is in (the code is such
that every class is in a separate file - this cannot be changed); the
size of the file in bytes would probably be enough for this (or perhaps
the last modification time?). However, that would mean that simple
adding a comment to the class would cause the class to reload, and that
wouldn't be too good.

then i thought about having a variable in each class called "version",
or something similar, so that when a developer updates a class
significantly, he can change the version number, and the classes would
reload themselves, if their version number didn't match that in the
class source code file. The trouble with that is that developers are
lazy, and would probably forget.

Also, i have no idea how to go about doing this "reloading". It may be
that the objects will have to be re-created every time the class
changes, or that I'll have to make a conversion script, but there you go

Here is how pickle handles re-initialising. From the pickle docs:

"When a pickled class instance is unpickled, its __init__() method is normally not invoked. If it is desirable that the __init__() method be called on unpickling, a class can define a method __getinitargs__(), which should return a tuple containing the arguments to be passed to the class constructor (i.e. __init__()). The __getinitargs__() method is called at pickle time; the tuple it returns is incorporated in the pickle for the instance.

Classes can further influence how their instances are pickled; if the class defines the method __getstate__(), it is called and the return state is pickled as the contents for the instance, instead of the contents of the instance's dictionary. If there is no __getstate__() method, the instance's __dict__ is pickled.
Upon unpickling, if the class also defines the method __setstate__(), it is called with the unpickled state. If there is no __setstate__() method, the pickled object must be a dictionary and its items are assigned to the new instance's dictionary. If a class defines both __getstate__() and __setstate__(), the state object needn't be a dictionary and these methods can do what they want."

Based on this you could accomplish the mechanics by using __getinitargs__ or __setstate__. Here's how __getinitargs__ could work:

design __init__ to take a version # as an argument. Save the old version number (class property) using __getinitargs__ and have  __init__ compare that to the current version number to decide if things needed to be re-initialised.

class Foo:

  def __init__(self, version):
    if version != self.version:
      reinitialise code goes here
      self.version = '0.9.1'

  def __getinitargs__():
      return (self.version, )

The issue of HOW to recognize changes or enforce developers to maintain version #s is of course a different topic.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_44158977==.ALT-- --=======4B2D47A0======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-7B3454B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.492 / Virus Database: 291 - Release Date: 6/24/2003 --=======4B2D47A0=======-- From jmricker@nc.rr.com Thu Jul 3 23:38:04 2003 From: jmricker@nc.rr.com (Jody) Date: Thu Jul 3 22:38:04 2003 Subject: [Tutor] is it a right choice? In-Reply-To: <06738462136C054B8F8872D69DA140DB01082B@corp-exch-1.pjinet.com> Message-ID: <004c01c341d5$40b0e480$1d944a18@joelom35kpq2rs> Someone on the Useless Python list mentioned recently this article: http://www.peek-a-booty.org/pbhtml/index.php. The author of this article discusses the problems that he ran into when it came to compiled = languages like C++ and how much easier the project will be when he switches to = Python. Also, something I don't believed anyone has mentioned regarding Python = is the wonderful community you get with it. Having learned many languages myself and being involved in the communities associated with them, the openness of sharing and teaching that prevails in this mailing list and other Python related areas is very unique. I've seen other groups where = the users are openly hostile to new programmers and do not encourage = questions or give much help and instead take a "for me to know and for you to find out" attitude. With Python, people are very willing to be patient with = you as long as you are patient with them. That is the #1 reason I've stuck = with Python over any language. Jody From idiot1@netzero.net Fri Jul 4 00:17:05 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 3 23:17:05 2003 Subject: [Tutor] email stuff in python Message-ID: <3F04F180.2010002@netzero.net> well, by now you know that python email is what I like to do. Recently, having dealt with a lot of spam, I decided to create an alias to trap and save spam for later examination by our coven of dread legal vampires- simple, an alias feeds it to a file where it is appended, and a ssi include in a web page lets us inspect the contents any time I like. This looks like: More on this later on. Then I realized, this is what a local delivery program does. So I wrote a simple program to absorb the input from an alias, and write it out to a file for later access. With more work, such a program could listen to an incoming port and receive email, extract the TO: field data, and send the message to a pop3 mailbox, or to an alternate destination were one defined, or just eat it. I may just write one as a giggle later on this weekend. Anyroad, it's useless, but is a working example of using stdin to accept email from an alias and do something intresting with it. Possible useless python candidate? OK, it's later. An intresting challenge is to get the browser to preserve paragraphing and composition and still word wrap the display to fit the screen. See, simple html wordwraps, but ignores newlines, obliterating the spacing of paragraphs and ending lines where you want them to. As some email transmission clients depend on the recipient to wrap to fit space, they tend to send on one line until you click the [return] key, which looks terrible in a

 zone.

My quick and dirty solution is to use a textarea, and until I find a simple and powerful 
alternate, that's how I will address such issues in the future.

Anyonw who wants to see this thing click here:
http://www.tinylist.org/mailbox.shtml

To email something to it and see the result, email:
mailto:mailbox@tinylist.org

Here is the actual script:

#!/usr/local/bin/python
import sys, string
#
def gangstrip(thing):                   # ok, everybody STRIP!
         index=0                         # This strips out whitespace chars
         while index < len(thing):       # define exit
                 thing[index]=string.rstrip(thing[index])
                 index=index+1           # increase the counter
#
filename=sys.argv[1]    # the idea is the alias has a command line arguement
pwd='/www/www.tinylist.org/cgi-bin/'
print pwd
msg=sys.stdin.readlines() #and standard_in receives the entire message.
gangstrip(msg)
f1=open(pwd+filename,'a')
for line in msg:
         f1.write(line+'\n')
f1.close()


-- 

end

Cheers!
         Kirk D Bailey
                               think
http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/
http://www.listville.net/    | BOX | http://www.sacredelectron.org/
                              +-----+
"Thou art free"-ERIS          think    'Got a light?'-Promethieus

.



From abli@freemail.hu  Fri Jul  4 03:04:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Fri Jul  4 02:04:01 2003
Subject: [Tutor] Memory Problem
In-Reply-To: <5.2.1.1.0.20030704033042.01efca50@www.thinkware.se>
References:  <5.2.1.1.0.20030704033042.01efca50@www.thinkware.se>
Message-ID: <20030704060258.GA639@hooloovoo>

Magnus Lyck? wrote:
> If you just use xrange() instead of range(), you won't create any
> list, but I don't know if Python will actually release the memory
> used for integers, since they are interned. (That integers are interned
> means that if you use 42 in several different places in your code, it
> will always use the same integer object.)
Isn't this only done for small ( < 100) integers?

>>> a=99
>>> b=99
>>> id(a)
135432252
>>> id(b)
135432252
>>> a=100
>>> b=100
>>> id(a)
135431964
>>> id(b)
135432000

Abel Daniel


From yduppen@xs4all.nl  Fri Jul  4 05:14:01 2003
From: yduppen@xs4all.nl (Yigal Duppen)
Date: Fri Jul  4 04:14:01 2003
Subject: [Tutor] checking for class version info.
In-Reply-To: <20030704112303.66bb8f6b.thomi@thomi.imail.net.nz>
References: <20030702233925.6cb79b60.thomi@thomi.imail.net.nz> <20030704112303.66bb8f6b.thomi@thomi.imail.net.nz>
Message-ID: <200307041013.52946.yduppen@xs4all.nl>

=2D----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On Friday 04 July 2003 01:23, Thomas CLive Richards wrote:
> i guess that from the HUGE non-reply this thread has gotten that it's
> not possible, correct?

It seems to be possible; just not that easy. A quick look on "python=20
persistence" resulted, among others, in the following article:

http://www-106.ibm.com/developerworks/linux/library/l-pypers.html

The chapter "Schema evolution" seems to be what you're looking for. It also=
=20
contains a link to ZODB, a different way of managing persistence.

YDD
=2D --=20
http://www.xs4all.nl/~yduppen
=2D----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQE/BTdALsKMuCf5EdwRAtHVAKCsv9NLnCi5XJk2nkkPknMLNrSEpwCg5rYk
6PWXl/cFgmV1HSzP8vRBxBo=3D
=3DHJBS
=2D----END PGP SIGNATURE-----



From jim_938@hotmail.com  Fri Jul  4 05:40:03 2003
From: jim_938@hotmail.com (Jimmy verma)
Date: Fri Jul  4 04:40:03 2003
Subject: [Tutor] Multiplication without overflow
Message-ID: 

Hello Sir,

I am having some problem in understanding this small one line function in 
python.

def u16mult(a,b):
  return ((a*(b&0x0fff)&0xffff)+(((a*(b>>12))&0x000f)<<12))&0xffff

we need a multiplication function that will handle 16-bit unsigned values 
without the overflow that 32-bit signed values can suffer from.

I am not getting completely how this is being done here. I need some 
suggestions regarding this.

Thanks in advance.

Regards,
Jim

_________________________________________________________________
Race along with NK. The fastest Indian 
http://server1.msn.co.in/sp03/tataracing/index.asp Feel the thrill!



From sudhirchauhan1@yahoo.co.in  Fri Jul  4 05:59:02 2003
From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=)
Date: Fri Jul  4 04:59:02 2003
Subject: [Tutor] Getting list of installed software on a Windows 2000/XP machine
In-Reply-To: 
Message-ID: <20030704085736.53690.qmail@web8206.mail.in.yahoo.com>

--0-1231372990-1057309056=:53434
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit

Dear All,
 
 How I can get the list of installed softwares on Windows  machine using Perl. any pointers will be helpful
 
Regards,
 
Sudhir


 

SMS using the Yahoo! Messenger;Download latest version.
--0-1231372990-1057309056=:53434
Content-Type: text/html; charset=iso-8859-1
Content-Transfer-Encoding: 8bit

Dear All,
 
 How I can get the list of installed softwares on Windows  machine using Perl. any pointers will be helpful
 
Regards,
 
Sudhir


 

Yahoo! India Mobile SMS using the Yahoo! Messenger; Download latest version. --0-1231372990-1057309056=:53434-- From sudhirchauhan1@yahoo.co.in Fri Jul 4 06:02:26 2003 From: sudhirchauhan1@yahoo.co.in (=?iso-8859-1?q?sudhir=20chauhan?=) Date: Fri Jul 4 05:02:26 2003 Subject: [Tutor] Getting list of installed software on a Windows 2000/XP machine In-Reply-To: <20030704085736.53690.qmail@web8206.mail.in.yahoo.com> Message-ID: <20030704090109.45898.qmail@web8204.mail.in.yahoo.com> sorry i mean python :) --- sudhir chauhan wrote: > Dear All, > > How I can get the list of installed softwares on > Windows machine using Perl. any pointers will be > helpful > > Regards, > > Sudhir > > > > > SMS using the Yahoo! Messenger;Download latest version. ________________________________________________________________________ Send free SMS using the Yahoo! Messenger. Go to http://in.mobile.yahoo.com/new/pc/ From abli@freemail.hu Fri Jul 4 06:30:03 2003 From: abli@freemail.hu (Abel Daniel) Date: Fri Jul 4 05:30:03 2003 Subject: [Tutor] Multiplication without overflow In-Reply-To: References: Message-ID: <20030704092911.GA842@hooloovoo> Jimmy verma wrote: > I am having some problem in understanding this small one line function in > python. > > def u16mult(a,b): > return ((a*(b&0x0fff)&0xffff)+(((a*(b>>12))&0x000f)<<12))&0xffff > > we need a multiplication function that will handle 16-bit unsigned values > without the overflow that 32-bit signed values can suffer from. What overflow? Python 2.2.2 (#1, Mar 21 2003, 23:01:54) [GCC 3.2.3 20030316 (Debian prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=2**32 >>> a 4294967296L >>> a*a 18446744073709551616L >>> Abel Daniel From Suresh Kumar" Hi, In Tkinter, how to convert canvas coordinates to window coordinates? To convert window coordinates to canvas coordinates we are using "canvasx,canvasy". But how to do vice-versa? With Regards, V.Suresh Kumar. ___________________________________________________ Click below to experience Sooraj R Barjatya's latest offering 'Main Prem Ki Diwani Hoon' starring Hrithik, Abhishek & Kareena http://www.mpkdh.com From Anish.Mehta@enst-bretagne.fr Fri Jul 4 09:28:02 2003 From: Anish.Mehta@enst-bretagne.fr (Mehta, Anish) Date: Fri Jul 4 08:28:02 2003 Subject: [Tutor] match? Message-ID: <3F05778D.7050906@antares.enst-bretagne.fr> Hello *.*, Can someone suggest me sthig abt this : num = re.compile("\-?[0-9]+(\.[0-9]+)?") What kind of pattern i can match with this. Thanks in advance. Regards, Anish From python@kyle.sent.com Fri Jul 4 10:08:01 2003 From: python@kyle.sent.com (Kyle Babich) Date: Fri Jul 4 09:08:01 2003 Subject: [Tutor] FYI In-Reply-To: <3F04ECA8.5050305@netzero.net> References: <20030703014802.A9DBB6BC69@smtp.us2.messagingengine.com> <3F04ECA8.5050305@netzero.net> Message-ID: <20030704130729.F3CB37210A@smtp.us2.messagingengine.com> Sure... http://www.pyboards.com/ On Thu, 03 Jul 2003 22:55:36 -0400, "Kirk Bailey" said: > fine, great, glad to hear it. > > Um, Kyle, could you post the url to it on this list for us all to click > on? > It helps... > > > Kyle Babich wrote: > > I just launched pyBoards.com, please check it out. It's a community for > > Python programmers. > > -- > > Kyle > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > > end > > Cheers! > Kirk D Bailey > think > http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ > http://www.listville.net/ | BOX | http://www.sacredelectron.org/ > +-----+ > "Thou art free"-ERIS think 'Got a light?'-Promethieus > > . > > -- Kyle pyBoards.com :: A community for Python programmers From shalehperry@comcast.net Fri Jul 4 10:49:03 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Fri Jul 4 09:49:03 2003 Subject: [Tutor] match? In-Reply-To: <3F05778D.7050906@antares.enst-bretagne.fr> References: <3F05778D.7050906@antares.enst-bretagne.fr> Message-ID: <200307040648.22096.shalehperry@comcast.net> On Friday 04 July 2003 05:48, Mehta, Anish wrote: > Hello *.*, > > Can someone suggest me sthig abt this : > > num = re.compile("\-?[0-9]+(\.[0-9]+)?") > > What kind of pattern i can match with this. > break it down: \-? zero or one dash (or minus sign) [0-9]+ one or more numbers in the range 0 - 9 ( begin a group \.[0-9]+ of one or more numbers, preceded by a period )? that can occur once or not at all. So this matches: 9 -987 2.5 3.72 -5.300 -12345.6789 and so on. In other words, it appears to be designed to match any real number. From silviucc@home.ro Fri Jul 4 11:00:17 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Fri Jul 4 10:00:17 2003 Subject: [Tutor] EOF function Message-ID: I want to write a function that will return 1 if EndOfFile is reached and 0 if not. Problem is I have no idea how that's done. Maybe there is a function that could return the current position in a file and if the char at that position is the EOF char then return 1. Problems: I do not know the escape sequence for EOF I do not know a function that returns the current position in a file so maybe I need to write it as well :/ and again I would be at a loss. If anyone can help me, I would be grateful. -- Registered Linux user #298569 In this vale Of toil and sin Your head grows bald But not your chin. -- Burma Shave From Shey@argonaut.com Fri Jul 4 11:54:03 2003 From: Shey@argonaut.com (Shey Crompton) Date: Fri Jul 4 10:54:03 2003 Subject: [Tutor] wxPython demo Message-ID: <415C917D807AD411B72C00805FF7330B053F8757@MAILSRV> Hi all, Apologies if this is the wrong mailing list. I thought I would install wxPython this afternoon, and see what the demo was like. I have installed everything off the wxPython.org site, but when I choose 'run the wxPython demo' from the start menu, I get a flash up on the screed, which disappears quickly, and then nothing. Does anyone have an idea of what I'm doing wrong, and how to run the demo? I'm on win2k pro, and downloaded the wxPython for python 2.2, which I have installed. Also, is there an editor that is tailored to wxPython (I don't know if one came with it)? Sorry if these are obvious questions. Any help would be greatly appreciated. Thanks, Shey From pythontutor@venix.com Fri Jul 4 12:01:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Fri Jul 4 11:01:02 2003 Subject: [Tutor] EOF function References: Message-ID: <3F05965C.3010805@venix.com> I suspect you are writing in Python, but thinking in C. However, I'll try to help. There is no escape sequence for EOF. Very old MS-DOS used a (chr(26)) character to mark the end of a file. The normal process is that the OS knows how many bytes are in a file. Trying to read more than that means you have reached the EOF. The Python file object includes methods: tell seek tell reports the current position, an offset in bytes from the start of the file. seek allows you to set the position within the file using an offset and specifying if that offset is relative to the start, current position, or end of the file. You can use the os and stat modules to find the size of a file. import os, stat file_size = os.stat(file_path_name)[stat.ST_SIZE] myfile = file(file_path_name,'rb') mydata = myfile.read(1000) if myfile.tell() < file_size: print "more data" else: print "reached end" os.stat returns a tuple. The stat module provides constants for decoding the tuple. For more detail see the module documentation. Now the file objects read methods will return '' when there is no more data to be read. I would expect that it is easier to read and get a '' than it is to constantly check the file position before reading. Silviu Cojocaru wrote: > I want to write a function that will return 1 if EndOfFile is reached > and 0 if not. Problem is I have no idea how that's done. Maybe there is > a function that could return the current position in a file and if the > char at that position is the EOF char then return 1. > > Problems: > I do not know the escape sequence for EOF > I do not know a function that returns the current position in a file so > maybe I need to write it as well :/ and again I would be at a loss. > > If anyone can help me, I would be grateful. > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From monashee@junction.net Fri Jul 4 13:30:23 2003 From: monashee@junction.net (J or M Montgomery) Date: Fri Jul 4 12:30:23 2003 Subject: [Tutor] Re: Linux versions In-Reply-To: <5.2.1.1.0.20030703140058.01fd1df8@www.thinkware.se> References: <5.2.1.1.0.20030702151758.01f949b8@www.thinkware.se> <5.2.1.1.0.20030703140058.01fd1df8@www.thinkware.se> Message-ID: <200307040927.13164.monashee@junction.net> On Thursday 03 July 2003 06:37, Magnus Lyck=E5 wrote: > After massive pruning. > I've tried to get started with Debian a few times, but I always gave up > before I had a running system.=20 > I have had exactly the same experience with Debian. I use Mandrake and t= he=20 setup and installation is faster, more complete and much much simpler tha= n=20 Win 98 offers. In addition, the Mandrake community is very generous with= =20 helping out and tolerate the less skillful very well. Cheers John Montgomery From magnus@thinkware.se Fri Jul 4 18:58:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 4 17:58:02 2003 Subject: [Tutor] Memory Problem In-Reply-To: <20030704060258.GA639@hooloovoo> References: <5.2.1.1.0.20030704033042.01efca50@www.thinkware.se> <5.2.1.1.0.20030704033042.01efca50@www.thinkware.se> Message-ID: <5.2.1.1.0.20030704230905.01ff3e28@www.thinkware.se> At 08:02 2003-07-04 +0200, Abel Daniel wrote: >Magnus Lyck? wrote: > > If you just use xrange() instead of range(), you won't create any > > list, but I don't know if Python will actually release the memory > > used for integers, since they are interned. (That integers are interned > > means that if you use 42 in several different places in your code, it > > will always use the same integer object.) >Isn't this only done for small ( < 100) integers? Oh, I didn't know that. Thanks! Is that a recent change? I seem to remember that construction of big ranges was a problem, since the integers weren't garbage collected. Making a one billion item list with range will still use 8 GB of memory though, but if the big integers go away when we no longer use them, xrange(1000000000) should present no problems. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From project5@redrival.net Fri Jul 4 19:03:01 2003 From: project5@redrival.net (Andrei) Date: Fri Jul 4 18:03:01 2003 Subject: [Tutor] Re: wxPython demo In-Reply-To: <415C917D807AD411B72C00805FF7330B053F8757@MAILSRV> References: <415C917D807AD411B72C00805FF7330B053F8757@MAILSRV> Message-ID: Shey Crompton wrote: > Hi all, > Apologies if this is the wrong mailing list. There is a wxPython mailing list (link on the wxpython site). > I have installed everything off the wxPython.org site, but when I choose > 'run the wxPython demo' from the start menu, I get a flash up on the screed, > which disappears quickly, and then nothing. Open a console (Start -> Run -> "cmd" or "command", I'm not sure which one you get with win2k) and go to "\Lib\site-packages\wxPython\demo" (use "cd " to switch directories in dos mode). When you're there, type "python demo.py". You'll get a traceback in the console. Copy it to clipboard and ask for help using that traceback. Btw, this traceback appears now when you start the demo, but only very, very briefly as the console is automatically shut down if you use the Start menu shortcut for the demo. > Does anyone have an idea of what I'm doing wrong, and how to run the demo? > I'm on win2k pro, and downloaded the wxPython for python 2.2, which I have > installed. My guess would be a mismatch between your Python version and the wxPython version, as I've never had any problems with the demo. But the traceback should give more info. > Also, is there an editor that is tailored to wxPython (I don't know if one > came with it)? PyCrust is a shell written in wxPython and included in the distro, but I don't think you need a special editor for wxPython. Perhaps you're looking for an IDE like Boa Constructor or wxGlade (both are open source). There's also wxDesigner, but that one's not free. I use wxGlade to generate GUI code and subclass that to add functionality, working in the Scite editor. Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From magnus@thinkware.se Fri Jul 4 20:53:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 4 19:53:01 2003 Subject: [Tutor] EOF function In-Reply-To: Message-ID: <5.2.1.1.0.20030705015648.01f7e720@www.thinkware.se> At 17:16 2003-07-04 +0300, Silviu Cojocaru wrote: >I want to write a function that will return 1 if EndOfFile is reached >and 0 if not. Why? What are you *really* trying to achieve. This is nothing you normally need in Python. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Fri Jul 4 21:02:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 4 20:02:02 2003 Subject: [Tutor] wxPython demo In-Reply-To: <415C917D807AD411B72C00805FF7330B053F8757@MAILSRV> Message-ID: <5.2.1.1.0.20030705015811.01f5b890@www.thinkware.se> At 15:56 2003-07-04 +0100, Shey Crompton wrote: >Hi all, >Apologies if this is the wrong mailing list. The wxpython mailing list is probably better... >I thought I would install wxPython this afternoon, and see what the demo was >like. Good idea! :) >I have installed everything off the wxPython.org site, but when I choose >'run the wxPython demo' from the start menu, I get a flash up on the screed, >which disappears quickly, and then nothing. Try this: Start -> Run cmd.exe Type "cd " and then drop the lib/site-packages/wxPython/demo directory from Explorer on the command prompt. Press enter. You should now be in the wxPython/demo directory. Type "python demo.py". What happens? What error messages do you get? >Also, is there an editor that is tailored to wxPython (I don't know if one >came with it)? What do you mean? Any editor can be used with wxPython. Are you after a GUI builder or a GUI debugger or what? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Sat Jul 5 08:06:15 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sat Jul 5 07:06:15 2003 Subject: [Tutor] EOF function In-Reply-To: References: <5.2.1.1.0.20030705015648.01f7e720@www.thinkware.se> Message-ID: <5.2.1.1.0.20030705125330.01f782a8@www.thinkware.se> At 13:15 2003-07-05 +0300, Silviu Cojocaru wrote: >On Sat, 5 Jul 2003, Magnus Lyck=E5 wrote: > > > At 17:16 2003-07-04 +0300, Silviu Cojocaru wrote: > > >I want to write a function that will return 1 if EndOfFile is reached > > >and 0 if not. > > > > Why? What are you *really* trying to achieve. > > This is nothing you normally need in Python. > >I was trying to read a file line by line. Being used to Pascal I tried >the Pascal way :) Then a post to the tutor list enlightened me. There >was something about using readlines(). So I did :) It shrank the code I >have already written and working to half its size, and it even worked >better :) But .readlines() reads the whole file at once, and puts it in a list. That might be a problem with a big file. With modern python versions, you can simply iterate over the file object. f =3D file(filename) for line in f: print line, f.close() If you are lazy, you can simply do for line in file(filename): print line, Note that each line will end with a line-feed (or whatever you have on your platform). That's why I end the print statement with a comma--do avoid double line feeds. Note that you don't explicitly close the file in the shorter version. I the current C based version of Python, I think it will be closed as soon as the loop ends, but the language doesn't guarantee that, and in the Java implementation of Python--Jython, the file might not be closed just yet. Java's garbage collection handles that. This means that there might be problems with a long-running program, or if you want to open the same file for writing further ahead. In other words, you might want to get a reference to the file object and close it explicitly as soon as you can unless you know that it's ok to leave it open until the program terminates--at least if you want to be sure that your program works as well in five years as it does now. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From silviucc@home.ro Sat Jul 5 08:34:01 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Sat Jul 5 07:34:01 2003 Subject: [Tutor] EOF function In-Reply-To: <5.2.1.1.0.20030705125330.01f782a8@www.thinkware.se> Message-ID: On Sat, 5 Jul 2003, Magnus Lyck=E5 wrote: > But .readlines() reads the whole file at once, and puts it in a list. > That might be a problem with a big file. With modern python versions, > you can simply iterate over the file object. >=20 > f =3D file(filename) > for line in f: > print line, > f.close() >=20 > If you are lazy, you can simply do >=20 > for line in file(filename): > print line, >=20 > Note that each line will end with a line-feed (or whatever you > have on your platform). That's why I end the print statement > with a comma--do avoid double line feeds. >=20 > Note that you don't explicitly close the file in the shorter version. > I the current C based version of Python, I think it will be closed as > soon as the loop ends, but the language doesn't guarantee that, and in > the Java implementation of Python--Jython, the file might not be closed > just yet. Java's garbage collection handles that. >=20 > This means that there might be problems with a long-running program, > or if you want to open the same file for writing further ahead. >=20 > In other words, you might want to get a reference to the file object > and close it explicitly as soon as you can unless you know that it's > ok to leave it open until the program terminates--at least if you want > to be sure that your program works as well in five years as it does now. Yeah I never looked at the builtin objects . I imported "os" and used=20 readlines(). It was kinda intuitive like: "Hey where should the stuff=20 for manipulating files be? well there's no file module so lemme have a=20 look in the os module. Hey, here they are!" :) Thanks for the pointers ! --=20 Registered Linux user #298569 This fortune is false. From silviucc@home.ro Sat Jul 5 10:39:01 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Sat Jul 5 09:39:01 2003 Subject: [Tutor] OT: useless python webpage Message-ID: Is this website still maintained ? I want to send solutions to a few of the problems in the ACM prog. contest plus a solution to one of the challenges posted by the site authors. -- Registered Linux user #298569 I owe the government $3400 in taxes. So I sent them two hammers and a toilet seat. -- Michael McShane From dyoo@hkn.eecs.berkeley.edu Sat Jul 5 18:18:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Jul 5 17:18:02 2003 Subject: [Tutor] Memory Problem [for loops, range(), and psyco] In-Reply-To: <5.2.1.1.0.20030704230905.01ff3e28@www.thinkware.se> Message-ID: On Fri, 4 Jul 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > At 08:02 2003-07-04 +0200, Abel Daniel wrote: > >Magnus Lyck? wrote: > > > If you just use xrange() instead of range(), you won't create any > > > list, but I don't know if Python will actually release the memory > > > used for integers, since they are interned. (That integers are > > > interned means that if you use 42 in several different places in > > > your code, it will always use the same integer object.) > >Isn't this only done for small ( < 100) integers? > > Oh, I didn't know that. Thanks! Is that a recent change? I seem to > remember that construction of big ranges was a problem, since the > integers weren't garbage collected. Hi Magnus, The problem with big ranges had to do with the construction of the range list itself, and not as much with the integers. I believe that 'psyco', the Specializing Python Compiler, does optimize range()s away if a program uses them as loop counters. Let me see... Ok, I found that reference: http://psyco.sourceforge.net/psycoguide/node27.html Footnote 8 says that psyco will transform 'for i in range(42)' into a standard C 'for(i=3D0;i<42;i++)' loop, and that's really cool. Dorsey's application sounds really computational, so Dorsey may want to look into psyco and see if it's useful. Psyco can be found here: http://psyco.sourceforge.net From idiot1@netzero.net Sun Jul 6 00:48:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sat Jul 5 23:48:01 2003 Subject: [Tutor] Autoreply wars Message-ID: <3F079BD5.6000503@netzero.net> AUTOREPLY WAR: Where 2+ programs which generate replies to incoming email begin talking to one another, and then replying to one another's replies, ad infinitum. This endless loop is not broken until human intervention or the exausting of the operating resources of one or both server systems. It is also annoying as all living hell to innicent bystanders on the lists in question, and is known to produce considerable flamage to the Luser in question upon his return to cyberspace. There are features in TinyList to supress this sort of thing, so that people with idiotic vacation programs (and idiots who configure them) who subscribe to lists don't incurr the wrath of the list's membership. Thinking about these things, I also realized it is possible for the clueless to couple 2 lists together, crashing their own system- it rather strained my credulity to think 2 people on 2 different servers would do such a thing. (watch some luser come along and prove me wrong later). SO, to test the effectiveness of my precautions, I *INTENTIONALLY* cross coupled 2 lists on my server, then sent in a message. It was sent out fine. NO LOOP. I sent to the other one. It came back fine. NO LOOP. Were there a loop, the two lists would be talking to one another, replying to each other- and spewing into my constantly monitored mailbox. I had the ssh running and could kill an alias lickety split, if need be. It was not; the precautions worked perfectly in a nightmare scenario. ME happy hacker this saterday evening. :-) Oh- and I disassembled the coupling. I'm daring, but I still have TRACES of sanity. Let's see majordomo try this test... -- end Cheers! Kirk D Bailey think http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ http://www.listville.net/ | BOX | http://www.sacredelectron.org/ +-----+ "Thou art free"-ERIS think 'Got a light?'-Promethieus Fnord. From spamfilter2@mupp.net Sun Jul 6 07:34:02 2003 From: spamfilter2@mupp.net (j2) Date: Sun Jul 6 06:34:02 2003 Subject: [Tutor] COnvert a string? Message-ID: <0b2401c343a9$f8f90830$7800a8c0@fozzie> This is a multi-part message in MIME format. ------=_NextPart_000_0B21_01C343BA.BC4AE9B0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Ok, i am not a _total_ newbie (just almost). But i need to convert a = string that looks a little something like this =3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_fredag= s_efterm?=3D =3D?iso-8859-1?Q?iddag!_/Rolf?=3D into a "plain" textfile (ASCII text only, with spaces between words).=20 Any hints? I can not figure this out? ------=_NextPart_000_0B21_01C343BA.BC4AE9B0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Ok, i am not a _total_ newbie (just = almost). But i=20 need to convert a string that looks a little something like = this
 
=3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_f= redags_efterm?=3D
    =3D?iso-8859-1?Q?iddag!_/Rol= f?=3D
 
into a "plain" textfile (ASCII text = only, with=20 spaces between words).
Any hints? I can not figure this=20 out?
------=_NextPart_000_0B21_01C343BA.BC4AE9B0-- From molhanec@seznam.cz Sun Jul 6 07:56:02 2003 From: molhanec@seznam.cz (Michal Molhanec) Date: Sun Jul 6 06:56:02 2003 Subject: [Tutor] COnvert a string? In-Reply-To: <0b2401c343a9$f8f90830$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> Message-ID: <3F08000B.1030208@seznam.cz> j2 wrote: > Ok, i am not a _total_ newbie (just almost). But i need to convert a > string that looks a little something like this > > =?iso-8859-1?Q?Hej=2C_tack_f=F6r_bra_team_work_p=E5_ndc5_i_fredags_efterm?= > =?iso-8859-1?Q?iddag!_/Rolf?= > > into a "plain" textfile (ASCII text only, with spaces between words). > Any hints? I can not figure this out? look at decode_header function in email package i've used: header_line = email.Header.decode_header(header_line) s = u'' for text, charset in header_line: if charset: try: s += text.decode(charset) except: s += text else: s += text warning: i'm also only beginner From spamfilter2@mupp.net Sun Jul 6 08:18:01 2003 From: spamfilter2@mupp.net (j2) Date: Sun Jul 6 07:18:01 2003 Subject: [Tutor] COnvert a string? References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> Message-ID: <0b3501c343b0$30b21c70$7800a8c0@fozzie> > look at decode_header function in email package > i've used: Ok, i did #!/usr/bin/python2.2 import string import email x = "=?iso-8859-1?Q?Hej=2C_tack_f=F6r_bra_team_work_p=E5_ndc5_i_fredags_efterm?= =?iso-8859-1?Q?iddag!_/Rolf?=" y = email.Header.decode_header(x) s = u'' for text, charset in header_line: if charset: try: s += text.decode(charset) except: s += text else: s += text and i get cookiemonster:/root/scripts# ./test.py Traceback (most recent call last): File "./test.py", line 15, in ? y = email.Header.decode_header(x) AttributeError: 'module' object has no attribute 'Header' cookiemonster:/root/scripts# any hints? From molhanec@seznam.cz Sun Jul 6 08:23:01 2003 From: molhanec@seznam.cz (Michal Molhanec) Date: Sun Jul 6 07:23:01 2003 Subject: [Tutor] COnvert a string? In-Reply-To: <0b3501c343b0$30b21c70$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> Message-ID: <3F08063E.4010501@seznam.cz> j2 wrote: >>look at decode_header function in email package >>i've used: > > > Ok, i did > > #!/usr/bin/python2.2 > import string > import email you need import email.Header > > x = > "=?iso-8859-1?Q?Hej=2C_tack_f=F6r_bra_team_work_p=E5_ndc5_i_fredags_efterm?= > =?iso-8859-1?Q?iddag!_/Rolf?=" > > y = email.Header.decode_header(x) > s = u'' > for text, charset in header_line: for text, charset in y: > if charset: > try: > s += text.decode(charset) > except: > s += text > else: > s += text > From spamfilter2@mupp.net Sun Jul 6 08:45:01 2003 From: spamfilter2@mupp.net (j2) Date: Sun Jul 6 07:45:01 2003 Subject: [Tutor] COnvert a string? References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> <3F08063E.4010501@seznam.cz> Message-ID: <0b3d01c343b3$eb51f610$7800a8c0@fozzie> > you need > import email.Header import email should impor teverything, shouldnt it? cookiemonster:/root/scripts# ./test.py Traceback (most recent call last): File "./test.py", line 5, in ? import email.Header ImportError: No module named Header cookiemonster:/root/scripts# cookiemonster:/root/scripts# python2.2 Python 2.2.1 (#1, Sep 7 2002, 14:34:30) From magnus@thinkware.se Sun Jul 6 08:59:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 6 07:59:02 2003 Subject: [Tutor] COnvert a string? In-Reply-To: <0b3d01c343b3$eb51f610$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> <3F08063E.4010501@seznam.cz> Message-ID: <5.2.1.1.0.20030706140230.02032040@www.thinkware.se> At 13:44 2003-07-06 +0200, j2 wrote: >import email should impor teverything, shouldnt it? Nope. email is not a module, it's a package. Header is a module in the email package. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From spamfilter2@mupp.net Sun Jul 6 09:04:02 2003 From: spamfilter2@mupp.net (j2) Date: Sun Jul 6 08:04:02 2003 Subject: [Tutor] COnvert a string? References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> <3F08063E.4010501@seznam.cz> <5.2.1.1.0.20030706140230.02032040@www.thinkware.se> Message-ID: <0b9301c343b6$a18e43f0$7800a8c0@fozzie> > Nope. email is not a module, it's a package. Header is a module > in the email package. Aha, still doesnt work tho. Hjälp? :) From molhanec@seznam.cz Sun Jul 6 09:08:02 2003 From: molhanec@seznam.cz (Michal Molhanec) Date: Sun Jul 6 08:08:02 2003 Subject: [Tutor] COnvert a string? In-Reply-To: <0b3d01c343b3$eb51f610$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> <3F08063E.4010501@seznam.cz> <0b3d01c343b3$eb51f610$7800a8c0@fozzie> Message-ID: <3F081116.1090401@seznam.cz> j2 wrote: >>you need >>import email.Header > > > import email should impor teverything, shouldnt it? it depends on how is the package's __init__.py written > > cookiemonster:/root/scripts# ./test.py > Traceback (most recent call last): > File "./test.py", line 5, in ? > import email.Header > ImportError: No module named Header > cookiemonster:/root/scripts# > cookiemonster:/root/scripts# python2.2 > Python 2.2.1 (#1, Sep 7 2002, 14:34:30) oops, sorry i forgot that email.Header is available since 2.2.2 in this case you probably have to use older packages like rfc822 package but i have no experience with it (or you can download the new email package from http://mimelib.sourceforge.net/ ) (or update python :-) ) From dman@dman13.dyndns.org Sun Jul 6 09:19:01 2003 From: dman@dman13.dyndns.org (Derrick 'dman' Hudson) Date: Sun Jul 6 08:19:01 2003 Subject: [Tutor] Re: COnvert a string? In-Reply-To: <0b2401c343a9$f8f90830$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> Message-ID: <20030706121833.GA18353@dman13.dyndns.org> --7JfCtLOvnd9MIVvH Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sun, Jul 06, 2003 at 12:32:59PM +0200, j2 wrote: | Ok, i am not a _total_ newbie (just almost). But i need to convert a stri= ng that looks a little something like this |=20 | =3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_fredag= s_efterm?=3D | =3D?iso-8859-1?Q?iddag!_/Rolf?=3D |=20 | into a "plain" textfile (ASCII text only, with spaces between words).=20 | Any hints? I can not figure this out? First of all, you can't convert that string to plain ASCII unless you are willing to lose some data. Second of all, take a look at RFC 2047. It explains the encoding used in email headers for non-ASCII data. The way that works is =3D? Start of the encoded data. iso-8859-1 The charset. ? A separator. Q The encoding (quoted-printable or base64). ? A separator. Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_fredags_efterm The text. QP uses the form '=3DXX' for all non-ASCII and various punctuation characters where XX is the hex value of the character. (this string becomes "Hej,_tack_f=F6r_bra_team_work_p=E5_ndc5_i_fredags_eft= erm") ?=3D The end of the encoded data. Plain ascii data follows, or data encoded like the previous but (probably, but not necessarily) in a different charset. (While a complete understanding isn't wholly necessary, the more you know the easier it is to do your work. Now that you know what is going on here you can upgrade your python version to use the latest 'email' module.) HTH, -D --=20 For society, it's probably a good thing that engineers value function over appearance. For example, you wouldn't want engineers to build nuclear power plants that only _look_ like they would keep all the radiation inside. (Scott Adams - The Dilbert principle) =20 http://dman13.dyndns.org/~dman/ --7JfCtLOvnd9MIVvH Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj8IE5kACgkQiB6vp1xAVUD/kACfd4L+FHzUjZU4MvvYjprAvaxB MR4AmwWKePduz1EbgiCsZVcWva0gMexs =XkLd -----END PGP SIGNATURE----- --7JfCtLOvnd9MIVvH-- From magnus@thinkware.se Sun Jul 6 09:40:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 6 08:40:02 2003 Subject: [Tutor] COnvert a string? In-Reply-To: <0b9301c343b6$a18e43f0$7800a8c0@fozzie> References: <0b2401c343a9$f8f90830$7800a8c0@fozzie> <3F08000B.1030208@seznam.cz> <0b3501c343b0$30b21c70$7800a8c0@fozzie> <3F08063E.4010501@seznam.cz> <5.2.1.1.0.20030706140230.02032040@www.thinkware.se> Message-ID: <5.2.1.1.0.20030706143122.00b177f8@www.thinkware.se> At 14:03 2003-07-06 +0200, j2 wrote: >Aha, still doesnt work tho. Hj=E4lp? :) The code below prints the right thing for me. The last conversion to cp850 is there to make the Swedish letters look right at a Windows command prompt, since that still uses an ancient DOS encoding. You don't want that if you print in a normal Windows context or run it in a better operating system. I'm using Python 2.2.2. -------- from email.Header import decode_header raw_text =3D=20 """=3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_fredag= s_efterm?=3D =3D?iso-8859-1?Q?iddag!_/Rolf?=3D""" header =3D decode_header(raw_text) result =3D u'' for text, encoding in header: result +=3D text.decode(encoding) print result.encode('cp850') -------- As you see I'm not using the safety nets that Michal showed. They are not needed for this particular example, but it's probably good to have something like that. I think it's enough with just the try block though, it will catch empty encodings, and in general I try to avoid unqualified except clauses. I guess I'd use (untested): for text, encoding in header: try: result +=3D text.decode(encoding) except (UnicodeError, ValueError): result +=3D text -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From spamfilter2@mupp.net Sun Jul 6 16:47:01 2003 From: spamfilter2@mupp.net (j2) Date: Sun Jul 6 15:47:01 2003 Subject: [Tutor] More string conversions. Message-ID: <0c9101c343f6$f6889d70$7800a8c0@fozzie> This is a multi-part message in MIME format. ------=_NextPart_000_0C8E_01C34407.B9FE5AA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Thankyou all for the help with decoding the email headers.. Now i got = myself another problem. I am trying to do=20 #!/usr/bin/python2.2 import email import email.Header x =3D = "=3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_freda= gs_efterm?=3D=3D?iso-8859-1?Q?iddag!_/Rolf?=3D" y =3D email.Header.decode_header(x) s =3D u'' for text, charset in header_line: if charset: try: s +=3D text.decode(charset) except: s +=3D text else: s +=3D text print y print s cookiemonster:~/scripts# ./test.py =20 [('Hej, tack f\xf6r bra team work p\xe5 ndc5 i fredags eftermiddag! = /Rolf', 'iso-8859-1')] Traceback (most recent call last): File "./test.py", line 28, in ? print s UnicodeError: ASCII encoding error: ordinal not in range(128) cookiemonster:~/scripts#=20 But how could i convert the text in "y" to "plain ascii"? ------=_NextPart_000_0C8E_01C34407.B9FE5AA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Thankyou all for the help with decoding = the email=20 headers.. Now i got myself another problem.
 
I am trying to do
 
#!/usr/bin/python2.2
import = email
import=20 email.Header
 
x =3D=20 "=3D?iso-8859-1?Q?Hej=3D2C_tack_f=3DF6r_bra_team_work_p=3DE5_ndc5_i_freda= gs_efterm?=3D=3D?iso-8859-1?Q?iddag!_/Rolf?=3D"
 
y =3D = email.Header.decode_header(x)
s =3D u''
for=20 text, charset in = header_line:
        if=20 charset:
          &= nbsp;    =20 try:
           = ;            = =20 s +=3D=20 text.decode(charset)
        &= nbsp;      =20 except:
          &n= bsp;           &nb= sp;=20 s +=3D text
       =20 else:
          &nbs= p;    =20 s +=3D text
print y
print s
 
cookiemonster:~/scripts# = ./test.py  =20
[('Hej, tack f\xf6r bra team work p\xe5 ndc5 i fredags eftermiddag! = /Rolf',=20 'iso-8859-1')]
 
Traceback (most recent call = last):
  File=20 "./test.py", line 28, in ?
    print = s
UnicodeError: ASCII=20 encoding error: ordinal not in range(128)
cookiemonster:~/scripts#=20
 
But how could i convert the text in "y" = to "plain=20 ascii"? 
------=_NextPart_000_0C8E_01C34407.B9FE5AA0-- From molhanec@seznam.cz Sun Jul 6 19:38:02 2003 From: molhanec@seznam.cz (Michal Molhanec) Date: Sun Jul 6 18:38:02 2003 Subject: [Tutor] More string conversions. In-Reply-To: <0c9101c343f6$f6889d70$7800a8c0@fozzie> References: <0c9101c343f6$f6889d70$7800a8c0@fozzie> Message-ID: <3F08A49A.3020803@seznam.cz> imho should something like: s = s.encode('ascii', 'replace') s = s.encode('ascii', 'ignore') work. the first one replaces non-ascii characters with ? and the second simply ignores them From magnus@thinkware.se Sun Jul 6 19:45:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 6 18:45:02 2003 Subject: [Tutor] More string conversions. In-Reply-To: <0c9101c343f6$f6889d70$7800a8c0@fozzie> Message-ID: <5.2.1.1.0.20030706235914.01ff51b8@www.thinkware.se> At 21:44 2003-07-06 +0200, j2 wrote: >Traceback (most recent call last): > File "./test.py", line 28, in ? > print s >UnicodeError: ASCII encoding error: ordinal not in range(128) >cookiemonster:~/scripts# Your default character encoding is ASCII. That means you can't print a unicode string containing non-ascii characters. This is Python you know: "In the face of ambiguity, refuse the temptation to guess." and "Explicit is better than implicit." (See "import this") You need to tell python what encoding to use when you print the unicode string. One way to do this is print s.encode('iso-8859-1') I seem to remember that there was some way to do that without having to do .encode(encoding) for each print statement, but I don't remember how. You can change your default encoding in 'site.py', but then your program might not work on another computer than your own, and it might break when you upgrade Python I guess. After a little experimentation, I seem to have found a way... I'm sure there is a more kosher way to do this, but my code seems to work... from email.Header import decode_header raw_text = """=?iso-8859-1?Q?Hej=2C_tack_f=F6r_bra_team_work_p=E5_ndc5_i_fredags_efterm?= =?iso-8859-1?Q?iddag!_/Rolf?=""" header = decode_header(raw_text) result = u'' for text, encoding in header: result += text.decode(encoding) # The rest is new... import sys class UnicodeToEncoding: def __init__(self, encoding, file_handle): self.enc = encoding self.f = file_handle def write(self, data): return self.f.write(data.encode(self.enc)) sys.stdout = UnicodeToEncoding('iso-8859-1', sys.stdout) print result -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From jpaish@freenet.edmonton.ab.ca Sun Jul 6 20:27:33 2003 From: jpaish@freenet.edmonton.ab.ca (Joseph Paish) Date: Sun Jul 6 19:27:33 2003 Subject: [Tutor] updating shelved record Message-ID: <03070617291501.01310@localhost.localdomain> i am trying to update a file "in place" using shelve. =20 this is what i have so far, using an example i found in a book to build t= he=20 original database in order to test ideas an my understanding of how shelv= e=20 works : Python 2.0 (#1, Apr 11 2001, 19:18:08)=20 [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386 Type "copyright", "credits" or "license" for more information. IDLE 0.6 -- press F1 for help >>> import shelve >>> dbase =3D shelve.open("mydbase") >>> object1 =3D ['The', 'bright', ('side', 'of'), ['life']] >>> object2 =3D {'name': 'Brian', 'age': 33, 'motto': object1} >>> dbase['brian'] =3D object2 >>> dbase.close() >>> import shelve >>> dbase =3D shelve.open("mydbase") >>> dbase['brian'] {'age': 33, 'name': 'Brian', 'motto': ['The', 'bright', ('side', 'of'),=20 ['life']]} >>> dbase['brian']['age'] 33 # okay so far >>> dbase.close() >>> dbase =3D shelve.open("mydbase") >>> print dbase['brian']['age'] 33 # try and change brian's age to 44 >>> dbase['brian']['age'] =3D '44' >>> print dbase['brian']['age'] 33 # no luck # try closing and re-opening the file to force a flush and hopefully comm= it=20 the change. >>> dbase.close() >>> dbase =3D shelve.open("mydbase") >>> print dbase['brian']['age'] 33 # brian still 33 years old. i guess the question is "how can i change brian's age on disk?". i must = be=20 missing something very obvious. thanks joe ps. i have stripped out a lot of the IDLE session (mainly errors), but=20 nothing that impacts what i am trying to do. From magnus@thinkware.se Sun Jul 6 20:50:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 6 19:50:02 2003 Subject: [Tutor] updating shelved record In-Reply-To: <03070617291501.01310@localhost.localdomain> Message-ID: <5.2.1.1.0.20030707014034.02031af0@www.thinkware.se> I've never used shelve for anything real, but I suspect that you need to rebind dbase['brian'], like this: brian = dbase['brian'] brian['age'] = 44 dbase['brian'] = brian I suspect that "dbase['brian']" will return a copy of what is in the shelve, and in your code below, you update this copy and then throw it away, since you have no references to it. Do you understand what I mean? What you are doing is a bit like doing s.upper() instead of s = s.upper() if you want to convert a string s to upper case. To understand what I mean you must understant the difference between names and objects in Python. There are probably neater alternatives to shelve. Have a look at... http://www-106.ibm.com/developerworks/library/l-pypers.html and http://www.thinkware.se/cgi-bin/thinki.cgi/PersistenceSystems At 17:29 2003-07-06 -0600, Joseph Paish wrote: >i am trying to update a file "in place" using shelve. > >this is what i have so far, using an example i found in a book to build the >original database in order to test ideas an my understanding of how shelve >works : > > >Python 2.0 (#1, Apr 11 2001, 19:18:08) >[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386 >Type "copyright", "credits" or "license" for more information. >IDLE 0.6 -- press F1 for help > > >>> import shelve > >>> dbase = shelve.open("mydbase") > >>> object1 = ['The', 'bright', ('side', 'of'), ['life']] > >>> object2 = {'name': 'Brian', 'age': 33, 'motto': object1} > >>> dbase['brian'] = object2 > >>> dbase.close() > > >>> import shelve > >>> dbase = shelve.open("mydbase") > >>> dbase['brian'] >{'age': 33, 'name': 'Brian', 'motto': ['The', 'bright', ('side', 'of'), >['life']]} > >>> dbase['brian']['age'] >33 > ># okay so far > > >>> dbase.close() > >>> dbase = shelve.open("mydbase") > >>> print dbase['brian']['age'] >33 > ># try and change brian's age to 44 > >>> dbase['brian']['age'] = '44' > >>> print dbase['brian']['age'] >33 ># no luck > ># try closing and re-opening the file to force a flush and hopefully commit >the change. > >>> dbase.close() > >>> dbase = shelve.open("mydbase") > >>> print dbase['brian']['age'] >33 > ># brian still 33 years old. > > >i guess the question is "how can i change brian's age on disk?". i must be >missing something very obvious. > >thanks > >joe > >ps. i have stripped out a lot of the IDLE session (mainly errors), but >nothing that impacts what i am trying to do. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From jpaish@freenet.edmonton.ab.ca Sun Jul 6 20:54:02 2003 From: jpaish@freenet.edmonton.ab.ca (Joseph Paish) Date: Sun Jul 6 19:54:02 2003 Subject: [Tutor] updating shelved record In-Reply-To: <03070617291501.01310@localhost.localdomain> References: <03070617291501.01310@localhost.localdomain> Message-ID: <03070617570802.01310@localhost.localdomain> On Sunday 06 July 2003 17:29, you wrote: > i am trying to update a file "in place" using shelve. > > this is what i have so far, using an example i found in a book to build= the > original database in order to test ideas an my understanding of how she= lve > works : > > > Python 2.0 (#1, Apr 11 2001, 19:18:08) > [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386 > Type "copyright", "credits" or "license" for more information. > IDLE 0.6 -- press F1 for help > > >>> import shelve > >>> dbase =3D shelve.open("mydbase") > >>> object1 =3D ['The', 'bright', ('side', 'of'), ['life']] > >>> object2 =3D {'name': 'Brian', 'age': 33, 'motto': object1} > >>> dbase['brian'] =3D object2 > >>> dbase.close() > >>> > >>> import shelve > >>> dbase =3D shelve.open("mydbase") > >>> dbase['brian'] > > {'age': 33, 'name': 'Brian', 'motto': ['The', 'bright', ('side', 'of'), > ['life']]} > > >>> dbase['brian']['age'] > > 33 > > # okay so far > > >>> dbase.close() > >>> dbase =3D shelve.open("mydbase") > >>> print dbase['brian']['age'] > > 33 > > # try and change brian's age to 44 > > >>> dbase['brian']['age'] =3D '44' > >>> print dbase['brian']['age'] > > 33 > # no luck > > # try closing and re-opening the file to force a flush and hopefully co= mmit > the change. > > >>> dbase.close() > >>> dbase =3D shelve.open("mydbase") > >>> print dbase['brian']['age'] > > 33 > > # brian still 33 years old. > > > i guess the question is "how can i change brian's age on disk?". i mus= t be > missing something very obvious. > > thanks > > joe > > ps. i have stripped out a lot of the IDLE session (mainly errors), but > nothing that impacts what i am trying to do. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor never mind. found the answer almost immediately after posting the question, though i=20 swear i looked for at least an hour before asking on this mailing list. anyway, the solution : item =3D dbase['brian'] item ['age'] =3D 44 dbase['brian'] =3D item sorry for the wasted bandwidth. joe From magnus@thinkware.se Sun Jul 6 21:55:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 6 20:55:01 2003 Subject: [Tutor] updating shelved record In-Reply-To: <03070617570802.01310@localhost.localdomain> References: <03070617291501.01310@localhost.localdomain> <03070617291501.01310@localhost.localdomain> Message-ID: <5.2.1.1.0.20030707021121.0203ae48@www.thinkware.se> At 17:57 2003-07-06 -0600, Joseph Paish wrote: >never mind. > >found the answer almost immediately after posting the question, though i >swear i looked for at least an hour before asking on this mailing list. > >anyway, the solution : > >item = dbase['brian'] >item ['age'] = 44 >dbase['brian'] = item > >sorry for the wasted bandwidth. You're not wasting bandwidth. This is not obvious, and I'm sure you're neither the first nor the last to fall into this trap. We might say that shelve isn't behaving quite as one would expect it to behave. Our expectations that it will act as a persistent dictionary (which is a fair assumption) makes us draw the wrong conclusion. To understand what happens, we must really understand the implementation of shelve. When you do x[y], this will be translated into x.__getitem__(y). In a dictionary, this function call will return a reference to the object that dictionary x has a reference to under the key y. If x[y] is modified, as in x[y][z] = 42, it will be the object that dict x has keyed y to that is updated, so the next call to x[y] will show the new value. If I understand correctly, shelves use a simple database (dbm- style) that stores strings keyed by other strings, and it uses pickle, the standard python module for turning an arbitrary object into a string. This means that the dictionary object in your "dbase['brian']" doesn't exist in your string. So, it's impossible for dbase.__getitem__('brian') to simply return a reference to an existing object, in this case a dictionary. It's not so easy to make it work smarter than this if our aim is that shelve is to be a light and simple module that keeps a dbm file updated and keeps memory usage small. When we do "dbase[key] = somehing" we will call "dbase.__setitem__(key, something)" and that's a convenient time to update the underlying database. if we do "dbase[key][subkey] = 42" this will turn into "dbase.__getitem__(key).__setitem__(subkey, 42)". The shelve object, dbase, will only see a call to __getitem__ which is just the same as if someone would just try to read the value of dbase[key]. There is no way dbase can see that we are trying to update the shelve. __getitem__ returns a dict object, and an ordinary dict object has no concept of being a component inside a shelve, so it won't "report" its update to dbase, so dbase can't be aware that it needs to be updated. After all, if dbase['brian']['age'] = 42 would lead to a database change, then x = dbase['brian'] x['age'] = 42 should do the same. I can't see how this could work. It would certainly be possible to make a replacement to shelve that brought in objects into memory when they were requested, and kept a reference to each unpickled object inside itself so that we wouldn't need to rebind it as Joseph showed above, but it would use much more memory if many items in the database were updated during a program run, and it could (as far as I can see) only update the database file through specific save() calls, and/or on close(). It would be quite different from shelve, with much larger memory usage and no instant reflection of changes to the disk. To make it even smarter, something much more complex such as the object database in Zope, ZODB, would be needed. Even ZODB has problems with mutable objects such as dictionaries... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From spamfilter2@mupp.net Mon Jul 7 04:44:02 2003 From: spamfilter2@mupp.net (j2) Date: Mon Jul 7 03:44:02 2003 Subject: [Tutor] More string conversions. In-Reply-To: <5.2.1.1.0.20030706235914.01ff51b8@www.thinkware.se> References: <5.2.1.1.0.20030706235914.01ff51b8@www.thinkware.se> Message-ID: <1057563813.3f0924a5f090b@www.mupp.net> Quoting Magnus Lyckå : > You need to tell python what encoding to use when you print the > unicode string. One way to do this is Thankyou. I used your code and it does what i want. But, uhm, all of a sudden my mySQL-segfaults. Can ANYONE offer any light on what might cause that? Ill include my source, and a strace... i cant figure it out, it only segfaults with a string that HAS been converted, a "non-encoded" string goes straight through... cookiemonster:~/scripts# cat mail2sms.py #!/usr/bin/python2.2 dbhost = "localhost" dbuser = "gnokii" dbpwd = "Hn7fg5F(nonotreally)" dbdb = "gnokii-smsd" import time import os import sys import MySQLdb import string import smtplib import email import time from MySQLdb.constants import FIELD_TYPE import email.Header from email.Header import decode_header def concat_tuple (var): # Rutin för att slå ihop tuples till en sträng text = "" for y in var: text = text + " " + y return text def selectAllMessages (): # Hämtar alla meddelanden som inte är processade från databasen, db = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpwd, db=dbdb) cursor = db.cursor() cursor.execute("""select * from inbox where processed ='0'""") foo = cursor.fetchall() db.commit() return foo def matchPrefix (number): #Routine to determine if the number is a swedish cell number #If the leftmost 4 characters match, return true if not str(number)[0:4] == "+467": print "False match" return 0 else: print "True Match" return 1 def setSuccess (id): db = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpwd, db=dbdb) cursor = db.cursor() cursor.execute("""update inbox set processed ='1' where id = %s""", (id,)) foo = cursor.fetchall() db.commit() return foo def sendSMS (number, text): db = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpwd, db=dbdb) cursor = db.cursor() cursor.execute("""insert into outbox (number, text) values(%s, %s)""", (number, text,)) foo = cursor.fetchall() db.commit() return foo def updateTracker (sender, receiver): db = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpwd, db=dbdb) cursor = db.cursor() cursor.execute("""insert into tracker (sender, receiver) values(%s, % s)""", (sender, receiver,)) foo = cursor.fetchall() db.commit() return foo def sendEmail (to, sender, msg): try: server = smtplib.SMTP('localhost') server.sendmail(sender, to, msg) server.quit() success = 1 except: success = 0 return success class UnicodeToEncoding: def __init__(self, encoding, file_handle): self.enc = encoding self.f = file_handle def write(self, data): return self.f.write(data.encode(self.enc)) receiver = sys.argv[1] message = concat_tuple(sys.argv[3:]) sender = sys.argv[2] print "Receiver: "+receiver print "message: "+message print "sender: "+sender if str(receiver)[0:4] == "+467": # print "true match" #Konvertera meddelandet # Bryt ut text och encoding convertedMessage = decode_header(message) message = u'' # # Slå ihop texten for text, encoding in convertedMessage: # # Om vi har någon encoding, använd den. Annars slå bara ihop texten. if encoding: message += text.decode(encoding) else: message += text # # Välj teckentabell sys.stdout = UnicodeToEncoding('iso-8859-1', sys.stdout) # # Skicka SMS, och uppdatera databasen. print message print len(message) sendSMS(receiver, message) updateTracker(sender, receiver) else: print "false match" # sendEmail(sender, "klkj", "Det där var inte ett svenskt nummer") cookiemonster:~/scripts# read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0\3\0\1\0\0\0(\35\0\000"..., 1024) = 1024 fstat64(3, {st_mode=S_IFREG|0644, st_size=32204, ...}) = 0 old_mmap(NULL, 35584, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0x4037a000 mprotect(0x40382000, 2816, PROT_NONE) = 0 old_mmap(0x40382000, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0x7000) = 0x40382000 close(3) = 0 munmap(0x40376000, 13668) = 0 open("/etc/services", O_RDONLY) = 3 fcntl64(3, F_GETFD) = 0 fcntl64(3, F_SETFD, FD_CLOEXEC) = 0 fstat64(3, {st_mode=S_IFREG|0644, st_size=16127, ...}) = 0 old_mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x40376000 read(3, "# /etc/services:\n# $Id: services"..., 4096) = 4096 read(3, "209/udp\t\t\t\t# The Quick Mail Tran"..., 4096) = 4096 read(3, "CM SC-104 IANA 1/29/99\nrtcm-sc10"..., 4096) = 4096 close(3) = 0 munmap(0x40376000, 4096) = 0 rt_sigaction(SIGPIPE, {SIG_IGN}, {SIG_IGN}, 8) = 0 socket(PF_UNIX, SOCK_STREAM, 0) = 3 fcntl64(3, F_GETFL) = 0x2 (flags O_RDWR) connect(3, {sin_family=AF_UNIX, path="/var/run/mysqld/mysqld.sock"}, 110) = 0 brk(0) = 0x8222000 brk(0x8224000) = 0x8224000 setsockopt(3, SOL_IP, IP_TOS, [8], 4) = -1 EOPNOTSUPP (Operation not supported) setsockopt(3, SOL_SOCKET, SO_KEEPALIVE, [1], 4) = 0 read(3, ",\0\0\0", 4) = 4 read(3, "\n3.23.49-log\0QS\0\0-l\\dcDic\0, \10\2\0\0"..., 44) = 44 open("/usr/share/mysql/charsets/Index", O_RDONLY|O_LARGEFILE) = 4 fstat64(4, {st_mode=S_IFREG|0644, st_size=549, ...}) = 0 old_mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x40376000 read(4, "# sql/share/charsets/Index\n#\n# T"..., 4096) = 549 brk(0) = 0x8224000 brk(0x8225000) = 0x8225000 read(4, "", 4096) = 0 close(4) = 0 munmap(0x40376000, 4096) = 0 write(3, " \0\0\1\215 \0\0\0gnokii\0V\\YZGF]M\0gnokii-"..., 36) = 36 read(3, "\5\0\0\2", 4) = 4 read(3, "\0\0\0\2\0", 5) = 5 --- SIGSEGV (Segmentation fault) --- +++ killed by SIGSEGV +++ cookiemonster:/root/scripts# ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From spamfilter2@mupp.net Mon Jul 7 07:05:02 2003 From: spamfilter2@mupp.net (j2) Date: Mon Jul 7 06:05:02 2003 Subject: [Tutor] More string conversions. In-Reply-To: <1057563813.3f0924a5f090b@www.mupp.net> References: <5.2.1.1.0.20030706235914.01ff51b8@www.thinkware.se> <1057563813.3f0924a5f090b@www.mupp.net> Message-ID: <1057572281.3f0945b98a09c@www.mupp.net> Quoting j2 : Please ignore my segfault. I am so sorry, but i had a version missmatch between Python and Python-mysqldb Everything works like i want.. (well, like i have coded anyway). Thankyou all. ------------------------------------------------- This mail sent through IMP: http://horde.org/imp/ From camartin@snet.net Mon Jul 7 13:23:02 2003 From: camartin@snet.net (Cliff Martin) Date: Mon Jul 7 12:23:02 2003 Subject: [Tutor] open file form Message-ID: <3F0999EF.4060709@snet.net> Hi, A few days ago I asked for some help with an ASCII file. It was a large file which I needed to read all the data into a file. (It's an interferometry file so I can't manipulate it line by line, especially if I want to fit it to orthogonal poynomials). I got help back (thanks dman and Rick Pasotto) but in one case someone used a form for opening a file like: f = 3D file(filename) then manipulated the opened file using 3D. etc. When I tried this it didn't work. Then today on a completely different question I saw the same form again. What is this form? I can't seem to find it in the doc's and the following is what I get when I try it. Thanks in advance for the help. f =3D file('c:/transfer/doctst.txt') Traceback ( File "", line 1 f =3D file('c:/transfer/doctst.txt') ^ SyntaxError: invalid syntax Cliff From dyoo@hkn.eecs.berkeley.edu Mon Jul 7 13:38:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 7 12:38:02 2003 Subject: [Tutor] open file form In-Reply-To: <3F0999EF.4060709@snet.net> Message-ID: On Mon, 7 Jul 2003, Cliff Martin wrote: > A few days ago I asked for some help with an ASCII file. It was a large > file which I needed to read all the data into a file. (It's an > interferometry file so I can't manipulate it line by line, especially if > I want to fit it to orthogonal poynomials). I got help back (thanks > dman and Rick Pasotto) but in one case someone used a form for opening a > file like: > > f = 3D file(filename) > > then manipulated the opened file using 3D. etc. When I tried this it > didn't work. Then today on a completely different question I saw the > same form again. What is this form? I can't seem to find it in the > doc's and the following is what I get when I try it. Thanks in advance > for the help. > > f =3D file('c:/transfer/doctst.txt') > Traceback ( File "", line 1 > f =3D file('c:/transfer/doctst.txt') > ^ > SyntaxError: invalid syntax Hi Cliff, There appears to have been some kind of quotation bug in someone's email client. The line should have been: f = file('c:/transfer/doctst.txt') By the way, let me check something... What does 3D stand for? It looks like some kind of hexidecimal constant. ### >>> 0x3d 61 >>> chr(61) '=' ### Ah. I see now. What happened was that, somehow in the email transmission, the '=' character got quote-escaped into the sequence '=3d'. Hope this helps! From DORSEY_EDMUND_K@LILLY.COM Mon Jul 7 13:40:03 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Mon Jul 7 12:40:03 2003 Subject: [Tutor] Memory Problem Continued Message-ID: This is a multipart message in MIME format. --=_alternative 005B759405256D5C_= Content-Type: text/plain; charset="us-ascii" Previously I was having a memory problem and it was pointed out that the range function is quite the memory hog and to use xrange instead. Unfortunately this didn't solve the problem (though it did fix a problem that I would have probably encountered later with larger data sets) I don't like just pasting code into my email but I'm afraid it's the only way I can explain the problem. So here it goes. When I start up the program and it loads the data set it uses up a fixed amount of memory. As the subvoxelize function shown below continues to run (takes about 5 minutes before crashing) the memory usage just keeps increasing at a constant rate until I run out of memory. def subvoxelize(self, progressFunc=None): value = 0 updateNum = self._numVoxelsOrig/100 for n in xrange(self._numVoxelsOrig): #self._numVoxelsOrig has a value of around 20 million x, y, z = self.to3d(n) #not causing any problems with memory x2, y2, z2 = x*2, y*2, z*2 index0 = x2 + y2*self._newXsize + z2 * (self._newXY) #here is where the problem is and with the subsequent assignments index1 = x2+1 + y2*self._newXsize + z2 * (self._newXY) index2 = x2 + (y2+1)*self._newXsize + z2 * (self._newXY) index3 = x2+1 + (y2+1)*self._newXsize + z2 * (self._newXY) index4 = x2 + y2*self._newXsize + (z2+1) * (self._newXY) index5 = x2+1 + y2*self._newXsize + (z2+1) * (self._newXY) index6 = x2 + (y2+1)*self._newXsize + (z2+1) * (self._newXY) index7 = x2+1 + (y2+1)*self._newXsize + (z2+1) * (self._newXY) #if I don't do these assignments and make each index go to a constant it doesn't leak memory self._newData[index0] = self._data[n] self._newData[index1] = self._data[n] self._newData[index2] = self._data[n] self._newData[index3] = self._data[n] self._newData[index4] = self._data[n] self._newData[index5] = self._data[n] self._newData[index6] = self._data[n] self._newData[index7] = self._data[n] if n % updateNum == 0: progressFunc(value) value = value+1 return self._newData That is my function. I have narrowed the problem down to where I assign values to index 0 through 7. If I just assign those values to some constant ie. 0 it doesn't eat up my memory. (shown below) index0 = 0 index1 =0 index2 = 0 .... #doing this works Does anyone have any idea why I would be "leaking" memory?? The above algorithm works fine with smaller data sets and even does what I want it to do but anything large and it uses up all the memory and dies. Thank you for any advice. ~Ed --=_alternative 005B759405256D5C_= Content-Type: text/html; charset="us-ascii"
Previously I was having a memory problem and it was pointed out that the range function is quite the memory hog and to use xrange instead.  Unfortunately this didn't solve the problem (though it did fix a problem that I would have probably encountered later with larger data sets)  I don't like just pasting code into my email but I'm afraid it's the only way I can explain the problem.  So here it goes.  When I start up the program and it loads the data set it uses up a fixed amount of memory.  As the subvoxelize function shown below continues to run (takes about 5 minutes before crashing) the memory usage just keeps increasing at a constant rate until I run out of memory.  

    def subvoxelize(self, progressFunc=None):
        value = 0
        updateNum = self._numVoxelsOrig/100
        for n in xrange(self._numVoxelsOrig):   #self._numVoxelsOrig has a value of around 20 million
            x, y, z = self.to3d(n)                                  #not causing any problems with memory
            x2, y2, z2 = x*2, y*2, z*2  
            index0 = x2      + y2*self._newXsize     + z2 * (self._newXY)   #here is where the problem is and with the subsequent assignments
            index1 = x2+1 + y2*self._newXsize     + z2 * (self._newXY)
            index2 = x2      + (y2+1)*self._newXsize + z2 * (self._newXY)
            index3 = x2+1 + (y2+1)*self._newXsize + z2 * (self._newXY)
            index4 = x2      + y2*self._newXsize     + (z2+1) * (self._newXY)
            index5 = x2+1 + y2*self._newXsize     + (z2+1) * (self._newXY)
            index6 = x2      + (y2+1)*self._newXsize + (z2+1) * (self._newXY)
            index7 = x2+1 + (y2+1)*self._newXsize + (z2+1) * (self._newXY)  #if I don't do these assignments and make each index go to a constant it doesn't leak memory
            self._newData[index0] = self._data[n]
            self._newData[index1] = self._data[n]
            self._newData[index2] = self._data[n]
            self._newData[index3] = self._data[n]
            self._newData[index4] = self._data[n]
            self._newData[index5] = self._data[n]
            self._newData[index6] = self._data[n]
            self._newData[index7] = self._data[n]
            if n % updateNum == 0:
                progressFunc(value)
                value = value+1
        return self._newData


That is my function.  I have narrowed the problem down to where I assign values to index 0 through 7.  
If I just assign those values to some constant ie. 0 it doesn't eat up my memory.  (shown below)

index0 = 0
index1 =0
index2 = 0 ....  #doing this works

Does anyone have any idea why I would be "leaking" memory?? The above algorithm works fine with smaller data sets and even does what I want it to do but anything large and it uses up all the memory and dies.  Thank you for any advice. ~Ed

--=_alternative 005B759405256D5C_=-- From DORSEY_EDMUND_K@LILLY.COM Mon Jul 7 15:20:07 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Mon Jul 7 14:20:07 2003 Subject: [Tutor] Memory Problem Continued Message-ID: This is a multipart message in MIME format. --=_alternative 0064964305256D5C_= Content-Type: text/plain; charset="us-ascii" I did a little more testing and I realized I'm having a different problem. The problem seems to be in assinging data to each index. Calculating the indices doesn't eat any memory. Sorry about that. Each call self._newData[index] = self._data[n] eats up some memory. Prior to this function I initialized self._newData by saying newData = [0] * self._numVoxelsOrig Then I proceeded to fill up newData. Everytime I put something into a different index it uses up some more memory. Any ideas as why it would do this?? Thanks for any advice. Previously I was having a memory problem and it was pointed out that the range function is quite the memory hog and to use xrange instead. Unfortunately this didn't solve the problem (though it did fix a problem that I would have probably encountered later with larger data sets) I don't like just pasting code into my email but I'm afraid it's the only way I can explain the problem. So here it goes. When I start up the program and it loads the data set it uses up a fixed amount of memory. As the subvoxelize function shown below continues to run (takes about 5 minutes before crashing) the memory usage just keeps increasing at a constant rate until I run out of memory. def subvoxelize(self, progressFunc=None): value = 0 updateNum = self._numVoxelsOrig/100 for n in xrange(self._numVoxelsOrig): #self._numVoxelsOrig has a value of around 20 million x, y, z = self.to3d(n) #not causing any problems with memory x2, y2, z2 = x*2, y*2, z*2 index0 = x2 + y2*self._newXsize + z2 * (self._newXY) index1 = x2+1 + y2*self._newXsize + z2 * (self._newXY) index2 = x2 + (y2+1)*self._newXsize + z2 * (self._newXY) index3 = x2+1 + (y2+1)*self._newXsize + z2 * (self._newXY) index4 = x2 + y2*self._newXsize + (z2+1) * (self._newXY) index5 = x2+1 + y2*self._newXsize + (z2+1) * (self._newXY) index6 = x2 + (y2+1)*self._newXsize + (z2+1) * (self._newXY) index7 = x2+1 + (y2+1)*self._newXsize + (z2+1) * (self._newXY) self._newData[index0] = self._data[n] #the problem is here Each of these calls seems to eat up memory self._newData[index1] = self._data[n] self._newData[index2] = self._data[n] self._newData[index3] = self._data[n] self._newData[index4] = self._data[n] self._newData[index5] = self._data[n] self._newData[index6] = self._data[n] self._newData[index7] = self._data[n] if n % updateNum == 0: progressFunc(value) value = value+1 return self._newData That is my function. I have narrowed the problem down to where I assign values to index 0 through 7. If I just assign those values to some constant ie. 0 it doesn't eat up my memory. (shown below) index0 = 0 index1 =0 index2 = 0 .... #doing this works Does anyone have any idea why I would be "leaking" memory?? The above algorithm works fine with smaller data sets and even does what I want it to do but anything large and it uses up all the memory and dies. Thank you for any advice. ~Ed --=_alternative 0064964305256D5C_= Content-Type: text/html; charset="us-ascii"
I did a little more testing and I realized I'm having a different problem.  The problem seems to be in assinging data to each index.  Calculating the indices doesn't eat any memory.  Sorry about that.
Each call self._newData[index] = self._data[n] eats up some memory.  

Prior to this function I initialized self._newData by saying

newData = [0] * self._numVoxelsOrig

Then I proceeded to fill up newData.  Everytime I put something into a different index it uses up some more memory.  Any ideas as why it would do this??

Thanks for any advice.




Previously I was having a memory problem and it was pointed out that the range function is quite the memory hog and to use xrange instead.  Unfortunately this didn't solve the problem (though it did fix a problem that I would have probably encountered later with larger data sets)  I don't like just pasting code into my email but I'm afraid it's the only way I can explain the problem.  So here it goes.  When I start up the program and it loads the data set it uses up a fixed amount of memory.  As the subvoxelize function shown below continues to run (takes about 5 minutes before crashing) the memory usage just keeps increasing at a constant rate until I run out of memory.  

   def subvoxelize(self, progressFunc=None):

       value = 0

       updateNum = self._numVoxelsOrig/100

       for n in xrange(self._numVoxelsOrig):   #self._numVoxelsOrig has a value of around 20 million

           x, y, z = self.to3d(n)                                  #not causing any problems with memory

           x2, y2, z2 = x*2, y*2, z*2  

           index0 = x2      + y2*self._newXsize     + z2 * (self._newXY)  
           index1 = x2+1 + y2*self._newXsize     + z2 * (self._newXY)

           index2 = x2      + (y2+1)*self._newXsize + z2 * (self._newXY)

           index3 = x2+1 + (y2+1)*self._newXsize + z2 * (self._newXY)

           index4 = x2      + y2*self._newXsize     + (z2+1) * (self._newXY)

           index5 = x2+1 + y2*self._newXsize     + (z2+1) * (self._newXY)

           index6 = x2      + (y2+1)*self._newXsize + (z2+1) * (self._newXY)

           index7 = x2+1 + (y2+1)*self._newXsize + (z2+1) * (self._newXY)  
           self._newData[index0] = self._data[n]
  #the problem is here  Each of these calls seems to eat up memory
           self._newData[index1] = self._data[n]

           self._newData[index2] = self._data[n]

           self._newData[index3] = self._data[n]

           self._newData[index4] = self._data[n]

           self._newData[index5] = self._data[n]

           self._newData[index6] = self._data[n]

           self._newData[index7] = self._data[n]

           if n % updateNum == 0:

               progressFunc(value)

               value = value+1

       return self._newData



That is my function.  I have narrowed the problem down to where I assign values to index 0 through 7.  

If I just assign those values to some constant ie. 0 it doesn't eat up my memory.  (shown below)


index0 = 0

index1 =0

index2 = 0 ....  #doing this works


Does anyone have any idea why I would be "leaking" memory?? The above algorithm works fine with smaller data sets and even does what I want it to do but anything large and it uses up all the memory and dies.  Thank you for any advice. ~Ed



--=_alternative 0064964305256D5C_=-- From dyoo@hkn.eecs.berkeley.edu Mon Jul 7 15:58:06 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 7 14:58:06 2003 Subject: [Tutor] Memory Problem Continued In-Reply-To: Message-ID: On Mon, 7 Jul 2003 DORSEY_EDMUND_K@LILLY.COM wrote: > I did a little more testing and I realized I'm having a different problem. > The problem seems to be in assinging data to each index. Calculating the > indices doesn't eat any memory. Sorry about that. > Each call self._newData[index] = self._data[n] eats up some memory. Hi Dorsey, Sure; the problem is that keeping the values in memory is what's eating your memory. *grin* Python's numbers are objects --- this is important, because each new integer or floating-point number will take up a little more space than you might expect. > Prior to this function I initialized self._newData by saying > > newData = [0] * self._numVoxelsOrig > > Then I proceeded to fill up newData. Everytime I put something into a > different index it uses up some more memory. Any ideas as why it would > do this?? Out of curiosity: how large is _numVoxelsOrig? > #self._numVoxelsOrig has a value of around 20 million Since your vector of numers is very large, you may want to try saving space by using a more "homogenous" data structure, like the vector and matrix data types provided by the Numeric Python project. numpy's matrix classes are optimized to hold numbers efficiently. http://pfdubois.com/numpy/ Modifying the code to use numpy should be fairly nonintrusive: I think all you need to do is modify the initialization of newData, perhaps like this: newData = Numeric.zeros(self._numVoxelsOrig) Just wondering: do you expect your newData to be very sparse, or will most of your values be nonzero? Good luck to you! From DORSEY_EDMUND_K@LILLY.COM Mon Jul 7 16:21:06 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Mon Jul 7 15:21:06 2003 Subject: [Tutor] Memory Problem Solved Message-ID: This is a multipart message in MIME format. --=_alternative 006A3A0C05256D5C_= Content-Type: text/plain; charset="us-ascii" I fixed the memory problem and just wanted to share the solution just in case anyone else runs across the problem in the future. I used the array module (not numeric's array) I chose to use this array module because it has the tofile and fromfile methods which are extremely useful and fast for reading and writing huge data sets. Thus the first lesson is that when working with datasets of a single type use arrays and not lists. The second problem was in how I initialized my array. If you are using Numeric.array you can use the ones or zeros methods. However the normal array module does not include these. My first attempt to initialize my array was this a = array('h') a = [0] * arraySize The problem here is that it just turns a into a list and it's no longer an array and thus becomes inefficient again. (real dumb mistake on my part) Instead do this a = array('h', [0] * arraySize) Everything works. Thanks for all the help. ~Ed --=_alternative 006A3A0C05256D5C_= Content-Type: text/html; charset="us-ascii"
I fixed the memory problem and just wanted to share the solution just in case anyone else runs across the problem in the future.

I used the array module (not numeric's array)

I chose to use this array module because it has the tofile and fromfile methods which are extremely useful and fast for reading and writing huge data sets.  Thus the first lesson is that when working with datasets of a single type use arrays and not lists.

The second problem was in how I initialized my array.  If you are using Numeric.array you can use the ones or zeros methods.  However the normal array module does not include these.  My first attempt to initialize my array was this

a = array('h')
a = [0] * arraySize

The problem here is that it just turns a into a list and it's no longer an array and thus becomes inefficient again.  (real dumb mistake on my part) Instead do this

a = array('h', [0] * arraySize)

Everything works.  Thanks for all the help. ~Ed

--=_alternative 006A3A0C05256D5C_=-- From hader@planet.nl Mon Jul 7 18:53:01 2003 From: hader@planet.nl (Huib) Date: Mon Jul 7 17:53:01 2003 Subject: [Tutor] Database and Python Message-ID: <000b01c343aa$6b66b3e0$78203d50@borah> This is a multi-part message in MIME format. --Boundary_(ID_jNPM2qVTTB9v9lTQzfVtrg) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT Hello, I am trying to learn Python. Have been busy with other languages as well such as TAS and Delphi. But unfortunately I am blocked at the stage that I can not come through. I have worked through the book Programming in Python 2nd edition. I would like to go a bit faster without getting a lot information, which at this stage is not required for my goals. I would like to make a programma for a databass with details of customers, with all the normal information such as names, adresses, telephone nrs., etc. Furtheron I would like to make a programm where I can combine these details with actions we are doing. I would like to have some advise. If I would start at databeses etc. Would I be able to make such a programm. Are there applications whihc make if easier to develop forms etc? I konw that I have to work to understand and being able to programm but for me it would make it easier if I can make some usefull programms quickly without all the "Hello world" examples. Perhaps I want to get my goals to quick but I am learning better with acutally creating something usefull than all (crap)programms. Of which I know I need to know the bases but do not anything I need. Thank in advance for your comments. Hugo --Boundary_(ID_jNPM2qVTTB9v9lTQzfVtrg) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
Hello,
 
I am trying to learn Python. Have been busy with other languages as well such as TAS and Delphi. But unfortunately I am blocked at the stage that I can not come through. I have worked through the book Programming in Python 2nd edition. I would like to go a bit faster without getting a lot information, which at this stage is not required for my goals. I would like to make a programma for a databass with details of customers, with all the normal information such as names, adresses, telephone nrs., etc. Furtheron I would like to make a programm where I can combine these details with actions we are doing.
 
I would like to have some advise. If I would start at databeses etc. Would I be able to make such a programm.
 
Are there applications whihc make if easier to develop forms etc?
 
I konw that I have to work to understand and being able to programm  but for me it would make it easier if I can make some usefull programms quickly without all the "Hello world" examples.
 
Perhaps I want to get my goals to quick but I am learning better with acutally creating something usefull than all (crap)programms. Of which I know I need to know the bases but do not anything I need.
 
Thank in advance for your comments.
 
Hugo
--Boundary_(ID_jNPM2qVTTB9v9lTQzfVtrg)-- From dyoo@hkn.eecs.berkeley.edu Mon Jul 7 19:16:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 7 18:16:01 2003 Subject: [Tutor] Database and Python In-Reply-To: <000b01c343aa$6b66b3e0$78203d50@borah> Message-ID: On Sun, 6 Jul 2003, Huib wrote: > I am trying to learn Python. Have been busy with other languages as well > such as TAS and Delphi. Hi Hugo, It sounds like you're already pretty familiar with programming. Have you looked at the Official Tutorial yet? It's at: http://www.python.org/doc/tut/ It goes quick, and you should be able to pick up enough fundamentals there to get some work done. > I can not come through. I have worked through the book Programming in > Python 2nd edition. Programming Python is meant as a leisurely, in-depth tour through the language: it's probably the last thing you want to read if you are in a hurry. Go for the official tutorial link above, and you'll probably be happier with its pacing. You can find an introduction to Python and database stuff in: http://www.amk.ca/python/writing/DB-API.html and there's more material in the Database Topic Guide: http://python.org/topics/database/ Please feel free to ask questions as you go through the tutorials; we'll be happy to help. From magnus@thinkware.se Mon Jul 7 21:53:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jul 7 20:53:02 2003 Subject: [Tutor] open file form In-Reply-To: <3F0999EF.4060709@snet.net> Message-ID: <5.2.1.1.0.20030708025317.01f6a7c8@www.thinkware.se> At 12:03 2003-07-07 -0400, Cliff Martin wrote: >but in one case someone used a form for opening a file like: > >f = 3D file(filename) See http://www.freesoft.org/CIE/RFC/1521/6.htm for an explanation. This has nothing to do with Python. It's sad that email is still so brittle that it often breaks as soon as someone dares to include a non-ASCII character somewhere in an email. Particularly mailing list digests usually stink! I hope a real unicode revolution will come soon. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From idiot1@netzero.net Mon Jul 7 22:22:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Mon Jul 7 21:22:02 2003 Subject: [Tutor] software quest Message-ID: <3F0A058F.8020600@netzero.net> I am looking for a good FREE ftp client for win95/98; anyone got a url for a good one? -- end Cheers! Kirk D Bailey think http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ http://www.listville.net/ | BOX | http://www.sacredelectron.org/ +-----+ "Thou art free"-ERIS think 'Got a light?'-Promethieus Fnord. From idiot1@netzero.net Mon Jul 7 22:49:07 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Mon Jul 7 21:49:07 2003 Subject: [Tutor] is it a right choice? References: <20030703024420.GA1522@linux.local> Message-ID: <3F0A22A5.3090006@netzero.net> payal, I started learning FreeBSD, and began hammering sh/bourne shell scripting into my concrete skull (brains of gold, skull of feroconcrete), and I wanted to write some scripts. Language of choice appeared to be perl. Tried, bounced. Tried again, bounced. Sigh. then I discovered python. And this list. I took off like wildfire. I kept annoying my other half with the phrase 'this is too easy...', and asked a huge number of questions here, and searched the docs on the site like mad. And I wrote some useful real world software. in 7 weeks. I went from ZERO to working list server #1. I am not bragging. I am using myself as an example of how this language is easy to learn, flexible, and powerful. I still find perl a puzzle. But I love my python. And the snake charmers here are all friendly, and we love Monty Pythonistic humor, and never a bad pun. So if you are thinking of becoming a snakecharmer, come on in! Payal Rathod wrote: > Hi, > Before I venture in the python infested world, I want to ask whether I > am making a right choice by taking python as my first programming > language. I cannot program in C, C++ or Java etc. I can *just* do little > shell scripting. > My objective in learning a better language is that I have huge log files > in my office and get many logs files from friends who are sytem admins. > I love to analyse those files and find out browing habits of my compnay > (from squid logs), most number of mails sent to a domain ( like > hotmail), number of bytes data transferred thru' http, pop3 and smtp > etc. I prefer to write my own programs to do these things. > With rudimentary shell scripting knowledge analysing log files which are > many times over 200Mb is difficult so I was seeking a language which can > do these tasks beautifully without getting too much involved in > underlying concepts. > Am I looking for Python? Is Perl easier to learn for a newbie than > python? Is it OK to continue with Python? > > Also can Python produce binary programs like perl (perlcc)? > > Thanks, > With warm regards, > -Payal > > > > > > -- end Cheers! Kirk D Bailey think http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ http://www.listville.net/ | BOX | http://www.sacredelectron.org/ +-----+ "Thou art free"-ERIS think 'Got a light?'-Promethieus Fnord. From shalehperry@comcast.net Tue Jul 8 00:02:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Mon Jul 7 23:02:02 2003 Subject: [Tutor] software quest In-Reply-To: <3F0A058F.8020600@netzero.net> References: <3F0A058F.8020600@netzero.net> Message-ID: <200307072000.31825.shalehperry@comcast.net> On Monday 07 July 2003 16:43, Kirk Bailey wrote: > I am looking for a good FREE ftp client for win95/98; anyone got a url for > a good one? I assume you have looked at tucows? Of course, you could always code one up in Python (-: The ftplib module is VERY easy to use. From fredm@smartypantsco.com Tue Jul 8 03:53:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Tue Jul 8 02:53:02 2003 Subject: [Tutor] software quest In-Reply-To: <3F0A058F.8020600@netzero.net> Message-ID: <5.1.0.14.0.20030708163917.043219c0@192.168.1.1> At 07:43 PM 7/07/03 -0400, Kirk Bailey wrote: >I am looking for a good FREE ftp client for win95/98; anyone got a url for >a good one? I have used WS_FTP LE with no problems. You can download it from http://download.com.com/3000-2160-1572132.html?tag=lst-0-1 The info there says: "This version is available free to government employees, non-commercial home users, and students and staff of educational institutions" HTH Fred Milgrom From magnus@thinkware.se Tue Jul 8 06:15:47 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 8 05:15:47 2003 Subject: [Tutor] software quest In-Reply-To: <200307072000.31825.shalehperry@comcast.net> References: <3F0A058F.8020600@netzero.net> <3F0A058F.8020600@netzero.net> Message-ID: <5.2.1.1.0.20030708100623.02052538@www.thinkware.se> At 20:00 2003-07-07 -0700, Sean 'Shaleh' Perry wrote: >The ftplib module is VERY easy to use. Do you think so? I always felt it was more complicated than it had to be, and that the docs have too few examples. In my opinion, it's more written from the perspective of implementing RFC 959 http://www.faqs.org/rfcs/rfc959.html in a logical way than to make it easy for normal FTP users to upload and download files in a simple way from a script. Typical FTP users don't know things know of things like RETR and NLST. On the other hand, I guess a lot of current FTP users only know how to use a GUI FTP client, so making an API that is more like the traditional FTP client, and let you do things like 'get', 'mget', 'put' and 'mput' might not be intuitive for everybody either... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From molhanec@seznam.cz Tue Jul 8 08:25:07 2003 From: molhanec@seznam.cz (Michal Molhanec) Date: Tue Jul 8 07:25:07 2003 Subject: [Tutor] software quest In-Reply-To: <3F0A058F.8020600@netzero.net> References: <3F0A058F.8020600@netzero.net> Message-ID: <3F0AA9FF.5000300@seznam.cz> Kirk Bailey wrote: > I am looking for a good FREE ftp client for win95/98; anyone got a url > for a good one? FileZilla http://filezilla.sourceforge.net/ LeechFTP http://stud.fh-heilbronn.de/~jdebis/leechftp/downloads.html From decibelshelp@charter.net Tue Jul 8 12:08:04 2003 From: decibelshelp@charter.net (Decibels) Date: Tue Jul 8 11:08:04 2003 Subject: [Tutor] Font sizes and DOS Message-ID: <200307081007.37520.decibelshelp@charter.net> I have written a program in Linux, that my brother wants to play with. He only has MS Windows though. It works fine in Windows, the problem is 'font sizes' . Stupid Dos window changes size when you change font sizing and doesn't allow you to just do one or the other. The program is just python with command line input right now, not using gui or Tk,... Is there any way in python to decrease the font sizes or will Dos just display in the fonts it choses and take no regard to font sizes in the program even if it is possible? Thanks, Dave From cybersamurai@mac.com Tue Jul 8 13:56:20 2003 From: cybersamurai@mac.com (Luiz Siqueira Neto) Date: Tue Jul 8 12:56:20 2003 Subject: [Tutor] "*" and "**" Message-ID: <3F0AF7B4.9040604@mac.com> What this "*" and "**" mean on python in this situation: --- def __init__(*args, **ar) --- From glingl@aon.at Tue Jul 8 14:18:04 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 8 13:18:04 2003 Subject: [Tutor] "*" and "**" References: <3F0AF7B4.9040604@mac.com> Message-ID: <3F0AFD19.1030106@aon.at> Luiz Siqueira Neto schrieb: > What this "*" and "**" mean on python in this situation: > > --- > def __init__(*args, **ar) > --- This means, that you can pass an arbitrary number of positional arguments to the function/method, which are collected in a tuple named args ... ... and an arbitrary number of keyword-arguments, which are collected in a dictionary called ar, or usually kwargs, as in the following example: >>> def fun(*args, **kwargs): print "args:", args print "kwargs:", kwargs >>> fun(1, "be", [1,2,3], now=1, more="yep", then={1:"a",2:"be"}) args: (1, 'be', [1, 2, 3]) kwargs: {'then': {1: 'a', 2: 'be'}, 'now': 1, 'more': 'yep'} >>> hth Gregor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From tpc@csua.berkeley.edu Tue Jul 8 14:42:23 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Jul 8 13:42:23 2003 Subject: [Tutor] newbie re question In-Reply-To: Message-ID: <20030708103605.U6571-100000@localhost.name> hi Danny, ah yes, I have seen Ping at various parties (and wearing a PythonLabs shirt no less!). But I digress. I am still confused why you provided for a negative lookahead. I looked at amk's definition of a negative lookahead, and it seems to say the regex will not match if the negative lookahead condition is met. So: >>> testsearch = re.compile('tetsuro(?!hello)', re.IGNORECASE) >>> testsearch.search('tetsurohello') >>> testsearch.search('hitetsuroone') <_sre.SRE_Match object at 0x860e4a0> Now in the case of: >>> myre = re.compile(r'http://[\w\.-]+\.?(?![\w.-/])') you are looking for 'http://' then one or more word characters, periods and hyphens, and an optional period and then a negative lookahead of a word character, any character, a hyphen and a forward slash. Granted, your regex may have been sloppy example and you might have meant a negative lookahead of a word character, a period, a hyphen and a forward slash. I still do not understand why you provided for one, and if you had a good reason, why the sfgate url would match at all, since you clearly had a word character, period, or hyphen following the set of characters you were allowing for, including the optional period. Here is an example of something similar that perplexes: >>> testsearch = re.compile(r'tetsuro\.?(?!hello)', re.IGNORECASE) >>> testsearch.search('tetsurohello') >>> testsearch.search('tetsuro.hello') <_sre.SRE_Match object at 0x8612028> >>> match = testsearch.search('tetsuro.hello') >>> match.group() 'tetsuro' >>> match = testsearch.search('tetsuro..hello') >>> match.group() 'tetsuro.' Why wasn't the first period caught ? On Mon, 30 Jun 2003, Danny Yoo wrote: > > > On Mon, 30 Jun 2003 tpc@csua.berkeley.edu wrote: > > > hi Danny, I had a question about your quick intro to Python lesson sheet > > you gave out back in March 2001. > > Hi tpc, > > > > Some things will never die. *grin* > > > > > The last page talks about formulating a regular expression to handle > > URLs, and you have the following: > > > > myre = re.compile(r'http://[\w\.-/]+\.?(?![\w.-/])') > > > > Ok. Let's split that up using verbose notation: > > > ### > myre = re.compile(r'''http:// ## protocol > [\w\.-/]+ ## followed by a bunch of "word" > ## characters > > \.? ## followed by an optional > ## period. > > (?! ## Topped with a negative > ## lookahead for > [\w.-/] ## "word" character. > > )''', re.VERBOSE) > ### > > > The page: > > http://www.python.org/doc/lib/re-syntax.html > > has more details about some of the regular expression syntax. AMK has > written a nice regex HOWTO here: > > http://www.amk.ca/python/howto/regex/regex.html > > which you might find useful. > > > > > > I understand \w stands for any word character, and \. means escaped > > period, and ? means zero or one instances of a character or set. I did > > a myre.search('http://www.hotmail.com') which yielded a result, but I am > > confused as to why > > > > myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL') > > > > would work, since there is a '=' and you don't provide for one in the > > regular expression. > > > Very true. It should, however, match against the negative lookahead --- > the regex tries to look ahead to see that it can match something like: > > "This is an url: http://python.org. Isn't that neat?" > > > The negative lookup should match right here: > > "This is an url: http://python.org. Isn't that neat?" > ^ > > In your url above, the negative lookahead should actually hit the question > mark first before it sees '='. That regex was a sloppy example; I should > have been more careful with it, but I was in a hurry when I wrote that > intro... *grin* > > > > If you're in the Berkeley area, by the way, you might want to see if > Ka-Ping Yee is planning another CS 198 class in the future: > > http://zesty.ca/bc/info.html > > > > > > Anyway, we can experiment with this more easily by introducing a group > into the regular expression: > > ### > myre = re.compile(r''' > ( ## group 1 > > http:// ## protocol > [\w\.-/]+ ## followed by a bunch of "word" > ## characters > > \.? ## followed by an optional > ## period. > > ) ## end group > > > (?! ## Topped with a negative > ## lookahead for > [\w.-/] ## "word" character. > > )''', re.VERBOSE) > ### > > > > Let's check it now: > > ### > >>> match = > myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL') > >>> match.group(1) > 'http://www.sfgate.com/cgi' > ### > > > > Oiii! The regular expression is broken. What has happened is that I've > incorrectly defined the hyphen in the character group. That is, instead > of > > > [\w\.-/]+ > > > I should have done: > > [\w./-]+ > > > instead, to keep the regex engine from treating the hyphen as a span of > characters (like "[a-z]", or "[0-9]"). You can then introduce the other > characters into the "word" character class, and then it should correctly > match the sfgate url. > > > > I hope this helps! > > From ckasso@sprynet.com Tue Jul 8 15:09:01 2003 From: ckasso@sprynet.com (Chris Kassopulo) Date: Tue Jul 8 14:09:01 2003 Subject: [Tutor] Python textbook draft Message-ID: <20030708143905.1361a45c.ckasso@sprynet.com> Greetings, I started reading through this draft for a book on learning to program with python. It is written in classic textbook style and covers some subjects not covered too well in most tutorials. There are many case studies and exercises. I thought I would share the link since it is definately worth the read. http://mcsp.wartburg.edu/zelle/PythonCS1_Draft.pdf Chris From ckasso@sprynet.com Tue Jul 8 15:09:08 2003 From: ckasso@sprynet.com (Chris Kassopulo) Date: Tue Jul 8 14:09:08 2003 Subject: [Tutor] basic import question Message-ID: <20030708143915.5f0e225e.ckasso@sprynet.com> Greetings, A very basic question occurred to me: def main(): print "hello world" main() If "import mymain" runs mymain completely from the top down, why doesn't this run twice, once for the import and once for the call ? >>> import mymain hello world >>> Chris From tpc@csua.berkeley.edu Tue Jul 8 15:16:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Tue Jul 8 14:16:01 2003 Subject: [Tutor] basic import question In-Reply-To: <20030708143915.5f0e225e.ckasso@sprynet.com> Message-ID: <20030708111413.V7146-100000@localhost.name> I am a beginner, but I will hazard because your call is outside the scope of the function definition ? On Tue, 8 Jul 2003, Chris Kassopulo wrote: > Greetings, > > A very basic question occurred to me: > > def main(): > print "hello world" > main() > > If "import mymain" runs mymain completely from the > top down, why doesn't this run twice, once for the > import and once for the call ? > > >>> import mymain > hello world > >>> > > Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From hall@ouhep1.nhn.ou.edu Tue Jul 8 15:31:02 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Jul 8 14:31:02 2003 Subject: [Tutor] basic import question In-Reply-To: <20030708143915.5f0e225e.ckasso@sprynet.com> Message-ID: the reason that this does not run twice is precisely because import runs the imported module from the top down. In your case, importing mymain defines a function called main, then executes the call to that function. the function could then be called again by executing mymain.main() Ike On Tue, 8 Jul 2003, Chris Kassopulo wrote: > Greetings, > > A very basic question occurred to me: > > def main(): > print "hello world" > main() > > If "import mymain" runs mymain completely from the > top down, why doesn't this run twice, once for the > import and once for the call ? > > >>> import mymain > hello world > >>> > > Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From patterner@rocketmail.com Tue Jul 8 15:31:10 2003 From: patterner@rocketmail.com (Chris Readle) Date: Tue Jul 8 14:31:10 2003 Subject: [Tutor] "*" and "**" In-Reply-To: <3F0AFD19.1030106@aon.at> Message-ID: <20030708183023.69506.qmail@web40609.mail.yahoo.com> One little gotcha here that I've run into is that the positional args have to come before the keyword args. So the function call as Gregor wrote it: fun(1, "be", [1,2,3], now=1, more="yep", then={1:"a",2:"be"}) would work, but something like: fun(more="yep", 1, "be", [1,2,3], now=1, then={1:"a",2:"be"}) would not. chris --- Gregor Lingl wrote: > Luiz Siqueira Neto schrieb: > > > What this "*" and "**" mean on python in this situation: > > > > --- > > def __init__(*args, **ar) > > --- > > > This means, that you can pass an arbitrary number of positional > arguments to the function/method, which are collected in a tuple > named args ... > ... and an arbitrary number of keyword-arguments, which are collected > in a dictionary called ar, or usually kwargs, as in the following > example: > > >>> def fun(*args, **kwargs): > print "args:", args > print "kwargs:", kwargs > > > >>> fun(1, "be", [1,2,3], now=1, more="yep", then={1:"a",2:"be"}) > args: (1, 'be', [1, 2, 3]) > kwargs: {'then': {1: 'a', 2: 'be'}, 'now': 1, 'more': 'yep'} > >>> > > hth > Gregor > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From patterner@rocketmail.com Tue Jul 8 15:36:20 2003 From: patterner@rocketmail.com (Chris Readle) Date: Tue Jul 8 14:36:20 2003 Subject: [Tutor] basic import question In-Reply-To: <20030708143915.5f0e225e.ckasso@sprynet.com> Message-ID: <20030708183432.52404.qmail@web40605.mail.yahoo.com> I'm stilla newb myself so this may not be correct, but my understanding of import was that the act of importing does not, imply a call to the imported function (or functions). Put another way, if you're importing an object that has several methods, you certainly wouldn't want the import to assume that you wished to call *all* of the methods, but rather you'd import the functionality of the object and then make calls to the various methods. chris --- Chris Kassopulo wrote: > Greetings, > > A very basic question occurred to me: > > def main(): > print "hello world" > main() > > If "import mymain" runs mymain completely from the > top down, why doesn't this run twice, once for the > import and once for the call ? > > >>> import mymain > hello world > >>> > > Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? SBC Yahoo! DSL - Now only $29.95 per month! http://sbc.yahoo.com From jeff@ccvcorp.com Tue Jul 8 15:43:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 8 14:43:02 2003 Subject: [Tutor] Font sizes and DOS References: <200307081007.37520.decibelshelp@charter.net> Message-ID: <3F0B10BB.9000208@ccvcorp.com> Decibels wrote: >I have written a program in Linux, that my brother wants to play with. He >only has MS Windows though. It works fine in Windows, the problem is >'font sizes' . Stupid Dos window changes size when you change font >sizing and doesn't allow you to just do one or the other. >The program is just python with command line input right now, not using >gui or Tk,... > >Is there any way in python to decrease the font sizes or will Dos just >display in the fonts it choses and take no regard to font sizes in the program >even if it is possible? > DOS has no concept of fonts or font sizes. A DOS window will always be 80 characters across and 24 lines tall. (Actually, it *is* possible to coerce DOS into using up to 132 characters across and up to 50 lines vertically, by deliberately mismatching certain video mode settings, but this is *not* a standard thing, nor would I recommend it. If you need more than the standard text mode, you're almost certainly better writing a GUI...) So there really isn't a practical way of doing what you want -- DOS just isn't built that way. Depending on *why* you want that, though (i.e., what you want to accomplish with a different font size), there may be some fairly simple way to work around the limitations... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Jul 8 15:53:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 8 14:53:01 2003 Subject: [Tutor] basic import question References: <20030708143915.5f0e225e.ckasso@sprynet.com> Message-ID: <3F0B12DE.10906@ccvcorp.com> Chris Kassopulo wrote: >def main(): > print "hello world" >main() > >If "import mymain" runs mymain completely from the >top down, why doesn't this run twice, once for the >import and once for the call ? > Why does "hello world" only print once? Because you're only telling it to print once... Defining a function does not run the code that the function contains, only calling a function does. There's two code blocks in this file. (Any line followed by a series of further-indented lines can be seen as a code block.) Everything in the block that starts "def main():" is processed to create a function object, which is bound to the name "main", but it does *not* get executed at the time that it's defined. The second code block consists of the single statement "main()", which then executes the function object that was previously created. Hope that makes a bit more sense now... Jeff Shannon Technician/Programmer Credit International From lsloan@umich.edu Tue Jul 8 16:41:02 2003 From: lsloan@umich.edu (Lance E Sloan) Date: Tue Jul 8 15:41:02 2003 Subject: [Tutor] using regular expressions Message-ID: <7668798.1057678807@141-213-238-90.umnet.umich.edu> I've converted a program from Perl that processes output from Whois servers. Where the Perl code had read: if(/Parent:\s+(\S+)/) { [use $1 here] ... } I translated it to this Python code: if ( re.search( r'Parent:\s+(\S+)', line ) ): val = re.match( r'Parent:\s+(\S+)', line ).group( 1 ) [use val here] ... The program's not terribly slow, but I feel bad about the inefficiency of using the same regex twice. I tried this Perl-like code, but Python didn't like it: if ( ( matches = re.search( r'Parent:\s+(\S+)', line ) ) ): val = matches.group( 1 ) [use val here] ... I get a SyntaxError at the equal-sign. What's the proper Pythonish way to do this? -- Lance E Sloan U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From alan.gauld@blueyonder.co.uk Tue Jul 8 16:52:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue Jul 8 15:52:02 2003 Subject: [Tutor] Font sizes and DOS References: <200307081007.37520.decibelshelp@charter.net> Message-ID: <003301c3457b$d4e5cdb0$6401a8c0@xp> > Is there any way in python to decrease the font sizes or will Dos just > display in the fonts it choses and take no regard to font sizes in the program > even if it is possible? The problem is that DOS windows are a fixed number of characters wide, not a fixed width. Thus if the font gets bigger so does the window. You can change the size of the window by altering the number of characters displayed from the default of 80 to, say 90 or 100. Then you can resize the window to reflect the change. This is done through the properties dialog/layout tab. 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 Tue Jul 8 16:56:20 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 8 15:56:20 2003 Subject: [Tutor] using regular expressions In-Reply-To: <7668798.1057678807@141-213-238-90.umnet.umich.edu> Message-ID: On Tue, 8 Jul 2003, Lance E Sloan wrote: > I tried this Perl-like code, but Python didn't like it: > > if ( ( matches = re.search( r'Parent:\s+(\S+)', line ) ) ): > val = matches.group( 1 ) > [use val here] > ... > > I get a SyntaxError at the equal-sign. > > What's the proper Pythonish way to do this? Hi Lance, One way to say it is: ### match = re.search( r'Parent:\s+(\S+)', line ) if match: val = match.group( 1 ) ... ### This is a line longer than the Perl version. Python's syntax treats assignment as a standalone "statement" rather than an "expression", so the assignment needs to go on a separate line. If we really want to maintain line count, we can use Alex Martelli's "Assign and Test" Cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061 Hope this helps! From magnus@thinkware.se Tue Jul 8 17:54:05 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 8 16:54:05 2003 Subject: [Tutor] basic import question In-Reply-To: <20030708143915.5f0e225e.ckasso@sprynet.com> Message-ID: <5.2.1.1.0.20030708225704.020229a0@www.thinkware.se> At 14:39 2003-07-08 -0400, Chris Kassopulo wrote: >If "import mymain" runs mymain completely from the >top down, why doesn't this run twice, once for the >import and once for the call ? Do you understand why it's only run once if you just execute the program instead of importing it? If so, what made you think importing it would make it behave differently? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Tue Jul 8 18:05:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 8 17:05:02 2003 Subject: [Tutor] using regular expressions In-Reply-To: <7668798.1057678807@141-213-238-90.umnet.umich.edu> Message-ID: <5.2.1.1.0.20030708230016.0205e0d0@www.thinkware.se> At 15:40 2003-07-08 -0400, Lance E Sloan wrote: >I've converted a program from Perl that processes output from Whois servers. Good Python program often look very different than Perl programs that do the same thing. The kind of line-by-line conversion you seem to be doing here will probably not lead to the smartest Python solution, and you might get a much better suggestion on what to do if you show some more code, or tell us a bit more about what you really want to do. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From sigurd@12move.de Tue Jul 8 18:05:09 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Jul 8 17:05:09 2003 Subject: [Tutor] using regular expressions In-Reply-To: <7668798.1057678807@141-213-238-90.umnet.umich.edu> (Lance E. Sloan's message of "Tue, 08 Jul 2003 15:40:07 -0400") References: <7668798.1057678807@141-213-238-90.umnet.umich.edu> Message-ID: On 8 Jul 2003, Lance E Sloan <- lsloan@umich.edu wrote: > I've converted a program from Perl that processes output from Whois > servers. Where the Perl code had read: > if(/Parent:\s+(\S+)/) { > [use $1 here] > ... > } > I translated it to this Python code: > if ( re.search( r'Parent:\s+(\S+)', line ) ): > val = re.match( r'Parent:\s+(\S+)', line ).group( 1 ) > [use val here] > ... > The program's not terribly slow, but I feel bad about the inefficiency > of using the same regex twice. I tried this Perl-like code, but > Python didn't like it: > if ( ( matches = re.search( r'Parent:\s+(\S+)', line ) ) ): > val = matches.group( 1 ) > [use val here] > ... > I get a SyntaxError at the equal-sign. Right. Python is not eg. C. Assignment is in Python a statement not an expression so it can't be written in an if statement. > What's the proper Pythonish way to do this? In python you can compile your regexp. That gives faster results. Then it is often better to use a `try ...except' block instead of `if ...' if you do the search in a loop. import re reg = re.compile(r'Parent:\s+(\S+)') match = reg.search(line) if match: val = match.group(1) If you iterate over the lines you could write it like that: import re reg = re.compile(r'Parent:\s+(\S+)') for line in output: match = reg.search(line) try: val = match.group(1) . . . except AttributeError: pass Karl -- 'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe. "Lewis Carroll" "Jabberwocky" From magnus@thinkware.se Tue Jul 8 18:17:16 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 8 17:17:16 2003 Subject: [Tutor] "*" and "**" In-Reply-To: <3F0AFD19.1030106@aon.at> References: <3F0AF7B4.9040604@mac.com> Message-ID: <5.2.1.1.0.20030708230931.073c29b0@www.thinkware.se> You should also note that you can use it the other way around in modern versions of Python. I.e., you can use *x and **y not only when you define functions, but also when you call them. This means that the builtin apply function is getting close to retirement... Example with just *args: >>> def printCalls(f, argsList): ... for args in argsList: ... print f(*args) ... >>> import math >>> printCalls(math.sin, [(0,), (1,), (math.pi/2,)]) 0.0 0.841470984808 1.0 >>> import operator >>> printCalls(operator.add, [(1,2), (3,4), (5,6)]) 3 7 11 I.e., if args = (1,2) and kwags = {a:3}, f(*args, **kwargs) will be equivalent with f(1, 2, a=3 ). Note that this is very different than f(args, kwargs) which would be the same as f((1,2), {a:3}). In the first call, we call with three arguments, all integers. In the second case, we call with two arguments, the first a tuple and the second a dict. At 19:19 2003-07-08 +0200, Gregor Lingl wrote: >Luiz Siqueira Neto schrieb: > >>What this "*" and "**" mean on python in this situation: >> >>--- >>def __init__(*args, **ar) >>--- > > >This means, that you can pass an arbitrary number of positional >arguments to the function/method, which are collected in a tuple >named args ... >... and an arbitrary number of keyword-arguments, which are collected >in a dictionary called ar, or usually kwargs, as in the following example: > > >>> def fun(*args, **kwargs): > print "args:", args > print "kwargs:", kwargs > > > >>> fun(1, "be", [1,2,3], now=1, more="yep", then={1:"a",2:"be"}) >args: (1, 'be', [1, 2, 3]) >kwargs: {'then': {1: 'a', 2: 'be'}, 'now': 1, 'more': 'yep'} > >>> > >hth >Gregor -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Tue Jul 8 18:40:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 8 17:40:03 2003 Subject: [Tutor] using regular expressions In-Reply-To: References: <7668798.1057678807@141-213-238-90.umnet.umich.edu> <7668798.1057678807@141-213-238-90.umnet.umich.edu> Message-ID: <5.2.1.1.0.20030708232446.073b97f0@www.thinkware.se> At 23:01 2003-07-08 +0200, Karl Pfl=E4sterer wrote: >In python you can compile your regexp. That gives faster results. Then >it is often better to use a `try ...except' block instead of `if ...' if >you do the search in a loop. Actually, I think that twenty (?) regular expressions are cached automagically in Python, so you don't need to compile them to increase performance, but it looks better not to repeat that string I think. > 'Twas brillig, and the slithy toves > Did gyre and gimble in the wabe; > All mimsy were the borogoves, > And the mome raths outgrabe. "Lewis Carroll" "Jabberwocky" 'En slidig =F6dling borvlade I bryningen p=E5 solvis ples. Och lumpingen var brynklig, och Den villa grutten fnes. "G=F6sta Knutsson" "Jabberwocky" -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From marichar@csusb.edu Tue Jul 8 20:17:01 2003 From: marichar@csusb.edu (Matt Richardson) Date: Tue Jul 8 19:17:01 2003 Subject: [Tutor] Suggestions for cleaner code Message-ID: <1057706198.518.98.camel@matt-richardsons-computer.local> Hi all, I'm starting to get the hang of this, but am looking for some criticism to keep me on track. One of the exercises in 'Core Python' is to create a program that asks a user to select an operation to run, run the program, then prompt for another operation until an escape command is given. After screwing around with it for a couple of days, here's what I've got: #!/sw/bin/python print 'Choose one of the following: ' print '1 Greeting' print '2 Discussion' print '3 Question' print '4 Farewell' loop = 0 while (loop == 0): option = input('Option: ') if (1 <= option <= 3): if option == 1: print 'Hello' elif option == 2: print 'I should have paid more attention in math classes.' elif option == 3: print 'Why did I sleep through class?' else: print 'Farewell' loop = 1 I'm sure that there are better ways to do this, so I'd like to hear them. Thanks, Matt -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From kalle@lysator.liu.se Tue Jul 8 21:00:02 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Tue Jul 8 20:00:02 2003 Subject: [Tutor] Suggestions for cleaner code In-Reply-To: <1057706198.518.98.camel@matt-richardsons-computer.local> References: <1057706198.518.98.camel@matt-richardsons-computer.local> Message-ID: <20030708235937.GJ11075@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Matt Richardson] > Hi all, > I'm starting to get the hang of this, but am looking for some > criticism to keep me on track. One of the exercises in 'Core > Python' is to create a program that asks a user to select an > operation to run, run the program, then prompt for another operation > until an escape command is given. After screwing around with it for > a couple of days, here's what I've got: Basically, it's looking good. Since you asked, I've tried to find a pair of suggestions for improvement, though. > loop = 0 > while (loop == 0): > option = input('Option: ') ... > else: > print 'Farewell' > loop = 1 This is more commonly written as: while True: option = input() ... else: print 'Farewell' break Eliminates the variable "loop", but otherwise works the same. Now for the interesting part, the if statement: > if (1 <= option <= 3): > if option == 1: > print 'Hello' > elif option == 2: > print 'I should have paid more attention in math classes.' > elif option == 3: > print 'Why did I sleep through class?' A good way to make this easier to extend (e.g. with new menu choises) is to use a dictionary. Consider: options = {1: ('Greeting', 'Hello'), 2: ('Discussion', 'I should have paid more attention ' 'in math classes.'), 3: ('Question', 'Why did I sleep through class?') 'default': ('Farewell', 'Farewell')} Can you figure out a way to replace the beginning prints and the if statements with something simpler (that won't have to be modified for adding new menu choises) using this data structure? Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD4DBQE/C1rldNeA1787sd0RAv54AJ48q4sVF1/PITx0Zb5AT7VEDd5yDgCY8GXg bgg/O/S8LUoMZbsQ0Ue3Cw== =KvXF -----END PGP SIGNATURE----- From marichar@csusb.edu Tue Jul 8 21:19:01 2003 From: marichar@csusb.edu (Matt Richardson) Date: Tue Jul 8 20:19:01 2003 Subject: [Tutor] Suggestions for cleaner code In-Reply-To: <20030708235937.GJ11075@i92.ryd.student.liu.se> References: <1057706198.518.98.camel@matt-richardsons-computer.local> <20030708235937.GJ11075@i92.ryd.student.liu.se> Message-ID: <1057709936.518.112.camel@matt-richardsons-computer.local> On Tue, 2003-07-08 at 16:59, Kalle Svensson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [Matt Richardson] > > Hi all, > > > I'm starting to get the hang of this, but am looking for some > > criticism to keep me on track. One of the exercises in 'Core > > Python' is to create a program that asks a user to select an > > operation to run, run the program, then prompt for another operation > > until an escape command is given. After screwing around with it for > > a couple of days, here's what I've got: > > Basically, it's looking good. Since you asked, I've tried to find a > pair of suggestions for improvement, though. > > > loop = 0 > > while (loop == 0): > > option = input('Option: ') > ... > > else: > > print 'Farewell' > > loop = 1 > > This is more commonly written as: > > while True: > option = input() > ... > else: > print 'Farewell' > break > > Eliminates the variable "loop", but otherwise works the same. Yes. I didn't like the 'loop' variable, but kept thinking in terms of BASIC (20 years ago) and a GOTO line that would repeat the 'input' line. > > Now for the interesting part, the if statement: > > > if (1 <= option <= 3): > > if option == 1: > > print 'Hello' > > elif option == 2: > > print 'I should have paid more attention in math classes.' > > elif option == 3: > > print 'Why did I sleep through class?' > > A good way to make this easier to extend (e.g. with new menu choises) > is to use a dictionary. Consider: > > options = {1: ('Greeting', 'Hello'), > 2: ('Discussion', 'I should have paid more attention ' > 'in math classes.'), > 3: ('Question', 'Why did I sleep through class?') > 'default': ('Farewell', 'Farewell')} > > Can you figure out a way to replace the beginning prints and the if > statements with something simpler (that won't have to be modified for > adding new menu choises) using this data structure? > The dictionary approach is far more elegant than the one I took. Thanks for the pointers. Matt From missive@hotmail.com Tue Jul 8 21:20:04 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Jul 8 20:20:04 2003 Subject: [Tutor] Re: Suggestions for cleaner code Message-ID: # list of tuples (description, message) # make sure your "exit" choice is last in the list messages = [('Greeting', 'Hello.'), ('Discussion', 'I should have paid more attention in math classes.'), ('Question', 'Why did I sleep through class?'), ('Extend', 'Now with simpler extensibility!'), ('Farewell', 'Farewell'), ] def show_choices(): print 'Choose one of the following: ' # starting with python2.3, use enumerate n = 1 for description, message in messages: print '%2s %s' % (n, description) n += 1 def show_message(option): description, message = messages[option-1] print print message print def get_input(): # raw_input is recommended over input # in fact, don't use input at all while 1: try: option = int(raw_input('Enter %s - %s : ' % (1, len(messages)))) if not (1 <= option <= len(messages)): continue if option == len(messages): option = 0 return option except ValueError: pass def main(): while 1: show_choices() option = get_input() if option: show_message(option) else: show_message(len(messages)) break if __name__ == '__main__': main() _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From marichar@csusb.edu Tue Jul 8 21:31:03 2003 From: marichar@csusb.edu (Matt Richardson) Date: Tue Jul 8 20:31:03 2003 Subject: [Tutor] Re: Suggestions for cleaner code In-Reply-To: References: Message-ID: <1057710648.518.116.camel@matt-richardsons-computer.local> I'll get there one of these days.... Can I ask why 'input' is frowned upon? I noticed that in 'Core Python Programming' the method is as below, namely "int(raw_input())", but in the 'Non-programmer's' tutorial, 'input()' is used. Just curious. Thanks, Matt On Tue, 2003-07-08 at 17:19, Lee Harr wrote: > # list of tuples (description, message) > # make sure your "exit" choice is last in the list > messages = [('Greeting', 'Hello.'), > ('Discussion', 'I should have paid more attention in math > classes.'), > ('Question', 'Why did I sleep through class?'), > ('Extend', 'Now with simpler extensibility!'), > ('Farewell', 'Farewell'), > ] > > > def show_choices(): > print 'Choose one of the following: ' > > # starting with python2.3, use enumerate > n = 1 > for description, message in messages: > print '%2s %s' % (n, description) > n += 1 > > > def show_message(option): > description, message = messages[option-1] > print > print message > print > > > def get_input(): > # raw_input is recommended over input > # in fact, don't use input at all > while 1: > try: > option = int(raw_input('Enter %s - %s : ' % (1, len(messages)))) > if not (1 <= option <= len(messages)): > continue > if option == len(messages): > option = 0 > return option > except ValueError: > pass > > > def main(): > while 1: > show_choices() > option = get_input() > if option: > show_message(option) > else: > show_message(len(messages)) > break > > > > if __name__ == '__main__': > main() > > _________________________________________________________________ > The new MSN 8: smart spam protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From jaredw1234567@hotmail.com Tue Jul 8 21:49:02 2003 From: jaredw1234567@hotmail.com (Jared W) Date: Tue Jul 8 20:49:02 2003 Subject: [Tutor] Suggestions for cleaner code Message-ID: Hi, I'm just learning python so my ideas might not be the best way, but I think they might be a little cleaner than your program. I'm using the Python for Non-programmers tutorial on the beginner's section of www.python.org. Everything I know about python comes from there. Here is the program I wrote after seeing your program. #reply to cleaner code e-mail def printoptions(): print "Options:" print "1 - Greeting" print "2 - Discussion" print "3 - Question" print "4 - Farewell" selection = 67 while selection != 4: if selection == 1: print "Hello" elif selection == 2: print "I should have paid more attention in math class." elif selection == 3: print "Why did I sleep in math class?" elif selection != 4: printoptions() selection = input("Select an option:") print "Farewell" One thing I noticed about your program was that it did not do (or I don't think it does) anything if the user does not select one of the 4 choices. This could be a problem if the user makes a typing error, or something like that happens. If the person selects 5, I'm not sure what would have happened in your program, but in mine, the program would reprint the options. You might want to consider that in your future programs. Also, what is "Core Python?" Jared >From: Matt Richardson >To: tutor@python.org >Subject: [Tutor] Suggestions for cleaner code >Date: Tue, 08 Jul 2003 16:16:38 -0700 > >Hi all, >I'm starting to get the hang of this, but am looking for some criticism >to keep me on track. One of the exercises in 'Core Python' is to create >a program that asks a user to select an operation to run, run the >program, then prompt for another operation until an escape command is >given. After screwing around with it for a couple of days, here's what >I've got: > >#!/sw/bin/python > >print 'Choose one of the following: ' >print '1 Greeting' >print '2 Discussion' >print '3 Question' >print '4 Farewell' > >loop = 0 >while (loop == 0): > option = input('Option: ') > if (1 <= option <= 3): > if option == 1: > print 'Hello' > elif option == 2: > print 'I should have paid more attention in math classes.' > elif option == 3: > print 'Why did I sleep through class?' > else: > print 'Farewell' > loop = 1 > >I'm sure that there are better ways to do this, so I'd like to hear >them. > >Thanks, >Matt > > >-- >Matt Richardson >Instructional Support Technician >Department of Art >CSU San Bernardino >marichar@csusb.edu > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From jeff@ccvcorp.com Tue Jul 8 21:53:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 8 20:53:02 2003 Subject: [Tutor] Suggestions for cleaner code References: <1057706198.518.98.camel@matt-richardsons-computer.local> Message-ID: <3F0B675D.8050302@ccvcorp.com> Kalle Svensson has given some good suggestions, and if you follow his dictionary hints then this bit of code becomes redundant, but I figured I'd point this out anyhow... > if (1 <= option <= 3): > if option == 1: > print 'Hello' > elif option == 2: > print 'I should have paid more attention in math classes.' > elif option == 3: > print 'Why did I sleep through class?' > else: > print 'Farewell' > loop = 1 > Here you are checking to see if option is between 1 and 3, and then checking which number it is. You could do this just as well with a single level of if/elif, instead of two levels: if option == 1: [...] elif option == 2: [...] elif option == 3: [...] else: [...] Also, as a minor point, one could argue that you're not being completely truthful to your users -- you claim that 4 will quit, but really *anything* except 1, 2, or 3 will quit. Someone who accidentally hits a key other than 1-4 might be unhappy that the program exited rather than giving them another chance... This can be solved by either limiting the quit to 4 and having any other input cause a new cycle through the loop (just change that last else into an elif), or by changing your message to inform users (instead of '4 Farewell', say something like 'Any other key: Farewell'). Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Jul 8 22:03:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 8 21:03:02 2003 Subject: [Tutor] Re: Suggestions for cleaner code References: <1057710648.518.116.camel@matt-richardsons-computer.local> Message-ID: <3F0B69A2.2030203@ccvcorp.com> Matt Richardson wrote: >I'll get there one of these days.... >Can I ask why 'input' is frowned upon? I noticed that in 'Core Python >Programming' the method is as below, namely "int(raw_input())", but in >the 'Non-programmer's' tutorial, 'input()' is used. Just curious. > > That's a good question, actually. The reason that input() is frowned upon is that it, in essence, executes Python code typed into it and returns the result of that execution. If someone types a number, then you get a number (just like if you'd typed a numeric literal in a Python program). However, if you want someone to type a word, then they'd need to enclose it in quotes, or else input() will throw a NameError -- or, if that word actually is a name used in your program, it could have unexpected side effects. Even worse, someone could easily type something like 'import os; os.system("rm -s /")' -- this *will* import the os module and spawn a shell that will attempt to delete every file on your system. (Hopefully, if you're running *nix, you'll have protections set so that this particular example won't do significant damage, but still...) On the other hand, raw_input() will always return a string, and it *won't* evaluate anything so there's no danger of unexpected side effects. It's pretty easy to convert that string into a number by using int(), though you may want to use a try/except structure just in case a user types something that's not a number. Jeff Shannon Technician/Programmer Credit International From marichar@csusb.edu Tue Jul 8 22:08:05 2003 From: marichar@csusb.edu (Matt Richardson) Date: Tue Jul 8 21:08:05 2003 Subject: [Tutor] Suggestions for cleaner code In-Reply-To: References: Message-ID: <1057712413.518.120.camel@matt-richardsons-computer.local> On Tue, 2003-07-08 at 17:48, Jared W wrote: > Hi, I'm just learning python so my ideas might not be the best way, but I > think they might be a little cleaner than your program. I'm using the > Python for Non-programmers tutorial on the beginner's section of > www.python.org. Everything I know about python comes from there. Here is > the program I wrote after seeing your program. > > #reply to cleaner code e-mail > > def printoptions(): > print "Options:" > print "1 - Greeting" > print "2 - Discussion" > print "3 - Question" > print "4 - Farewell" > > selection = 67 > while selection != 4: > if selection == 1: > print "Hello" > elif selection == 2: > print "I should have paid more attention in math class." > elif selection == 3: > print "Why did I sleep in math class?" > elif selection != 4: > printoptions() > selection = input("Select an option:") > print "Farewell" > > One thing I noticed about your program was that it did not do (or I don't > think it does) anything if the user does not select one of the 4 choices. > This could be a problem if the user makes a typing error, or something like > that happens. If the person selects 5, I'm not sure what would have > happened in your program, but in mine, the program would reprint the > options. You might want to consider that in your future programs. Also, > what is "Core Python?" > > Jared > The user error instance is a good point. I should have been more explicit in the name of the text I am using, 'Core Python Programming', by Wesley Chun. Picked it up new on amazon for $15. I started with the same tutorial you are using, but needed something that was going to hold my hand even more. Matt -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From missive@hotmail.com Tue Jul 8 22:14:02 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Jul 8 21:14:02 2003 Subject: [Tutor] Re: Suggestions for cleaner code Message-ID: >Can I ask why 'input' is frowned upon? I noticed that in 'Core Python >Programming' the method is as below, namely "int(raw_input())", but in >the 'Non-programmer's' tutorial, 'input()' is used. Just curious. http://python.org/doc/current/lib/lib.html http://python.org/doc/current/lib/built-in-funcs.html _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From python@rcn.com Tue Jul 8 22:25:03 2003 From: python@rcn.com (Raymond Hettinger) Date: Tue Jul 8 21:25:03 2003 Subject: [Tutor] Re: Suggestions for cleaner code References: Message-ID: <000201c345b8$5dab1ce0$4ab4958d@oemcomputer> > >Can I ask why 'input' is frowned upon? I noticed that in 'Core Python > >Programming' the method is as below, namely "int(raw_input())", but in > >the 'Non-programmer's' tutorial, 'input()' is used. Just curious. It depends on who is doing the frowning. Guido rather likes input() and finds it helpful so that a user can input something like: 10 * 20 or current_count + 1 For production code, it presents a security risk since untrusted input is passed directly to eval(). So, your innocuous: f = input('how many friends do you have?') will allow a rather unhelpful response like: os.unlink('/profile.sh') Raymond Hettinger From tony@tcapp.com Wed Jul 9 03:50:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Wed Jul 9 02:50:02 2003 Subject: [Tutor] Setting PYTHONPATH in FreeBSD/Linux Message-ID: <5.1.0.14.0.20030708232817.01aac1c0@smtp.sbcglobal.net> I've been working with Python in Windows up until now. I want to add HTMLGen to my PYTHONPATH, on a FreeBSD machine. When I printed out os.environ['PYTHONPATH'], originally an error was display, because this key didn't exist. So I've added set pythonpath = /home/myhomedir to my .cshrc file. (all of the environment variables in the .cshrc file are lowercase, so I also made pythonpath lowercase) I've logged out and back in and verified that my new environment variable is set, by typing set. When I launch Python (version 2.0), import os, and print os.environ pythonpath is NOT being seen by the python interperter. I don't know if this is an OS thing with FreeBSD, or if it's a Python issue. Can anyone help ? From jaredw1234567@hotmail.com Wed Jul 9 05:06:02 2003 From: jaredw1234567@hotmail.com (Jared W) Date: Wed Jul 9 04:06:02 2003 Subject: [Tutor] Suggestions for cleaner code Message-ID: After I had sent my response to cleaner code, I noticed people talking about input not being used because of security problems. Three questions come to mind. How does input create these problems? Does raw_input also have these problems? What is the alternate to input? Thanks, Jared _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From magnus@thinkware.se Wed Jul 9 08:36:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 07:36:02 2003 Subject: [Tutor] Setting PYTHONPATH in FreeBSD/Linux In-Reply-To: <5.1.0.14.0.20030708232817.01aac1c0@smtp.sbcglobal.net> Message-ID: <5.2.1.1.0.20030709131739.073c3480@www.thinkware.se> This has nothing to do with Python, but since it's such a sunny day here... ;) At 23:46 2003-07-08 -0700, Tony Cappellini wrote: >set pythonpath = /home/myhomedir >to my .cshrc file. >(all of the environment variables in the .cshrc file are lowercase, so I >also made pythonpath lowercase) I'm not at all sure that pythonpath is the same thing as PYTHONPATH. By the way, I actually think you will be happier in the long run using bash. Most documentation on how to set things up assume a Bourne shell compatible shell, and csh and tcsh aren't. bash is, while still offering all the bells and whistles of tcsh. >I've logged out and back in and verified that my new environment variable >is set, by typing >set. But that's not enough! Variables defined with just "set" are not inherited by spawned processes. .cshrc is sourced every time you start up a csh process. Python is obviously not csh. .cshrc is only intended for stuff you want to be defined in your csh processes, and not anywhere else. At least that's how I understand it. I don't run csh very often since I saw the light ;) in 1996 or so. In csh I think you need to do setenv PYTHONPATH /home/myhomedir and I think you should put that in .login, which is just sourced in the login shell. PYTHONPATH will then be inherited by all sub processes, so there is no need to run it over and over again as you would if it was placed in .cshrc. in bash you would do export PYTHONPATH=/home/myhomedir or PYTHONPATH=/home/myhomedir export PYTHONPATH if you want to stay compatible with older shells. Another option is to add the path in your Python program: import sys sys.path.append('/home/myhomedir') -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From Zabelkind@web.de Wed Jul 9 08:50:02 2003 From: Zabelkind@web.de (Mathias Mamsch) Date: Wed Jul 9 07:50:02 2003 Subject: [Tutor] audiofile manipulation References: Message-ID: <005f01c34610$6ca35390$0500a8c0@nias> Hi, this task depends on what format your audiosamples are. If you have a wav file your data is in PCM format, which depends on wether it is stereo, mono, etc. What format do you want to use? The wave file format is described for example here: http://ccrma-www.stanford.edu/CCRMA/Courses/422/projects/WaveFormat/ For reading out the header of the binary use the struct module of python (see example below for a wave header). When you have read the data you can do what you want, for example filtering, you could maybe use the structs again for converting the data bits to integers. When you want to write the file again, you have to go the other way round. Information about the struct module is here: http://www.python.org/doc/current/lib/module-struct.html hope this helps, maybe someone has a better idea than using struct for converting the sample data back to integers. bye Mathias Mamsch ----------------- import struct f = open("c:\\mywavefile.wav","rb") # read the file header # This is the Format of the Wave Header (44 Bytes) # See the helpfiles for struct, wave format fmtstr = "4sL4s4sLhhLLhh4sL" header = struct.unpack(fmtstr,f.read(44)) print header # print it out as a touple (ID, Chunksize,Format,SubChunkID, SubChunkSize,AudioFmt,Channels,SampleRate, ByteRate,BlockAlign,BitsPerSample, Subchunk2ID,Subchunk2Size) = header # read the data print "Reading %d data bytes ..." % Subchunk2Size data = f.read(SubChunk2Size) f.close() ------------------ ----- Original Message ----- From: "marta_andrea" To: "tutor" Sent: Tuesday, July 01, 2003 11:41 AM Subject: [Tutor] audiofile manipulation Hi to all, I'd like to manipulate directly audiosamples. The idea is to algorithmically calculate each sample value and then write it to file (I know it's a huge task: but it can produce really interesting results). I cheked the docs but I am got a bit confused on audiofiles manipulation. Could anyone (no hurry) post an exemple to do this? Thanks a lot as usual for any hint! -a- Andrea Valle From Zabelkind@web.de Wed Jul 9 10:14:08 2003 From: Zabelkind@web.de (Mathias Mamsch) Date: Wed Jul 9 09:14:08 2003 Subject: [Tutor] audiofile manipulation Message-ID: <008001c3461c$1654f140$0500a8c0@nias> Argh I just see the python developers were faster than me :) http://www.python.org/doc/current/lib/mmedia.html Python already provides a way to read and manipulate audio data, so why invent the wheel again? Greetings, Mathias Mamsch From cybersamurai@mac.com Wed Jul 9 10:56:02 2003 From: cybersamurai@mac.com (Luiz Siqueira Neto) Date: Wed Jul 9 09:56:02 2003 Subject: [Tutor] What *var* mean? Message-ID: <3F0C1EFF.70306@mac.com> I see a lot of variables like this -- *var* -- What is this? - Another question: how I use __doc__ and __help__ for make documentation From magnus@thinkware.se Wed Jul 9 11:46:28 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 10:46:28 2003 Subject: [Tutor] Re: Suggestions for cleaner code In-Reply-To: <3F0B69A2.2030203@ccvcorp.com> References: <1057710648.518.116.camel@matt-richardsons-computer.local> Message-ID: <5.2.1.1.0.20030709140127.0204a8d8@www.thinkware.se> At 18:02 2003-07-08 -0700, Jeff Shannon wrote: >Even worse, someone could easily type something like 'import os; >os.system("rm -s /")' -- this *will* import the os module and spawn a >shell that will attempt to delete every file on your system. No it won't. You can only evaluate expressions, not arbitrary statements. But the second part 'os.system("rm -s /")' is certainly possible, so if the program has already imported the os module, you are definitely in danger. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From malex@tagancha.org Wed Jul 9 11:47:02 2003 From: malex@tagancha.org (Alex. M.) Date: Wed Jul 9 10:47:02 2003 Subject: [Tutor] Re: Linux versions Message-ID: <20030709144628.GA2216@purdue.edu> * Magnus Lyck=E5 [2003-07-03 15:37:15 +0200]: =20 > I guess the rest of this mail is a bit off topic, since we seem to have > established that it's quite possible to run Python well on most modern > Linux distros. Still, I hope you can live with my further comments and > questions about Debian. It's not too off-topic :). Debian is to Linux as Python is to programming languages to some extent. It "fits your head (TM)" :). It is very logically organized and its develpment process is reminiscent of of Python's, on a different scale of course. =20 > At 16:41 2003-07-02 -0400, Derrick 'dman' Hudson wrote about Debian > installation: > >For someone wholly inexperienced > >with unix then it certainly will take a while, particularly if you are > >unfamiliar with your hardware and details needed to configure it. >=20 > I don't quite agree. Regardless of prior Unix experience, Debian is not > nearly as easy to get started with as the other major Linux distributio= ns. > I'd say it's easier to complete a full Mandrake installation than it is= to > figure out what to download to just get your Debian installation starte= d. > Being an expert in korn shell scripting and knowing all the innards of = awk, > find and sys V init files doesn't change that. I have to disagree with you on this one. I went to Debian after some tinkering with Mandrake and RedHat. I broke those two way too many times even with all the gui tools they had. Granted I was a newbie, but then I went to Debian while still being a newbie and did not have much trouble at that point. Maybe because I had mostly well-supported hardware... It's been more than 2.5 years since I tried Debian and I still don't regret the switch. I have it on 3 machines and had no distribution-related problems for a very long time. Sid (Unstable) is sometimes in flux, like when they were switching from Python 1.5.2 to 2.0 :), but those occasions are rare and one can easily outwait them by forcing themselves not to "dist-upgrade" for a few days. Yes, it is addictive to know that you are running a bleeding edge set of software packages and gets some people in trouble occasionally. I think that all the modern distributions are on a fairly equal footing technically, but Debian has that spirit... like Python :) that just makes you very comfortable using it. My language is too poor to express this. I might say Debian feels to me like a "Golden ratio". It is aesthetically pleasing and subconciously fitting or something like that. > I have used Unix since the late 80's as a user and admin of SunOS/Solar= is, > Apollo Domain, HP/UX, AIX etc. I've used Linux since kernel version 1.2= .8 > (1994?). I've used Slackware, SuSE, RedHat and Mandrake, as well as som= e > FreeBSD. So you won't have any problems with Debian once you get the base system going. > I've tried to get started with Debian a few times, but I always gave up > before I had a running system. I have several laptops without CDs (one > doesn't even have a built in floppy--it's external) and it's trivial > to get Mandrake running on them, with support for the touch screen on > the smaller one etc. I just make a net installation floppy, and reply > to some trivial questions. As far as I remember, there's just this sing= le > floppy image to get, and I can use rawrite in Windows or the Linux dd > command to write that to a floppy. That part is identical for almost al= l > floppy based linux installs. I've done that when I gor tired trying to > navigate the Debian site. > With Debian I've tried CDs I got in a bundle some years ago, and at tha= t > time, it was hopelessly cumbersome to select what software to install. > I'm sure it's better now, but the problem seems to be that the Debian > project is run by people who are all very involved in Debian and most > things are trivial once you know them. I bet 90% of all Debian users go= t > on-site assistance from someone with prior Debian assistance the first > time they installed it. That cumbersomness is hopefully behind. You can very quickly install "tasks" at the beginning and then just use aptitude, gnome-apt, feta (very clever), or plain apt-get to get the system you want with the least hassle. > I surf to www.debian.org, I rather quickly reach something like > http://www.dk.debian.org/distrib/floppyinst to get instructions on what > to do next since I want to do a network install with floppys. Then the > confusion starts. The link to the files just lead me to a list of mirro= rs > full of files, and it's not clear what I need. I'm referred to five > different manuals, and the manual describing what files I need, "Instal= ling > Debian GNU/Linux 3.0 For Intel x86 Chapter 11 - Appendix" list almost 1= 00 > different files, and refers me to yet another manual to understand just= what > I need. All these files are for "current", whatever that means. As far = as I > understand, Debian always have three versions: "stable", "testing" and > "unstable". The currently stable version is called "woody", the current= =20 > testing version is "sarge", and the currently unstable version is > called "sid". I assume they also have numbers. But which does > "current" point to? I know, most Debian people, who have struggled to > get the hang of this will have a gut reaction to say, "Hang on, this > is very simple." Well, let me tell you: It isn't. It's confusing. All > this is just for the x86 files... >=20 > I'm sure I only need a few of all these files, but I certainly get the > impression that the Debian team is trying to scare people away, rather = than > to attract new users. Yes, boot floppies used to be the only way and they could be somewhat picky about the media and such. However, these days there are many other ways to install Debian. I recently used Jigdo to prepare a bleeding edge distribution on a CD-R for a friend easily. You could also use the Sarge or unofficial testing CDs from http://www.debian.org/CD/http-ftp/, or even a Knoppix CD. The latter option seemed to be gaining a lot of popularity lately. It supposedly has a good hardware detection and you can upgrade it to Debian proper lately very simply. As far as boot floppies go to the http://www.debian.org/releases/stable/i386/ch-install-methods.en.html#s-c= reate-floppy and download your minimal set: rescue, root, and drivers (if whatever is needed for your hardware is not on the root already).=20 > I currently have an old IBM 760LD laptop with a P90, 48MB RAM, 810 MB d= isk, > a floppy but no CD and a Netgear FA411 PCMCIA NIC that I'd be intereste= d > in running Debian on. No X, just a simple text based system with reason= able > security where I can run some Python stuff via ssh etc across the net. I've had a similar one as my primary work laptop for a while. First two floppies should be sufficient for a net install on it. For example: .../current/images-1.44/idepci/rescue.bin and .../current/images-1.44/idepci/root.bin should get you to the boot system, if I remember things correctly ;). It's been a while since I had to install from boot floppies. > Anyone who thinks he or she can guide me through this process is very > welcome to try. It seems many Python developers use Debian as their=20 > development > platform, so it's probably a good platform once you've got it running. >=20 > >As a first recommendation, try Knoppix. It is entirely cd-based. >=20 > Can I upgrade this to a current Debian version in a simple way, or > am I limited to debs made for Knoppix? I'd really only be interested > to use Knoppix as a more convenient installer for Debian. It does seem so. > Is there a way to use Knoppix on machines lacking a CD? Would that be > easier than other ways to get Debian running. >=20 If you don't need XFree86, then boot floppies should get you through just fine. If you don't have either a CD or a Floppy drive than it's a bit more convoluted, but if you have anything else running on that system you could do a lasy HDD based instal after tweking the partitions with Partition Magic or such. Best wishes, Alex. > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language=20 >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From magnus@thinkware.se Wed Jul 9 11:50:08 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 10:50:08 2003 Subject: [Tutor] What *var* mean? In-Reply-To: <3F0C1EFF.70306@mac.com> Message-ID: <5.2.1.1.0.20030709165124.073b6750@www.thinkware.se> At 10:56 2003-07-09 -0300, Luiz Siqueira Neto wrote: >I see a lot of variables like this >-- >*var* >-- > >What is this? Context please? Where do you see there, and what are you asking about? Asterisks surrounding variable names? If there are in the code they probably mean multiplication, if they appear in text describing code, they are probably just there for *emphasis*. There is no such thing as italics in a text file... On the other hand *args and **kwargs are different things, but we've recently covered that. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From marichar@csusb.edu Wed Jul 9 12:33:02 2003 From: marichar@csusb.edu (Matt Richardson) Date: Wed Jul 9 11:33:02 2003 Subject: [Tutor] Suggestions for cleaner code In-Reply-To: <3F0B675D.8050302@ccvcorp.com> References: <1057706198.518.98.camel@matt-richardsons-computer.local> <3F0B675D.8050302@ccvcorp.com> Message-ID: <1057764749.23760.21.camel@matt-richardsons-computer.local> Thanks for the suggestions, it's looking cleaner already. I haven't implemented the dictionary yet, but I have incorporated some of the suggestions posted: #!/sw/bin/python print 'Choose one of the following: ' print '1 Greeting' print '2 Discussion' print '3 Question' print '4 Farewell' while True: option = int(raw_input('Option: ')) if option == 1: print 'Hello' elif option == 2: print 'I should have paid more attention in math classes.' elif option == 3: print 'Why did I sleep through class?' elif option == 4: print 'Farewell' break Got rid of the unnecessary 'loop' variable I was using and a level of if statements. The tasks the options perform here are obviously trivial, but I have a real use for this type of program so getting it nice and clean is important to me. I manage four computer labs on a part-time basis (budgets constraints make for strange job descriptions) and need to make a program that gives the user (instructor or other tech) a simple interface to run a more complex suite of imaging and updating programs. thanks for the help, Matt On Tue, 2003-07-08 at 17:52, Jeff Shannon wrote: > Kalle Svensson has given some good suggestions, and if you follow his > dictionary hints then this bit of code becomes redundant, but I figured > I'd point this out anyhow... > > > if (1 <= option <= 3): > > if option == 1: > > print 'Hello' > > elif option == 2: > > print 'I should have paid more attention in math classes.' > > elif option == 3: > > print 'Why did I sleep through class?' > > else: > > print 'Farewell' > > loop = 1 > > > > Here you are checking to see if option is between 1 and 3, and then > checking which number it is. You could do this just as well with a > single level of if/elif, instead of two levels: > > if option == 1: [...] > elif option == 2: [...] > elif option == 3: [...] > else: [...] > > Also, as a minor point, one could argue that you're not being completely > truthful to your users -- you claim that 4 will quit, but really > *anything* except 1, 2, or 3 will quit. Someone who accidentally hits a > key other than 1-4 might be unhappy that the program exited rather than > giving them another chance... This can be solved by either limiting the > quit to 4 and having any other input cause a new cycle through the loop > (just change that last else into an elif), or by changing your message > to inform users (instead of '4 Farewell', say something like 'Any other > key: Farewell'). > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From pythontutor@venix.com Wed Jul 9 12:53:01 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Wed Jul 9 11:53:01 2003 Subject: [Tutor] Suggestions for cleaner code References: <1057706198.518.98.camel@matt-richardsons-computer.local> <3F0B675D.8050302@ccvcorp.com> <1057764749.23760.21.camel@matt-richardsons-computer.local> Message-ID: <3F0C39C3.80109@venix.com> You might want to look at the cmd module for some aspects of what you are doing. readline and curses would probably only be useful on unix systems. Lundh's book "Python Standard Library" and Martelli's "Python in a Nutshell" provide some pointers. Matt Richardson wrote: > Thanks for the suggestions, it's looking cleaner already. I haven't > implemented the dictionary yet, but I have incorporated some of the > suggestions posted: > > #!/sw/bin/python > > print 'Choose one of the following: ' > print '1 Greeting' > print '2 Discussion' > print '3 Question' > print '4 Farewell' > > while True: > option = int(raw_input('Option: ')) > if option == 1: > print 'Hello' > elif option == 2: > print 'I should have paid more attention in math classes.' > elif option == 3: > print 'Why did I sleep through class?' > elif option == 4: > print 'Farewell' > break > > Got rid of the unnecessary 'loop' variable I was using and a level of if > statements. The tasks the options perform here are obviously trivial, > but I have a real use for this type of program so getting it nice and > clean is important to me. I manage four computer labs on a part-time > basis (budgets constraints make for strange job descriptions) and need > to make a program that gives the user (instructor or other tech) a > simple interface to run a more complex suite of imaging and updating > programs. > > thanks for the help, > Matt > > > On Tue, 2003-07-08 at 17:52, Jeff Shannon wrote: > >>Kalle Svensson has given some good suggestions, and if you follow his >>dictionary hints then this bit of code becomes redundant, but I figured >>I'd point this out anyhow... >> >> >>> if (1 <= option <= 3): >>> if option == 1: >>> print 'Hello' >>> elif option == 2: >>> print 'I should have paid more attention in math classes.' >>> elif option == 3: >>> print 'Why did I sleep through class?' >>> else: >>> print 'Farewell' >>> loop = 1 >>> >> >>Here you are checking to see if option is between 1 and 3, and then >>checking which number it is. You could do this just as well with a >>single level of if/elif, instead of two levels: >> >> if option == 1: [...] >> elif option == 2: [...] >> elif option == 3: [...] >> else: [...] >> >>Also, as a minor point, one could argue that you're not being completely >>truthful to your users -- you claim that 4 will quit, but really >>*anything* except 1, 2, or 3 will quit. Someone who accidentally hits a >>key other than 1-4 might be unhappy that the program exited rather than >>giving them another chance... This can be solved by either limiting the >>quit to 4 and having any other input cause a new cycle through the loop >>(just change that last else into an elif), or by changing your message >>to inform users (instead of '4 Farewell', say something like 'Any other >>key: Farewell'). >> >>Jeff Shannon >>Technician/Programmer >>Credit International >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From cybersamurai@mac.com Wed Jul 9 13:29:02 2003 From: cybersamurai@mac.com (Luiz Siqueira Neto) Date: Wed Jul 9 12:29:02 2003 Subject: [Tutor] Re: *var* Message-ID: <3F0C42DB.7040801@mac.com> Okay, it is probable a *emphasis*. Thanks. :) I see this in a source generated by WxGlade tool. example: -- def makeSome(y): x = "Foobar" + y *return* x -- Now another question: the __doc__ is only a variable defined in some super class to associate the documentation or is more of this? Where I can get some about documentation inside a class? Thanks again. :) From magnus@thinkware.se Wed Jul 9 13:59:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 12:59:01 2003 Subject: [Tutor] Suggestions for cleaner code In-Reply-To: Message-ID: <5.2.1.1.0.20030709134907.073ce2d0@www.thinkware.se> At 04:05 2003-07-09 -0400, Jared W wrote: >After I had sent my response to cleaner code, I noticed people talking >about input not being used because of security problems. Three questions >come to mind. How does input create these problems? Does raw_input also >have these problems? What is the alternate to input? Jeff Shannon and Raymond Hettinger already answered this. As Lee Harr suggested somewhat implicitly, the answer is in the Python library reference chapter 2.1. Please read! The manual doesn't quite explain all the possible dangers though. raw_input is safe, unless you run eval() on the string it returns. I don't know how input is defined, but it *could* be written like this: def input(text): return eval(raw_input(text)) That's basically what it does: Reads a string entered by the user, and evaluates it. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From jeff@ccvcorp.com Wed Jul 9 14:11:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 9 13:11:03 2003 Subject: [Tutor] Re: Suggestions for cleaner code References: <1057710648.518.116.camel@matt-richardsons-computer.local> <5.2.1.1.0.20030709140127.0204a8d8@www.thinkware.se> Message-ID: <3F0C4C98.7020203@ccvcorp.com> Magnus Lycke wrote: > At 18:02 2003-07-08 -0700, Jeff Shannon wrote: > >> Even worse, someone could easily type something like 'import os; >> os.system("rm -s /")' -- this *will* import the os module and spawn a >> shell that will attempt to delete every file on your system. > > > No it won't. You can only evaluate expressions, not arbitrary > statements. But the second part 'os.system("rm -s /")' is > certainly possible, so if the program has already imported > the os module, you are definitely in danger. Ah, right, my mistake -- input() uses eval() internally, and eval() can only handle expressions, not statements. So the malicious possibilities aren't *quite* as open as I had suggested, though they are still definitely there, as are the possibilities for unintentional problems. Jeff Shannon Technician/Programmer Credit International From marta_andrea@libero.it Wed Jul 9 14:28:02 2003 From: marta_andrea@libero.it (Andrea Valle) Date: Wed Jul 9 13:28:02 2003 Subject: [Tutor] oo programming In-Reply-To: <008001c3461c$1654f140$0500a8c0@nias> Message-ID: Hi to all, I've started object oriented programming with Python after two years of "functional" use... I'm having a lot of fun, but, being a self-taught, I don't know exactly how to organize the software architecture: what is best to do, what is worst, etc. Could anyone indicate me some links or books on the subject? Are there Python resources related to the topic? thanks as usual best -a- From magnus@thinkware.se Wed Jul 9 14:29:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 13:29:02 2003 Subject: [Tutor] Re: *var* In-Reply-To: <3F0C42DB.7040801@mac.com> Message-ID: <5.2.1.1.0.20030709192715.073c91e8@www.thinkware.se> At 13:29 2003-07-09 -0300, Luiz Siqueira Neto wrote: >the __doc__ is only a variable defined in some super class to associate >the documentation or is more of this? Nope. All names with leading and trailing double underscores are magic. .__doc__ are constructed as bare strings in the beginning of a module, class or function/method. They are often triple-quoted to make it easy to make them several lines. >Where I can get some about documentation inside a class? >>> class X: ... """This is class X""" ... def y(self): ... """Method y of class X""" ... print "Hello" ... >>> X.__doc__ 'This is class X' >>> X.y.__doc__ 'Method y of class X' >>> help(X) Help on class X in module __main__: class X | This is class X | | Methods defined here: | | y(self) | Method y of class X | | ---------------------------------------------------------------------- | Data and non-method functions defined here: | | __doc__ = 'This is class X' | | __module__ = '__main__' >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Wed Jul 9 14:31:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 9 13:31:02 2003 Subject: [Tutor] Setting PYTHONPATH in FreeBSD/Linux In-Reply-To: <5.1.0.14.0.20030709091447.03d7a128@tcapp.com> References: <5.2.1.1.0.20030709131739.073c3480@www.thinkware.se> <5.1.0.14.0.20030708232817.01aac1c0@smtp.sbcglobal.net> Message-ID: <5.2.1.1.0.20030709185737.01f64e60@www.thinkware.se> BTW, I guess the right way is to place HTMLgen in site-packages, so that it can be found with a normal import. HTMLgen is very old though. (Why use that?) At 09:29 2003-07-09 -0700, Tony Cappellini wrote: >Hello Magnus, > >> >>But that's not enough! Variables defined with just "set" are >> >>not inherited by spawned processes. .cshrc is sourced every >> >>time you start up a csh process. Python is obviously not csh. >> >> >> export PYTHONPATH > >You know- it's been quite a while since I've used a Unix system, and I >have had to add >export statements to my .bashrc file. I'm just rusty on unix. > >However, none of the other vars in the .cshrc are exported, yet they do >show up >in os.environ. I guess they are defined twice: With setenv in .login and with set in .cshrc. >I can't understand that, however, I will export my pythonpath var and see >how that works for the cshell > >> >>Another option is to add the path in your Python program: >> >>import sys >>sys.path.append('/home/myhomedir') > >The problem with that is that I have to type that every time I start up python If you are talking about interactive use...yes. Using sys.path.append in a program is also a problem if other people, who might have HTMLgen somewhere else... >If there were a file I could add this to so it was added each time python >starts, I would do it that way. There is... site.py -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From alan.gauld@blueyonder.co.uk Wed Jul 9 15:08:07 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 9 14:08:07 2003 Subject: [Tutor] Suggestions for cleaner code References: <1057706198.518.98.camel@matt-richardsons-computer.local> <3F0B675D.8050302@ccvcorp.com> <1057764749.23760.21.camel@matt-richardsons-computer.local> Message-ID: <00c501c34645$0357f690$6401a8c0@xp> > Thanks for the suggestions, it's looking cleaner already. I have one more suggestion: def getOption(): #<--- DEFINE A FUNCTION HERE print ''' Choose one of the following: 1 Greeting 2 Discussion 3 Question 4 Farewell''' # <---- Note use of ''' to save multiple prints return int(raw_input('\nOption[1-4]: ')) > while True: option = getOption() #<--- CALL THE FUNCTION HERE > if option == 1: > print 'Hello' > elif option == 2: > print 'I should have paid more attention in math classes.' > elif option == 3: > print 'Why did I sleep through class?' > elif option == 4: > print 'Farewell' > break This has the advantage of representing the menu each time instead of just a list of: option: option: option: prompts. Also by adding the format clue '[1-4]' we reduce the chances of the user trying to enter a non digit and generating an exception. > but I have a real use for this type of program so getting it nice and > clean is important to me. There is a Python standard module for building interactive prompt systems you might like to look at, I think its called 'cmd'... So while this is a useful lesson the standard module might be better for "production" code. Python: comes with batteries included... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From glingl@aon.at Wed Jul 9 15:21:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Jul 9 14:21:02 2003 Subject: [Tutor] oo programming References: Message-ID: <3F0C5D60.1090905@aon.at> Andrea Valle schrieb: >Hi to all, >I've started object oriented programming with Python after two years of >"functional" use... >I'm having a lot of fun, but, being a self-taught, I don't know exactly how >to organize the software architecture: what is best to do, what is worst, >etc. > Hello Andrea! I think it's impossible to give an exact or even useful answer if your question is thus general and inexact. Nevertheless some pointers: Yesterday Chris Kassopulo posted this: http://mcsp.wartburg.edu/zelle/PythonCS1_Draft.pdf It has a strong emphasis on objects and also contains a chapter on object oriented design. If you have really just begun to do objects, this might be clearifying to you. You also can get a file graphics.py from zelle's homepage, which contains clear examples of oo-progamming. (He uses this as a basis for his course). Studying this you can certainly learn much. If you are interested in the OO-details of Python as a language, you might consult Alex Martellis Python in a Nutshell, which leaves nothing open and even discusses such advanced but relevant topics like the differences between classic and new-style classes, relevant since Python 2.2 (?). (IMHO this is an indispensable book for every Python programmer, anyway). (Perhaps one should only use new-style classes form now on?) Best wishes, Gregor >Could anyone indicate me some links or books on the subject? Are there >Python resources related to the topic? > >thanks as usual > >best > >-a- > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From dyoo@hkn.eecs.berkeley.edu Wed Jul 9 15:40:07 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 9 14:40:07 2003 Subject: [Tutor] Re: Suggestions for cleaner code [be careful about input()] In-Reply-To: <5.2.1.1.0.20030709140127.0204a8d8@www.thinkware.se> Message-ID: On Wed, 9 Jul 2003, Magnus [iso-8859-1] Lyck=E5 wrote: > At 18:02 2003-07-08 -0700, Jeff Shannon wrote: > > >Even worse, someone could easily type something like 'import os; > >os.system("rm -s /")' -- this *will* import the os module and spawn a > >shell that will attempt to delete every file on your system. > > No it won't. You can only evaluate expressions, not arbitrary > statements. But the second part 'os.system("rm -s /")' is certainly > possible, so if the program has already imported the os module, you are > definitely in danger. Jeff had the right idea. If we use the __import__() builtin, the approach works. That is: __import__('os').system('ls') is an example of something that input() will blissfully execute. This is what makes input() potentially dangerous. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Jul 9 15:48:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 9 14:48:01 2003 Subject: [Tutor] Re: Suggestions for cleaner code [a safer alternative to input()] In-Reply-To: <3F0C4C98.7020203@ccvcorp.com> Message-ID: On Wed, 9 Jul 2003, Jeff Shannon wrote: > Magnus Lycke wrote: > > > At 18:02 2003-07-08 -0700, Jeff Shannon wrote: > > > >> Even worse, someone could easily type something like 'import os; > >> os.system("rm -s /")' -- this *will* import the os module and spawn a > >> shell that will attempt to delete every file on your system. > > > > > > No it won't. You can only evaluate expressions, not arbitrary > > statements. But the second part 'os.system("rm -s /")' is certainly > > possible, so if the program has already imported the os module, you > > are definitely in danger. > > > Ah, right, my mistake -- input() uses eval() internally, and eval() can > only handle expressions, not statements. So the malicious possibilities > aren't *quite* as open as I had suggested, though they are still > definitely there, as are the possibilities for unintentional problems. Hi Jeff, No, you were right the first time. *grin* input(), as it stands, is very powerful. Because of its power, it's not usually a good idea to use it for casual user input. There is a way to make it slightly less dangerous: ### >>> def input(): ... return eval(raw_input(), {'__builtins__': None}) ... >>> input() 3*4 12 >>> input() __import__('os') Traceback (most recent call last): File "", line 1, in ? File "", line 2, in input File "", line 0, in ? NameError: name '__import__' is not defined ### This modified version of input() still allows for arithmetic expressions, but we prevent the user from calling any of the builtins. It probably still has weaknesses, but it's at least a little safer than the standard input() function. Hope this helps! From zak@harlekin-maus.com Wed Jul 9 18:14:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Wed Jul 9 17:14:01 2003 Subject: [Tutor] Weird list indexing Message-ID: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> Okay, I create a 2-d "array" like so: ### >>> a = [[None, None, None], [None, None, None], [None, None, None]] >>> a [[None, None, None], [None, None, None], [None, None, None]] >>> a[1][2] = 'a' >>> a [[None, None, None], [None, None, 'a'], [None, None, None]] ### This makes sense. Now, why does this happen? I'm using Python 2.2.3, by the way. ### >>> a = [[None] * 3] * 3 >>> a [[None, None, None], [None, None, None], [None, None, None]] >>> a[1][2] = 'a' >>> a [[None, None, 'a'], [None, None, 'a'], [None, None, 'a']] ### My guess is that the three lists are all the same object, just pointed to three different times? So it seems my shortcut to create a two-dimensional array doesn't work. Is there better shortcut? --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From dyoo@hkn.eecs.berkeley.edu Wed Jul 9 18:26:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 9 17:26:02 2003 Subject: [Tutor] Weird list indexing In-Reply-To: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> Message-ID: On Wed, 9 Jul 2003, Zak Arntson wrote: > Now, why does this happen? I'm using Python 2.2.3, by the way. > > ### > > >>> a = [[None] * 3] * 3 > >>> a > [[None, None, None], [None, None, None], [None, None, None]] > >>> a[1][2] = 'a' > >>> a > [[None, None, 'a'], [None, None, 'a'], [None, None, 'a']] > > ### > > My guess is that the three lists are all the same object, just pointed to > three different times? So it seems my shortcut to create a two-dimensional > array doesn't work. Is there better shortcut? Yes, exactly. A common idiom for making 2d arrays in Python is a list comprehension approach: ### >>> a = [ [None] * 4 ... for i in range(7) ] >>> a [[None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] >>> a[1][1] = "Foo!" >>> a [[None, None, None, None], [None, 'Foo!', None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None], [None, None, None, None]] ### This works because the subexpression in our list comprehension, [ [None] * 4 for i in range(7) ] ^^^^^^^^^^ is evaluated more than once. We get a new sublist for each row in our matrix, so we're able to avoid the shared-structure problem that you saw. Now that we know this, we can make a small utility function to construct 2d arrays for us: ### >>> def makeArray(rows, cols): ... return [ [None] * cols for i in range(rows) ] ... >>> makeArray(2, 3) [[None, None, None], [None, None, None]] ### Good luck to you! From nas-pytut@python.ca Wed Jul 9 18:26:09 2003 From: nas-pytut@python.ca (Neil Schemenauer) Date: Wed Jul 9 17:26:09 2003 Subject: [Tutor] Weird list indexing In-Reply-To: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> References: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> Message-ID: <20030709213031.GA7494@glacier.arctrix.com> Zak Arntson wrote: > My guess is that the three lists are all the same object, just pointed to > three different times? Right. > So it seems my shortcut to create a two-dimensional array doesn't > work. Is there better shortcut? The best solution is probably to use the Numeric or Numarry extension. Eg. >>> import Numeric >>> a = Numeric.zeros((5,5), 'O') >>> a array([[0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ]],'O') >>> a[2][1] = 'foo' >>> a array([[0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ], [0 , foo , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ], [0 , 0 , 0 , 0 , 0 ]],'O') The other solution is to use a 'for' loop (not really a short cut). Neil From elh@outreachnetworks.com Wed Jul 9 18:52:05 2003 From: elh@outreachnetworks.com (Eric L Howard) Date: Wed Jul 9 17:52:05 2003 Subject: [Tutor] Weird list indexing In-Reply-To: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> References: <3067.192.207.104.220.1057785209.squirrel@mail.harlekin-maus.com> Message-ID: <20030709215155.GA1316@outreachnetworks.com> At a certain time, now past [Jul.09.2003-02:13:29PM -0700], zak@harlekin-maus.com spake thusly: > Okay, I create a 2-d "array" like so: > > ### > > >>> a = [[None, None, None], [None, None, None], [None, None, None]] > >>> a > [[None, None, None], [None, None, None], [None, None, None]] > >>> a[1][2] = 'a' > >>> a > [[None, None, None], [None, None, 'a'], [None, None, None]] > > ### > > This makes sense. Now, why does this happen? I'm using Python 2.2.3, by > the way. > > ### > > >>> a = [[None] * 3] * 3 > >>> a > [[None, None, None], [None, None, None], [None, None, None]] > >>> a[1][2] = 'a' > >>> a > [[None, None, 'a'], [None, None, 'a'], [None, None, 'a']] > > ### > > My guess is that the three lists are all the same object, just pointed to > three different times? So it seems my shortcut to create a two-dimensional > array doesn't work. Is there better shortcut? I can't say anything towards the 'better shortcut', but....the first thing that came to mind to see if it was the same object [my first guess also] was id(). >>> a = [[None] * 3] * 3 >>> a [[None, None, None], [None, None, None], [None, None, None]] >>> a[1][2] = 'a' >>> a [[None, None, 'a'], [None, None, 'a'], [None, None, 'a']] >>> id(a) 135424172 >>> id(a[0]) 135627396 >>> id(a[1]) 135627396 >>> id(a[2]) 135627396 ~elh -- Eric L. Howard e l h @ o u t r e a c h n e t w o r k s . c o m ------------------------------------------------------------------------ www.OutreachNetworks.com 313.297.9900 ------------------------------------------------------------------------ JabberID: elh@jabber.org Advocate of the Theocratic Rule From rob@euglug.net Wed Jul 9 21:22:05 2003 From: rob@euglug.net (Rob Hudson) Date: Wed Jul 9 20:22:05 2003 Subject: [Tutor] sockets Message-ID: <20030709172054.D37800@cogit8.org> Hello, I'm new to the list. I'm taking a class at the local community college. I work as a PHP coder doing web design and have learned Perl in the past. Python looked intriguing and so far I'm having fun with it. I'm from Oregon if anyone else here is nearby. Anyway, here's my question... While reading a Randall Schwartz article on Perl and sockets[1], I decided to rewrite his little perl code in python. Here's the code: #!/usr/bin/env python import sys from socket import * if len(sys.argv) != 2: exit host = sys.argv[1] port = int(sys.argv[2]) # Create a socket # AF_INET means the IP address protocol # SOCK_STREAM means the TCP transfer protocol sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((host, port)) data = sockobj.recv(1024) print 'response from', host, 'port', port, 'was:' print data sockobj.close() I call it like this: python socket-test.py 132.163.4.203 13 My question is: What if the data the server sends is more than 1024 bytes? Python can't do this, right? while (recv = sockobj.recv(1024)): data += recv Specifically, I think Python can't make an assignment inside a conditional. Would you get the data, then check for NULL and break if the data is empty? Or check for EOF? Something like that? This code actually works since the data returned is small. The other thing to note is that since time servers don't expect any starting message, they just send the time automatically and kill the socket. That's why I don't need a sockobj.send(message) call. Thanks! -Rob [1] http://www.stonehenge.com/merlyn/UnixReview/col47.html From shalehperry@comcast.net Wed Jul 9 21:42:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Wed Jul 9 20:42:02 2003 Subject: [Tutor] sockets In-Reply-To: <20030709172054.D37800@cogit8.org> References: <20030709172054.D37800@cogit8.org> Message-ID: <200307091740.56189.shalehperry@comcast.net> On Wednesday 09 July 2003 17:20, Rob Hudson wrote: > > data = sockobj.recv(1024) > > > I call it like this: > python socket-test.py 132.163.4.203 13 > > > My question is: What if the data the server sends is more than 1024 > bytes? Python can't do this, right? > > while (recv = sockobj.recv(1024)): > data += recv > > Specifically, I think Python can't make an assignment inside a > conditional. Would you get the data, then check for NULL and break if > the data is empty? Or check for EOF? Something like that? > you are correct, no assignment in conditionals. One of the tricks to socket programming is the value passed to recv() is a MAXIMUM. The OS may decide to only give you 1/3, 1/8, 5/8, etc. of that value. So you have to check that you have received all of the data. This leads to the recv being called in a loop and the value being checked until the proper amount has been received or the data contains what you expect it to. From tony@tcapp.com Wed Jul 9 23:16:02 2003 From: tony@tcapp.com (Tony Cappellini) Date: Wed Jul 9 22:16:02 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030710002205.20659.77376.Mailman@mail.python.org> Message-ID: <20030709190952.H51747-100000@yamato.yamato.com> Why does os.name return 'nt' on a Windows 98 machine ? From thomi@thomi.imail.net.nz Thu Jul 10 00:04:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed Jul 9 23:04:01 2003 Subject: [Tutor] communicating with low level hardware in python? Message-ID: <20030710150322.5e893dfe.thomi@thomi.imail.net.nz> Hey, I'm writing an app which will talk to industrial scales through a serial port. I'm using wxWindows to form a simple GUI, but now i need to set up the serial port part of things. What's the best way to do this? I don't know enough C to write it in C, so it'll have to be python (and speed isn't an issue here). Any ideas? a quick scan of the modules list didn't reveal anything special... I'm hoping someone out there has written a module which will help me.. Thanks in advance ;) -- Thomi Richards, thomi@thomi.imail.net.nz From shalehperry@comcast.net Thu Jul 10 02:33:01 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Thu Jul 10 01:33:01 2003 Subject: [Tutor] communicating with low level hardware in python? In-Reply-To: <20030710150322.5e893dfe.thomi@thomi.imail.net.nz> References: <20030710150322.5e893dfe.thomi@thomi.imail.net.nz> Message-ID: <200307092232.04456.shalehperry@comcast.net> On Wednesday 09 July 2003 20:03, Thomas CLive Richards wrote: > Hey, > > I'm writing an app which will talk to industrial scales through a serial > port. I'm using wxWindows to form a simple GUI, but now i need to set up > the serial port part of things. > > What's the best way to do this? I don't know enough C to write it in C, > so it'll have to be python (and speed isn't an issue here). Any ideas? a > quick scan of the modules list didn't reveal anything special... > > I'm hoping someone out there has written a module which will help me.. > > Thanks in advance ;) a quick google for 'python serial' turns up: http://pyserial.sourceforge.net/ trust in google ...... From thomi@thomi.imail.net.nz Thu Jul 10 02:37:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 10 01:37:01 2003 Subject: [Tutor] communicating with low level hardware in python? In-Reply-To: <200307092232.04456.shalehperry@comcast.net> References: <20030710150322.5e893dfe.thomi@thomi.imail.net.nz> <200307092232.04456.shalehperry@comcast.net> Message-ID: <20030710173632.122b9d3e.thomi@thomi.imail.net.nz> > http://pyserial.sourceforge.net/ ahhhh.. exactly what I was after.. thank you so much ! -- Thomi Richards, thomi@thomi.imail.net.nz From alan.gauld@blueyonder.co.uk Thu Jul 10 04:22:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu Jul 10 03:22:01 2003 Subject: [Tutor] oo programming References: Message-ID: <012f01c346b3$fc1e4b80$6401a8c0@xp> The basic proinciples of OO design apply to any OO language. Try looking on cetus-links.org for tutorials etc on OOD. Also Bruce Eckels "Thinking in Python" web book has some hints, and his "Thinking in Java" even more...albeit expressed in Java. The general principles that I find most useful are to think of the problem in terms of role-playing actors. Each actor has a job, or responsibility, within the task. Work out what each actor is responsible for and translate that into data and methods. Remember too that whichever object holds a piece of data, that is the object that should maniplulate that data. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ----- Original Message ----- From: "Andrea Valle" To: "tutor" Sent: Wednesday, July 09, 2003 6:12 PM Subject: [Tutor] oo programming > Hi to all, > I've started object oriented programming with Python after two years of > "functional" use... > I'm having a lot of fun, but, being a self-taught, I don't know exactly how > to organize the software architecture: what is best to do, what is worst, > etc. > Could anyone indicate me some links or books on the subject? Are there > Python resources related to the topic? > > thanks as usual > > best > > -a- > > > > > > From thomi@thomi.imail.net.nz Thu Jul 10 05:35:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 10 04:35:01 2003 Subject: [Tutor] threading vs. forking? Message-ID: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Hi, I'm *trying* to develop a program which (amongst other things) reads information from a serial port and prints it in a nice GUI interface. The problem i have is that i don't know when data is going to be sent to the port, so i have to use a polling method to fetch the data. The problem with that is that while the program is polling the serial port, the GUI isn't getting updated. So, AFAIK, there are two methods around this. there are probably many more ways to do this, but i haven't a clue what they are. The first would be forking the process using os.fork(), and running the serial port polling in one fork, and the GUI in another, and somehow send the data to the GUI. the other would be using threading. The problem with that is that I've never done it before, and from reading the documentation, I can't see how to get information from one thread to another. There is likely to be a lot of information on the port, so the information passing would have to be easy... so, what are the differences between forking and threading? why would you use one, and not the other? thanks, -- Thomi Richards, thomi@thomi.imail.net.nz From Zabelkind@web.de Thu Jul 10 07:35:01 2003 From: Zabelkind@web.de (Mathias Mamsch) Date: Thu Jul 10 06:35:01 2003 Subject: [Tutor] threading vs. forking? References: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Message-ID: <000c01c346cf$0b722370$0500a8c0@nias> Threading is quite easy, once you know how it is done. I think for solving your problem there are several advantages using a thread instead of a fork If you fork, another process will be generated. So the complete memory of the parent will be copied to another process - thats a waste of resources as the child process does not need gui data. As you run in a 32 Bit enviroment the new process will not get access to the data of the parent process. You will have to use a shared memory or something to transfer data from the child to the parent which is slower because you have to copy around your data alot. Another problem I had with forking is killing the forked process, when you want to. A problem is for example, when the parent exits before the forked child, you will get a ghost process. That is all much easier with a thread. You can end, suspend and resume threads from the parent easily. And if your parent exits suddenly the thread will be ended automatically. I think there are a lot of examples how threading works out there. I cannot give you one at moment but look for example here: http://mail.python.org/pipermail/thread-sig/2001-January/000568.html Hope this helped a bit for your decision. Regards, Mathias Mamsch ----- Original Message ----- From: "Thomas CLive Richards" To: Sent: Thursday, July 10, 2003 10:34 AM Subject: [Tutor] threading vs. forking? > > Hi, > > I'm *trying* to develop a program which (amongst other things) reads > information from a serial port and prints it in a nice GUI interface. > > The problem i have is that i don't know when data is going to be sent to > the port, so i have to use a polling method to fetch the data. The > problem with that is that while the program is polling the serial port, > the GUI isn't getting updated. > > So, AFAIK, there are two methods around this. there are probably many > more ways to do this, but i haven't a clue what they are. > > The first would be forking the process using os.fork(), and running the > serial port polling in one fork, and the GUI in another, and somehow > send the data to the GUI. > > the other would be using threading. The problem with that is that I've > never done it before, and from reading the documentation, I can't see > how to get information from one thread to another. There is likely to be > a lot of information on the port, so the information passing would have > to be easy... > > so, what are the differences between forking and threading? why would > you use one, and not the other? > > thanks, > > > > -- > > Thomi Richards, > thomi@thomi.imail.net.nz > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From op73418@mail.telepac.pt Thu Jul 10 08:34:01 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Thu Jul 10 07:34:01 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Thomas CLive Richards > Sent: quinta-feira, 10 de Julho de 2003 9:34 > To: tutor@python.org > Subject: [Tutor] threading vs. forking? > > > > Hi, > > I'm *trying* to develop a program which (amongst other things) reads > information from a serial port and prints it in a nice GUI > interface. > > The problem i have is that i don't know when data is going > to be sent to > the port, so i have to use a polling method to fetch the data. The > problem with that is that while the program is polling the > serial port, > the GUI isn't getting updated. > > So, AFAIK, there are two methods around this. there are > probably many > more ways to do this, but i haven't a clue what they are. > > The first would be forking the process using os.fork(), and > running the > serial port polling in one fork, and the GUI in another, and somehow > send the data to the GUI. > You can use a pipe to have the polling process pass whatever it has to the gui process. > the other would be using threading. The problem with that > is that I've > never done it before, and from reading the documentation, I > can't see > how to get information from one thread to another. There is > likely to be > a lot of information on the port, so the information > passing would have > to be easy... > The best way I know is to use the Queue module along with the high-level threading module. It implements a Queue that's thread-safe. So you could do it like this: have the gui thread (the main thread?) a public attribute referencing the queue. The polling thread just pushes whatever data it has to this queue, which then is popped off by the gui thread and processed accordingly > so, what are the differences between forking and threading? > why would > you use one, and not the other? > This is a tough question. Threads are easier when it comes to communication since global memory is shared between threads. But this also poses problems of it's own. I'm leaving this one to the more knowledgeable people in the list. I'm eager to hear their responses. > thanks, > > Thomi Richards, > thomi@thomi.imail.net.nz With my best regards, G. Rodrigues From tpc@csua.berkeley.edu Thu Jul 10 11:45:02 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Jul 10 10:45:02 2003 Subject: [Repost] Re: [Tutor] newbie re question Message-ID: <20030710074354.A19966-100000@localhost.name> hi Danny, I sent this to the list two days ago and to you yesterday and wasn't sure if you received it. ---------- Forwarded message ---------- Date: Wed, 9 Jul 2003 07:33:03 -0700 (PDT) From: tpc@csua.berkeley.edu To: dyoo@hkn.eecs.berkeley.edu Subject: Re: [Tutor] newbie re question (fwd) hi Danny, I sent this to the list yesterday and wasn't sure if you received it. ---------- Forwarded message ---------- Date: Tue, 8 Jul 2003 10:41:44 -0700 (PDT) From: tpc@csua.berkeley.edu To: tutor@python.org Subject: Re: [Tutor] newbie re question hi Danny, ah yes, I have seen Ping at various parties (and wearing a PythonLabs shirt no less!). But I digress. I am still confused why you provided for a negative lookahead. I looked at amk's definition of a negative lookahead, and it seems to say the regex will not match if the negative lookahead condition is met. So: >>> testsearch = re.compile('tetsuro(?!hello)', re.IGNORECASE) >>> testsearch.search('tetsurohello') >>> testsearch.search('hitetsuroone') <_sre.SRE_Match object at 0x860e4a0> Now in the case of: >>> myre = re.compile(r'http://[\w\.-]+\.?(?![\w.-/])') you are looking for 'http://' then one or more word characters, periods and hyphens, and an optional period and then a negative lookahead of a word character, any character, a hyphen and a forward slash. Granted, your regex may have been sloppy example and you might have meant a negative lookahead of a word character, a period, a hyphen and a forward slash. I still do not understand why you provided for one, and if you had a good reason, why the sfgate url would match at all, since you clearly had a word character, period, or hyphen following the set of characters you were allowing for, including the optional period. Here is an example of something similar that perplexes: >>> testsearch = re.compile(r'tetsuro\.?(?!hello)', re.IGNORECASE) >>> testsearch.search('tetsurohello') >>> testsearch.search('tetsuro.hello') <_sre.SRE_Match object at 0x8612028> >>> match = testsearch.search('tetsuro.hello') >>> match.group() 'tetsuro' >>> match = testsearch.search('tetsuro..hello') >>> match.group() 'tetsuro.' Why wasn't the first period caught ? On Mon, 30 Jun 2003, Danny Yoo wrote: > > > On Mon, 30 Jun 2003 tpc@csua.berkeley.edu wrote: > > > hi Danny, I had a question about your quick intro to Python lesson sheet > > you gave out back in March 2001. > > Hi tpc, > > > > Some things will never die. *grin* > > > > > The last page talks about formulating a regular expression to handle > > URLs, and you have the following: > > > > myre = re.compile(r'http://[\w\.-/]+\.?(?![\w.-/])') > > > > Ok. Let's split that up using verbose notation: > > > ### > myre = re.compile(r'''http:// ## protocol > [\w\.-/]+ ## followed by a bunch of "word" > ## characters > > \.? ## followed by an optional > ## period. > > (?! ## Topped with a negative > ## lookahead for > [\w.-/] ## "word" character. > > )''', re.VERBOSE) > ### > > > The page: > > http://www.python.org/doc/lib/re-syntax.html > > has more details about some of the regular expression syntax. AMK has > written a nice regex HOWTO here: > > http://www.amk.ca/python/howto/regex/regex.html > > which you might find useful. > > > > > > I understand \w stands for any word character, and \. means escaped > > period, and ? means zero or one instances of a character or set. I did > > a myre.search('http://www.hotmail.com') which yielded a result, but I am > > confused as to why > > > > myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL') > > > > would work, since there is a '=' and you don't provide for one in the > > regular expression. > > > Very true. It should, however, match against the negative lookahead --- > the regex tries to look ahead to see that it can match something like: > > "This is an url: http://python.org. Isn't that neat?" > > > The negative lookup should match right here: > > "This is an url: http://python.org. Isn't that neat?" > ^ > > In your url above, the negative lookahead should actually hit the question > mark first before it sees '='. That regex was a sloppy example; I should > have been more careful with it, but I was in a hurry when I wrote that > intro... *grin* > > > > If you're in the Berkeley area, by the way, you might want to see if > Ka-Ping Yee is planning another CS 198 class in the future: > > http://zesty.ca/bc/info.html > > > > > > Anyway, we can experiment with this more easily by introducing a group > into the regular expression: > > ### > myre = re.compile(r''' > ( ## group 1 > > http:// ## protocol > [\w\.-/]+ ## followed by a bunch of "word" > ## characters > > \.? ## followed by an optional > ## period. > > ) ## end group > > > (?! ## Topped with a negative > ## lookahead for > [\w.-/] ## "word" character. > > )''', re.VERBOSE) > ### > > > > Let's check it now: > > ### > >>> match = > myre.search('http://www.sfgate.com/cgi-bin/article.cgi?f=/gate/archive/2003/06/29/gavin29.DTL') > >>> match.group(1) > 'http://www.sfgate.com/cgi' > ### > > > > Oiii! The regular expression is broken. What has happened is that I've > incorrectly defined the hyphen in the character group. That is, instead > of > > > [\w\.-/]+ > > > I should have done: > > [\w./-]+ > > > instead, to keep the regex engine from treating the hyphen as a span of > characters (like "[a-z]", or "[0-9]"). You can then introduce the other > characters into the "word" character class, and then it should correctly > match the sfgate url. > > > > I hope this helps! > > From silviucc@home.ro Thu Jul 10 13:47:10 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Thu Jul 10 12:47:10 2003 Subject: [Tutor] reading matrixes from a file Message-ID: I'm trying to read matrixes from a given file. I have writen three functions for this: # this will be used to initialize a matrix def initMatrix(matrix_,rows_): matrix_ = '' matrix_ = list(matrix_) for i in range(rows_): null = ' ' null = list(null) matrix_ = matrix_ + null return matrix_ # this one does the actual readinf from the file def readMatrix(filename): f = file(filename,'r') cr = f.readline() rows = int(cr[0]) matrix ='' matrix = initMatrix(matrix,rows) matrix = list(matrix) for i in range(rows): line = f.readline() line2 = '' line2 = list(line2) for j in range(len(line)): if line[j] == ' ' or line[j] == '\n' or line[j] == '\r': continue else: line2 = line2 + list(line[j]) matrix[i] = list(matrix[i]) + line2 del(matrix[i][0]) f.close() return matrix # I use this one to convert, for example, '1' to 1 or '0' to 0 def intMatrix(matrix): for row in range(len(matrix)): for col in range(len(matrix[row])): matrix[row][col] = int(matrix[row][col]) return matrix The problem: These functions work well for this file: http://www.computing.dcu.ie/~cdaly/ire_comp/ire01/problems/test2/test1.dat but not for this one: http://www.computing.dcu.ie/~cdaly/ire_comp/ire01/problems/test2/test8.dat For this one I get only the first line. I have triple checked the function and I have no clue to what may be wrong. Please help me :) -- Registered Linux user #298569 QOTD: "Do you smell something burning or is it me?" -- Joan of Arc From jeff@ccvcorp.com Thu Jul 10 14:24:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 10 13:24:01 2003 Subject: [Tutor] threading vs. forking? References: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Message-ID: <3F0DA100.9030509@ccvcorp.com> Thomas CLive Richards wrote: >Hi, > >I'm *trying* to develop a program which (amongst other things) reads >information from a serial port and prints it in a nice GUI interface. > >[...] > >So, AFAIK, there are two methods around this. there are probably many >more ways to do this, but i haven't a clue what they are. > >The first would be forking the process using os.fork(), and running the >serial port polling in one fork, and the GUI in another, and somehow >send the data to the GUI. > >the other would be using threading. The problem with that is that I've >never done it before, and from reading the documentation, I can't see >how to get information from one thread to another. There is likely to be >a lot of information on the port, so the information passing would have >to be easy... > If you fork, then you have two independent processes, which need to talk to each other in some way. You could set up a pipe or a socket connection. However, you'll then have the same problem talking to the pipe/socket that you currently have talking to the serial port directly -- you'll need *some* method of polling to see when there's new data there. Threads are probably your best / most robust option here. There's a number of different ways to pass data back and forth between threads; the most robust of those is the Queue module. Queues are automatically thread-safe -- hand one end of the Queue to each thread. The worker thread can sit in a loop polling the serial port; when something comes in, it packages up the data and drops it in the Queue. The GUI thread checks the queue when it has a chance (either in a timer event or an idle handler), and if there's data there it pulls it out and processes it. The queue will make sure that the data is retrieved in the same order that it's inserted, and that nothing gets overwritten or otherwise mangled. If you need to also send from your serial port, as well as receive, you can have another Queue that goes in the other direction. Your worker thread would then alternate between checking if there's data to read on the serial port, and checking if there's anything in the Queue that it should send on the serial port. Note that a worker thread cannot be killed from the main thread -- if you want a worker thread to end before the entire program shuts down, that thread needs to end on its own, so you may want to have some way to ask that thread to commit suicide. This could be a matter of sending a special token in the output-queue, if you have one, or it could be an independent threading signal. One other possibility, depending on the constraints of your application, would be to forget about threading and just check the serial port directly from a timer event. You can look at the serial port, say, ten times per second, and read any data that's waiting there. However, this method is far more likely to be delayed and possibly miss data -- if serial data comes in faster than you're reading it, you'll overflow the serial port buffer and lose data. But that might not really be an issue -- if you're reading a scale, and are just grabbing the current weight, it probably doesn't matter much if you miss a sample or two. Jeff Shannon Technician/Programmer Credit International From silviucc@home.ro Thu Jul 10 14:38:07 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Thu Jul 10 13:38:07 2003 Subject: [Tutor] reading matrixes from a file In-Reply-To: Message-ID: On Thu, 10 Jul 2003, Silviu Cojocaru wrote: :) Never mind, I fixed the problem. It was in the function that read the matrix from the file. I had a bad way of getting the number of rows :) -- Registered Linux user #298569 Love is like the measles; we all have to go through it. -- Jerome K. Jerome From Sean Abrahams Thu Jul 10 16:56:02 2003 From: Sean Abrahams (Sean Abrahams) Date: Thu Jul 10 15:56:02 2003 Subject: [Tutor] Web Form Error Handling Message-ID: <1001198420906.20030710125845@sfsu.edu> I'm learning to write unit tests and am trying to write them for a web application I'm working on. I'm currently writing a test that is to purposefully fail by passing invalid data to a function. However this brought me to thinking about how to handle errors. Let me set up a hypothetical scenario. I have a web form with name and age as its two fields. When a person enters his/her information and submits the form, I take the two fields and create a dict that contains {'name' : 'Foo', 'age' : '82'}. I pass this information to a function called, insertData which looks something like this: def insertData(data): # test data for validity if not data['name'].isalpha(): raise InvalidDataError(data['name'], "Name contains non-alpha characters") if not data['age'].isdigit(): raise InvalidDataError(data['age'], "Age contains non-digit characters") sql = """ INSERT INTO people (name, age) VALUES ('%s', '%s') """ % (data['name'], data['age']) executeSQL(sql) I should first check to see if the data is valid, meaning that the name contains only alpha characters and the age only containing numeric characters. If I raise an exception, how would one handle the reprinting of the web form with a red * next to the field that contains invalid data? If one field is in error, I can see that upon receiving an exception you can have your code just reprint the web form with the red star, but what about when both fields are in error, do you have the exception create a list which then your code checks to see if it exists and then loops through it to know what fields are in error? And then again, perhaps I'm completely wrong and am going about this in an amateur manner. I realize this is more of a style question, but that's what I'm interested in discussing. Thanks, --Sean From samacomber@comcast.net Thu Jul 10 17:34:02 2003 From: samacomber@comcast.net (Scott Macomber) Date: Thu Jul 10 16:34:02 2003 Subject: [Tutor] python scripts Message-ID: <200307090501.23097.samacomber@comcast.net> I recently started toying with some python programming. I enjoy it. How= ever,=20 when I save a python file after producing it in a text editor (e.g., spam= =2Epy)=20 the interpreter can't locate it to run it as a script afterwards. I don'= t=20 know where I should save the file. Furthermore, I don't know how to=20 determine where I should save the file. I have some texts that suggest=20 various places, but I need to change permissions, etc. =20 I am running SuSe 8.1. The version of python I am using is 2.2.1. =20 Thanks for suggestions. From mwelsh@abwatley.com Thu Jul 10 17:34:10 2003 From: mwelsh@abwatley.com (Michael Welsh) Date: Thu Jul 10 16:34:10 2003 Subject: [Tutor] asynchat and queue? Message-ID: <200307092048.32109.mwelsh@abwatley.com> I'm trying to learn how to use sockets in Python. =20 Using samples available on the web, I've managed to set up a simple echo=20 'server' using asyncore and asynchat (below). I built a small GUI (wxPytho= n)=20 client that sends a bit of text to the server and recieve it back. I can=20 even run multiple clients. The server responds to the client that sent the= =20 message. Now, I'd like to take the next step and have the server respond = to=20 ALL clients, regardless of which client sent the message. =46rom my web browsing and book reading it may be suitable to use Queues. = This=20 is where I am having difficulty. I'm probably way off, but.. I believe I=20 want the server to receive the clients' msgs and throw them into a queue. = A=20 separate action would read from the queue and act on it (possibly sending i= t=20 back out to all the clients then logging to a db).=20 I may not be on the right track, I can't find simple examples anywhere of=20 using queues with asyncore/asynchat. Anybody have any insight? Michael p.s. I'm aware that twisted exits. I'm doing this exercise to get a bette= r=20 understanding of the Python fundamentals. p.p.s Python 2.2 on NT and Linux # Simple Server -------------------------------------------------------- import asyncore import asynchat import socket class MainServerSocket(asyncore.dispatcher): def __init__(self, port): print 'initing Listening Port' asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(('',port)) self.listen(5) def handle_accept(self): newSocket, address =3D self.accept() print "Connected from", address SecondaryServerSocket(newSocket) class SecondaryServerSocket(asynchat.async_chat): def __init__(self, *args): print 'initing OutBound Port' asynchat.async_chat.__init__(self, *args) self.set_terminator('\n') self.data =3D [] def collect_incoming_data(self, data): self.data.append(data) def found_terminator(self): self.push(''.join(self.data)) self.data =3D [] def handle_close(self): print "Disconnected from", self.getpeername() self.close() MainServerSocket(50006) asyncore.loop() # ------------------------------------------------------------- From Sean Abrahams Thu Jul 10 17:34:22 2003 From: Sean Abrahams (Sean Abrahams) Date: Thu Jul 10 16:34:22 2003 Subject: [Tutor] Web Form Error Handling Message-ID: <901193375390.20030710113439@sfsu.edu> I'm learning to write unit tests and am trying to write them for a web application I'm working on. I'm currently writing a test that is to purposefully fail by passing invalid data to a function. However this brought me to thinking about how to handle errors. Let me set up a hypothetical scenario. I have a web form with name and age as its two fields. When a person enters his/her information and submits the form, I take the two fields and create a dict that contains {'name' : 'Foo', 'age' : '82'}. I pass this information to a function called, insertData which looks something like this: def insertData(data): # test data for validity if not data['name'].isalpha(): raise InvalidDataError(data['name'], "Name contains non-alpha characters") if not data['age'].isdigit(): raise InvalidDataError(data['age'], "Age contains non-digit characters") sql = """ INSERT INTO people (name, age) VALUES ('%s', '%s') """ % (data['name'], data['age']) executeSQL(sql) I should first check to see if the data is valid, meaning that the name contains only alpha characters and the age only containing numeric characters. If I raise an exception, how would one handle the reprinting of the web form with a red * next to the field that contains invalid data? If one field is in error, I can see that upon receiving an exception you can have your code just reprint the web form with the red star, but what about when both fields are in error, do you have the exception create a list which then your code checks to see if it exists and then loops through it to know what fields are in error? And then again, perhaps I'm completely wrong and am going about this in an amateur manner. I realize this is more of a style question, but that's what I'm interested in discussing. Thanks, --Sean From dyoo@hkn.eecs.berkeley.edu Thu Jul 10 17:57:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 10 16:57:01 2003 Subject: [Repost] Re: [Tutor] newbie re question In-Reply-To: <20030710074354.A19966-100000@localhost.name> Message-ID: On Thu, 10 Jul 2003 tpc@csua.berkeley.edu wrote: > hi Danny, I sent this to the list two days ago and to you yesterday and > wasn't sure if you received it. Hi tpc, I'm still trying to catch up with email; my apologies for not responding to this sooner. > I am still confused why you provided for a negative lookahead. I looked > at amk's definition of a negative lookahead, and it seems to say the > regex will not match if the negative lookahead condition is met. So: > > >>> testsearch = re.compile('tetsuro(?!hello)', re.IGNORECASE) > >>> testsearch.search('tetsurohello') > >>> testsearch.search('hitetsuroone') > <_sre.SRE_Match object at 0x860e4a0> The negative lookahead in the URL detection routines allow us to find URLs at the end of sentences. For example, the string: """You can find out more information about Python at http://python.org/doc/Newbies.html. It's very helpful.""" contains an embedded URL that can be tricky to pull out correctly. Normally, periods are legal "word" characters in that regular expression, and a regular expression without negative lookahead will probably grab "http://python.org/doc/Newbies.html.", including the last period. Looking back on the regular expression: (http:// [\w\.-]+ ## bunch of "word" characters ) \.? (?![\w.-/]) the negative lookup is there to detect a period that's being used to end a sentence, and allows us to exclude it so that we can correctly extract "http://python.org/doc/Newbies.html" without the trailing period. > Here is an example of something similar that perplexes: > > >>> testsearch = re.compile(r'tetsuro\.?(?!hello)', re.IGNORECASE) > >>> match = testsearch.search('tetsuro.hello') > >>> match.group() > 'tetsuro' In this first case, we allow the period to be optional: that's the key that allows this to match. The regular expression, then, eats its input up to 'tetsuro', and the negative lookahead is happy, since the remaining input --- that lone period '.' --- is not equal to 'hello'. If we remove '?' from the query, you'll see what you probably expect: ### >>> import re >>> testsearch = re.compile(r'tetsuro\.(?!hello)', re.IGNORECASE) >>> match = testsearch.search('tetsuro.hello') >>> match.group() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'NoneType' object has no attribute 'group' ### And now it doesn't match at all. > >>> match = testsearch.search('tetsuro..hello') > >>> match.group() > 'tetsuro.' > > Why wasn't the first period caught ? Going back to the example, ### testsearch = re.compile(r'tetsuro\.?(?!hello)', re.IGNORECASE) match = testsearch.search('tetsuro.hello') ### If the first period catches, then the negative lookahead constraint gets violated since the rest of the input, 'hello', matches against (?!hello). The regular expression engine is forced by constraint to not match that period. I have to admit: I'm not a regular expression guru. *grin* I have heard, though, that the book "Mastering Regular Expressions", http://www.oreilly.com/catalog/regex/ Good luck! From gus.tabares@verizon.net Thu Jul 10 18:41:01 2003 From: gus.tabares@verizon.net (Gus Tabares) Date: Thu Jul 10 17:41:01 2003 Subject: [Tutor] python scripts In-Reply-To: <200307090501.23097.samacomber@comcast.net> Message-ID: Scott, Why not save it to your home directory? As long as your python is located in your PATH you should have no problems executing your script after you have made it executable. If you are importing your script/module from the interpreter, your home directory (or wherever you're working from) must be in your PYTHONPATH which is accessible through sys.path. HTH, Gus -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Scott Macomber Sent: Wednesday, July 09, 2003 5:01 AM To: tutor@python.org Subject: [Tutor] python scripts I recently started toying with some python programming. I enjoy it. However, when I save a python file after producing it in a text editor (e.g., spam.py) the interpreter can't locate it to run it as a script afterwards. I don't know where I should save the file. Furthermore, I don't know how to determine where I should save the file. I have some texts that suggest various places, but I need to change permissions, etc. I am running SuSe 8.1. The version of python I am using is 2.2.1. Thanks for suggestions. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From guillermo.fernandez@epfl.ch Thu Jul 10 19:10:02 2003 From: guillermo.fernandez@epfl.ch (Guillermo Fernandez) Date: Thu Jul 10 18:10:02 2003 Subject: [Tutor] Bits operations Message-ID: <3F0DE415.6090805@epfl.ch> Cheers, I'm playing with crypto algorithms (I just get out of the exam and I'm kind of masochist ;-) and there's of course bit operations. Here's my problems: 1- How much bits does an integer take? I would like to play with 32 bits words and I don't really know how to limit this and specially fix the size in python (they say an int is represented by a long with _at least_ 32 bits...). 2- I've not seen any binary representation of integers (thus there exist octal and hexa...). It's easier to see something like 00101001B... does it exist? 3- I've seen some bit-sting operations. Is there an easy way of reading the value of a bit in python in a straightforward manner? (for example "the bit i of integer n has a value 1 or 0?"). Could you please point me to a source of information or give me some comments? Thanks!! Guille From ckasso@sprynet.com Thu Jul 10 19:29:02 2003 From: ckasso@sprynet.com (Chris Kassopulo) Date: Thu Jul 10 18:29:02 2003 Subject: [Tutor] basic import question In-Reply-To: <3F0B12DE.10906@ccvcorp.com> References: <20030708143915.5f0e225e.ckasso@sprynet.com> <3F0B12DE.10906@ccvcorp.com> Message-ID: <20030710185854.3abe2d9c.ckasso@sprynet.com> > "Jeff Shannon" wrote: > Chris Kassopulo wrote: > > >def main(): > > print "hello world" > >main() > > > > There's two code blocks in this file. (Any line followed by a series of > further-indented lines can be seen as a code block.) Everything in the > block that starts "def main():" is processed to create a function > object, which is bound to the name "main", but it does *not* get > executed at the time that it's defined. The second code block consists > of the single statement "main()", which then executes the function > object that was previously created. > > Hope that makes a bit more sense now... > Yes it does. For some reason I was forgeting about what the def main() statement does and thought that an import would just execute the rest of the code. As Magnus asked, "what made you think importing it would make it behave differently?". It doesn't. Thank you all for the clarification. Chris From idiot1@netzero.net Thu Jul 10 19:45:04 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 10 18:45:04 2003 Subject: [Tutor] fhat the wuck? Message-ID: <3F0CDA55.2070404@netzero.net> OK, all you happy hackers, ready for some REALLY odd programming? Free Esoteric, Obfuscated, Unusual and Wierd Programming Languages Fnord! -- end Cheers! Kirk D Bailey think http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ http://www.listville.net/ | BOX | http://www.sacredelectron.org/ +-----+ "Thou art free"-ERIS think 'Got a light?'-Promethieus Fnord. From idiot1@netzero.net Thu Jul 10 19:46:46 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 10 18:46:46 2003 Subject: [Tutor] archives without using cgi scripts Message-ID: <3F0CCE0B.3050006@netzero.net> What? HERESY! Well, ok, but it works. I wrote a page about making a simple but effective email list archiver and reader WITHOUT USING CGI SCRIPTS. No, no, it really is possible, it works, it's practical. You DO have to be able to do ssi includes, but many hosts that are real tight about letting you run your own scripts- some don't let you do ANY scripts, others only let you access the limited library they have inspected and improved- will cheerfully let you do ssi includes. http://www.tinylist.org/archivereaders.shtml -- end Cheers! Kirk D Bailey think http://www.howlermonkey.net/ +-----+ http://www.tinylist.org/ http://www.listville.net/ | BOX | http://www.sacredelectron.org/ +-----+ "Thou art free"-ERIS think 'Got a light?'-Promethieus Fnord. From magnus@thinkware.se Thu Jul 10 19:59:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 18:59:01 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030709190952.H51747-100000@yamato.yamato.com> References: <20030710002205.20659.77376.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030711005155.073e0cf8@www.thinkware.se> At 19:14 2003-07-09 -0700, Tony Cappellini wrote: >Why does os.name return 'nt' on a Windows 98 machine ? Read The Fine Manual: "os.name The name of the operating system dependant module imported..." If its any consolation, it returns 'posix' on all Unix-like operating system, regardless of whether it's Linux, AIX or whatever... You can also use sys.platform, and on Linux that says 'linux2', which is a lot more detail, but on Win2k it says 'win32' and I guess is says the same on win98. Otherwise, that is really what you should use to figure out what kind of computer you are running on. This is a bit of a shortcoming, since not all things work the same way on Win98 and the NT-derived operating systems. Why does your program need to know this? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Thu Jul 10 20:04:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 19:04:02 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030711010655.073fb480@www.thinkware.se> At 20:34 2003-07-10 +1200, Thomas CLive Richards wrote: >The problem i have is that i don't know when data is going to be sent to >the port, so i have to use a polling method to fetch the data. The >problem with that is that while the program is polling the serial port, >the GUI isn't getting updated. What GUI? For wxPython see http://wiki.wxpython.org/index.cgi/LongRunningTasks -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Thu Jul 10 20:07:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 19:07:02 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: <5.2.1.1.0.20030711010655.073fb480@www.thinkware.se> References: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030711011047.073c74a0@www.thinkware.se> At 01:08 2003-07-11 +0200, Magnus Lyck=E5 wrote: >At 20:34 2003-07-10 +1200, Thomas CLive Richards wrote: >>The problem i have is that i don't know when data is going to be sent to >>the port, so i have to use a polling method to fetch the data. The >>problem with that is that while the program is polling the serial port, >>the GUI isn't getting updated. > >What GUI? For wxPython see >http://wiki.wxpython.org/index.cgi/LongRunningTasks And for Tkinter (and PyQt) see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From tony@tcapp.com Thu Jul 10 20:16:24 2003 From: tony@tcapp.com (Tony Cappellini) Date: Thu Jul 10 19:16:24 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <5.2.1.1.0.20030711005155.073e0cf8@www.thinkware.se> Message-ID: <20030710160650.S66938-100000@yamato.yamato.com> Hello Magnus, > >Why does os.name return 'nt' on a Windows 98 machine ? The question should have been "Why does os.name return the wrong name for the OS on a Windows 98 machine ? os.name obviously returns "some" name for the OS, but not the correct one in this case. So the manual is of no use becaus eit does not explain why the function returns the wrong name. > You can also use sys.platform, and on Linux that says 'linux2', this isn't any better, as it doesn't differentiate between Windows 2000, and Win98. What's the point of providing a function that doesn't return the correct info, or ambiguous information ? > which is a lot more detail, but on Win2k it says 'win32' and > I guess is says the same on win98. Otherwise, that is really > what you should use to figure out what kind of computer you > are running on. I won't use it if it doesn't give me the correct information. > Why does your program need to know this? Because different drivers are required to talk to various hardware, on each OS, and I need to make the differentiation in order to know which driver to use. thanks Tony From jeff@ccvcorp.com Thu Jul 10 20:26:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 10 19:26:01 2003 Subject: [Tutor] Bits operations References: <3F0DE415.6090805@epfl.ch> Message-ID: <3F0DF5D4.9050304@ccvcorp.com> Guillermo Fernandez wrote: > 1- How much bits does an integer take? I would like to play with 32 > bits words and I don't really know how to limit this and specially fix > the size in python (they say an int is represented by a long with _at > least_ 32 bits...). A Python integer, IIRC, uses whatever the given platform's C long is. For most systems (i.e., 32bit platforms), this is 32 bits. (Note that for most 32-bit platforms, C compilers use the same size for a long and an int ...) However, on 64-bit platforms this would probably be 64 bits. > 2- I've not seen any binary representation of integers (thus there > exist octal and hexa...). It's easier to see something like > 00101001B... does it exist? There isn't a built-in function to do this, but it's not too difficult to write one. (You can find several examples in the archives of this list.) However, you may be better off using hex -- with a little bit of practice, it's not too hard to recognize each hex digit as a pattern of four bits. > 3- I've seen some bit-sting operations. Is there an easy way of > reading the value of a bit in python in a straightforward manner? (for > example "the bit i of integer n has a value 1 or 0?"). The best way to do this is to bitwise-AND your unknown byte with a known constant. if myvar & 0x01: # the first (least significant) bit is set if myvar & 0x04: # the third-least significant bit is set if myvar & 0x80: # the 8th (i.e. most significant) bit is set Note that any byte can be uniquely represented with two hex digits, and it doesn't take long before you can see that 0x0C (12) is equivalent to binary 0000 1100. Jeff Shannon Technician/Programmer Credit International From thomi@thomi.imail.net.nz Thu Jul 10 20:26:11 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 10 19:26:11 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030710160650.S66938-100000@yamato.yamato.com> References: <5.2.1.1.0.20030711005155.073e0cf8@www.thinkware.se> <20030710160650.S66938-100000@yamato.yamato.com> Message-ID: <20030711112529.548e7a86.thomi@thomi.imail.net.nz> > > You can also use sys.platform, and on Linux that says 'linux2', > this isn't any better, as it doesn't differentiate between Windows > 2000, and Win98. > What's the point of providing a function that doesn't return the > correct info, or ambiguous information ? > perhaps the people who originally design the function thought that windows2000 and windows98 were going to be pretty much identical in the way they handle hardware, which is why they use the same name for both? come to think of it, are there any huge differences between the two?? besides, with python being available on many different OS's, it kinda makes sense to have several os "groupings", don't you think? anyway, that's my $0.02... -- Thomi Richards, thomi@thomi.imail.net.nz From missive@hotmail.com Thu Jul 10 20:28:02 2003 From: missive@hotmail.com (Lee Harr) Date: Thu Jul 10 19:28:02 2003 Subject: [Tutor] Re: python scripts Message-ID: >I recently started toying with some python programming. I enjoy it. >However, >when I save a python file after producing it in a text editor (e.g., >spam.py) >the interpreter can't locate it to run it as a script afterwards. I don't >know where I should save the file. Furthermore, I don't know how to >determine where I should save the file. I have some texts that suggest >various places, but I need to change permissions, etc. > >I am running SuSe 8.1. The version of python I am using is 2.2.1. > Sometimes the best way to show us the problem you are having is to paste in to your email a script of the error messages you are getting... You do not say, but I suspect you are running this from IDLE? Here is a script of an interactive session that might help you. You would do this in a shell (xterm, console, konsole, gnome-terminal, etc) The > and the >>> at the start of a line are the prompts and would not be typed. Your prompt might look different. Most of the lines that do not start with > or >>> are responses from the computer, and should not be typed in One exception is the long section after the command that starts with cat. Type those lines in or copy and paste them from this message. >cd >mkdir foo_project >cd foo_project >cat > foo_module.py import random import sys def random_bar(baz): return random.randrange(0, baz) if __name__ == '__main__': choices = int(sys.argv[1]) print random_bar(choices) >python foo_module.py 5 4 >python foo_module.py 64 61 >python foo_module.py 923 405 >python Python 2.2.3 (#1, Jun 9 2003, 18:01:50) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>>import foo_module >>>baz = foo_module.random_bar(12) >>>print baz 3 >>>baz = foo_module.random_bar(12) >>>print baz 2 Basically, you can create a script anywhere, but in a unix-like system, your best bet is to work in your home directory, or a directory inside there that you create. That way you will not need to change any permissions. As long as your shell is "in" that directory, ie you have changed directory (cd) to that location, python will find your script. I recommend a book on basic unix commands to go along with your python programming. It is interesting and very useful. _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From tpc@csua.berkeley.edu Thu Jul 10 20:31:01 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Jul 10 19:31:01 2003 Subject: [Tutor] bash find equivalent in Python Message-ID: <20030710160849.M22075-100000@localhost.name> I am trying to index all html files within a document tree and so far I have: DIR = '/usr/local/apache2/htdocs' myList = [] for f in os.listdir(DIR): path = os.path.join(DIR, f) if os.path.isfile(path) and f.endswith('.html'): myList.append(path) elif os.path.isdir(path): os.chdir(path) for f in os.listdir(os.getcwd()): path = os.path.join(os.getcwd(), f) if os.path.isfile(path) and f.endswith('.html'): myList.append(path) elif os.path.isdir(path): ... While this seems to work, it also seems wrong to have to guess how many levels deep my directory structure is and copy, paste and indent the code accordingly. Is there a recursive find utility in Python similar to bash find ? For example: find . -name '*.html' will return all html files from current working directory and on, along with their paths respective to the current working directory. I looked at string module find in the Python documentation and shutils and did not find the analog. From magnus@thinkware.se Thu Jul 10 20:32:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 19:32:02 2003 Subject: [Tutor] Bits operations In-Reply-To: <3F0DE415.6090805@epfl.ch> Message-ID: <5.2.1.1.0.20030711011450.073fdaf0@www.thinkware.se> At 00:09 2003-07-11 +0200, Guillermo Fernandez wrote: >Cheers, > >I'm playing with crypto algorithms (I just get out of the exam and I'm >kind of masochist ;-) and there's of course bit operations. I guess you'll get what you deserve! ;) >Here's my problems: >1- How much bits does an integer take? I would like to play with 32 bits >words and I don't really know how to limit this and specially fix the size >in python (they say an int is represented by a long with _at least_ 32 >bits...). 32 bits today, but I'd like to raise a warning here! While 0xffffffff means -1 in Python version < 2.3, it's like below in 2.3: >>> 0xffffffff :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up -1 This is because of the ongoing unifiction between the integer and long types. Maybe you should use pyrex? That will let you use C types, and get much faster code than normal Python code. >2- I've not seen any binary representation of integers (thus there exist >octal and hexa...). It's easier to see something like 00101001B... does it >exist? Nope. I pestered Guido about that in Charleroi during EuroPython, and he was determined there was no practical use for it. If you really want it, pester him on Python-dev! :) I think it would be good for learning about computers, but he doesn't seem to be very keen on ones and zeroes... >3- I've seen some bit-sting operations. Is there an easy way of reading >the value of a bit in python in a straightforward manner? (for example >"the bit i of integer n has a value 1 or 0?"). Write a function? def bits(x): i = 0 while x: print "%i: %i" % (i, x%2) x = x >> 1 i += 1 If you just wonder about a particular bit, just do >>> def set_bit(n, i): ... return (n & (1<>> set_bit(127,6) True >>> set_bit(127,7) False -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo@hkn.eecs.berkeley.edu Thu Jul 10 20:45:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 10 19:45:03 2003 Subject: [Tutor] bash find equivalent in Python In-Reply-To: <20030710160849.M22075-100000@localhost.name> Message-ID: On Thu, 10 Jul 2003 tpc@csua.berkeley.edu wrote: > While this seems to work, it also seems wrong to have to guess how many > levels deep my directory structure is and copy, paste and indent the code > accordingly. Is there a recursive find utility in Python similar to bash > find ? For example: > > find . -name '*.html' > > will return all html files from current working directory and on, along > with their paths respective to the current working directory. I looked > at string module find in the Python documentation and shutils and did > not find the analog. Hi tpc, Your wish is my command. *grin* Here's a function --- DFS() --- that'll let you march through each subdirectory: ### import os import os.path def DFS(root, skip_symlinks = 1): """Depth first search traversal of directory structure. Children are visited in alphabetical order.""" stack = [root] visited = {} while stack: d = stack.pop() if d not in visited: ## just to prevent any possible recursive ## loops visited[d] = 1 yield d stack.extend(subdirs(d, skip_symlinks)) def subdirs(root, skip_symlinks = 1): """Given a root directory, returns the first-level subdirectories.""" try: dirs = [os.path.join(root, x) for x in os.listdir(root)] dirs = filter(os.path.isdir, dirs) if skip_symlinks: dirs = filter(lambda x: not os.path.islink(x), dirs) dirs.sort() return dirs except OSError, IOError: return [] ### DFS() returns an iteratable object that marches through all the subdirectories of a given root. Your code for going through all the .html files, then, might look something like: ### for subdir in DFS(root): htmls = glob.glob(os.path.join(subdir, "*.html")) ... ### Another way to do something like 'find' is to use the os.path.walk() utility function: http://www.python.org/doc/lib/module-os.path.html but I find DFS() a little easier on the brain... *grin* Hope this helps! From missive@hotmail.com Thu Jul 10 20:55:02 2003 From: missive@hotmail.com (Lee Harr) Date: Thu Jul 10 19:55:02 2003 Subject: [Tutor] Re: asynchat and queue? Message-ID: >I'm trying to learn how to use sockets in Python. > >I may not be on the right track, I can't find simple examples anywhere of >using queues with asyncore/asynchat. > It does not use queues, but this works for me: import asyncore import asynchat import socket class MainServer: def __init__(self): self.all_connections = [] self.mss = MainServerSocket(50006) self.mss.set_server(self) def add_connection(self, connection): self.all_connections.append(connection) def remove_connection(self, connection): self.all_connections.remove(connection) def send_to_all(self, data): for connection in self.all_connections: connection.push(data) class MainServerSocket(asyncore.dispatcher): def __init__(self, port): print 'initing Listening Port' asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(('',port)) self.listen(5) def set_server(self, server): self.server = server def handle_accept(self): newSocket, address = self.accept() print "Connected from", address sss = SecondaryServerSocket(newSocket) self.server.add_connection(sss) sss.set_server(self.server) class SecondaryServerSocket(asynchat.async_chat): def __init__(self, *args): print 'initing OutBound Port' asynchat.async_chat.__init__(self, *args) self.set_terminator('\n') self.data = [] def set_server(self, server): self.server = server def collect_incoming_data(self, data): self.data.append(data) def found_terminator(self): data = ''.join(self.data) self.server.send_to_all(data) self.data = [] def handle_close(self): print "Disconnected from", self.getpeername() self.close() self.server.remove_connection(self) server = MainServer() asyncore.loop() _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From magnus@thinkware.se Thu Jul 10 21:14:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 20:14:02 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030710160650.S66938-100000@yamato.yamato.com> References: <5.2.1.1.0.20030711005155.073e0cf8@www.thinkware.se> Message-ID: <5.2.1.1.0.20030711021418.073e6918@www.thinkware.se> At 16:15 2003-07-10 -0700, Tony Cappellini wrote: > > >Why does os.name return 'nt' on a Windows 98 machine ? >The question should have been "Why does os.name return the wrong name for >the OS on a Windows 98 machine ? Beacuse os.name was never intended to tell you the name of any operating system. It tells you the name of a Python module it uses! Didn't you read the quote from the docs I gave? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Thu Jul 10 21:30:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 10 20:30:01 2003 Subject: [Tutor] bash find equivalent in Python In-Reply-To: References: <20030710160849.M22075-100000@localhost.name> Message-ID: <5.2.1.1.0.20030711022204.073c7158@www.thinkware.se> At 16:44 2003-07-10 -0700, Danny Yoo wrote: >Another way to do something like 'find' is to use the os.path.walk() >utility function: > > http://www.python.org/doc/lib/module-os.path.html > >but I find DFS() a little easier on the brain... *grin* Nah, os.path.walk is just the thing here! >>> l = [] >>> def htmlFinder(arg, dirname, fnames): ... for fn in fnames: ... if fn.endswith('.html'): ... l.append(os.path.join(dirname, fn)) ... >>> os.path.walk('c:\\', htmlFinder, None) >>> for fn in l: print fn Just read through the help text a few times... >>> help(os.path.walk) Help on function walk in module ntpath: walk(top, func, arg) Directory tree walk with callback function. For each directory in the directory tree rooted at top (including top itself, but excluding '.' and '..'), call func(arg, dirname, fnames). dirname is the name of the directory, and fnames a list of the names of the files and subdirectories in dirname (excluding '.' and '..'). func may modify the fnames list in-place (e.g. via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in fnames; this can be used to implement a filter, or to impose a specific order of visiting. No semantics are defined for, or required of, arg, beyond that arg is always passed to func. It can be used, e.g., to pass a filename pattern, or a mutable object designed to accumulate statistics. Passing None for arg is common. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From tutor@python.org Thu Jul 10 21:33:02 2003 From: tutor@python.org (Tim Peters) Date: Thu Jul 10 20:33:02 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030710160650.S66938-100000@yamato.yamato.com> Message-ID: [Tony Cappellini] > os.name obviously returns "some" name for the OS, but not the correct > one in this case. So the manual is of no use becaus eit does not > explain why the function returns the wrong name. Read Magnus's reply again. > What's the point of providing a function that doesn't return the > correct info, or ambiguous information ? If you're running on Windows and need access to Windows internals, you should install the Python Win32 extensions. Then you can use the Win32 API's GetVersionEx() to get more info than most people have any idea what to do with . Starting in Python 2.3, you can get the same info from the new-in-2.3 sys.getwindowsversion() function (which exists only on Windows Python builds). From thomi@thomi.imail.net.nz Thu Jul 10 22:02:01 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Thu Jul 10 21:02:01 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: <3F0DA100.9030509@ccvcorp.com> References: <20030710203409.49491ce3.thomi@thomi.imail.net.nz> <3F0DA100.9030509@ccvcorp.com> Message-ID: <20030711130122.48d557d8.thomi@thomi.imail.net.nz> > Your worker thread would then alternate between checking if there's > data to read on the serial port, and checking if there's anything in > the Queue that it should send on the serial port. Note that a worker > thread cannot be killed from the main thread -- if you want a worker > thread to end before the entire program shuts down, that thread needs > to end on its own, so you may want to have some way to ask that thread > to commit suicide. This could be a matter of sending a special token > in the output-queue, if you have one, or it could be an independent > threading signal. > with "main" and "child" threads, am i correct when i say that if you only have two threads (a min and a child thread), you only actually need to create the child thread, and the main thread is just run as the rest of the program? (kind of like how it's done with forking)? or do you need to create two threads....hmmm.. /me is confused -- Thomi Richards, thomi@thomi.imail.net.nz From sigurd@12move.de Thu Jul 10 22:47:01 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Jul 10 21:47:01 2003 Subject: [Tutor] bash find equivalent in Python In-Reply-To: <5.2.1.1.0.20030711022204.073c7158@www.thinkware.se> (Magnus Lyck's message of "Fri, 11 Jul 2003 02:34:37 +0200") References: <20030710160849.M22075-100000@localhost.name> <5.2.1.1.0.20030711022204.073c7158@www.thinkware.se> Message-ID: On 11 Jul 2003, Magnus Lyck=E5 <- magnus@thinkware.se wrote: > Nah, os.path.walk is just the thing here! > > >>> l =3D [] > >>> def htmlFinder(arg, dirname, fnames): > ... for fn in fnames: > ... if fn.endswith('.html'): > ... l.append(os.path.join(dirname, fn)) > ... > >>> os.path.walk('c:\\', htmlFinder, None) > >>> for fn in l: print fn That is pretty short but I always found os.path.walk a little bit slow. Some time ago I had a similar problem and I solved it like that (only a bit customized for that problem here (I didn't search for html files)) import os, os.path def filelist(d): files =3D [] =20=20=20=20 for file in os.listdir(d): fulldir =3D os.path.join(d, file) if os.path.isdir(fulldir): flist =3D [os.path.join(fulldir, x) for x in os.listdir(fulldir= ) \ if os.path.isfile(os.path.join(fulldir, x)) and x.ends= with('.html')] files.extend(flist) files.extend(filelist(fulldir)) return files Here that solution compared with os.path.walk was faster. Karl --=20 "Programs must be written for people to read, and only incidentally for machines to execute." -- Abelson & Sussman, SICP (preface to the first edition) From alan.gauld@blueyonder.co.uk Fri Jul 11 04:48:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 11 03:48:01 2003 Subject: [Tutor] Bits operations References: <3F0DE415.6090805@epfl.ch> Message-ID: <024901c34780$bfe04d80$6401a8c0@xp> > 1- How much bits does an integer take? I would like to play with 32 bits Most machines nowadays use 32 bits/integer but as 64 bit machines come on stream that will change(eg the new G5 Mac). > 2- I've not seen any binary representation of integers (thus there exist > octal and hexa...). It's easier to see something like 00101001B... does > it exist? Discussed here many times, search the archives :-) > 3- I've seen some bit-sting operations. Is there an easy way of reading > the value of a bit in python in a straightforward manner? (for example > "the bit i of integer n has a value 1 or 0?"). Try creating a dictionary of bit masks: bits = {0:1,1:2,2:4,3:8,...,31:0x8000} then you can extract the nth bit by bit = val & bits[n] Or alternatively write a function that returns 2**n to get the mask: def mask(n): return 2**n bit = val & mask(n) HTH, Alan G. From op73418@mail.telepac.pt Fri Jul 11 06:28:02 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Fri Jul 11 05:28:02 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: <20030711130122.48d557d8.thomi@thomi.imail.net.nz> Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Thomas CLive Richards > Sent: sexta-feira, 11 de Julho de 2003 2:01 > To: tutor@python.org > Subject: Re: [Tutor] threading vs. forking? > > [Quote snipped] > > with "main" and "child" threads, am i correct when i say that if you > only have two threads (a min and a child thread), you only > actually need > to create the child thread, and the main thread is just run > as the rest > of the program? (kind of like how it's done with forking)? > > or do you need to create two threads....hmmm.. > Yes, you are correct. For a given process there is always one thread, the main thread. This thread could be the Gui thread. You would spawn a new thread to poll the port and set up a Queue where the child would push its data. > /me is confused > > -- > With my best regards, G. Rodrigues > Thomi Richards, > thomi@thomi.imail.net.nz > From op73418@mail.telepac.pt Fri Jul 11 06:34:02 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Fri Jul 11 05:34:02 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: <20030710160650.S66938-100000@yamato.yamato.com> Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Tony Cappellini > Sent: sexta-feira, 11 de Julho de 2003 0:16 > To: Magnus Lycka > Cc: tutor@python.org > Subject: Re: [Tutor] os.name on Windows 98 > [text snipped] > > Why does your program need to know this? > > Because different drivers are required to talk to various > hardware, on > each OS, and I need to make the differentiation in order to > know which > driver to use. > In the upcoming 2.3 there is a module called platform for, and I quote "find out everything you always wanted to know about your platform, but were afraid to ask. " > thanks > > Tony > With my best regards, G. Rodrigues From magnus@thinkware.se Fri Jul 11 07:41:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 11 06:41:02 2003 Subject: [Tutor] bash find equivalent in Python In-Reply-To: References: <5.2.1.1.0.20030711022204.073c7158@www.thinkware.se> <20030710160849.M22075-100000@localhost.name> <5.2.1.1.0.20030711022204.073c7158@www.thinkware.se> Message-ID: <5.2.1.1.0.20030711111901.073c72a0@www.thinkware.se> At 03:42 2003-07-11 +0200, Karl Pfl=E4sterer wrote: > > Nah, os.path.walk is just the thing here! > > > > >>> l =3D [] > > >>> def htmlFinder(arg, dirname, fnames): > > ... for fn in fnames: > > ... if fn.endswith('.html'): > > ... l.append(os.path.join(dirname, fn)) > > ... > > >>> os.path.walk('c:\\', htmlFinder, None) > > >>> for fn in l: print fn > >That is pretty short but I always found os.path.walk a little bit slow. True! But it was fast to write! ;) Have you tried profiling and improving walk? The code is very small and simple, but I'm sure it could be improved. Making os.profile.walk better will benefit all of us, and let you continue to write very small and simple functions. There is a cost you can't avoid in the function call for each directory, but compared to the speed of disk accesses, that seems rather tiny. It's also doing 'isdir()' on each file. Is that a resourse hog? But you do that as well! def walk(top, func, arg): # Extracted from ntpath.py. Doc string removed try: names =3D os.listdir(top) except os.error: return func(arg, top, names) exceptions =3D ('.', '..') for name in names: if name not in exceptions: name =3D join(top, name) if isdir(name): walk(name, func, arg) By the way, a more generic version of my program would use regular expressions. The version below prints the found files at once instead of putting them in a list. >>> def fnFinder(reg_exp, dirname, fnames): ... for fn in fnames: ... if reg_exp.search(fn): ... print os.path.join(dirname, fn) ... >>> import re >>> os.path.walk('C:\\', fnFinder, re.compile('\.html$')) Another version is obviously to supply the list to put the file names in. >>> def fnFinder((aList, reg_exp), dirname, fnames): ... for fn in fnames: ... if reg_exp.search(fn): ... aList.append(os.path.join(dirname, fn)) ... >>> l =3D [] >>> os.path.walk('p:/tmp/', fnFinder, (l, re.compile('\.html$'))) >>> print l ['p:/tmp/index.html', 'p:/tmp/install_guide_2.0.html'] >>> -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From thomi@thomi.imail.net.nz Fri Jul 11 08:51:22 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Fri Jul 11 07:51:22 2003 Subject: [Tutor] threading vs. forking? In-Reply-To: References: <20030711130122.48d557d8.thomi@thomi.imail.net.nz> Message-ID: <20030711235011.45a6b093.thomi@thomi.imail.net.nz> > Yes, you are correct. For a given process there is always one thread, > the main thread. This thread could be the Gui thread. You would spawn > a new thread to poll the port and set up a Queue where the child would > push its data. > ahh.. thanks so much. i got it working!! whew! -- Thomi Richards, thomi@thomi.imail.net.nz From R. Alan Monroe" References: <20030710160849.M22075-100000@localhost.name> Message-ID: <152195723094.20030711123624@columbus.rr.com> > While this seems to work, it also seems wrong to have to guess how many > levels deep my directory structure is and copy, paste and indent the code > accordingly. Is there a recursive find utility in Python similar to bash > find ? For example: You could probably convert your existing program into a recursive one. Here's one I wrote a few months ago that might give you some ideas. class node: def __init__(self,name): self.size=0 self.name=name self.files=[] self.dirs=[] #---------- import os startdir="c:\\winnt" def walker(startdir): print "BEGIN", startdir, "\r", os.chdir(startdir) here=node(startdir) #print here listing = os.listdir(startdir) #print listing for x in listing: #print " DECIDE ", x, #print x #print os.path.abspath(x) if os.path.isfile(x): #print x, "is a file" y=os.path.getsize(x) here.files.append((x,y)) here.size += y elif os.path.isdir(x): #print x, "is a dir" #print os.path.abspath(x) recurse = walker(os.path.abspath(x)) here.dirs.append(recurse) here.size += recurse.size os.chdir(startdir) else: #print x, "is neither" pass #print "DONE ", startdir return here def display(here,level): for x in range(level): print " ", print level, here.name, ":", here.size, #y=0 for x in here.dirs: if here.size>0: #y += float(x.size)/float(here.size) print float(x.size)/float(here.size) else: print "0.0000000000" display(x,level+1) #print y root=walker(startdir) print root.size print "\n\n\n\n" display(root,0) From jeff@ccvcorp.com Fri Jul 11 14:28:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Jul 11 13:28:01 2003 Subject: [Tutor] threading vs. forking? References: Message-ID: <3F0EF374.5010107@ccvcorp.com> Rodrigues wrote: >>[mailto:tutor-admin@python.org]On Behalf Of >>Thomas CLive Richards >> >>with "main" and "child" threads, am i correct when i say that if you >>only have two threads (a min and a child thread), you only >>actually need >>to create the child thread, and the main thread is just run >>as the rest >>of the program? (kind of like how it's done with forking)? >> >> >Yes, you are correct. For a given process there is always one thread, >the main thread. This thread could be the Gui thread. > Indeed, if you're using wxPython for your GUI (as you mentioned that you were, previously), then your main thread *must* be your GUI thread -- wxPython does quite a bit of setup when it's first imported, and the GUI must run from the thread in which that initial import occurs. (It's possible to coerce it to run in a secondary thread, by ensuring that no imports of wxPython happen until after that thread starts, but it's definitely an exercise in coercion -- it's not something you'd want to do without exceptional circumstances dictating it.) Jeff Shannon Technician/Programmer Credit International From tim@johnsons-web.com Fri Jul 11 15:46:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Fri Jul 11 14:46:01 2003 Subject: [Tutor] wxPythonGTK-py2.2 on RH 7.2 Message-ID: <20030711185045.GF20920@johnsons-web.com> Just download xPythonGTK-py2.2 (rpm) and tested (but did not yet install). It tested fine, but here's the thing that makes me nervous -- I run python2.2 explicitly as a distinct binary on RH 7.2 because I have found that some of my services break when python1.5 is overwritten by python2.2. Does anyone know if this might occur if I install xPythonGTK-py2.2? TIA -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From alan.gauld@blueyonder.co.uk Fri Jul 11 18:38:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 11 17:38:01 2003 Subject: [Tutor] Bits operations References: <5.2.1.1.0.20030711011450.073fdaf0@www.thinkware.se> Message-ID: <029701c347f4$d9400670$6401a8c0@xp> > >octal and hexa...). It's easier to see something like 00101001B... > > Nope. I pestered Guido about that in Charleroi during > EuroPython, and he was determined there was no practical > use for it. If you really want it, pester him on Python-dev! :) Really? I'm surprised. I assume Guido doesn't do much with bitmaps or reading raw data from devices. The lack of a binary representation is a real pain. Not hard to code but why should I have to?! And watching a single bit toggling in binary is much easier than watching a hex or octal digit changing and mentally working out which input line triggered it! Alan g. From pan@uchicago.edu Fri Jul 11 20:38:01 2003 From: pan@uchicago.edu (pan@uchicago.edu) Date: Fri Jul 11 19:38:01 2003 Subject: [Tutor] dynamic property of a class ? In-Reply-To: <20030711160006.11550.33573.Mailman@mail.python.org> References: <20030711160006.11550.33573.Mailman@mail.python.org> Message-ID: <1057966644.3f0f4a34207c2@webmail.uchicago.edu> I'm wondering if it's possible to make a class with dynamic properties. For example, a normal class: class car(object): def set_doors(self, val): self.__dict__['__doors']= val def get_doors(self): return self.__dict__['__doors'] doors= property(get_doors, set_doors) c = car() c.doors = 4 print c.doors So far so good. Now, is it possible to make this: c.color= 'black' print c.color and make 'color' a property (instead of an entry in the self.__dict__) at the runtime, even though it is not defined in the class ? I'm imaging an approach like: self.__setproperty__(propName, getFunc, setFunc) but is it even possible? In the above example, "print type(t.doors)" doesn't give any info regarding if 'doors' is a property or an entry in __dict__. Is it possible to distinquish this at runtime ? pan From SWidney@ci.las-vegas.nv.us Fri Jul 11 21:09:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Jul 11 20:09:02 2003 Subject: [Tutor] bash find equivalent in Python Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC868E@sovereign.ci.las-vegas.nv.us> > On Fri, 11 Jul 2003, Scott Widney wrote: > > > > def subdirs(root, skip_symlinks = 1): > > > """Given a root directory, returns the first-level > > > subdirectories.""" > > > try: > > > dirs = [os.path.join(root, x) > > > for x in os.listdir(root)] > > > dirs = filter(os.path.isdir, dirs) > > > > I'm thinking that these two steps can be condensed into one: > > > > dirs = [os.path.join(root, x) > > for x in os.listdir(root) > > if os.path.isdir(x)] > > Hi Scott, > > This almost works. *grin* We have to do the os.path.join()ing > thing when we check if it's a directory: > > > dirs = [os.path.join(root, x) > for x in os.listdir(root) > if os.path.isdir(os.path.join(root, x))] > > But this looked a little too ugly, so that's why I broke it > down into two steps. > > > Is it ok to forward this to Tutor as well? > > > Talk to you later! > Ah yes. You're right, why type something twice in such close vicinity? I don't have an interactive prompt right now to test this: dirs = filter(os.path.isdir, [os.path.join(root, x) for x in os.listdir(root)]) Will Python eval the list comprehension before or during the filter? If it were to yield the list and filter at the same time, it would fairly fly.... From magnus@thinkware.se Fri Jul 11 21:52:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 11 20:52:01 2003 Subject: [Tutor] Bits operations In-Reply-To: <029701c347f4$d9400670$6401a8c0@xp> References: <5.2.1.1.0.20030711011450.073fdaf0@www.thinkware.se> Message-ID: <5.2.1.1.0.20030712014407.073dd3a0@www.thinkware.se> At 22:39 2003-07-11 +0100, Alan Gauld wrote: > > >octal and hexa...). It's easier to see something like 00101001B... > > > > Nope. I pestered Guido about that in Charleroi during > > EuroPython, and he was determined there was no practical > > use for it. If you really want it, pester him on Python-dev! :) > >Really? I'm surprised. I assume Guido doesn't do much with >bitmaps or reading raw data from devices. The lack of a binary >representation is a real pain. Not hard to code but why should >I have to?! He's not an engineer you know. He is basically a mathematician as far as I understand, and that makes him a bit...different I guess. ;) (BTW, I just noticed that he quit working for Zope Corp and is now with Elemental Security, founded by Dan Farmer, the guy who wrote the security checker Satan a number of years ago. It seems Guido prefers to live in California...) >And watching a single bit toggling in binary is much easier >than watching a hex or octal digit changing and mentally >working out which input line triggered it! It's no huge thing. Binary string to integer value is handled by int(x,2), e.g. >>> int('10100101',2) 165 I can agree that is would be neat if I could simply type >>> 0b10100101 165 but I can live without that... Going the other way around, it would be nice with a builtin companion to hex and oct, as well as a "%b" to complement "%x%o%i"... But "%s" % b(n) with b() defined as below does the job I guess... at least for non-negative numbers. def b(i, l=0): s = [] while i: s.append(str(i%2)) i >>= 1 s.extend(['0']*(l-len(s))) s.reverse() return "".join(s) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Fri Jul 11 22:26:59 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 11 21:26:59 2003 Subject: [Tutor] dynamic property of a class ? In-Reply-To: <1057966644.3f0f4a34207c2@webmail.uchicago.edu> References: <20030711160006.11550.33573.Mailman@mail.python.org> <20030711160006.11550.33573.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030712030840.07419d70@www.thinkware.se> At 18:37 2003-07-11 -0500, pan@uchicago.edu wrote: >I'm wondering if it's possible to make a class with dynamic >properties. For example, a normal class: > >class car(object): > > def set_doors(self, val): > self.__dict__['__doors']= val > > def get_doors(self): > return self.__dict__['__doors'] > > doors= property(get_doors, set_doors) > >c = car() >c.doors = 4 >print c.doors > >So far so good. > >Now, is it possible to make this: > >c.color= 'black' >print c.color > >and make 'color' a property (instead of an entry in the self.__dict__) >at the runtime, even though it is not defined in the class ? It's certainly easy to add the feature to the class dynamically: >>> class car(object): ... def set_doors(self, val): ... self.__dict__['__doors']= val ... def get_doors(self): ... return self.__dict__['__doors'] ... doors= property(get_doors, set_doors) ... >>> c = car() >>> c.doors = 4 >>> print c.doors 4 >>> def set_color(self, color): ... if color in ['blue', 'red', 'green']: ... self.__color = color ... else: ... self.__color = 'black' ... >>> def get_color(self): ... return self.__color ... >>> car.color = property(get_color, set_color) >>> c.color = '42' >>> print c.color black but doing "c.color ..." instead of "car.color" won't work. I.e. you can affect all instances of a class in runtime. But if you want instances to behave differently, they should really have different classes. It's more or less the definition of classes that two instances of the same class share the same behaviour... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From dyoo@hkn.eecs.berkeley.edu Fri Jul 11 23:33:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 11 22:33:01 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] In-Reply-To: <029701c347f4$d9400670$6401a8c0@xp> Message-ID: On Fri, 11 Jul 2003, Alan Gauld wrote: > > > >octal and hexa...). It's easier to see something like 00101001B... > > > > Nope. I pestered Guido about that in Charleroi during EuroPython, and > > he was determined there was no practical use for it. If you really > > want it, pester him on Python-dev! :) Hi Alan, We already have hex(), which almost does the trick. If we really wanted a binary() function, we can write it like this: ### def binary(x): 'Returns the binary representation of x.' binary_mapping = {'0' : '0000', '1' : '0001', '2' : '0010', '3' : '0011', '4' : '0100', '5' : '0101', '6' : '0110', '7' : '0111', '8' : '1000', '9' : '1001', 'a' : '1010', 'b' : '1011', 'c' : '1100', 'd' : '1101', 'e' : '1110', 'f' : '1111'} return ''.join([binary_mapping[hex_digit] for hex_digit in hex(x)[2:]]) ### Here's what it looks like in action: ### >>> for n in range(20): ... print n, binary(n) ... 0 0000 1 0001 2 0010 3 0011 4 0100 5 0101 6 0110 7 0111 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1110 15 1111 16 00010000 17 00010001 18 00010010 19 00010011 >>> binary(-42) '11111111111111111111111111010110' ### So that's yet another way to do binary()... *grin* It might seem like cheating to take advantage of hex(). But then again, it's a common programming technique to improve on a function that's almost does what we want. > Really? I'm surprised. I assume Guido doesn't do much with bitmaps or > reading raw data from devices. The lack of a binary representation is a > real pain. Not hard to code but why should I have to?! I don't know... I feel that binary() is a bit too specialized to be put in as a builtin. But perhaps it might fit into a standard library module somewhere? Talk to you later! From alan.gauld@blueyonder.co.uk Sat Jul 12 03:20:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat Jul 12 02:20:02 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] References: Message-ID: <02c401c3483d$bbd92140$6401a8c0@xp> > We already have hex(), which almost does the trick. If we really wanted a > binary() function, we can write it like this: Yes, I know its easy enough to write a function to generate binary strings, but it just seems a shame its not standard when octal and hex are there already. Personally I use binary format far more than I ever use octal! > ### > def binary(x): > 'Returns the binary representation of x.' > binary_mapping = {'0' : '0000', > '1' : '0001', > '2' : '0010', > .... > 'e' : '1110', > 'f' : '1111'} > return ''.join([binary_mapping[hex_digit] > for hex_digit in hex(x)[2:]]) > ### I suspect you can do the same using octal and it would be a smaller table. Personally thats how I generate binary strings - convert to octal then do a digit by digit conversion to binary... Its about the only use I have for octal! > > Really? I'm surprised. I assume Guido doesn't do much with bitmaps or > > reading raw data from devices. The lack of a binary representation is a > > real pain. Not hard to code but why should I have to?! > > I don't know... I feel that binary() is a bit too specialized to be put in > as a builtin. But perhaps it might fit into a standard library module > somewhere? AS Magnus says, maybe its coz I'm an engineer but I use binary a lot more than octal or hex. Actually I can convert hex to binary pretty well in my head but its not fast enough for monitoring input lines or bit mask changes. Even at the newbie level most classes teach binary before octal or hex so beginners are more likely to want to explore binary numbers than octal ones IMHO. And going by the number of times it comes up on tutor I think I'm right! :-) Alan G. From thomi@thomi.imail.net.nz Sat Jul 12 05:57:02 2003 From: thomi@thomi.imail.net.nz (Thomas Clive Richards) Date: Sat Jul 12 04:57:02 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] In-Reply-To: <02c401c3483d$bbd92140$6401a8c0@xp> References: <02c401c3483d$bbd92140$6401a8c0@xp> Message-ID: <20030712205529.1efcc858.thomi@thomi.imail.net.nz> hey... > I suspect you can do the same using octal and it would > be a smaller table. Personally thats how I generate binary > strings - convert to octal then do a digit by digit conversion > to binary... Its about the only use I have for octal! The small trouble that i have with using octal as an intermediate step between decimal and binary is that one octal digit represents 3 binary digits, and this is not easily divisible into an 8 or 16 bit binary number. It's nothing a computer can't handle, but it seems easier to use hex, esp. as you have to do fewer conversions, and thereby limit the chances for a stuff up. again, it's nothing a computer would have trouble with, only us less intelligent humans ;) -- Thomi Richards, thomi@thomi.imail.net.nz From guillermo.fernandez@epfl.ch Sat Jul 12 07:57:06 2003 From: guillermo.fernandez@epfl.ch (Guillermo Fernandez) Date: Sat Jul 12 06:57:06 2003 Subject: [Tutor] Bits operations In-Reply-To: <024901c34780$bfe04d80$6401a8c0@xp> References: <3F0DE415.6090805@epfl.ch> <024901c34780$bfe04d80$6401a8c0@xp> Message-ID: <3F0FE957.5020102@epfl.ch> Hi, I ended up constructing a binary() fct and usig masks and longs. I used longs because I remarked that: >>> 0x100000000&0xFFFF0000>>16 4294967296L ?? This si probably due to the 32 bit integer limit you told me about, because: >>> 0x100000000&0xFFFF0000L>>16 0L Thank you for your answers! Guille From alan.gauld@blueyonder.co.uk Sat Jul 12 16:17:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat Jul 12 15:17:01 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] References: <02c401c3483d$bbd92140$6401a8c0@xp> <20030712205529.1efcc858.thomi@thomi.imail.net.nz> Message-ID: <030b01c348aa$2554f1f0$6401a8c0@xp> > > strings - convert to octal then do a digit by digit conversion > > to binary... Its about the only use I have for octal! > > The small trouble that i have with using octal as an intermediate step > between decimal and binary is that one octal digit represents 3 binary > digits, and this is not easily divisible into an 8 or 16 bit binary For strings that doesn't matter you just expand each octal character into 3 binary characters... But if you want real numbers then it becomes messy I agree. Alan g From thomi@thomi.imail.net.nz Sun Jul 13 02:25:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Sun Jul 13 01:25:02 2003 Subject: [Tutor] how to specify floating point precision from another variable? Message-ID: <20030713172439.11d763e6.thomi@thomi.imail.net.nz> hey, how can i print out floating point numbers with a precision specified by the user? to print it out normally, I'm doing this: self.outtxt.AppendText("%s %f\n"% (str(command), arg)) where arg is a floating point number. however, the user can select to have the floating point numbers print out to a precision of their choosing. this number is stored in config.floatplaces (as an integer number). what I'm wondering is, how can i set this up? i thought i could use exec, like this: exec('self.outtxt.AppendText("%s %.%df\n"% (str(command), arg))' % (config.floatplaces)) but that doesn't print anything at all... i guess exec is getting confused over which float variable it should use, and it's pretty ugly anyway. is there an easy way to do this? i thought there might be a built-in function to do this, but couldn't see anything obvious. (i thought that maybe the float() function could take an additional argument which would specify how many decimal places to include.... hmmm.. I'm, stuck.. any ideas? -- Thomi Richards, thomi@thomi.imail.net.nz From glingl@aon.at Sun Jul 13 05:35:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Sun Jul 13 04:35:01 2003 Subject: [Tutor] how to specify floating point precision from another variable? References: <20030713172439.11d763e6.thomi@thomi.imail.net.nz> Message-ID: <3F111A22.4050303@aon.at> Thomas CLive Richards schrieb: >hey, > >how can i print out floating point numbers with a precision specified by >the user? > >to print it out normally, I'm doing this: > >self.outtxt.AppendText("%s %f\n"% (str(command), arg)) > >where arg is a floating point number. > >however, the user can select to have the floating point numbers print >out to a precision of their choosing. this number is stored in >config.floatplaces (as an integer number). > > This can be done as follows: >>> "%s %10.*f" % ("A STRING", input("Dezimals: "), 0.123456789) Dezimals: 2 'A STRING 0.12' >>> "%s %10.*f" % ("A STRING", input("Dezimals: "), 0.123456789) Dezimals: 7 'A STRING 0.1234568' >>> config_floatplaces = int(raw_input("What precision do you want? ")) What precision do you want? 4 >>> "%s %10.*f" % ("A STRING", config_floatplaces, 0.123456789) 'A STRING 0.1235' >>> A description of how this has to be done you can find at http://www.python.org/doc/current/lib/typesseq-strings.html See especially the numbered paragraph 4. Regards, Gregor From python@rcn.com Sun Jul 13 06:33:02 2003 From: python@rcn.com (Raymond Hettinger) Date: Sun Jul 13 05:33:02 2003 Subject: [Tutor] os.name on Windows 98 References: <20030710160650.S66938-100000@yamato.yamato.com> Message-ID: <001901c34921$38406ac0$125ffea9@oemcomputer> > > Why does your program need to know this? > > Because different drivers are required to talk to various hardware, on > each OS, and I need to make the differentiation in order to know which > driver to use. Try this (it's not pretty but it works): >>> import os >>> print os.popen('ver').read() Windows Millennium [Version 4.90.3000] Raymond Hettinger From magnus@thinkware.se Sun Jul 13 07:39:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Sun Jul 13 06:39:01 2003 Subject: [Tutor] os.name on Windows 98 In-Reply-To: References: <20030710160650.S66938-100000@yamato.yamato.com> Message-ID: <5.2.1.1.0.20030713121337.01f3d600@www.thinkware.se> At 10:34 2003-07-11 +0100, Rodrigues wrote: >In the upcoming 2.3 there is a module called platform for, and I quote > >"find out everything you always wanted to know about your platform, >but were afraid to ask. " Yet another reason to upgrade to Python 2.3b2... :) >>> import platform >>> for x in dir(platform): try: print "%s = %s" % (x, eval('platform.%s()' % x)) except: pass _node = nida _sys_version = ('2.3b2.0', 43, 'Jun 29 2003 16:43:04', 'MSC v.1200 32 bit (Intel)') _syscmd_ver = ('Microsoft Windows', '2000', '5.0.2195') architecture = ('32bit', 'WindowsPE') dist = ('', '', '') java_ver = ('', '', ('', '', ''), ('', '', '')) libc_ver = ('', '') mac_ver = ('', ('', '', ''), '') machine = node = nida platform = Windows-2000-5.0.2195-SP3 processor = python_build = (43, 'Jun 29 2003 16:43:04') python_compiler = MSC v.1200 32 bit (Intel) python_version = 2.3b2.0 python_version_tuple = ['2', '3b2', '0'] release = 2000 system = Windows uname = ('Windows', 'nida', '2000', '5.0.2195', '', '') version = 5.0.2195 win32_ver = ('2000', '5.0.2195', 'SP3', 'Uniprocessor Free') The "win32_ver" thingie didn't work until I installed the win32all toolkit. Same code on a Linux box: _node = kaunas _sys_version = ('2.3b2.0', 1, 'Jul 4 2003 23:13:33', 'GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk)') _syscmd_ver = ('', '', '') architecture = ('32bit', 'ELF') dist = ('mandrake', '9.0', 'dolphin') java_ver = ('', '', ('', '', ''), ('', '', '')) libc_ver = ('glibc', '2.2') mac_ver = ('', ('', '', ''), '') machine = i686 node = kaunas platform = Linux-2.4.19-16mdk-i686-with-mandrake-9.0-dolphin processor = python_build = (1, 'Jul 4 2003 23:13:33') python_compiler = GCC 3.2 (Mandrake Linux 9.0 3.2-1mdk) python_version = 2.3b2.0 python_version_tuple = ['2', '3b2', '0'] release = 2.4.19-16mdk system = Linux uname = ('Linux', 'kaunas', '2.4.19-16mdk', '#1 Fri Sep 20 18:15:05 CEST 2002', 'i686', '') version = #1 Fri Sep 20 18:15:05 CEST 2002 win32_ver = ('', '', '', '') -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From chrisj@liquid.sec-d.net Sun Jul 13 15:45:03 2003 From: chrisj@liquid.sec-d.net (Chris Johnson) Date: Sun Jul 13 14:45:03 2003 Subject: [Tutor] newbie confused about text parsing Message-ID: <003e01c3496f$11ab1c90$0217a8c0@win2k> hi group, I'm a unix administrator and I want to learn python to help in my job. I thought parsing a log file would be a good start but I'm stuck on how to start. I'm working with a firewall log file the contents of which look something like this. Nov 30 00:58:05 firewall kernel: Shorewall:man1918:DROP:IN=eth0 OUT= MAC=ff:ff:ff:ff:ff:ff:00:90:f5:1e:15:aa:08:00 SRC=10.1.2.27 DST=10.1.2.255 LEN=96 TOS=0x00 PREC=0x00 TTL=128 ID=4853 PROTO=UDP SPT=137 DPT=137 LEN=76 I'd like to eventually have these put into a mysql data base. But I'm having trouble figuring out how to parse this. some of the fields won't be there every time and the file contains other logs (ie. this came out of /var/log/messages) I want to loop through log file looking for a string (Shorewall) then parse each matching line into a dictionary which I can sort or put into database fields. I've been reading the documentation on both modules re and string but which do I use. I'd like to run this script all the time so entries are added in near real time to the database. I've actually worked out the MySQLdb part of it pretty well it's just the text parsing I'm having trouble starting. sorry if this is post is to log winded. thank for any suggestions. chrisj From DORSEY_EDMUND_K@LILLY.COM Sun Jul 13 19:00:02 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Sun Jul 13 18:00:02 2003 Subject: [Tutor] Tkinter layout problem Message-ID: --=_mixed 0078B9C705256D62_= Content-Type: multipart/alternative; boundary="=_alternative 0078B9C805256D62_=" --=_alternative 0078B9C805256D62_= Content-Type: text/plain; charset="us-ascii" I can't seem to figure out how to get the grid layout manager to work. I'm using the pmw.Group and I have three groups. I'm having problems arranging the items inside of the groups. I attached a screenshot of the program to make it easier to see the problem. The FileInfo group is layed out how I want it But I can't seem to get the progress bar to fill the entire Progress Group. It just wants to sit in the middle and same goes for the Actions group. I tried setting sticky=W+E to make the progress bar stretch out and fill the entire Progress Group but that didn't do anything. From what I understand each Group has it's own grid layout within it. Is this correct? Thank you for any help or advice. ~Ed I coded it up as follows data_frame = Pmw.Group(parent, tag_text='File Info') Label(data_frame.interior(), text = "Input File:").grid(row=0,column=0) Label(data_frame.interior(), textvariable=self._inputLabel, relief = "sunken", bg = "white", width = 50, anchor="w").grid(row=0, column=1) self.openButt = Button(data_frame.interior(), text="Load", padx=20, bg='DodgerBlue', command=self.loadCB).grid(row=0, column=2) Label(data_frame.interior(), text="Output File:").grid(row=1, column=0) Label(data_frame.interior(), textvariable = self._outputLabel, relief = "sunken", bg = "white", width = 50, anchor="w").grid(row=1, column=1) self.saveButt = Button(data_frame.interior(), text="Save", padx=20, bg='DodgerBlue', command=self.saveCB).grid(row=1, column=2) data_frame.grid(row=0, column=0, sticky=W+E) prog_frame = Pmw.Group(parent, tag_text='Progress') self.progressMeter = ProgressMeter(prog_frame.interior(), finishvalue=100, progresscolor='DodgerBlue', labelpos='n', label_text='') prog_frame.grid(row=1, column=0, sticky=W+E) self.progressMeter.grid(row=0, column=0, sticky=W+E) #!!won't stretch to fill prog_frame button_frame = Pmw.Group(parent, tag_text='Actions') self.startButt = Button(button_frame.interior(), padx=20,text="Start", bg='Green',command=self.startCB) self.exitButt = Button(button_frame.interior(), padx=20,text="Exit", bg='red', command=parent.destroy) self.pauseButt = Button(button_frame.interior(), padx=20,text="Pause", bg='orange', command=self.pauseCB) self.startButt.grid(row=0,column=0) self.exitButt.grid(row=0, column=1) self.pauseButt.grid(row=0, column=2) button_frame.grid(row=2, column=0, sticky=W+E) --=_alternative 0078B9C805256D62_= Content-Type: text/html; charset="us-ascii"
I can't seem to figure out how to get the grid layout manager to work.  I'm using the pmw.Group and I have three groups.  I'm having problems arranging the items inside of the groups.

I attached a screenshot of the program to make it easier to see the problem.


The FileInfo group is layed out how I want it

But I can't seem to get the progress bar to fill the entire Progress Group.  It just wants to sit in the middle and same goes for the Actions group.  I tried setting sticky=W+E to make the progress bar stretch out and fill the entire Progress Group but that didn't do anything.  From what I understand each Group has it's own grid layout within it.  Is this correct?  Thank you for any help or advice. ~Ed

I coded it up as follows


        data_frame = Pmw.Group(parent, tag_text='File Info')
        Label(data_frame.interior(), text = "Input File:").grid(row=0,column=0)
        Label(data_frame.interior(), textvariable=self._inputLabel, relief = "sunken", bg = "white", width = 50, anchor="w").grid(row=0, column=1)
        self.openButt = Button(data_frame.interior(), text="Load", padx=20, bg='DodgerBlue', command=self.loadCB).grid(row=0, column=2)
        Label(data_frame.interior(), text="Output File:").grid(row=1, column=0)
        Label(data_frame.interior(), textvariable = self._outputLabel, relief = "sunken", bg = "white", width = 50, anchor="w").grid(row=1, column=1)
        self.saveButt = Button(data_frame.interior(), text="Save", padx=20, bg='DodgerBlue', command=self.saveCB).grid(row=1, column=2)
        data_frame.grid(row=0, column=0, sticky=W+E)
       
       

        prog_frame = Pmw.Group(parent, tag_text='Progress')
        self.progressMeter = ProgressMeter(prog_frame.interior(),
                                               finishvalue=100,
                                               progresscolor='DodgerBlue',
                                               labelpos='n',
                                               label_text='')
        prog_frame.grid(row=1, column=0, sticky=W+E)
        self.progressMeter.grid(row=0, column=0, sticky=W+E) #!!won't stretch to fill prog_frame

        button_frame = Pmw.Group(parent, tag_text='Actions')        
        self.startButt = Button(button_frame.interior(), padx=20,text="Start", bg='Green',command=self.startCB)
        self.exitButt = Button(button_frame.interior(), padx=20,text="Exit", bg='red', command=parent.destroy)
        self.pauseButt = Button(button_frame.interior(), padx=20,text="Pause", bg='orange', command=self.pauseCB)
        self.startButt.grid(row=0,column=0)
        self.exitButt.grid(row=0, column=1)
        self.pauseButt.grid(row=0, column=2)
        button_frame.grid(row=2, column=0, sticky=W+E)
--=_alternative 0078B9C805256D62_=-- --=_mixed 0078B9C705256D62_= Content-Type: image/jpeg; name="layout.jpg" Content-Disposition: attachment; filename="layout.jpg" Content-Transfer-Encoding: base64 /9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0a HBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIy MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCADpAcwDASIA AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA AAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3 ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm p6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA AwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx BhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK U1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3 uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDr/HXj pvBbaeq6bFdi6QnllTbtVD3Q5zurkP8AheMn/QvRf9/1/wDjdO+NzBLnQGKhgEckHv8ALFXmQvLi UPJuBjyFVNn3ye3f8ea6Y00qcZcl79W2utraJ/ob4elTquSnUcWuiinpa7bu1p6Xfltf0v8A4XjJ /wBC9F/3/X/43Sj44SH/AJl6L/v+v/xuvLrqLyLcR4wQw3cZ3HB5z6eg/rnHqs+i6B4rhSbw3f2c ekLc2FvdWA0mOK5to5XSPi5KlnfcCSckdckjht4Qw8486jp6v+tehhiqNbDVPZTfvW1/y+X9aajR 8bpD/wAy/F/3+X/43Sj42SH/AJgEX/f5f/jdXfAXhKw0rxZHqME1y01p4hvNKRXZSpiW2lYMcAfN kdentXO2PgzQtRh0KaO5vLT+3ba7S0juJ0YR3UT7U3ybBlG6YC7s4AJzxXssNe3L+fn/AJHNzVLb muPjVIf+YBF/3+X/AON04fGiT/oAxf8Af5f/AI3WRd+DNC02LXJpLm7u/wCwra1S7jgnRVkupX2v sk2HCL0wV3ZyCRjnV/4Vfpn9sXmn/wBpTQ/ZdVgt/PunWJJoJYw/lxnad04z04BBBxzij2WG7fn5 f5oOar3Hj4zSH/mAxf8Af1f/AI3Th8ZJD/zAov8Av6v/AMbrM/4RDwvZ6Va3uq6nfaet/NdpALhD 5kCxOUUPGsbb2zjd80fXAzirOsQxXHi34ewzRpJFJpmmo6OoKspkIIIPUGj2NBvSP59A56ncuD4x SH/mBxf9/V/+N04fF+Q/8wOL/v6v/wAbqaXSvDmveJk8Nym3F4dWusPplsLcwWyRsViY7FDNvUc4 fgH5uecTSfC+gX1jb34l1Ka2utWg0uIbo4XVmjBeRuHBG4nCjoByxoVLD21j+Yc9Tuaw+Lsh/wCY JF/38X/43Th8W5D/AMwSL/v4v/xusDXfDOneGtJgkuGury6ubi8gjeORYUj8mTywSpVi2Tz94env V7X/AAr4Y0S5l02TXJYtQgkgVy0byBlYL5jbBGAmA24AO+QMdTT9jh3tH8xc9TuaY+LMh/5gsX/f xf8A43Sj4ryH/mDRf9/F/wDjdVrnwZoVtrVrFJqKxaXcwzvbXh1BHjuXQgBC4jAiPckhx2GTWlY+ A7SZl028We2/4nDWzKjxSPtFqZQwl8sMQSAccDB5XdzUOnh0r2/MalV7kA+Ksh/5g0X/AH8X/wCN 04fFOQ/8weL/AL7X/wCIqjaeENLvNMttXSS8jtH0+7vHtWlVpCYGC4Em0AA7gfuHGD1zxDLoen2H izwtHbpK9tqEdpcyRXLLJjzJOVOFAIwMdPWq9jh3pb8xc9Tuao+KMh/5g8X/AH2v/wARTh8T5D/z CIv++1/+IqxJpug614hTQJDALs6nc4fT7cQGG3VGIjY7AGbco5w3APzc85GmeHdEvLOC9EmoS29z qcOnRjckTqWQF5Dw4I3E4XsOpNSqVC2sfzG51OjNEfE2Q/8AMJi/77X/AOIpw+Jch/5hMX/fS/8A xFNsvBGmrf6bY3k93NJfXF5EJYXWMRiAkfdKtkttJ6jGe+Oacnhaya50Oxs2u5r/AFG3guXR3RI1 RlYyYfBIPAx8pwAfvEgU/ZYft+Yuer3L4+JMh/5hUX/fS/8AxFOHxHkP/MLi/wC+l/8AiKZH4R0e S0TUI7m4ltG0+5ugkcvJaFlGA7RqcEN3QYI7iopfC2nGKUQvdJIdIGqxM8isFHGY2AUbj1+YEdRx xyvZYft+Yc9XuWR8RZD/AMwuL/vpf/iKcPiHIf8AmGRfmv8A8RWV4a8P2OvWsm+78i4tplkuPMkV U+zY+Zl4J3AjqflGRXRaNp+lyf8ACP28VnHJaai975puIlaV1XIT5sZUgAfdI5onSoR05fz9QjOo +pUHxBkP/MMi/Nf/AIinDx/If+YbF+a//EVj6Eq6a91c6lplw8D2n7uQ2glWJnI2SYfC44OD36V1 M+lRw6YdK1L97v1yOIPaBIAN0K7W27SOh5AHXv6qVKjF25fxYKdRrczx49kP/MOi/Nf/AIinDx3I f+YdF/47/wDEVyt9a/YdRurTfv8AImeLfjG7aSM47dKiFa/VqL1t+ZHtqnc7EeOZD/zD4v8Ax3/4 ilHjeQ/8w+L/AMd/+IrkBUgo+q0u35h7afc60eNJD/y4Rf8Ajv8A8TTh4ykP/LjF+S//ABNcmKkF L6rS7fmHtp9zqh4wkP8Ay4xfkv8A8TSjxdIf+XKL8l/+JrmBTxR9VpdvzD20+50w8WSH/lzi/Jf/ AImlHiqQ/wDLnF/3yv8A8TXNinrR9WpdvzD20+50Y8USH/l0i/75X/4mnDxNIf8Al0i/75X/AOJr nhTxS+rUu35h7efc6AeJJD/y6xf98r/8TSjxFIf+XaL/AL4X/wCJrCFPFH1al2/MXt6nc3B4gkP/ AC7Rf98L/wDE04a9If8Al3i/74X/AOJrEFSCl9WpdvzH7efc2Brkh/5d4v8Avhf/AImnDWpD/wAs Iv8Avhf/AImsgU8UfVqXb8xe3qdzWGsSH/ljF/37X/4mnDVpD/yxi/79r/hWWKeKPq9Lt+Ye3qdz SGqSH/llF/37X/CnDUZD/wAs4v8Av2v+FZ4qQUvq9PsHt6nc1ibxWKtFagjggmLioLy9ews5ru5+ yRwQoXdsxHAHsOT9BzVbW9Y0zSbx/wC0tRs7PzZH8v7TOse/B5xuIzjI/OsTxNeWt/4Hv7qzuYbm 3eI7JYXDo2GwcEcHkEfhXn86/l/P/M7eV9/y/wAjqybxWKtFagjggmLioLy9ews5ru5+yRwQoXds xHAHsOT9BzXH+IfCeieKPiHqf9s2X2n7PZW/lfvXTbuluc/dIz90dfSsS68PaV4ah8VWekWv2a3f TbSVk8xnyxknBOWJPRR+VHNH+X8/8w5X3/L/ACPUEkupI1cRW4VuRu8sZ5x0P0p266/552v5xVi+ I5LGLwrI+pX81haLbkyXUEzRSRfO2CrLzuzjA5yeMHODx/hTUtXvPENuniq4vLS7FsTplq0f2eO7 T+OWRVdg0wGMxHAQHIHORU3GMmlHb1/zFFNxTv8AkdH4n1QXvgzVXt3iKeW8ZeNVGSG2sAQOmQRx wR7V6Tb/APHvF/uD+VeM/wDNMb//ALbf+jmr2aD/AI94v9wfypSSUtP62HFtrU8Z+K/hrV/EMuk/ 2VafaPIjbzP3iJt3LHj7xGehrz0fDvxgBGBpIHlnK4uIeuev3vp+VfQdz/rV/wCuaf8AoIrkn8W7 fE0+kZ0iLybmODFzqflTyb0R8pF5Z3ffwBu5IPStIYqUYqFk0u/9eY1FpuUW1ft8n+aTPKX+HnjK VQr6YWA9bmL/AOK5q9feFviNqsCwaib+8hVt4juNRWRQ2CM4Zzzgnn3r0jTPGFvdQzzXPIMkYt47 OCWd3RreGUttVd5UGXG4qoGVBAJ56SGaK4gjngkSWGRQ6SIwZWUjIII6girWNnHRRS+QpwdR805N vzZ44+h/E+V4nkutVdom3xs2qglGwVyP3nBwxGfQn1qC48JeP7y+hvrpLye7hx5U8t+jSJg5G1i+ Rg5Ix3r2PUL+LTbNrmVXcBkjVEA3O7sERRnAyWYDJIAzyQOazH8RHTSY9et0tJmUPELR3ullXeke BhA24PIgxt/jXBPzbWsdPpFf18yPYR7s8xtvCfj2zvZb22S7gu5s+bPFfosj5OTuYPk5PJz3p48K ePP7l3/x8/a/+P5P9f8A89fv/f8A9rr716WPFVk+qWNnFHcuLpZcn7PKHhdGiAWSPZuQEShtzbQB g9GBp9l4o027js8zfPcxxNujjkaFGkUMqGUoFVjuXCttY7l+X5gKPr1Tsv6+Yewj3Z5zbaB8RLPz fs02ow+dIZZfL1ILvc9WbD8k9yeagPhDxq89tM8Fw0tqqpbubxC0SqcqFO/5QO2Olem23izRru1N zHcTLEYxKhltZYjMpIAMYZQZMllHyZ5dR1YZ1LS6jvbVLiJZlR84E0LxPwccq4DDp3FH16p2X9fM PYR7s8gh8I+NIL838UFxHeFmc3CXiCQs2dx3b85OTn1zU1h4Y8b6X5n9nrd2nmY3/Z71Y92M4zhx nGT+depaxqH9k6Jf6l5Xm/ZLaSfy923fsUtjODjOOuKzP+Ez0V9SS2ttQs7qL7NJPJLbTiUoVeNF TamSWcyYAHJIwASaPr1R9F/XzD2Ee7OCtvDPja0s5bO3W6htZc+ZBHeqqPkYOVD4ORxVhdF8fC3j txNfiCLb5cX9oDam0grgb8DBAI9MCuxuPF9lDf22XcWbwSmUNbS+ekokgRE8vG8E+eOCuTlSODzt WGoW2pQNLbM5CtsdJI2jdGwDhkYBlOCDyBkEHoRS+uz7IPYR7s82Gi+PPtn2zzr/AO1eX5Xnfbxv 2Zzt3b84zziiLQfG8LFo2vEYytOSt8oPmEEF/v8A3iCQT1wa9Too+uz7IPYR7s8x0/Q/F1hcWkgt ZZEtN/kxNe7VTcDu27JFK5zk4Iz3zU+raZ4w1nU4b+ez8ua3jSOExXCgxheRhi5YnOTkknJ616PR S+uzvey/r5h7CNrXZ5bF4a8Vw3pvY4p0uyxYzrdKHyep3bs5OTn61LZaB4u07f8AYhc2vmY3+Rdq m7GcZw3PU/nXptFP67Psg+rx7s4bRIPFugW7xWVgoZmZg7XJwpK7c7BIEJHX5lP6Cs4+HvFDSwSt HMZLdVWFzcqTGF+6FO7gDtjpXpVFJYyad7L+vmHsI7XZ59JpnjGfPnTXsmUaM770HKtjcvLdDgZH fApo0XxT6XH+p+z/APH0v+q/ufe+77dK9Doo+uz7IPq8e7POYPDviG28zyYJIvMQxvsnVdynqpw3 IPpU8Gj+Jre2ktoftEVvJnfElyArZGDkBsHI4rv6KHjZvohfV492cLFpniiGVJI3ukkSMQqy3QBV B0UHdwvt0qSGx8VW+/yZruPzHMj7LsDcx6scNyT6121FH1yfZD+rx7s8/HhvV/8An0/8iJ/jTx4c 1b/n0/8AIif413tFP67U7IX1aBwg8O6r/wA+v/kRf8aePD+qf8+v/kRf8a7iil9dqdkH1aBxI0DU /wDn2/8AIi/408aFqX/Pt/4+v+NdnRR9dqdkH1aBx40PUf8An3/8fX/GnDRdQ/59/wDx9f8AGuuo o+u1OyD6tA5MaNf/APPv/wCPr/jTxo9+P+WH/j6/411NFH12p2QfVoHMDSb7/nh/4+v+NPGl3v8A zx/8eH+NdJRR9cqdkH1aBzw0y8/54/8Ajw/xpw027/55f+PD/Gt+ij65U7IPq0DDGn3X/PL/AMeH +NOFhc/88/8Ax4VtUUvrk+yD6tAyBZXH/PP/AMeFOFnP/wA8/wBRWrRR9cn2QfVoGaLWb+5+op4t pf7n6ir9FH1yfZB9WgUhBL/d/UU8Qyf3f1q1RR9bn2QfVoHLat4d1HXJ/N1K40u6wzMiz6Ukgj3H kLuckdB+QqN/C+qNpD6VHqVnBYspXyYNOWNVBOTgK4xzzXW0Vj7Rfyr8f8zXkfd/h/kcnqvhe81u +a81GTSLmY5AabSI5Cq5J2gsxOASe/eq6+C7qKxurO2udNtYbpQswtdLSIuB0yVYZxk4+tdpRR7R fyr8f8xcj7v8P8jJvbfXJ5V+y6lBbQIu1YzaBz1JJJL88k9hxj61W+weJP8AoOQf+AA/+LrfoodR N3cV+P8AmChZWTf4HI6rpr6T8P8AULSSUSsqOxcLtBLOW6ZOOvrXrMH/AB7xf7g/lXnHjH/kUdS/ 65f1Fejwf8e8X+4P5UnLmdxpWVjmrn/Wr/1zT/0EVmWOn/Y7vUp/N3/bbkT7duNmIo48def9XnPH XHatO5/1q/8AXNP/AEEVDUFHERfDuKG2t1M9jdzQKqL9v08TxbfIgiJ2bx82bdSDu4DMMHrXY2ds llY29pGcpBGsanaq8KMDhQFHToAB6AVBqGsaZpPl/wBpajZ2fm58v7TOse/GM43EZxkfnT7fUrC7 dUtr22mZl3qscqsSuFbIwemJEP0dfUUAGoWEWpWbW0rOgLJIroRuR0YOjDORkMoOCCDjkEcVz+r6 Dqt7apcSXVtc6pHPbrbtHbmKKGMXEUkhKGQlj+7BPz8hAFAJJbp5poreCSeeRIoY1LvI7BVVQMkk noAKfQM5+28O3Vvqa6r9vhbUHkc3J+zEROjrCrKib8o2LePBLMM7jg5AWrp/g+WwtLaxXUUeyVrW adTbkSSSwLEqlW34VT5EZKlWP3vm5GOniminQvDIkihmQsjAgMpKsOO4IIPoQafQI5h/COdM0u08 +zn+wad9g23ln50UvzQneybx/wA8eBnqwOeOdrSbB9M0yG0kuprp03FpZnZiSWLEAsS20ZwASSAA CT1q7RQBS1jT/wC1tEv9N83yvtdtJB5m3ds3qVzjIzjPTNZ/iDw1Fr8sTzSoFigeMRSRCRHYywyr uBIyuYACvcMeR1rdooGcReeC7mC1tpNOaxjuo50byraxWCAZuLZy4QMDhVt8kFizZOCOFHT6Vp0t iLuW5uEnurufz5njjMabgiRjapZiBtjXqx5yeM4GhRQIKKKKBhRRRQAUUUUAFFFFABRRRQAUUUUA FFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAU UUUAYfjH/kUdS/65f1Fejwf8e8f+6P5V5x4x/wCRR1L/AK5f1Fejwf6iP/dH8qqJLOUu1aXUY4/O ljQWnmHytuSR5SjllP8AeNR/Z0/5+77/AL7i/wDjdTT/APIVH/Xgf/QoKbSGc3rEd/J4w0kafc21 vN9gvCWuLdplK+ZbcYDpznHOfwrn9c1fU4PFF+9tIhktFmgiZ8KsETf2cXcttOAokkfcwYLjJBAx XolFIDiJb28vvhp4jku7y2vdtpcrFcW8nmq6eTn/AFgjjVyGLDKKAMYOWDVauNS1WLU9SuBf/wCi 2mrWlnHa+SuGWZbcPubG4480suCMHOSwwo62igDzSw1W90zwnpcS6q8EkOh29xYQusWdQnZXPkYK 5cLtiULHh8SDJJINekNErnJnuU9omQD/AMeQn9afRRcCP7On/P3ff99xf/G6Ps6f8/d9/wB9xf8A xupKKLgR/Z0/5+77/vuL/wCN0fZ0/wCfu+/77i/+N1JRRcCP7On/AD933/fcX/xuj7On/P3ff99x f/G6koouBH9nT/n7vv8AvuL/AON0fZ0/5+77/vuL/wCN1JRRcCP7On/P3ff99xf/ABuj7On/AD93 3/fcX/xupKKLgR/Z0/5+77/vuL/43R9nT/n7vv8AvuL/AON1JRRcCP7On/P3ff8AfcX/AMbo+zp/ z933/fcX/wAbqSii4Ef2dP8An7vv++4v/jdH2dP+fu+/77i/+N1JRRcCP7On/P3ff99xf/G6Ps6f 8/d9/wB9xf8AxupKKLgR/Z0/5+77/vuL/wCN0fZ0/wCfu+/77i/+N1JRRcCP7On/AD933/fcX/xu j7On/P3ff99xf/G6koouBH9nT/n7vv8AvuL/AON0fZ0/5+77/vuL/wCN1JRRcCP7On/P3ff99xf/ ABuj7On/AD933/fcX/xupKKLgR/Z0/5+77/vuL/43R9nT/n7vv8AvuL/AON1JRRcCP7On/P3ff8A fcX/AMbo+zp/z933/fcX/wAbqSii4Ef2dP8An7vv++4v/jdH2dP+fu+/77i/+N1JRRcCP7On/P3f f99xf/G6Ps6f8/d9/wB9xf8AxupKKLgR/Z0/5+77/vuL/wCN0fZ0/wCfu+/77i/+N1JRRcCP7On/ AD933/fcX/xuj7On/P3ff99xf/G6koouBH9nT/n7vv8AvuL/AON0fZ0/5+77/vuL/wCN1De6hb6d Gsly5VGO0EKTz+FUv+En0r/nu3/ftv8ACuinha9SPNCDa9DCeJo05cs5JM0/s6f8/d9/33F/8bo+ zp/z933/AH3F/wDG6zP+En0r/nu3/ftv8KP+En0r/nu3/ftv8Kv6jiv+fb+4n67h/wCdfeaf2dP+ fu+/77i/+N0fZ0/5+77/AL7i/wDjdZn/AAk+lf8APdv+/bf4Uf8ACT6V/wA92/79t/hR9RxX/Pt/ cH13D/zr7zT+zp/z933/AH3F/wDG6Ps6f8/d9/33F/8AG6zP+En0r/nu3/ftv8KP+En0r/nu3/ft v8KPqOK/59v7g+u4f+dfeaf2dP8An7vv++4v/jdH2dP+fu+/77i/+N1mf8JPpX/Pdv8Av23+FNfx TpEaM7XDBVGSfLbp+VH1HFf8+39wfXMP/OvvIPFP/ImayC8j7HKK0mN2NkTYOAB1Y9q9Mh/1Ef8A uj+VeU6vfxap8OdQ1CBXWG6AnRXADBWhgYZxnnBr1aH/AFEf+6P5VzI6GcrP/wAhUf8AXgf/AEKC q91dwWUKy3D7EaSOIHBPzO4RRx6swH41Yn/5Co/68D/6FBWN4khln0uFIY3kYX9k5VFJIVbmJmPH YAEn0ANJjNeivO9ZTWLDw7fail3qguHn1NHLSPthtwl00RVeijckRV/vcgBtpC1dhlubbUobqxGt HQoJ42lW4S5klLGK4V/kkBldctbcAFQeR0YhWA7QTRNO8AkQzIqu0YYblUkgEjsCVbH0PpWXH4l0 6aeaKJb6QxNKjOmn3DJujLBwHCbSQVI4JyRgZNYvha3v21+81DUba+hkuIJI4luGY7VW8uG2tglc hJIdp5+UnYSN1MTT9VtfCfiKaG71EXEn9pG2s1jVdjNNKUePagk3Hgj5jndx2wAdda3cF7C0tu+9 FkkiJwR8yOUYc+jKR+FTV5pPaa8lxIkU99Zx+fdPZrDZzylpmu52JOyREAKmEjz8xkH0359FtfL8 lvK87b5kmfO35zvOcbuduc47Yxt4xQBiaN4eh8TeJfE323UdXiW0uoY4UtdQlhRVNvGxG1Wx1JPT uatR+F/Ck1rNcxeJNfeKG9/s+Urq9wSlx5oi8thnIO9lHPGCD0OaveBf+Rl8Y/8AX7b/APpNHWO+ h6pZWSz2VhPIt/4lDX1vs2mNE1R5UugO+UCqxwcp5bZCxnda2JN7/hWulf8AQW8Rf+Dif/4qq9v4 C0K7nu4YNa8RPJaSiGcf2tcDY5RZAOTz8rqePX1zTtO/tP8A4SiDf/av27+0Lr7f5vnfZPsOJvI2 Z/cbv+PX/V/P97d/y0qO503UrjxDcwxtqVra3XiMNPLalo/MtxpaqcsBwhkUJuGCGxtIYAhgWv8A hWulf9BbxF/4OJ//AIqo5/h5olrby3FxrmvwwRIXkkk1qZVRQMkklsAAc5rmZJ9UOoatZvL4gOrW 1ky6NHE10UEgu71IGm2/uyCscHzz5DAZYkbjVzxEniDUdFm8PQWeqzXkl3qomkIYQmKWG8NshkYh WU74cYJVCqqxRtoIBe1bwf4d0SKCS91jxV/pEvkwpBf3c7u+1nwEj3N91GPTtUcHhXw3O9mn9r+L YnvH2QLcXd7CXbbI2PnAwdsMhwccBT/EudrXNPm1CPwmmmz6lbRx3u/7SsZaeGP7HOAX89WIJJVS ZBnLc/Maw/Fdn4l/4SCEaUb66mtrSM2s7ouz7T9k1Jd54EYYs0AbgD5kBABAoA1v+Fa6V/0FvEX/ AIOJ/wD4qq9h4C0LU9Otr+z1rxFJa3USTQv/AGtcDcjAFTgnIyCOtWvAsN9F9v8AOvr66tD5flfa 7O5t9r/Nvx9qleY8eX6IMDbli+MvSdSuG+G+laTa2us29/aWVkl6radcwMsKNEtwEcoMv5fmYEZL nqnIFAGl/wAK10r/AKC3iL/wcT//ABVV73wFoWnwLNda14ijjaWOEH+1rg5eR1jQcHuzKPbPPFZt 4dSfTXt4jrMGjtes9ndyw6hNcIgiiHlvHE6XJDSNcENIcARgYw0ZFMDVtRs9Lk16DXJNZe70iaBI 4bhYBEDbPMZUjAhVhILknzAGGB0ASgDpv+Fa6V/0FvEX/g4n/wDiqr2/gLQrue7hg1rxE8lpKIZx /a1wNjlFkA5PPyup49fXNYOlQ+K0sZnur7VZbgxQ/wBqwrZ3MexvOi8/ypJJWDMI/tAX7Iqqeowf KFdZ4HgjhPiB7eLUktJtTDwNqKziV1+zQKT+/wD3hG5WAJ9MDgUAQ/8ACtdK/wCgt4i/8HE//wAV R/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2 VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE/ /wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A /FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/ 8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDB xP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCg t4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i /wDBxP8A/FV2VFAHG/8ACtdK/wCgt4i/8HE//wAVR/wrXSv+gt4i/wDBxP8A/FV2VFAHmPjHRLbQ dGtLW1lu5laYu0l3cvO5JBH3nJIHA4HH4k1xNej/ABM/49LP/rp/Q15xX2GUf7pH5/mfK5p/vMvl +QVHPPHbW8s8zbYokLu2M4AGSeKkqlrMby6HqEcaM7vbSKqqMkkqcACvQm3GLaOCCTkky7RWReXg u4ovKW+W3WUfadsEsb7CrY28Bj823O38eM1mX0mpLYKU+1JJGkj2zCOaRpPmbYrBSMEKI/8AWA53 HIyGzjPEqN2lf+v6+ehtDDuVru39f18tTppJ44niR2w0r7EGOp2lsfkp/KpK55Y5H1i0aVLxrlLy VnJEhhWLZIEI/wCWY4KDjnJ55zXQ1pSqOd2+/wCi/EipBQsgqG8/48p/+ubfyqaobz/jyn/65t/K rl8LIj8SOhg/5Iun/XnD/wCk9vXs0P8AqI/90fyrxmD/AJIun/XnD/6T29ezQ/6mP/dH8q/PUfdH Kz/8hUf9eB/9CgptOn/5Co/68D/6FBTahjQyaGK4gkgnjSWGRSjxuoZWUjBBB6gin0UUDCiiigAo oooANJSHR7rUbmCMtNqEyzTF24BWNYwAOwwoPrkn2A1P7bl/54p+Zrj5PEUx1O9sbLw/q+oNZusc 0lqkRQMyK4HzSA9GHb1pf7b1X/oTPEX/AH6g/wDjtPUWh1/9ty/88U/M0f23L/zxT8zXIf23qv8A 0JniL/v1B/8AHaP7b1X/AKEzxF/36g/+O0ahodWNUC3D3C2kIndFR5APmZVJKgnqQCzEDtuPrUn9 ty/88U/M1yH9t6r/ANCZ4i/79Qf/AB2j+29V/wChM8Rf9+oP/jtGoaHX/wBty/8APFPzNH9ty/8A PFPzNch/beq/9CZ4i/79Qf8Ax2j+29V/6EzxF/36g/8AjtGoaHX/ANty/wDPFPzNH9ty/wDPFPzN ch/beq/9CZ4i/wC/UH/x2j+29V/6EzxF/wB+oP8A47RqGh1/9ty/88U/M0f23L/zxT8zXIf23qv/ AEJniL/v1B/8do/tvVf+hM8Rf9+oP/jtGoaHX/23L/zxT8zR/bcv/PFPzNch/beq/wDQmeIv+/UH /wAdo/tvVf8AoTPEX/fqD/47RqGh1/8Abcv/ADxT8zR/bcv/ADxT8zXIf23qv/QmeIv+/UH/AMdo /tvVf+hM8Rf9+oP/AI7RqGh1/wDbcv8AzxT8zR/bcv8AzxT8zXIf23qv/QmeIv8Av1B/8do/tvVf +hM8Rf8AfqD/AOO0ahodf/bcv/PFPzNH9ty/88U/M1yH9t6r/wBCZ4i/79Qf/HaP7b1X/oTPEX/f qD/47RqGh1/9ty/88U/M0f23L/zxT8zXIf23qv8A0JniL/v1B/8AHaP7b1X/AKEzxF/36g/+O0ah odf/AG3L/wA8U/M0f23L/wA8U/M1yH9t6r/0JniL/v1B/wDHaP7b1X/oTPEX/fqD/wCO0ahodf8A 23L/AM8U/M0f23L/AM8U/M1yH9t6r/0JniL/AL9Qf/HaP7b1X/oTPEX/AH6g/wDjtGoaHX/23L/z xT8zR/bcv/PFPzNch/beq/8AQmeIv+/UH/x2j+29V/6EzxF/36g/+O0ahodf/bcv/PFPzNH9ty/8 8U/M1yH9t6r/ANCZ4i/79Qf/AB2j+29V/wChM8Rf9+oP/jtGoaHX/wBty/8APFPzNH9ty/8APFPz Nch/beq/9CZ4i/79Qf8Ax2j+29V/6EzxF/36g/8AjtGoaHX/ANty/wDPFPzNH9ty/wDPFPzNch/b eq/9CZ4i/wC/UH/x2j+29V/6EzxF/wB+oP8A47RqGh1/9ty/88U/M0f23L/zxT8zXIf23qv/AEJn iL/v1B/8do/tvVf+hM8Rf9+oP/jtGoaHX/23L/zxT8zR/bcv/PFPzNch/beq/wDQmeIv+/UH/wAd o/tvVf8AoTPEX/fqD/47RqGgfEDUFn061kmKRAS4BLYB4PrXn/2y2/5+If8AvsV1niiJdR0e0u9S 0A28gmZI4tTt4ZHC45IALhQSB6H5emMZ5L7Bpv8A0CNK/wDBfD/8TX1uVOt9VjypW13b7+h8xmSp fWXzN306eXqL9stv+fiH/vsUfbLb/n4h/wC+xSfYNN/6BGlf+C+H/wCJo+wab/0CNK/8F8P/AMTX o3xHZfe/8jgtQ7v7l/mL9stv+fiH/vsUfbLb/n4h/wC+xSfYNN/6BGlf+C+H/wCJo+wab/0CNK/8 F8P/AMTRfEdl97/yC1Du/uX+Yv2y2/5+If8AvsUfbLb/AJ+If++xSfYNN/6BGlf+C+H/AOJo+wab /wBAjSv/AAXw/wDxNF8R2X3v/ILUO7+5f5i/bLb/AJ+If++xUN1dW7WkyrPESY2AAcc8VL9g03/o EaV/4L4f/iaPsGm/9AjSv/BfD/8AE0m8Q1ay+9/5DXsE73f3L/M6KD/ki6f9ecP/AKT29ezRf6lP 90V4Zo08lx8GL+SVtzfarlRxgKqsoVQBwAAAABwAABwK9zi/1Kf7or4Vq0mj7NO6TOVn/wCQqP8A rwP/AKFBXIatf6ksPiTUYNRmgGi7vKtkjjMU223Sb95uUvyXKnay8AYwck9fP/yFR/14H/0KCsO+ 8Nw3s13/AKdeQ219/wAflrF5fl3HyBDuLIXXKKqnay8DIwcmoKJ5ddtYfte6OY/Zb2GyfAHLy+Vt I5+7++XPfg8HjOLp3jYy6RaXV7pV4rf2dDf3ssXleVBG+/58GTcV/duwChmxjjPFad54Ztby+a4a 6vI0e5hu3gikAjeaIptduMniNVK524GcBsNWePBo+1zQjULmPSGsIbH7KhQmWJGmzG5KFgoSRVBV g2M5OcNS0Am1nxZFY+HbjULaJzMGvIIVkUbfNgSZjuwfukwN055HTseJdSube20YpNfaeLu78ucW 1us86r5Er7QoWQE7lXJUHoecc1Jc+DtOvJv9ImvHtfMmkW083bEDMkiy9AGO7zWOSSVP3SoJB05N NSdtOeeeaSWxk81JDtBkby3jJYAAch2PAHOO3FAHN3fiAaRfafFNqd9JAqrPdyXduikwNBdyA7VR WDAwjI2jhFGMls6mh+K7LxA8iWUbtJEyiZVmhlEasGKuWjkZcEoVwCWBwSADmn6n4X07V79ru885 98YieIPhGUJOmDgZ5FzJ0I6L0wc2rPTJrV98urX11IWBZpzHhlAYBNqoqgZbdkAMSACSABQBP4F/ 5GXxj/1+2/8A6TR1TtfFurm1voLuaNLka6kdnKsYHm2Z1IWzJzwXUAqxA4WSI53NmtDwZbzW2ueK bieMxQ3F5CYXfgSBbeMEj1GcjPTII7GtG48KaNd2NpazyyOtpqp1eB/NAZJzM0x6DBXLsuCPun1w atbEk9v4otrnVEtBaXaQTXEtpBesE8qaePf5kagMXBHlS8soU7DgnK7sPWtT1ZLfxZqtvqs9svh/ d5FnHFEYbjZaxz/vSyF+WkKnYy/KBjByx2bfw7Y22qJdi/uHghuJbuCyZ4/Khnk3+ZIpChyT5svD MVG84Awu2PUfDNnqE99/xNbu3tNR/wCP+yhaLy7r5BG24shdcxqqHYy8DIw2SWBbm8SWcH23dHOf seoW+nyYUcyTeTtI5+6PPTJ68NweM8/pXxCM2h2V7qGi3yt/ZUGp6hND5Pk20Um/58GXeVxE7AKG bbjI3fLWrf8AhfTr/UWum1C7iR7uC+ktoZlWOS4hMe2RuNx+WJFK52YGdofDDLXwPD9tntxq9xFo b6ZBp32ON4iZoUecmJ2aMsECSqisrB8ZJYthqALev+NYdN8K3WqWkEjTh763t1lQFfOtknYl8NnY TbPjBzyOmTg8W6td2tpoDJcalpgvb0R3ItLVLm4Rfs80mwIElBO5FyVDcA845pbvwTo19OftV5dy Wfm3Eq2P2gLCpnSVJugDHf5ztksSp4QqpKnYl0+3uG0qS4vZJZtNl85JGZAZX8p4iXAAHIkY/KF5 x24oA5a98TjQ9R0uGfWNSlt0RLm+lvbWNCbdre+lBKrGrq4MAyu0EBFGMl87nhjxhpnir7Utids1 rsMsfnwzYV87Tuhd05Ktxu3DGSACCWav4U0bXNTa9v5ZJN8SwyQiUKjoI7iPBwNwyt3JnBHRcYwc 6GmWX9n+a1xrF3qM0mB5l28Y2qM4AWNUQck87dxyASQFAAOe0PXprW3ubvxBq13HPBZNdahZXdgY 1t2QAyfZnCKZYkJZSQZc5jO7n547T4jWusX2mW2kwedJNqCW11CJ4JmjieGd1kDxStH1hOQWLbVb 5clc6q+F9Ol+0LqGoXepQy2ktikd3Mp8m3k2+ZGGUK7bgifM7M/yg7sliZItAh3wT3et397d29wk 8NxPJEDHtVl2hERY8FZJFJ27iH65VCoBv0Uzzov+eif99Cjzov8Anon/AH0KAH0Uzzov+eif99Cj zov+eif99CgB9FM86L/non/fQo86L/non/fQoAfRTPOi/wCeif8AfQo86L/non/fQoAfRTPOi/56 J/30KPOi/wCeif8AfQoAfRTPOi/56J/30KPOi/56J/30KAH0Uzzov+eif99Cjzov+eif99CgB9FM 86L/AJ6J/wB9Cjzov+eif99CgB9FM86L/non/fQo86L/AJ6J/wB9CgB9FM86L/non/fQo86L/non /fQoAfRTPOi/56J/30KPOi/56J/30KAH0Uzzov8Anon/AH0KPOi/56J/30KAH0Uzzov+eif99Cjz ov8Anon/AH0KAOF+Jn/HpZ/9dP6GvOK9G+JTK1nZlWBHmdj7GvOa+wyj/dI/P8z5XNP95l8vyCob tp0s52tUV7gRsYkbozY4B5HepqbIgkjZGLAMCCVYqfwI5H1Fek1dWPPTs7mdaXax29zI13PcLCm8 rcwiGRRg+oQbTjgkAZDc+ha69ZXSqwfYnzhnZ1KIVAYqWBKk7Tu4J4DdMGpP7KRkl864nmlk2fvn 2hl2NuTAVQvDEnkHOecjimjRoWhljnmluDLMJneQJkkBVxwoGCq7SMcgkd65kqytb+vx/wAzovSd 7/1+H+RCPEdl9rhtnDxyybAVkKqyM4BVShbdn5h0BAz14ONeqZ09ftbTpcTxq7h5IkICuwAAJON3 RV4BAOORyc3K1pqor87MqnJpyBRRRWpmWtA/5Inf/wDX3d/+jFr3eL/Up/uivCNA/wCSJ3//AF93 f/oxa93i/wBSn+6K/PZ/Gz7mHwo5S6WZb9ZY4DKv2QRnbIikE+UR95h/dPSos3X/AD4yf9/4P/jl S39zBbyp588cW6NMb3C5+UetVP7TsP8An9tv+/q/41maE2br/nxk/wC/8H/xyjN1/wA+Mn/f+D/4 5WZqep39vqlnp+n2VtczXEE05a4uWhVVjaNe0b5JMg9OlFh4isLq3c3FxbWtzCsrTwPOuY1ikaN3 5wfLDI2GIHGMgHgIDTzdf8+Mn/f+D/45Rm6/58ZP+/8AB/8AHKpvr2jxafFqEmrWKWUrbI7lrlBG 7c8Bs4J+U/kfSg69o4gmnOrWPkwLG8sn2lNsayDKFjngMCMZ654oAuZuv+fGT/v/AAf/AByjN1/z 4yf9/wCD/wCOVCNSsGe0Rb22LXil7ZRKuZ1A3Epz8wwQeO1OhvrO5Sd4LqCVbeRo5ikgYRuv3lbH QjuD0oAkzdf8+Mn/AH/g/wDjlGbr/nxk/wC/8H/xyof7TsP+f22/7+r/AI0f2nYf8/tt/wB/V/xo Amzdf8+Mn/f+D/45Rm6/58ZP+/8AB/8AHKh/tOw/5/bb/v6v+NH9p2H/AD+23/f1f8aAJs3X/PjJ /wB/4P8A45Rm6/58ZP8Av/B/8cqH+07D/n9tv+/q/wCNH9p2H/P7bf8Af1f8aAJs3X/PjJ/3/g/+ OUZuv+fGT/v/AAf/AByof7TsP+f22/7+r/jR/adh/wA/tt/39X/GgCbN1/z4yf8Af+D/AOOUZuv+ fGT/AL/wf/HKh/tOw/5/bb/v6v8AjR/adh/z+23/AH9X/GgCbN1/z4yf9/4P/jlGbr/nxk/7/wAH /wAcqH+07D/n9tv+/q/40f2nYf8AP7bf9/V/xoAmzdf8+Mn/AH/g/wDjlGbr/nxk/wC/8H/xyof7 TsP+f22/7+r/AI0f2nYf8/tt/wB/V/xoAmzdf8+Mn/f+D/45Rm6/58ZP+/8AB/8AHKh/tOw/5/bb /v6v+NH9p2H/AD+23/f1f8aAJs3X/PjJ/wB/4P8A45Rm6/58ZP8Av/B/8cqH+07D/n9tv+/q/wCN H9p2H/P7bf8Af1f8aAJs3X/PjJ/3/g/+OUZuv+fGT/v/AAf/AByof7TsP+f22/7+r/jR/adh/wA/ tt/39X/GgCbN1/z4yf8Af+D/AOOUZuv+fGT/AL/wf/HKh/tOw/5/bb/v6v8AjR/adh/z+23/AH9X /GgCbN1/z4yf9/4P/jlGbr/nxk/7/wAH/wAcqH+07D/n9tv+/q/40f2nYf8AP7bf9/V/xoAmzdf8 +Mn/AH/g/wDjlGbr/nxk/wC/8H/xyof7TsP+f22/7+r/AI0f2nYf8/tt/wB/V/xoAmzdf8+Mn/f+ D/45Rm6/58ZP+/8AB/8AHKh/tOw/5/bb/v6v+NH9p2H/AD+23/f1f8aAJs3X/PjJ/wB/4P8A45Rm 6/58ZP8Av/B/8cqH+07D/n9tv+/q/wCNH9p2H/P7bf8Af1f8aAJs3X/PjJ/3/g/+OUZuv+fGT/v/ AAf/AByof7TsP+f22/7+r/jR/adh/wA/tt/39X/GgCbN1/z4yf8Af+D/AOOUZuv+fGT/AL/wf/HK h/tOw/5/bb/v6v8AjR/adh/z+23/AH9X/GgCbN1/z4yf9/4P/jlGbr/nxk/7/wAH/wAcqH+07D/n 9tv+/q/40f2nYf8AP7bf9/V/xoAmzdf8+Mn/AH/g/wDjlGbr/nxk/wC/8H/xyof7TsP+f22/7+r/ AI0f2nYf8/tt/wB/V/xoAxPFdh4h1O1t4dJ061JVy0jXV7GmOMAAKWz1PpjHfPHK/wDCKeOv+gfo 3/gxH+Fei/2nYf8AP7bf9/V/xo/tOw/5/bb/AL+r/jXZRx+Iow5KcrI5auCoVZc843Z51/winjr/ AKB+jf8AgxH+FH/CKeOv+gfo3/gxH+Fei/2nYf8AP7bf9/V/xo/tOw/5/bb/AL+r/jWv9q4v+f8A L/Iz/s3C/wAv5nnX/CKeOv8AoH6N/wCDEf4Uf8Ip46/6B+jf+DEf4V6L/adh/wA/tt/39X/Gj+07 D/n9tv8Av6v+NH9q4v8An/L/ACD+zcL/AC/medf8Ip46/wCgfo3/AIMR/hR/winjr/oH6N/4MR/h Xov9p2H/AD+23/f1f8aP7TsP+f22/wC/q/40f2ri/wCf8v8AIP7Nwv8AL+Z51/winjr/AKB+jf8A gxH+FH/CKeOv+gfo3/gxH+Fei/2nYf8AP7bf9/V/xo/tOw/5/bb/AL+r/jR/auL/AJ/y/wAg/s3C /wAv5nHRaJfeHvhJfafqSwrdedPMVhlEigOykcj8R+Fezxf6pP8AdFeaeLJop/BupSQyJInlldyM CM5HGR9R+demR/6pP90Vw3bd2dlrKyOVkdk1dWRirCwOCDg9Yaf9ruf+fiX/AL7NRz/8hUf9eB/9 CgptSykYuq+HrXWNbsbq/tLO7tLa2njMVzGJPndoirAEEcBGGevPuaq33hyWS5uZLMW0MIgsFtoR lVDW07y7DgfKpBVQRnHJwcAHpKKQHEXUWoaJqw1x7ZJ727aYNaQJcSxxqyW6582OFjn/AEdTgoud 5wfk+aDTvB2ox+HLKKYIt1BPb3IgW7kgJK2SWzIZY8lCGDHK7gQAP4jjvqKLgcra+Gru0l0/yorF Y1bfc5eSU/61pdpL5Mx3NlXJRkcFxkO0daPh7TLvS2nM62iD5UgFsD8qLkgAkAqmWJWLLeXkgOQQ F2aKAJvtdz/z8S/99mj7Xc/8/Ev/AH2ahooGTfa7n/n4l/77NH2u5/5+Jf8Avs1DRQBN9ruf+fiX /vs0fa7n/n4l/wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/AL7NQ0UATfa7n/n4l/77NH2u5/5+Jf8A vs1DRQBN9ruf+fiX/vs0fa7n/n4l/wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/AL7NQ0UATfa7n/n4 l/77NH2u5/5+Jf8Avs1DRQBN9ruf+fiX/vs0fa7n/n4l/wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/ AL7NQ0UATfa7n/n4l/77NH2u5/5+Jf8Avs1DRQBN9ruf+fiX/vs0fa7n/n4l/wC+zUNFAE32u5/5 +Jf++zR9ruf+fiX/AL7NQ0UATfa7n/n4l/77NH2u5/5+Jf8Avs1DRQBN9ruf+fiX/vs0fa7n/n4l /wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/AL7NQ0UATfa7n/n4l/77NH2u5/5+Jf8Avs1DRQBN9ruf +fiX/vs0fa7n/n4l/wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/AL7NQ0UATfa7n/n4l/77NH2u5/5+ Jf8Avs1DRQBN9ruf+fiX/vs0fa7n/n4l/wC+zUNFAE32u5/5+Jf++zR9ruf+fiX/AL7NQ0UATfa7 n/n4l/77NH2u5/5+Jf8Avs1DRQBN9ruf+fiX/vs0fa7n/n4l/wC+zUNFAGB4rdn8H64zsWYytkk5 P+rhr0yP/VJ/uivMvFP/ACJuuf8AXVv/AEXDXpsf+qT/AHRVIlnKT/8AIVH/AF4H/wBCgptOn/5C o/68D/6FBTaljQUUUUDCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACisca8XaQ Q6VfSokrxb1MIDFWKnGZAcZB6inf23N/0BdQ/wC+oP8A45RZiua1FZP9tzf9AXUP++oP/jlH9tzf 9AXUP++oP/jlFmFzWorJ/tub/oC6h/31B/8AHKP7bm/6Auof99Qf/HKLMLmtRWT/AG3N/wBAXUP+ +oP/AI5R/bc3/QF1D/vqD/45RZhc1qKyf7bm/wCgLqH/AH1B/wDHKP7bm/6Auof99Qf/AByizC5r UVk/23N/0BdQ/wC+oP8A45R/bc3/AEBdQ/76g/8AjlFmFzWoqhZajNeXSwHTLuAEMxklaLaMKTzt cntjpV+gAooooGFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAc/4p/5E3XP+urf +i4a9Nj/ANUn0FeZeKf+RN1z/rq3/ouGvTY/9Wn0FUiWcpP/AMhUf9eB/wDQoKbS3RZNRWQQzyKb PZmKFpMEmIgHaDjhT+VRea//AD6X3/gHL/8AE0mMkoqPzX/59L7/AMA5f/iaPNf/AJ9L7/wDl/8A iaVmBJRUfmv/AM+l9/4By/8AxNHmv/z6X3/gHL/8TRZgSUVH5r/8+l9/4By//E0ea/8Az6X3/gHL /wDE0WYElFR+a/8Az6X3/gHL/wDE0ea//Ppff+Acv/xNFmBJRUfmv/z6X3/gHL/8TR5r/wDPpff+ Acv/AMTRZgSUVH5r/wDPpff+Acv/AMTR5r/8+l9/4By//E0WYElFR+a//Ppff+Acv/xNHmv/AM+l 9/4By/8AxNFmBJRUfmv/AM+l9/4By/8AxNHmv/z6X3/gHL/8TRZgSUVH5r/8+l9/4By//E0ea/8A z6X3/gHL/wDE0WYElFR+a/8Az6X3/gHL/wDE0ea//Ppff+Acv/xNFmBiaV/x7T/9flz/AOj3q7SW Omy28EiyCbLzzS4FnccB5GcD/V9cMM1a+yN/03/8Arj/AON1oSVqKs/ZG/6b/wDgFcf/ABuj7I3/ AE3/APAK4/8AjdAFairP2Rv+m/8A4BXH/wAbo+yN/wBN/wDwCuP/AI3QBWoqz9kb/pv/AOAVx/8A G6Psjf8ATf8A8Arj/wCN0AVqKs/ZG/6b/wDgFcf/ABuj7I3/AE3/APAK4/8AjdAFairP2Rv+m/8A 4BXH/wAbo+yN/wBN/wDwCuP/AI3QAunf8fn/AGzk/wDQDVio7aI28xkZblgEcYWyuMklSB1j96PN f/n0vv8AwDl/+JqZDRJRUfmv/wA+l9/4By//ABNHmv8A8+l9/wCAcv8A8TU2YySio/Nf/n0vv/AO X/4mjzX/AOfS+/8AAOX/AOJoswJKKj81/wDn0vv/AADl/wDiaPNf/n0vv/AOX/4mizAkoqPzX/59 L7/wDl/+Jo81/wDn0vv/AADl/wDiaLMCSio/Nf8A59L7/wAA5f8A4mjzX/59L7/wDl/+JoswJKKj 81/+fS+/8A5f/iaPNf8A59L7/wAA5f8A4mizAkoqPzX/AOfS+/8AAOX/AOJo81/+fS+/8A5f/iaL MCSio/Nf/n0vv/AOX/4mjzX/AOfS+/8AAOX/AOJoswJKKj81/wDn0vv/AADl/wDiaPNf/n0vv/AO X/4mizAkoqPzX/59L7/wDl/+Jo81/wDn0vv/AADl/wDiaLMDD8U/8ibrn/XVv/RcNemx/wCrX6Cv M/FKyDwVrDvFLGHkZlEsbISNkQzhgD1B/KvTI/8AVr9BVoTOYuf9av8A1zT/ANBFQ0l3DDNqsfnQ xShbIsoljDgHMIzgjHQmmfZrT/nwsf8AwEj/APiagZW1TVbXSLVbi7fajSLGOQOp5bkj5VXc7Hsq Me1Xa5/WdK1HVdXi8o2cdpb2zLi8t/tMU7S5Vh5YddrKi43HORMw9c5C6NqBNuNU0h9WkitEtLeZ 7hA0MsbyA3BctuiMimJ90e5xt5yVXIB1ttfxXhBtleSHdLG0oACq8b7GUg4OdwbBAI+U89M2q4Gf wxqC3DeTYoU8+8luCjIBdpLd282zkjcWhR4iHwMqQTtIJnsfCoudailvNHSHRwtyYtPkKbINwtQE aNGKEFoppMDcuSGOG6AHb0Vx2g6RqdvqWmXN/Yu1ylhElzdy3Idt4iCldwO4kvuzGQ0ZwsgYPkN1 pt7ViS1lZsx5LNbRkn3JI5oAkoqP7Naf8+Fj/wCAkf8A8TR9mtP+fCx/8BI//iaNAJKKj+zWn/Ph Y/8AgJH/APE0fZrT/nwsf/ASP/4mjQCSio/s1p/z4WP/AICR/wDxNH2a0/58LH/wEj/+Jo0AkoqP 7Naf8+Fj/wCAkf8A8TR9mtP+fCx/8BI//iaNAJKKj+zWn/PhY/8AgJH/APE0fZrT/nwsf/ASP/4m jQCSio/s1p/z4WP/AICR/wDxNH2a0/58LH/wEj/+Jo0AkoqP7Naf8+Fj/wCAkf8A8TR9mtP+fCx/ 8BI//iaNAJKKj+zWn/PhY/8AgJH/APE0fZrT/nwsf/ASP/4mjQCSio/s1p/z4WP/AICR/wDxNH2a 0/58LH/wEj/+Jo0AkoqP7Naf8+Fj/wCAkf8A8TR9mtP+fCx/8BI//iaNAJKKj+zWn/PhY/8AgJH/ APE0fZrT/nwsf/ASP/4mjQCSio/s1p/z4WP/AICR/wDxNH2a0/58LH/wEj/+Jo0AkoqP7Naf8+Fj /wCAkf8A8TR9mtP+fCx/8BI//iaNAJKKj+zWn/PhY/8AgJH/APE0fZrT/nwsf/ASP/4mjQCSio/s 1p/z4WP/AICR/wDxNH2a0/58LH/wEj/+Jo0AkoqP7Naf8+Fj/wCAkf8A8TR9mtP+fCx/8BI//iaN AJKKj+zWn/PhY/8AgJH/APE0fZrT/nwsf/ASP/4mjQCSio/s1p/z4WP/AICR/wDxNH2a0/58LH/w Ej/+Jo0AkoqP7Naf8+Fj/wCAkf8A8TR9mtP+fCx/8BI//iaNAJKKj+zWn/PhY/8AgJH/APE0fZrT /nwsf/ASP/4mjQCSio/s1p/z4WP/AICR/wDxNH2a0/58LH/wEj/+Jo0AkoqP7Naf8+Fj/wCAkf8A 8TR9mtP+fCx/8BI//iaNAJKKj+zWn/PhY/8AgJH/APE0fZrT/nwsf/ASP/4mjQCSio/s1p/z4WP/ AICR/wDxNH2a0/58LH/wEj/+Jo0Ax/GP/Io6l/1y/qK9JT/Vr9BXmPidUTwZraxxxxqJWwsaBVH7 uHoBxXpyf6tfoKpCZyk//IVH/Xgf/QoKbTp/+QqP+vA/+hQU2pY0FFFFAwooooAKKKKACiiigAoo ooAKKKKAMG/1m6tr+aCNYdiEAblJPKg+vvVf/hIL7+7b/wDfDf8AxVQav/yF7n6r/wCgrVKvjcVj 8TCvOMZuyb/M/Osdm2Np4qpCNRpKTS+81P8AhIL7+7b/APfDf/FUf8JBff3bf/vhv/iqy6p395Ja i3jhhWWe4l8qJXfYudrOdzAEgYQ9AecfUYxzDFydlNnPHN8wk7Ko/wADoP8AhIL7+7b/APfDf/FU f8JBff3bf/vhv/iq51NSVbq0s7qPyLq5SRlQuCpKEAgHvkNkcZwDkDGKdHq2mzRJLFqFq8byiFXW ZSGkPRAc8t7dap47Gr7T/r/hinmeZL/l4/60/RnQf8JBff3bf/vhv/iqP+Egvv7tv/3w3/xVYWnX 8Gqadb31s2YZ0DryMj1BxnkHgj1BqzUyzDGRbTm7oiWb5hFuMqjujU/4SC+/u2//AHw3/wAVWTqH jm/0/UvINrbSRi0ac4DKSRJGgGcnj5yenpTq5TxF/wAhpv8AsGP/AOj4a68DjsRUrWlNtWf5H0XC WNxGMzmhh8RNyhJ6rub3/Czrj/oGRf8Af0/4Uf8ACzrj/oGRf9/T/hXBUV6X1qr/ADH9Bf2Blv8A z6X3v/M73/hZ1x/0DIv+/p/wo/4Wdcf9AyL/AL+n/CuCqpa3Us0C3E0cUULRiQN5pJAxnnKgDj3q liKzV7/kZyyXK4SUXS1f+Lp+W/U9I/4Wdcf9AyL/AL+n/Cj/AIWdcf8AQMi/7+n/AArzqe8it+Xd NoIDfOMqSVHT0+YEntx61YpPEVkr3HHJMrlJxVNXW+r/AMzvf+FnXH/QMi/7+n/Cj/hZ1x/0DIv+ /p/wrgqKX1qr/MX/AGBlv/Ppfe/8z1rwt4ul13Try7uLRI/KvXt40jc/dWONskkcnLn04x9a2/7W T/n3b/v5/wDWrgPh3/yLt/8A9hWb/wBFQV1deJj8zxdPEShCdlp27I+OeBw/NL3dnJdejZqf2sn/ AD7t/wB/P/rUf2sn/Pu3/fz/AOtWXVHVr6TTrDz4YVmlMsUKI8mwEySKgywBwBuz0PSuWOa46UlF VNX6CeCwyV3H8zov7WT/AJ92/wC/n/1qP7WT/n3b/v5/9auVh1nyXuo9XW1sXto45XkFzui2OzKv zsq4OUYYx3HJzgXhf2ZhaYXcBiWITs4kGBGckOT/AHTg89OD6VUsyzCO83+Alg8K/s/mbn9rJ/z7 t/38/wDrUf2sn/Pu3/fz/wCtWGb+zVrlTdwBrVQ1wDIMwgjIL/3RgZ57U+2ure9t1uLWeKeB87ZI nDK2Dg4I46g1LzXHpXc39y/yH9Sw23L+LNn+1k/592/7+f8A1qP7WT/n3b/v5/8AWrLopf2vjf8A n4/w/wAh/UMP/L+ZLdeIXj1vRtPitlC308iSO75KqsTvxwOcqOfTPHORvVw93/yOXhb/AK+bj/0n kruK+uyitUr4WM6ju9fzPExtONOs4wVkFFFFemcoUUUUAFFFFABRRRQAUUUUAFFFFAHP+Kf+RN1z /rq3/ouGvTU/1a/QV5l4p/5E3XP+urf+i4a9Nj5iT/dFUiWcpP8A8hUf9eB/9CgptMvbiC21NGnm jiVrIqC7BQTmE45+h/KoP7TsP+f22/7+r/jSY0WqKq/2nYf8/tt/39X/ABo/tOw/5/bb/v6v+NIZ aoqr/adh/wA/tt/39X/Gj+07D/n9tv8Av6v+NAFqiqv9p2H/AD+23/f1f8aP7TsP+f22/wC/q/40 AWqKq/2nYf8AP7bf9/V/xo/tOw/5/bb/AL+r/jQBaoqr/adh/wA/tt/39X/Gj+07D/n9tv8Av6v+ NAFqiqv9p2H/AD+23/f1f8aP7TsP+f22/wC/q/40Ac5q/wDyF7n6r/6CtUqq+IPEdnba7cxiG9uB 8p8y3tXkQ/KOjAYP4Vmf8JVaf8+Oq/8AgBJ/hXxeLwWJlXnKMHZt9PM/Nsfl2Lniqso05NOT6Pub tU9St5LqzMSW9rcqWG+C6HySD0zg4IODnB6Y4zkZ3/CVWn/Pjqv/AIASf4Uf8JVaf8+Oq/8AgBJ/ hWMcFiou6pv7mc0MuxsZKSpS+5ixaPeQx2xhuI4po4bmEEDcsAlYOuwEfMEKqoBABHpjaatloV7H rMV7KI40R4yUN7LcsQsc6n5nUEcyrx04Jqz/AMJVaf8APjqv/gBJ/hR/wlVp/wA+Oq/+AEn+Fb+x xtmvZvXyfXU6fYZjaS9k9b9H1d/67dDR0q1ksNJtbOQqzW8SwhlPDBRgH2JABx2zjJ61crC/4Sq0 /wCfHVf/AAAk/wAKP+EqtP8Anx1X/wAAJP8ACsJYLFybk6b18jmnl2NlJydKWvkzdrlPEX/Iab/s GP8A+j4avf8ACVWn/Pjqv/gBJ/hWHq+qLe6g1xDY6ls+xNCAbKQEsZYmx930Vvy+ldeAweIhWvKD Ss+nkfR8H4Wvhs6oVq8HGKeraskZ1FQefN/0DdS/8A5P8KPPm/6Bupf+Acn+Fel9Xq/ys/oz+18B /wA/o/eies20s5bezaD7LZqxh2lgSRIwGBuG0cde9W/Pm/6Bupf+Acn+FHnzf9A3Uv8AwDk/wq40 qyVuVmFXMMuqSUnWjdXW667lL+zJVZdsgcRklWkYl3O6NhuOP9gjPYY61qVB583/AEDdS/8AAOT/ AAo8+b/oG6l/4Byf4USpVpbxf3Co47LKLbhWjr/eXQnoqDz5v+gbqX/gHJ/hR583/QN1L/wDk/wq Pq9X+VnR/a+A/wCf0fvR3vw7/wCRdv8A/sKzf+ioK6uvP/COvwaNolzBd2epCWXUJZ1VbGU4QxxA Enbjqrfl9K3P+E10/wD58tW/8AJP8K8LMMBip4iUo021p08kfF/WqHNL318UuvmzpKz9a07+1dOF oVidGngd0lGVZElR2BGDnIUjFZf/AAmun/8APlq3/gBJ/hR/wmun/wDPlq3/AIASf4VywwGNhJSV OV15MUsTh5JpzX3ly80ZYtOFto8EFqnm+ZLBAxtRMMYxvjG5DnacgZOzaeCaxF8MavFpF/awPZiX ULaWCQyzSSCIGWZ1wxXdISJtpY4II3fN0q//AMJrp/8Az5at/wCAEn+FH/Ca6f8A8+Wrf+AEn+Fb woZhBW9m3rfZ9P6/TbQylUw0nfnX3jb3w9dXbXi/6KkTSLLD5bOrFhKspAI5h3bAGKlsthwFOQ2n omnPp9tN5sapLPL5rqtxJOc7VXmST5mOFHYADAxxk53/AAmun/8APlq3/gBJ/hR/wmun/wDPlq3/ AIASf4VMsNj5Q5HTlb0f9dClVwylzcy+86Siub/4TXT/APny1b/wAk/wo/4TXT/+fLVv/ACT/CsP 7Nxn/PqX3M0+tUP5195fu/8AkcvC3/Xzcf8ApPJXcV5nb67bar4v8PvFBeQx208zyyXNs8SKDBIo +ZhjqQPxFehf2nYf8/tt/wB/V/xr7LJ6U6WEjComnrv6ng46cZ13KLui1RVX+07D/n9tv+/q/wCN H9p2H/P7bf8Af1f8a9Q5C1RVX+07D/n9tv8Av6v+NH9p2H/P7bf9/V/xoAtUVV/tOw/5/bb/AL+r /jR/adh/z+23/f1f8aALVFVf7TsP+f22/wC/q/40f2nYf8/tt/39X/GgC1RVX+07D/n9tv8Av6v+ NH9p2H/P7bf9/V/xoAtUVV/tOw/5/bb/AL+r/jR/adh/z+23/f1f8aAMnxT/AMibrn/XVv8A0XDX pduc28R9UH8q8x8SSxzeCdbkidXQythlOQf3cPevS7M5sbc+sa/yqluSzkmsvG/ms0UeixqQAALq bOAMDJ2c0n2Tx5/e0f8A8C5v/iK7WinYRxX2Tx5/e0f/AMC5v/iKPsnjz+9o/wD4Fzf/ABFdrRRY Divsnjz+9o//AIFzf/EUfZPHn97R/wDwLm/+IrtaKLAcV9k8ef3tH/8AAub/AOIo+yePP72j/wDg XN/8RXa0UWA4r7J48/vaP/4Fzf8AxFH2Tx5/e0f/AMC5v/iK7WiiwHFfZPHn97R//Aub/wCIo+ye PP72j/8AgXN/8RXa0UWA4r7J48/vaP8A+Bc3/wARR9k8ef3tH/8AAub/AOIrtaKLAcV9k8ef3tH/ APAub/4ij7J48/vaP/4Fzf8AxFdrRRYDivsnjz+9o/8A4Fzf/EUfZPHn97R//Aub/wCIrtaKLAcV 9k8ef3tH/wDAub/4ij7J48/vaP8A+Bc3/wARXa0UWA4r7J48/vaP/wCBc3/xFH2Tx5/e0f8A8C5v /iK7WiiwHFfZPHn97R//AALm/wDiKPsnjz+9o/8A4Fzf/EV2tFFgOK+yePP72j/+Bc3/AMRR9k8e f3tH/wDAub/4iu1oosBxX2Tx5/e0f/wLm/8AiKPsnjz+9o//AIFzf/EV2tFFgOK+yePP72j/APgX N/8AEUfZPHn97R//AALm/wDiK7WiiwHFfZPHn97R/wDwLm/+Io+yePP72j/+Bc3/AMRXa0UWA4r7 J48/vaP/AOBc3/xFH2Tx5/e0f/wLm/8AiK7WiiwHFfZPHn97R/8AwLm/+Io+yePPXSP/AALm/wDi K7WiiwHFfZPHnrpH/gXN/wDEUn2Xx766R/4Fzf8AxNdtRRYDifsvj3/qEf8AgXN/8TR9l8e/9Qj/ AMC5v/ia7aiiwHE/ZvHvppP/AIFzf/E0n2bx76aT/wCBc3/xNdvRRYLnEfZvH393Sf8AwLl/+Jo+ z+Pv7ulf+Bcv/wATXb0UWC5w/wBn8ff3NK/8C5f/AImj7P4+/uaV/wCBcv8A8TXcUUWHc4fyPH3/ ADz0r/wMl/8AiaTyPH//ADz0v/wMl/8Aia7milyhc4byPH//ADy0v/wMl/8AiaPJ8f8A/PLS/wDw Mk/wruaKOXzC5wvk+P8A/njpn/gZJ/hR5Pj/AP546Z/4GSf4V3VFHL5hc4XyviB/zw0z/wADJP8A Ck8r4gf88NN/8DJP8K7uijl8wucJ5XxA/wCffTf/AAMk/wAKPL+IH/Ptpv8A4GSf4V3dFHL5hc81 1jRvHGtaZPY3NrpuyVCu77W5K/TI9q9EtEaKygjcYdY1Vh6ECpqKFGzuI//Z --=_mixed 0078B9C705256D62_=-- From dyoo@hkn.eecs.berkeley.edu Sun Jul 13 21:52:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Jul 13 20:52:02 2003 Subject: [Tutor] newbie confused about text parsing In-Reply-To: <003e01c3496f$11ab1c90$0217a8c0@win2k> Message-ID: On Sun, 13 Jul 2003, Chris Johnson wrote: > I'm a unix administrator and I want to learn python to help in my > job. I thought parsing a log file would be a good start but I'm stuck on > how to start. > > I'm working with a firewall log file the contents of which look something > like this. > Nov 30 00:58:05 firewall kernel: Shorewall:man1918:DROP:IN=eth0 OUT= > MAC=ff:ff:ff:ff:ff:ff:00:90:f5:1e:15:aa:08:00 SRC=10.1.2.27 DST=10.1.2.255 > LEN=96 TOS=0x00 PREC=0x00 TTL=128 ID=4853 PROTO=UDP SPT=137 DPT=137 LEN=76 Hi Chris, Ok, sounds like an interesting project! Shorewall is based on the Linux 'iptables' system, http://www.shorewall.net/ so if you can find a log parser that handles iptables's log format, you may be able to successfuly use it for shorewall. Anyway, let's see what we can help with, assuming that there's no third-party module out there yet. > I want to loop through log file looking for a string (Shorewall) This part shouldn't be too hard: as we're looping through the log, we can look for a "substring" by using each line's find() method. Lines that don't have 'Shorewall' should be skipped, and lines that do have it will need further parsing. Here's some sample code that says this more formally: ### def hasShoreline(s): "Returns true if the string 's' has the word "shoreline" in it." return s.find('shoreline') != -1 logfile = open("/var/log/messages") for line in logfile: if hasShoreline(line): doSomeMoreParsing(line) ### > then parse each matching line into a dictionary which I can sort or put > into database fields. > > I've been reading the documentation on both modules re and string but > which do I use. I'd like to run this script all the time so entries are > added in near real time to the database. Regular expressions sounds like a good thing for this project. It's very likely that you'll need to write a regular expression to extract certain patterns from the log file. A.M. Kuchling's written a pretty nice "Python Regular Expression HOWTO" that's a brief tutorial about regular expressions: http://www.amk.ca/python/howto/regex/regex.html Let's take a look again at that log file line: > Nov 30 00:58:05 firewall kernel: Shorewall:man1918:DROP:IN=eth0 OUT= > MAC=ff:ff:ff:ff:ff:ff:00:90:f5:1e:15:aa:08:00 SRC=10.1.2.27 DST=10.1.2.255 > LEN=96 TOS=0x00 PREC=0x00 TTL=128 ID=4853 PROTO=UDP SPT=137 DPT=137 LEN=76 There apperas to be a fairly consistant pattern here to the field-value pairs. There's a uppercased "field name", followed by an equal sign '=', and then the field value. In regular expression terms, we's say that we're looking for: [A-Z]+ ## A bunch of uppercased letters, the "field name" = ## followed by the equal sign \S+ ## and then the field value. I'll guess at the ## that this should be any "nonspace" ## character. In regular expression syntax, the plus sign means "one or more of the preceding kind of character'. Now, I have to admit that the above code is a complete hack: I have no clue if it'll capture all shoreline log messages properly. We can try this out, though, and see how well it works: ### >>> regex = re.compile(r''' [A-Z]+ ... = ... \S+''', re.VERBOSE) >>> s = '''Nov 30 00:58:05 firewall kernel: Shorewall:man1918:DROP: ... IN=eth0 OUT=MAC=ff:ff:ff:ff:ff:ff:00:90:f5:1e:15:aa:08:00 ... SRC=10.1.2.27 DST=10.1.2.255 LEN=96 TOS=0x00 PREC=0x00 ... TTL=128 ID=4853 PROTO=UDP SPT=137 DPT=137 LEN=76''' >>> regex.findall(s) ['IN=eth0', 'MAC=ff:ff:ff:ff:ff:ff:00:90:f5:1e:15:aa:08:00', 'SRC=10.1.2.27', 'DST=10.1.2.255', 'LEN=96', 'TOS=0x00', 'PREC=0x00', 'TTL=128', 'ID=4853', 'PROTO=UDP', 'SPT=137', 'DPT=137', 'LEN=76'] ### Looks sorta decent. This should get you started. *grin* But should we reinvent the wheel? Let's see... there do appear to be a few iptables parsers in Perl: http://caspian.dotconf.net/menu/Software/ScanAlert/ http://www.dshield.org/framework.php I haven't found any iptables parsers in Python yet. You may want to ask on the comp.lang.python newsgroup to see if anyone has one already cooked up. If you'd like, we can look at one of the Perl ones, and see how one might port the code into Python. Good luck to you! From thomi@thomi.imail.net.nz Sun Jul 13 22:11:26 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Sun Jul 13 21:11:26 2003 Subject: [Tutor] how to specify floating point precision from another variable? In-Reply-To: <3F111A22.4050303@aon.at> References: <20030713172439.11d763e6.thomi@thomi.imail.net.nz> <3F111A22.4050303@aon.at> Message-ID: <20030714130817.4ef73305.thomi@thomi.imail.net.nz> > A description of how this has to be done you can find at > > http://www.python.org/doc/current/lib/typesseq-strings.html > > See especially the numbered paragraph 4. ahaaa.. thank you very much ;) just what i needed. -- Thomi Richards, thomi@thomi.imail.net.nz From rmangaliag@slu.edu.ph Mon Jul 14 01:02:02 2003 From: rmangaliag@slu.edu.ph (rmangaliag@slu.edu.ph) Date: Mon Jul 14 00:02:02 2003 Subject: [Tutor] can you comment on this article... Message-ID: <1058157061.3f123205326ef@mbox.slu.edu.ph> http://www.russellbeattie.com/notebook/20030709.html ------------------------------------------------- Email Service Provided by SLU-Net Saint Louis University ( http://www.slu.edu.ph ) ------------------------------------------------- From phthenry@earthlink.net Mon Jul 14 09:41:00 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Jul 14 08:41:00 2003 Subject: [Tutor] A Telephony Question Message-ID: <1993714828.20030714083750@csi.com> I've been using python for a while and love it.. I've seen it and used it with IBM's (now Apache's) BSF and done numerous console programs... The problem is this, I can't seem to find a telepohony example anywhere. I need to dial someone and page them if an Internet connection goes down and maybe I'm being an idiot, but if someone could point me in the right direction that would be great. This would be a windoze system, so maybe a python and TAPI example would be huge (btw, I'm not a windowz programmer, but this has to be done on one). Thanks, Andrew From pythontutor@venix.com Mon Jul 14 11:13:03 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon Jul 14 10:13:03 2003 Subject: [Tutor] A Telephony Question In-Reply-To: <1993714828.20030714083750@csi.com> References: <1993714828.20030714083750@csi.com> Message-ID: <3F12BA35.3040909@venix.com> I can't address using TAPI. If you are using a simple pager service where the pager message is numbers typed using touch tones, then this approach may be OK (I used it years ago with a Perl script). The modem is a comm (serial) device. Open the COM port and send ATDT,,,,,, then send ATH0 Most modems support a command stream along these lines. Paul Tremblay wrote: > I've been using python for a while and love it.. I've seen it and used > it with IBM's (now Apache's) BSF and done numerous console programs... > > The problem is this, I can't seem to find a telepohony example > anywhere. I need to dial someone and page them if an Internet > connection goes down and maybe I'm being an idiot, but if someone > could point me in the right direction that would be great. This would > be a windoze system, so maybe a python and TAPI example would be > huge (btw, I'm not a windowz programmer, but this has to be done on > one). > > Thanks, > > Andrew > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From DORSEY_EDMUND_K@LILLY.COM Mon Jul 14 12:23:01 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Mon Jul 14 11:23:01 2003 Subject: [Tutor] Tkinter layout problem continued Message-ID: This is a multipart message in MIME format. --=_alternative 00544AC405256D63_= Content-Type: text/plain; charset="us-ascii" I'm still stuck with the grid manager but this time I coded it up real simple and as a running program below. # from Tkinter import * import Pmw parent = Tk() parent.geometry("400x200+300+300") button_frame = Pmw.Group(parent, tag_text='Actions') startButt = Button(button_frame.interior(), padx=20,text="Start", bg='Green', command=parent.destroy) exitButt = Button(button_frame.interior(), padx=20,text="Exit", bg='red', command=parent.destroy) pauseButt = Button(button_frame.interior(), padx=20,text="Pause", bg='orange', command=parent.destroy) startButt.grid(row=0,column=0, sticky=W) exitButt.grid(row=0, column=1, sticky=W) pauseButt.grid(row=0, column=2, sticky=W) button_frame.grid(row=2, column=0, sticky=W+E) #Why doesn't the frame fill the window? parent.mainloop() # I can't seem to get the button_frame to fill the window eventhough it should be expanding from left to right. The sticky calls don't seem to have any affect. Does anyone know why this might be? Thank you for any advice. ~Ed --=_alternative 00544AC405256D63_= Content-Type: text/html; charset="us-ascii"
I'm still stuck with the grid manager but this time I coded it up real simple and as a running program below.

#
from Tkinter import *
import Pmw
parent = Tk()
parent.geometry("400x200+300+300")

button_frame = Pmw.Group(parent, tag_text='Actions')        
startButt = Button(button_frame.interior(), padx=20,text="Start", bg='Green',  command=parent.destroy)
exitButt  = Button(button_frame.interior(), padx=20,text="Exit",  bg='red',    command=parent.destroy)
pauseButt = Button(button_frame.interior(), padx=20,text="Pause", bg='orange', command=parent.destroy)

startButt.grid(row=0,column=0, sticky=W)
exitButt.grid(row=0, column=1, sticky=W)
pauseButt.grid(row=0, column=2, sticky=W)      
button_frame.grid(row=2, column=0, sticky=W+E) #Why doesn't the frame fill the window?
       
parent.mainloop()
#

I can't seem to get the button_frame to fill the window eventhough it should be expanding from left to right.  The sticky calls don't seem to have any affect.  Does anyone know why this might be?  Thank you for any advice. ~Ed --=_alternative 00544AC405256D63_=-- From abli@freemail.hu Mon Jul 14 13:43:03 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Jul 14 12:43:03 2003 Subject: [Tutor] Tkinter layout problem continued In-Reply-To: References: Message-ID: <20030714164150.GA376@hooloovoo> > # > from Tkinter import * > import Pmw > parent = Tk() > parent.geometry("400x200+300+300") > > button_frame = Pmw.Group(parent, tag_text='Actions') > startButt = Button(button_frame.interior(), padx=20,text="Start", > bg='Green', command=parent.destroy) > exitButt = Button(button_frame.interior(), padx=20,text="Exit", bg='red', > command=parent.destroy) > pauseButt = Button(button_frame.interior(), padx=20,text="Pause", > bg='orange', command=parent.destroy) > > startButt.grid(row=0,column=0, sticky=W) > exitButt.grid(row=0, column=1, sticky=W) > pauseButt.grid(row=0, column=2, sticky=W) > button_frame.grid(row=2, column=0, sticky=W+E) #Why doesn't the frame fill > the window? parent.grid_columnconfigure(0, weight=1) > > parent.mainloop() > # Adding that line makes it work for me. The button_frame expands as expected, revealing that the buttons inside the button_frame have the same problem. So if you want the buttons to expand, too, you need: button_frame.interior().grid_columnconfigure(0, weight=1) button_frame.interior().grid_columnconfigure(1, weight=1) button_frame.interior().grid_columnconfigure(2, weight=1) Or, instead of all this grid_columnconfigure-ing you can simply use the pack geometry manager: # from Tkinter import * import Pmw parent = Tk() parent.geometry("400x200+300+300") button_frame = Pmw.Group(parent, tag_text='Actions') startButt = Button(button_frame.interior(), padx=20,text="Start", bg='Green', command=parent.destroy) exitButt = Button(button_frame.interior(), padx=20,text="Exit", bg='red', command=parent.destroy) pauseButt = Button(button_frame.interior(), padx=20,text="Pause", bg='orange', command=parent.destroy) startButt.pack(fill=X, side=LEFT, expand=1) exitButt.pack(fill=X, side=LEFT, expand=1) pauseButt.pack(fill=X, side=LEFT, expand=1) button_frame.pack(fill=X, expand=1) parent.mainloop() # And I think the padx=20 options aren't needed. Abel Daniel From jeff@ccvcorp.com Mon Jul 14 15:38:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 14 14:38:02 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] References: <02c401c3483d$bbd92140$6401a8c0@xp> <20030712205529.1efcc858.thomi@thomi.imail.net.nz> Message-ID: <3F12F857.4000004@ccvcorp.com> Thomas Clive Richards wrote: >The small trouble that i have with using octal as an intermediate step >between decimal and binary is that one octal digit represents 3 binary >digits, and this is not easily divisible into an 8 or 16 bit binary >number. > Once upon a time, there were a variety of mainframe/minicomputer systems that were based on 18- or 27-bit words. For these machines, each 9-bit byte would be exactly representable by a 3-digit octal number. Nowadays, virtually every machine on the market uses a word length that's some power of two (8, 16, 32, 64), so it makes more sense to use hex, where each 8-bit byte is exactly representable by 2 hex digits. In my opinion, support for octal is now a historical relic. (Keep in mind, though, that some historical relics have a long and productive lifetime -- COBOL comes to mind. Despite its "obsolescense", COBOL is still one of the most-used computer languages.) Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Mon Jul 14 16:17:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jul 14 15:17:02 2003 Subject: [Tutor] Bits operations [another version of binary() using hex()] In-Reply-To: <3F12F857.4000004@ccvcorp.com> References: <02c401c3483d$bbd92140$6401a8c0@xp> <20030712205529.1efcc858.thomi@thomi.imail.net.nz> Message-ID: <5.2.1.1.0.20030714210652.01f01cf0@www.thinkware.se> At 11:37 2003-07-14 -0700, Jeff Shannon wrote: >In my opinion, support for octal is now a historical relic. There is at least one important exception... PostScript and thus also PDF handles octal representation in strings. Thus (Python) and (\120ython) are equivalent to PostScript and PDF. If you want to write the same string with hex, all characters must be hex, and you have to write: <507974686f6e>. This meant that ReportLab broke and had to be rewritten in a slightly more complicated way when Python changed so that "print repr('Lyck=E5')" started to return 'Lyck\xe5' instead of 'Lyck\345'. It had basically put texts into PDF files with something like "(%r)" % text and that stopped working... You never know where these anachronisms hide... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language=20 From alan.gauld@blueyonder.co.uk Mon Jul 14 17:08:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Jul 14 16:08:02 2003 Subject: [Tutor] A Telephony Question References: <1993714828.20030714083750@csi.com> Message-ID: <039f01c34a43$7e0d7020$6401a8c0@xp> > The problem is this, I can't seem to find a telepohony example > anywhere. I'm not surprised, telephony falls into the category of: "The wonderful thing about standards is that there are so many to choose from!" On the PC there are: M$'s TAPI, Novell's NSTAPI, Sun's JTAPI, plus Dialogic's proprietary one (the de-facto standard for first party CTI cards!). Given the multiplicity it would be difficult to do a standard Pythonic version, it's one area where you are likely to have to write your own DLL or COM interface and wrap that up for Python. > I need to dial someone and page them if an Internet > connection goes down and maybe I'm being an idiot, If you don't need to handle voice then raw AT modem commands are probably the easiest way to go. If you can control the modem model there are some proprietary commands (ie non Hayes standard) for controlling voice messaging too. Alan G. From magnus@thinkware.se Mon Jul 14 19:37:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jul 14 18:37:02 2003 Subject: [Tutor] can you comment on this article... In-Reply-To: <1058157061.3f123205326ef@mbox.slu.edu.ph> Message-ID: <5.2.1.1.0.20030714205204.01ed6a58@www.thinkware.se> At 12:31 2003-07-14 +0800, rmangaliag@slu.edu.ph wrote: >http://www.russellbeattie.com/notebook/20030709.html There are 15 comments already... It's certainly true that there is nothing like J2EE for Python. There isn't one standard networked and component based framework for Python. On the other hand, there are plenty of frameworks already, and most of the big ones have Python support. Python supports CORBA, XML-RPC, SOAP etc. For someone who wants a pure Python based web development framework, the main contenders are Zope (which is mainly geared towards web content management) and Twisted (which can talk in a lot of different network protocols--great if you want both HTTP, NTTP, GUI, IRC and e-mail access to your app for instance). Other frameworks, such as PEAK and Webware and many others are also being actively developed. See for instance: http://www.python.org/cgi-bin/moinmoin/WebProgramming http://colorstudy.com/docs/shootout.html http://www.thinkware.se/cgi-bin/thinki.cgi/PythonForInternet As you see, there is great diversity, and there is a feeling within the Python community, that more collaboration and some more standards are a good thing. This has led to the creation of a new mailing list where this issue is currently discussed. See comp.lang.python and archives at http://www.amk.ca/mailman/listinfo/pyweb -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From mwelsh@abwatley.com Mon Jul 14 21:55:16 2003 From: mwelsh@abwatley.com (Michael Welsh) Date: Mon Jul 14 20:55:16 2003 Subject: [Tutor] asyncore, asynchat, sockets, and threads Message-ID: <200307142050.09026.mwelsh@abwatley.com> In order to learn sockets in Python I am trying to write a simple chat server and client. I need a little nudge, please. My question contains some GUI but only as decoration. The root question is asyncore / asynchat. I have read that twisted makes this all simple, but, I wanted to get my hands dirty here for educational purposes. I've managed (with some help from Lee Harr, thank you) to build a small echo server with asyncore and asynchat that can handle any number of connections and repeat to all clients what was sent in by individual clients. The GUI client, wxPython, creates a socket on open. The user types some text and clicks [SEND]. The send event puts the text out to the socket then reads the response and adds it to list control. Everything works well. I'm now ready for the next step, to disconnect the send data from the recieve data. So a user who does not send text, still gets what others may have written. I need to somehow poll the thread so "add to list control" can be triggered on recieving the data. I've tried several approaches and can't seem to get it right. First I tried setting up a separate threading.Thread that created the socket. This way I could put a poll on the socket. I even created (borrowed) a custom event so when data was found, it could notify the GUI and call the "add to list control" But I must have been doing it wrong because it kept locking up in the loop.. I knew from the server side that asynchat has built in helpers with collect_incoming_data() and found_terminator(). (my terminator is appended when data is sent to the server) I could then use the asyncore.poll() in my threading.Thread to raise the custom event that sends data to the GUI, when something comes over the socket. I think I have the concepts right, but the execution breaks down here. I tried having the threading.Thread create an asyn_chat but I keep getting errors that I assume the asyncore.dispatcher takes care of. So... maybe I should use both core and chat on the client as well as the server. The only examples of dispatcher I can find open up an asyn_chat on "listen". The client needs to initiate the communication when it starts. The server is listening and will respond. I won't know on which port the response will come back. Here's some bits showing what I'm trying to do. You may find some of it familiar, sometimes I borrow. I hope I didn't clip anything that may have been needed If anybody has time to point out where I'm going wrong it would be very helpful. Thank you if you were patient enough to get this far... import threading import time import socket import asyncore import asynchat from wxPython.wx import * # server is listening on ... REMOTE_HOST = '172.0.0.1' REMOTE_PORT = 50001 class MyTest(wxFrame): def __init__(self, parent, ID, title): # Initialize wxFrame wxFrame.__init__(self, ..... # start the thread self.network = NetworkThread(self) self.network.start() EVT_NETWORK(self,self.OnNetwork) # build rest of GUI... works fine # the network thread communicates back to the main # GUI thread via this sythetic event class NetworkEvent(wxPyEvent): def __init__(self,msg=""): wxPyEvent.__init__(self) self.SetEventType(wxEVT_NETWORK) self.msg = msg wxEVT_NETWORK = 2000 def EVT_NETWORK(win, func): win.Connect(-1, -1, wxEVT_NETWORK, func) class NetworkThread(threading.Thread): def __init__(self,win): threading.Thread.__init__(self) self.win = win self.keep_going = true self.running = false self.MySock = NetworkServer(REMOTE_HOST, REMOTE_PORT, self.received_a_line) self.event_loop = EventLoop() def push(self,msg): self.MySock.push(msg) def is_running(self): return self.running def stop(self): self.keep_going = 0 def check_status(self,el,time): if not self.keep_going: asyncore.close_all() else: self.event_loop.schedule(1,self.check_status) def received_a_line(self,m): self.send_event(m) def run(self): self.running = true self.event_loop.schedule(1,self.check_status) # loop here checking every 0.5 seconds for shutdowns etc.. self.event_loop.go(0.5) # server has shutdown self.send_event("Closed down network") time.sleep(1) self.running = false # send a synthetic event back to our GUI thread def send_event(self,m): evt = NetworkEvent(m) wxPostEvent(self.win,evt) del evt class NetworkServer (asyncore.dispatcher): def __init__ (self, host, port, handler=None): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.connect((host, port)) def handle_connect (self): # I thought, maybe, the server would trigger this... nope ChatSocket (host, port, self.handler) def handle_read (self): data = self.recv (8192) self.send_event(self.data) print data def writable (self): return (len(self.buffer) > 0) def handle_write (self): sent = self.send (self.buffer) self.buffer = self.buffer[sent:] # send a synthetic event back to our GUI thread def send_event(self,m): evt = NetworkEvent(m) wxPostEvent(self.win,evt) del evt class ChatSocket(asynchat.async_chat): def __init__(self, host, port, handler=None): asynchat.async_chat.__init__ (self, port) def collect_incoming_data(self, data): self.data.append(data) def found_terminator(self): if self.handler: self.send_event(self.data) else: print 'warning: unhandled message: ', self.data self.data = '' class EventLoop: socket_map = asyncore.socket_map def __init__ (self): self.events = {} def go (self, timeout=5.0): events = self.events while self.socket_map: print 'inner-loop' now = int(time.time()) for k,v in events.items(): if now >= k: v (self, now) del events[k] asyncore.poll (timeout) def schedule (self, delta, callback): now = int (time.time()) self.events[now + delta] = callback def unschedule (self, callback, all=1): "unschedule a callback" for k,v in self.events: if v is callback: del self.events[k] if not all: break # ----------------------------------------- # Run App # ------------------------------------------- class TestApp(wxApp): def OnInit(self): frame = MyTest(None, -1, "Test APP") frame.Show(true) self.SetTopWindow(frame) return true app = TestApp(0) app.MainLoop() From magnus@thinkware.se Mon Jul 14 22:12:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Mon Jul 14 21:12:02 2003 Subject: [Tutor] asyncore, asynchat, sockets, and threads In-Reply-To: <200307142050.09026.mwelsh@abwatley.com> Message-ID: <5.2.1.1.0.20030715031254.01f1b930@www.thinkware.se> At 20:50 2003-07-14 -0400, Michael Welsh wrote: >I've tried several approaches and can't seem to get it right. First I tried >setting up a separate threading.Thread that created the socket. This way I >could put a poll on the socket. I even created (borrowed) a custom event so >when data was found, it could notify the GUI and call the "add to list >control" But I must have been doing it wrong because it kept locking up in >the loop.. You can only access the GUI in one thread. See http://wiki.wxpython.org/index.cgi/LongRunningTasks or http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From mwagman@charter.net Mon Jul 14 23:38:03 2003 From: mwagman@charter.net (Mike Wagman) Date: Mon Jul 14 22:38:03 2003 Subject: [Tutor] Encrypting Passwords Message-ID: <1058236683.2485.6.camel@24-159-241-21.jvl.wi.charter.com> Can anyone point me to a good module that handles encrypting password, ideally one that doesn't have any issues with py2exe, as my final product will me a stand alone exe. Thanks Mike From carroll@tjc.com Tue Jul 15 02:58:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Jul 15 01:58:01 2003 Subject: [Tutor] "from future import division"? Message-ID: I'm running Python 2.2.2 (under Windows). I want / to perform true division, not integer division. That is, I want 1/2 to return 0.5, not 0.0. "Python in a Nutshell" says this will be the default in 2.3, and until then, I can either include the line: from future import division or invoke python as python -Qnew foo.py the -Qnew option works, but the import does not: ImportError: No module named future Any ideas? Is my syntax wrong, or is there a "future" module that's supposed to come with Python that's missing for me, but that I can install? Or is there some other change to the source code I can make to cause Python to do true division? I'd like to just use true division, rather than adding decimal points in every operation to force true division, which looks messy (I'm doing a lot of reciprocals), and without overriding the command line. -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From andrewm@object-craft.com.au Tue Jul 15 03:12:02 2003 From: andrewm@object-craft.com.au (Andrew McNamara) Date: Tue Jul 15 02:12:02 2003 Subject: [Tutor] "from future import division"? In-Reply-To: Message from Terry Carroll of "Mon, 14 Jul 2003 22:57:43 MST." References: Message-ID: <20030715061110.5E9AF3C421@coffee.object-craft.com.au> >"Python in a Nutshell" says this will be the default in 2.3, and until >then, I can either include the line: > > from future import division Try: from __future__ import division -- Andrew McNamara, Senior Developer, Object Craft http://www.object-craft.com.au/ From abli@freemail.hu Tue Jul 15 03:15:01 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Jul 15 02:15:01 2003 Subject: [Tutor] "from future import division"? In-Reply-To: References: Message-ID: <20030715061246.GA5087@hooloovoo> > from future import division > > or invoke python as > > python -Qnew foo.py > > the -Qnew option works, but the import does not: > > ImportError: No module named future it's from __future__ import division note the two underlines on both sides of 'future'. (If the underlines are missing in the book, it's most likely a typo.) Abel Daniel From carroll@tjc.com Tue Jul 15 03:36:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Jul 15 02:36:01 2003 Subject: [Tutor] "from future import division"? In-Reply-To: <20030715061246.GA5087@hooloovoo> Message-ID: On Tue, 15 Jul 2003, Andrew McNamara wrote: > Try: > from __future__ import division On Tue, 15 Jul 2003, Abel Daniel wrote: > it's > from __future__ import division > > note the two underlines on both sides of 'future'. > > (If the underlines are missing in the book, it's most likely a typo.) Thank you to you both. "from __future__" works correctly. It is indeed a typo in the book. I should have checked the errata page first; that's the very first error listed: http://www.oreilly.com/catalog/pythonian/errata/pythonian.confirmed -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From pauljhickey@eircom.net Tue Jul 15 04:41:59 2003 From: pauljhickey@eircom.net (Paul Hickey) Date: Tue Jul 15 03:41:59 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python Message-ID: <002c01c34aa4$4eb43230$c1b7fea9@pjhickey> This is a multi-part message in MIME format. ------=_NextPart_000_0029_01C34AAC.B0468DB0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi , im trying to "grab" a word or two in a program im trying to write = in Python, eh im a newbie! to Python and programming. Something like " input.... What is your favourite hobby? Answer.... I like to play golf. With a reply print "never played golf, sounds = boring!!!!" I tried to put the "key" word in a list but could not get it to work, = ive tried some other ideas to no avail. Any pointers would be great. Thanks Paul. ------=_NextPart_000_0029_01C34AAC.B0468DB0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi , im trying to "grab" a word or two = in a program=20 im trying to write in Python, eh im a newbie! to Python and=20 programming.
 
Something like " input.... What is your = favourite=20 hobby?
       =20             =    =20 Answer.... I like to play golf.
       =20             =     With=20 a reply    print "never played golf, sounds=20 boring!!!!"
 
I tried to put the "key" word in a list = but could=20 not get it to work, ive tried some other ideas to no avail.
Any pointers would be = great.
Thanks
Paul.
 
------=_NextPart_000_0029_01C34AAC.B0468DB0-- From magnus@thinkware.se Tue Jul 15 08:37:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Tue Jul 15 07:37:02 2003 Subject: [Tutor] Encrypting Passwords In-Reply-To: <1058236683.2485.6.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: <5.2.1.1.0.20030715132719.01f28508@www.thinkware.se> At 21:38 2003-07-14 -0500, Mike Wagman wrote: >Can anyone point me to a good module that handles encrypting password, >ideally one that doesn't have any issues with py2exe, as my final >product will me a stand alone exe. >>> import md5 >>> seed = "42" >>> digest = md5.new(seed) >>> digest.update('My Password') >>> digest.hexdigest() '22634f73ad7d03dbf826edc1e8fc68c6' If md5 isn't secure enough for you: >>> import sha >>> digest = sha.new(seed) >>> digest.update('My Password') >>> digest.hexdigest() '933257a3349a248d1e0fb19d7c953a00ff004a1d' md5 and sha are built-in modules, I assume they will always work. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From pythontutor@venix.com Tue Jul 15 11:09:30 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Tue Jul 15 10:09:30 2003 Subject: [Tutor] ldap access from Python Help In-Reply-To: <3F047655.1050204@mayo.edu> References: <3F047655.1050204@mayo.edu> Message-ID: <3F140AC0.7070708@venix.com> Just saw a link to this article: http://www.linuxjournal.com//article.php?sid=6988 LDAP Programming in Python Should fit the bill. (I remembered you request because I may soon face a similar need.) Dinakar wrote: > Hello: > > I would like to use Python to access LDAP server to get email address > and other info from our local ldap server. Can someone suggest what all > the things I need to do to access. Do I need to install any modules or > some other software. > > I am running Debian (testing) GNU/Linux and Python 2.2.3 > > Thank you very much. > > /dinakar > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From baris.metin@frontsite.com.tr Tue Jul 15 13:10:17 2003 From: baris.metin@frontsite.com.tr (Baris Metin) Date: Tue Jul 15 12:10:17 2003 Subject: [Tutor] ldap access from Python Help In-Reply-To: <3F140AC0.7070708@venix.com> References: <3F047655.1050204@mayo.edu> <3F140AC0.7070708@venix.com> Message-ID: <20030715160900.GK13193@frontsite.com.tr> --PZYVFYZbFYjzBslI Content-Type: text/plain; charset=iso-8859-9 Content-Disposition: inline Tue, Jul 15, 2003 at 10:08:00AM -0400 , Lloyd Kvam : > Just saw a link to this article: > http://www.linuxjournal.com//article.php?sid=6988 > LDAP Programming in Python > > Should fit the bill. > (I remembered you request because I may soon face a similar need.) > >I would like to use Python to access LDAP server to get email address > >and other info from our local ldap server. Can someone suggest what > >all > >the things I need to do to access. Do I need to install any modules > >or > >some other software. > > > >I am running Debian (testing) GNU/Linux and Python 2.2.3 Just install the python-ldap package. (apt-get install python-ldap). For an example you can take a look at my test script: ftp://ev.metin.org/ldapekle.py (be carefull with the bad code :). regards, -- __________ | | | | Baris Metin | | Software developer, IT consultant | FRONT | |==========| FrontSITE Bilgi Teknolojisi A.S. |_____SITE_| http://www.frontsite.com.tr --PZYVFYZbFYjzBslI Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) Comment: http://metin.org iD8DBQE/FCccxyezEhU1oVARAmKUAJ94bEMgaE8JrzUAIArsKVCLdxHuAACcDRZ1 EqQ74y9o5wQvIoA5xfJEgsw= =kDAK -----END PGP SIGNATURE----- --PZYVFYZbFYjzBslI-- From qsc@icon.co.za Tue Jul 15 13:42:02 2003 From: qsc@icon.co.za (Quentin) Date: Tue Jul 15 12:42:02 2003 Subject: [Tutor] looking for data in large text file Message-ID: <3F142EB5.500@icon.co.za> Hi All Newbie here. I want to lookup a list in a large text file (hunderd or so lines). The list I then use in a combobox. Got the wxComboBox figured out, and how to load it with a list. I want to keep the lists for various comboboxes in one text file. This makes it easier to edit via other means besides Python. (Something like a Windows .INI file with all your settings in it). But how do I look for a list in a text file without have to readline the whole file? I keep on refering to lists, with that I mean the list that loads into the combobox, not necessary the way it is stored in a text file. Please, no code, just some suggestions. I need to figure out the code for myself. Thanks Quentin From SWidney@ci.las-vegas.nv.us Tue Jul 15 14:02:01 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue Jul 15 13:02:01 2003 Subject: [Tutor] looking for data in large text file Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC869A@sovereign.ci.las-vegas.nv.us> > I want to keep the lists for various comboboxes in one text > file. This makes it easier to edit via other means besides > Python. (Something like a Windows .INI file with all your > settings in it). But how do I look for a list in a text file > without have to readline the whole file? Welcome! Have you looked at the ConfigParser module? It seems like it might be what you're looking for. It's covered in the Library Reference in section 5.10; the URL for the on-line version is: http://www.python.org/doc/current/lib/module-ConfigParser.html Best of luck! Scott From dbroadwell@mindspring.com Tue Jul 15 14:28:02 2003 From: dbroadwell@mindspring.com (David Broadwell) Date: Tue Jul 15 13:28:02 2003 Subject: [Tutor] Encrypting Passwords In-Reply-To: <1058236683.2485.6.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: > Can anyone point me to a good module that handles encrypting password, > ideally one that doesn't have any issues with py2exe, as my final > product will me a stand alone exe. For a lightweight implementation of DES in pure python try; http://home.pacific.net.au/~twhitema/des.html I implemented a password database system for myself in that, despite it's warning about being slow on a pII450 it was always fast enough. -- David Broadwell From sigurd@12move.de Tue Jul 15 14:33:08 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Jul 15 13:33:08 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python In-Reply-To: <002c01c34aa4$4eb43230$c1b7fea9@pjhickey> (Paul Hickey's message of "Tue, 15 Jul 2003 08:40:04 +0100") References: <002c01c34aa4$4eb43230$c1b7fea9@pjhickey> Message-ID: On 15 Jul 2003, Paul Hickey <- pauljhickey@eircom.net wrote: > Hi , im trying to "grab" a word or two in a program im trying to write in > Python, eh im a newbie! to Python and programming. > Something like " input.... What is your favourite hobby? > Answer.... I like to play golf. With a reply print > "never played golf, sounds boring!!!!" > I tried to put the "key" word in a list but could not get it to work, > ive tried some other ideas to no avail.=20 > Any pointers would be great. Could you elaborate a bit what you like to do? What do these words you like to filter have in common (in regard to the answer given)? Eg. are they always at the same place (the last word in the sentence). etc Karl --=20 M=E4nner der Wissenschaft! Man sagt ihr viele nach,=20 aber die meisten mit Unrecht.=20=20 Karl Kraus 'Aphorismen' From dyoo@hkn.eecs.berkeley.edu Tue Jul 15 14:35:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 15 13:35:02 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python In-Reply-To: <002c01c34aa4$4eb43230$c1b7fea9@pjhickey> Message-ID: On Tue, 15 Jul 2003, Paul Hickey wrote: > Hi , im trying to "grab" a word or two in a program im trying to write > in Python, eh im a newbie! to Python and programming. > > Something like " input.... What is your favourite hobby? > Answer.... I like to play golf. > With a reply print "never played golf, sounds boring!!!!" > > I tried to put the "key" word in a list but could not get it to work, > ive tried some other ideas to no avail. Any pointers would be great. Hi Paul, To check to see if a keyword lives in a sentence or not, we can use a string's find() method. Here's a brief description of its documentation: ### >>> help(''.find) Help on built-in function find: find(...) S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. ### The last part of the description is really useful: it says that as long as find() doesn't return -1, we can find the substring within the larger string fine. For example, here's a sample interpreter session that shows a little what find() does: ### >>> s = 'this is a test' >>> s.find('zork!') -1 >>> s.find('is') 2 >>> s.find('his') 1 ### Try a few examples one your own with find(), just to get a sense of what it's doing. By the way, the last find() example shows a problem we can run into: we might find our keyword embedded within a larger word. ('his' is a substring of 'this'). That's something we'll need to fix, but we can come back to it later. This should be enough for you to write a simple program to detect a keyword in a sentence; show us what you've tried so far, and we can make comments for improvement. And please feel free to ask questions; we'll be happy to chat about this. Good luck to you! From dyoo@hkn.eecs.berkeley.edu Tue Jul 15 15:56:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 15 14:56:01 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python (fwd) Message-ID: Hi everyone, I'm forwarding Paul's message to the list --- I'm actually slightly busy at the moment, but I'll try getting to it later today. Quick response: I recommend trying your program with just one keyword: have it respond to just 'golf' for the moment. We can always improve it later to make it respond to both 'golf' and 'tennis'. Paul, don't worry about my time; we're all volunteers here. *grin* But make sure you're sending your replies to the list at 'tutor@python.org', so that even if I'm out of commission, the other tutors can help you. Good luck! ---------- Forwarded message ---------- Date: Tue, 15 Jul 2003 19:11:45 +0100 From: Paul Hickey To: Danny Yoo Subject: Re: [Tutor] How to "grab" a word in a sentance,in Python Thanks Danny, sorry about this I think I jumped in too quick!! But I find that in the end its the best way!!You learn more quicker and have fun! Sorry to take your time . Im a bit wide of the mark it seems, what I wrote ( in my naivety!) is : #def list (): list = ['golf' 'tennis' ] item = raw_input("What is your favourite pastime") if item == list: print '',item.',is boring!!! Get a life!!'' elif item != list: print 'never did,',item,'sounds pretty cool!' The "key" word could be anywhere in the sentence, ie" I like swimming" or " I do like to go swimming" Embarrassingly that's it!! Hey im a Newbie.. I would happily let this go only im havin fun doin this! The rest of the program is pretty simple but works, if i can crack this ill be a happy dude for awhile! And impress the hell out of my friends.! Tell me to get off your case , and go back to simple stuff, I can take a hint Thanks for your time Paul Hickey ----- Original Message ----- From: "Danny Yoo" To: "Paul Hickey" Cc: Sent: Tuesday, July 15, 2003 6:34 PM Subject: Re: [Tutor] How to "grab" a word in a sentance,in Python > > > On Tue, 15 Jul 2003, Paul Hickey wrote: > > > Hi , im trying to "grab" a word or two in a program im trying to write > > in Python, eh im a newbie! to Python and programming. > > > > Something like " input.... What is your favourite hobby? > > Answer.... I like to play golf. > > With a reply print "never played golf, sounds boring!!!!" > > > > I tried to put the "key" word in a list but could not get it to work, > > ive tried some other ideas to no avail. Any pointers would be great. > > > Hi Paul, > > > To check to see if a keyword lives in a sentence or not, we can use a > string's find() method. Here's a brief description of its documentation: > > > ### > >>> help(''.find) > > Help on built-in function find: > > find(...) > S.find(sub [,start [,end]]) -> int > > Return the lowest index in S where substring sub is found, > such that sub is contained within s[start,end]. Optional > arguments start and end are interpreted as in slice notation. > > Return -1 on failure. > ### > > > The last part of the description is really useful: it says that as long as > find() doesn't return -1, we can find the substring within the larger > string fine. > > > For example, here's a sample interpreter session that shows a little what > find() does: > > ### > >>> s = 'this is a test' > >>> s.find('zork!') > -1 > >>> s.find('is') > 2 > >>> s.find('his') > 1 > ### > > > Try a few examples one your own with find(), just to get a sense of what > it's doing. > > > By the way, the last find() example shows a problem we can run into: we > might find our keyword embedded within a larger word. ('his' is a > substring of 'this'). That's something we'll need to fix, but we can come > back to it later. > > > This should be enough for you to write a simple program to detect a > keyword in a sentence; show us what you've tried so far, and we can make > comments for improvement. And please feel free to ask questions; we'll be > happy to chat about this. > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From pauljhickey@eircom.net Tue Jul 15 17:58:02 2003 From: pauljhickey@eircom.net (Paul Hickey) Date: Tue Jul 15 16:58:02 2003 Subject: [Tutor] How to "grab" a Word Update!Im gettin there!! Message-ID: <005401c34b13$a06dfb50$c1b7fea9@pjhickey> This is a multi-part message in MIME format. ------=_NextPart_000_0051_01C34B1C.02182490 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, with help from you , I've got this far, s =3D raw_input("What do you like to do") if s.find('music') print "So you like music then!" elif s.find('golf') print "You like golf, boring!!" elif s.find('walking') print " Us computers can't walk!" This works fine when only one argument is present, naturally im trying = to push it!!!!! Problem is it returns the first print statement whatever you enter,I've = played with this with no joy as yet Thanks for your help so far. Sorry to be a pest.... Paul ------=_NextPart_000_0051_01C34B1C.02182490 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi, with help from you , I've got this=20 far,
 
        s = =3D=20 raw_input("What do you like to do")
        = if=20 s.find('music')
       =20     print "So you like music then!"
        = elif=20 s.find('golf')
       =20     print "You like golf, boring!!"
        = elif=20 s.find('walking')
       =20     print " Us computers can't walk!"
 
This works fine when only one argument = is present,=20 naturally im trying to push it!!!!!
Problem is it returns the first print = statement=20 whatever you enter,I've played with this with no joy as yet
Thanks for your help so = far.
Sorry to be a pest....
Paul
------=_NextPart_000_0051_01C34B1C.02182490-- From dyoo@hkn.eecs.berkeley.edu Tue Jul 15 18:32:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 15 17:32:01 2003 Subject: [Tutor] How to "grab" a Word Update!Im gettin there!! In-Reply-To: <005401c34b13$a06dfb50$c1b7fea9@pjhickey> Message-ID: On Tue, 15 Jul 2003, Paul Hickey wrote: > Hi, with help from you , I've got this far, > > s = raw_input("What do you like to do") > if s.find('music') > print "So you like music then!" > elif s.find('golf') > print "You like golf, boring!!" > elif s.find('walking') > print " Us computers can't walk!" > > This works fine when only one argument is present, naturally im trying > to push it!!!!! Problem is it returns the first print statement whatever > you enter,I've played with this with no joy as yet Thanks for your help > so far. Sorry to be a pest.... Paul Hi Paul, No problem. *grin* Glad to see that you're getting closer. The condition that you're checking: elif s.find('walking') ^^^^^^^^^^^^^^^^^ is almost right. To fix that problem, take a look again at that message I sent about find(): http://mail.python.org/pipermail/tutor/2003-July/024021.html Remember that find() isn't giving a "yes/no" sort of answer: it's giving the position where it can find 'walking'. We need to do something extra with that result to turn it into a yes/no "boolean" thing. Good luck! From sigurd@12move.de Tue Jul 15 19:16:31 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Jul 15 18:16:31 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python (fwd) In-Reply-To: (Danny Yoo's message of "Tue, 15 Jul 2003 11:54:59 -0700 (PDT)") References: Message-ID: On 15 Jul 2003, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote: > ---------- Forwarded message ---------- > Date: Tue, 15 Jul 2003 19:11:45 +0100 > From: Paul Hickey > To: Danny Yoo > Subject: Re: [Tutor] How to "grab" a word in a sentance,in Python > > Thanks Danny, sorry about this I think I jumped in too quick!! But I find > that in the end its the best way!!You learn more quicker and have fun! > Sorry to take your time . > > Im a bit wide of the mark it seems, what I wrote ( in my naivety!) is : > #def list (): > list = ['golf' 'tennis' ] > item = raw_input("What is your favourite pastime") > if item == list: > print '',item.',is boring!!! Get a life!!'' > elif item != list: > print 'never did,',item,'sounds pretty cool!' > The "key" word could be anywhere in the sentence, ie" I like swimming" or " > I do like to go swimming" > Embarrassingly that's it!! So we know now what you want: you get input and like to find a certain word in it. The wors you like to find are in a list. First of all: it's not good to use a python builtin (like `list') as name for a function or a variable (if you don't know what the names of the builtins are type `dir(__builtins__)' at your python prompt). So let's see how the functiobn could look like (Danny wrote about `find' I'll show another version) Python has a nice function with which you can search for the occurence of an object in a sequence: `in' >>> 'a' in ['a', 'b', 'c'] 1 >>> So the only problem is how to coerce the return value from raw_input' to a list? For that we have a function: split >>> s = 'this is a test' >>> s.split() ['this', 'is', 'a', 'test'] >>> Now we build the function: def answer(): item = 'golf' ans = raw_input("What is your favourite pastime") ansl = ans.split() if item in ansl: print ans, 'is boring!!! Get a life!' else: print 'never did', ans, 'sounds pretty cool!' That's just one item but you like a list of items. So our check must be done for all items in the list and we would like to see if it suceeds for at least one item. The simplest way (IMO) is here to use list comprehensions (for a good explaination look in the python tutorial). Short: they are a concise way to build lists. They are written like that >>> [x for x in range(10) if x > 5] [6, 7, 8, 9] That means I told Python to build a list of `x' whereat x was assigned 0, 1, 2 ... 9 but the actual value of x was only used to build the list if x was greater than 5 (a silly example but you see what can be done) def answer(): iteml = ['golf', 'tennis'] ans = raw_input("What is your favourite pastime") ansl = ans.split() item = [x for x in iteml if x in ansl] if item: print ans, 'is boring!!! Get a life!' else: print 'never did', ans ,'sounds pretty cool!' Try to understand what's happening. The next thing to do could be to first downcase or upcase all characters before they are compared (at the moment the comparsion is case significant. The next step could be to take out `iteml' and the prompt out of the function and write the function with two parameters (the itemlist and the prompt). HTH Karl -- Mary had a little lambda, Its syntax white as snow, And every program Mary wrote, She wrote in Lisp, you know. From missive@hotmail.com Tue Jul 15 22:59:01 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Jul 15 21:59:01 2003 Subject: [Tutor] Re: asyncore, asynchat, sockets, and threads Message-ID: # server is listening on ... REMOTE_HOST = '172.0.0.1' # This looks funny... Do you mean # 127.0.0.1 ? REMOTE_PORT = 50001 I think your intuition about using a Queue may be the right thing in the gui client to you chat server. Basically, you would have 2 threads: Network client thread feeds messages in to queue. Gui thread reads messages from queue and displays them. _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From Zabelkind@web.de Wed Jul 16 04:34:20 2003 From: Zabelkind@web.de (Mathias Mamsch) Date: Wed Jul 16 03:34:20 2003 Subject: [Tutor] looking for data in large text file References: <3F142EB5.500@icon.co.za> Message-ID: <007e01c34c36$133289d0$0500a8c0@nias> You could just store some Inventory of the file somewhere and then read only the bit of the file, you need to read. See the documentation of file.seek() and file.tell() ... Greetings, Mathias ----- Original Message ----- From: "Quentin" To: Sent: Tuesday, July 15, 2003 6:41 PM Subject: [Tutor] looking for data in large text file > Hi All > Newbie here. > I want to lookup a list in a large text file (hunderd or so lines). The > list I then use in a combobox. > Got the wxComboBox figured out, and how to load it with a list. > > I want to keep the lists for various comboboxes in one text file. This > makes it easier to edit via other means besides Python. (Something like > a Windows .INI file with all your settings in it). > But how do I look for a list in a text file without have to readline the > whole file? > > I keep on refering to lists, with that I mean the list that loads into > the combobox, not necessary the way it is stored in a text file. > > Please, no code, just some suggestions. I need to figure out the code > for myself. > > Thanks > Quentin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld@blueyonder.co.uk Wed Jul 16 05:07:03 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 16 04:07:03 2003 Subject: [Tutor] looking for data in large text file References: <3F142EB5.500@icon.co.za> Message-ID: <001401c34b71$307afce0$6401a8c0@xp> > But how do I look for a list in a text file without have to readline the > whole file? First reading even a thousand lines won't take all that long. However you only need to read as many lines as it takes to get your list out. Second, you could store the lists in separate files. Third you could put a table of contents at the top of the file giving the byte offset to the start of each list then use seek() to go there directly - but the maintenance of that will be a lot of work and not noramally worth it for such relatively short files. Finally, and the method I would probably use - read the file once at startup and store the lists in memory somewhere. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld@blueyonder.co.uk Wed Jul 16 05:13:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 16 04:13:02 2003 Subject: [Tutor] How to "grab" a word in a sentance,in Python (fwd) References: Message-ID: <002101c34b71$f6e44ad0$6401a8c0@xp> > Im a bit wide of the mark it seems, what I wrote ( in my naivety!) is : > #def list (): > list = ['golf' 'tennis' ] > item = raw_input("What is your favourite pastime") > if item == list: THis says "if item equals the list" but item is single the list is plural. Instead try if item in list > elif item != list: and similarly if item not in list However using list as a variable name is bad since its also a python function used to convert things to lists! Mabe 'pastimes' would be a better name? Generally its a good idea to name variables after the problem objects rather than to reflect their structure (which might change!) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mwelsh@abwatley.com Wed Jul 16 10:02:01 2003 From: mwelsh@abwatley.com (Michael Welsh) Date: Wed Jul 16 09:02:01 2003 Subject: [Tutor] Re: asyncore, asynchat, sockets, and threads In-Reply-To: References: Message-ID: <200307160856.02929.mwelsh@abwatley.com> On Tuesday 15 July 2003 09:58 pm, Lee Harr wrote: > > I think your intuition about using a Queue may be the > right thing in the gui client to you chat server. > > Basically, you would have 2 threads: > > Network client thread feeds messages in to queue. > Gui thread reads messages from queue and displays them. > I may still turn to Queues but I got the basic plumbing working without them late last night. Reading the aysncore.py / asynchat.py source and the following documentation helped: Medusa http://www.nightmare.com/medusa/programming.html PythonDev http://www.python.org/dev/doc/devel/lib/module-asynchat.html I also have a few Python books that do their best to explain these concepts. I'll admit, programming asyn socket communication is not trivial the first time you do it. But that is true of most things. Here's what I've learned so far on the client side...maybe it will help somebody who is just discovering asyn. The main app inits a frame which inits a Thread and a ListCtrl among others. I then build the rest of the GUI including a function to recieve a 'custom network event'. This simple function calls my 'list.add' function of the ListCtrl. The custom network event is a separate class. The Thread creates a socket.socket, connects it (to the pre-defined constants - my server app on a different machine), and hands the socket off to an instance of asyn_chat. Discovering that you hand a live socket to aysn_chat was my first "AH-HA" moment. It kinda 'clicked' that the asyncore/asynchat collection is just a bunch of functions that help you work the live wire. Also included with the hand-off is a handler function that gets fired when the async_chat.collect_incoming_data gets fired. The handler function belongs to the Thread and only does one thing: call the custom network event... all the while passing the data from the socket as it goes. After socket creation, connection, and hand-off, the Thread then calls an instance of a custom event loop class containing an asyncore.loop. It took me a little while to figure out that it is OK to call the aysncore.loop on an asyn_chat object without a dispatcher. In all the samples, newsgroup threads, etc that I read; they all created an aysn_chat FROM the asyncore.dispatcher on listen(). AH-HA number two... you don't need a disptcher because asyn_chat IS a dispatcher (read the source). One of the great things about Python (and wxPython in my case) is that all this is tested and works on NT and Linux. I haven't tried to package it for distribution. So, to summarize: On App Launch frame > thread, list thread > socket > asyn_chat > loop On User Input send data to thread.socket (asyn_chat).push ..goes to server, server echos to all On All Clients asyn_chat colletcts > calls handler function (thread) thread fires network event GUI recieves event > calls list.add My next steps are to have the server log all messages to a database. I also want to add authentication. Maybe even the abiltiy to choose from several 'channels' before socket creation. If I can make it modular enough, I may be able to 'plug in' comm abilities to other apps. Hmmm, streaming data over the wire... Hey, asyn socket communication can really be fun! Michael From godoy@metalab.unc.edu Wed Jul 16 10:53:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Wed Jul 16 09:53:01 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not Message-ID: Hi! How can I find out if my program is running unde X or Windows instead of a console / DOS prompt? I'm willing to have two interfaces that are chosen based on where the user can see graphics or not (I'm disregarding the use of framebuffer). TIA, -- Godoy. From qsc@icon.co.za Wed Jul 16 11:09:01 2003 From: qsc@icon.co.za (Quentin) Date: Wed Jul 16 10:09:01 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer Message-ID: <3F155C41.7000800@icon.co.za> All the lists I belong to have an auto reply address that will return all replies back to the list, instead of to the original poster. Most mailing list servers have this option. Is it possible for the Tutor list to have it as well? If this was a pre decided decision not to have a reply address, I'll stand by it, else (elif? :) ), how do the other members feel about it? Quentin From godoy@metalab.unc.edu Wed Jul 16 11:36:34 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Wed Jul 16 10:36:34 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: <1058365330.2423.0.camel@24-159-241-21.jvl.wi.charter.com> (Mike Wagman's message of "16 Jul 2003 09:22:10 -0500") References: <1058365330.2423.0.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: Mike Wagman writes: > use try: to create your GUI if it fails then it's probably not there. Hmmm... This mean I'd have to expend resources importing the wxPython modules and trying to setup the whole environment before I import the curses modules and setup the correct environment? It will work --- and I confess I haven't tried it --- but is there any faster way to detect it? Thank you very much for your help. -- Godoy. From lonetwin@yahoo.com Wed Jul 16 11:44:02 2003 From: lonetwin@yahoo.com (lonetwin) Date: Wed Jul 16 10:44:02 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: References: Message-ID: <200307162027.27742.lonetwin@yahoo.com> Hi Jorge, On Wednesday 16 Jul 2003 7:22 pm, Jorge Godoy wrote: > How can I find out if my program is running unde X or Windows instead > of a console / DOS prompt? I'm willing to have two interfaces that are > chosen based on where the user can see graphics or not (I'm > disregarding the use of framebuffer). To distinguish between X or console mode you can rely on the 'DISPLAY' environment variable. ie: >>> if os.environ.get('DISPLAY', 1) == 1: ... # we are in console ... else: ... # we are in X I'm sorry I dunno about windows/dos. HTH Peace Steve -- Machines take me by surprise with great frequency. - Alan Turing From magnus@thinkware.se Wed Jul 16 12:07:22 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 16 11:07:22 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer In-Reply-To: <3F155C41.7000800@icon.co.za> Message-ID: <5.2.1.1.0.20030716170201.01f34940@www.thinkware.se> At 16:08 2003-07-16 +0200, Quentin wrote: >All the lists I belong to have an auto reply address that will return all >replies back to the list, instead of to the original poster. Most mailing >list servers have this option. Is it possible for the Tutor list to have >it as well? We've been through this, it's somewhere in the archives. The simple answer is that with most email clients, it's easy to answer either to the list of to the sender if it's set up as it is now. Just 'reply' will reply to the sender, and 'reply to all' will also reply to the list. With 'reply-to' header set to the list, it requires some manual labour to reply to the sender with most email clients. It's always good to prune the headers of an email manually, just as you should prune the rest of the mail, for instance removing uneeded quotes of previous mails. Also, if you have the 'reply-to' set to the mailing list, and just use 'reply' in your email client, the attribution for quotes will typically say "you wrote" instead of for instance "Quentin wrote". I guess the best thing would be if every subscriber could set up what they want 'reply-to' set to. Perhaps that is a reasonable feature request for Mailman? Or can it be configured like that? -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Wed Jul 16 12:11:03 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 16 11:11:03 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: Message-ID: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> At 10:52 2003-07-16 -0300, Jorge Godoy wrote: >How can I find out if my program is running unde X or Windows instead >of a console / DOS prompt? In X the typical approach is to check whether the DISPLAY environment variable is set. Will you ever run your programs on a Microsoft platform with DOS prompt but no GUI available? What would that be? A toaster? Personally, I'd use different scripts to start up the GUI and console version of the application. Keep it simple. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From godoy@metalab.unc.edu Wed Jul 16 12:19:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Wed Jul 16 11:19:01 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> (Magnus =?iso-8859-1?q?Lyck=E5's?= message of "Wed, 16 Jul 2003 17:16:56 +0200") References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: Magnus Lyck=E5 writes: > In X the typical approach is to check whether the DISPLAY > environment variable is set. OK. This is the second message that suggests that and it is less expensive than the 'try' approach. It also solves the problem to me.=20 > Will you ever run your programs on a Microsoft platform with DOS > prompt but no GUI available? What would that be? A toaster? Actually, I dunno. Probably not. > Personally, I'd use different scripts to start up the GUI and > console version of the application. Keep it simple. I've been doing that with other tools. I just wanted to know if I was doing the right thing or the wrong thing... Everything is in separate modules and the interface is a separate thing that can reuse the other code, so this won't make me write more core (actually, I wouldn't write the check for the X environment...).=20 Thanks, --=20 Godoy. From lonetwin@yahoo.com Wed Jul 16 12:49:02 2003 From: lonetwin@yahoo.com (lonetwin) Date: Wed Jul 16 11:49:02 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <200307162132.09622.lonetwin@yahoo.com> Hi Jorge, > > Personally, I'd use different scripts to start up the GUI and > > console version of the application. Keep it simple. > > I've been doing that with other tools. I just wanted to know if I was > doing the right thing or the wrong thing... Everything is in separate > modules and the interface is a separate thing that can reuse the other > code, so this won't make me write more core (actually, I wouldn't > write the check for the X environment...). Actually it's a common practise (at least for installation/configuration utils) to have a "wrapper" script that checks the environment and then calls the appropriate interface script .... ie: if os.environ.get('DISPLAY', 'console') == 'console': call_console_app() else: call_X_app() ...or the wrapper script can decide the interface depending on how the script was called : ie: if sys.argv[0] == 'proggy': call_console_app() elif sys.argv[0] == 'Xproggy': call_X_app() ...and link 'proggy' and 'Xproggy' The advantage of this is, if the user is in X, the DISPLAY variable may be set, however if some necessary interface/X libs are not present, calling Xproggy might fail. So, then he can always call (or you can fall back to call) 'proggy' (of course you'd want to use isatty() and stuff like that)... so on second thoughts, maybe keeping it simple is a good idea :). However, look and feel *does* matter. HTH Regards Steve -- The devil finds work for idle glands. From jeff@ccvcorp.com Wed Jul 16 14:20:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 16 13:20:02 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <3F158935.7000707@ccvcorp.com> Magnus Lycke wrote: > > Will you ever run your programs on a Microsoft platform with > DOS prompt but no GUI available? What would that be? A toaster? While it's unlikely that a given MS platform will not have a GUI available, the user may have specific reasons for wanting to run something in console mode instead of GUI mode. > Personally, I'd use different scripts to start up the GUI and console > version of the application. Keep it simple. This would be my preferred approach as well. Write a GUI and a CLI version of the interface; both can wrap the same core libraries and business logic. When installing, set the GUI menus and shortcuts to point to the GUI version, and put the CLI version somewhere that's easy to find (i.e. in a directory in $PATH, possibly modifying $PATH to arrange that) with a logical name. This way, you're giving the user control over which version gets run, but in the 99% of the cases where the user doesn't care, it'll just do the right thing. And you don't have to muck about with (possibly unreliable) code to try to guess the environment. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Jul 16 14:24:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 16 13:24:02 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer References: <3F155C41.7000800@icon.co.za> Message-ID: <3F1589F5.2070703@ccvcorp.com> Quentin wrote: > All the lists I belong to have an auto reply address that will return > all replies back to the list, instead of to the original poster. Most > mailing list servers have this option. Is it possible for the Tutor > list to have it as well? > If this was a pre decided decision not to have a reply address, I'll > stand by it, else (elif? :) ), how do the other members feel about it? Magnus already mentioned that it's deliberate; there's an essay that describes *why* it's not preferable in quite a bit more detail -- http://www.unicom.com/pw/reply-to-harmful.html Hope that this answers your questions. Jeff Shannon Technician/Programmer Credit International From alan.gauld@blueyonder.co.uk Wed Jul 16 15:11:33 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 16 14:11:33 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not References: <200307162027.27742.lonetwin@yahoo.com> Message-ID: <005901c34bc5$8d94b700$6401a8c0@xp> > >>> if os.environ.get('DISPLAY', 1) == 1: > ... # we are in console > ... else: > ... # we are in X > > I'm sorry I dunno about windows/dos. I guess post Windows Me you could just check the OS version as per earlier posts this month. But if you were running in a true DOS session then I dont know of any way to do it. I guess you could maybe do a search for a process - Explorer probably. The winall package should include the APIs to list processes. As to the try:/except: method somebody suggested, you wouldn't need to import everything, just enough to make a standard windows call(using winall again) to display an info box maybe? The box could effectively act as a primitive splash screen... Just some untested ideas... Alan G. From alan.gauld@blueyonder.co.uk Wed Jul 16 15:14:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 16 14:14:01 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <006001c34bc5$ed4b6e50$6401a8c0@xp> > > In X the typical approach is to check whether the DISPLAY > > environment variable is set. > > OK. This is the second message that suggests that and it is less > expensive than the 'try' approach. It also solves the problem to me. But its not foolproof. eg. I set DISPLAY in my .login/.profile file but I only start X when I need to. So the env var can be set but X not running. I'd check a 'ps' listing for a process called 'X' to be safe. Alan G. From magnus@thinkware.se Wed Jul 16 17:05:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 16 16:05:02 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: <3F158935.7000707@ccvcorp.com> References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <5.2.1.1.0.20030716220858.01fb03b0@www.thinkware.se> At 10:19 2003-07-16 -0700, Jeff Shannon wrote: >While it's unlikely that a given MS platform will not have a GUI >available, the user may have specific reasons for wanting to run something >in console mode instead of GUI mode. For autodetection of this, please use the Python standard mindreading module. ;) -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From python@kyle.sent.com Wed Jul 16 18:34:02 2003 From: python@kyle.sent.com (Kyle Babich) Date: Wed Jul 16 17:34:02 2003 Subject: [Tutor] 500 (hit counter) Message-ID: <20030716213316.5F75973542@smtp.us2.messagingengine.com> Pretty simple, it's a hit counter that gives me a 500... ############################### print "Content-type: text/html\r\n\r\n" import os import stat import string def increment () : current = os.stat('/data.txt')[stat.ST_SIZE] ip = os.environ['REMOTE_ADDR'] getHit = open('/ips.txt', 'r') hitIps = getHit.readlines() getHit.close() add = 1 for each in hitIps: each = string.strip(each) if each == ip: add = 0 else: pass if add == 1: addIp = open('/ips.txt', 'a') addIp.write("\n" . ip) addIp.close() current += 1 addHit = open('/data.txt', 'a') addHit.write('k') addHit.close() return current print increment() ############################### It is chmod'd to 755 and I also have ips.txt and data.txt that are both 777. Why the 500? I checked the error logs and it says 'Premature end of script headers', which seems to be a standard error, except I didn't do anything different with these headers than I do with headers in any other program I've written. -- Kyle From magnus@thinkware.se Wed Jul 16 18:41:31 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 16 17:41:31 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: <006001c34bc5$ed4b6e50$6401a8c0@xp> References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <5.2.1.1.0.20030716221151.01faea98@www.thinkware.se> At 19:13 2003-07-16 +0100, Alan Gauld wrote: >But its not foolproof. eg. I set DISPLAY in my .login/.profile file >but I only start X when I need to. So the env var can be set but >X not running. I'd check a 'ps' listing for a process called 'X' 'X' would be the X server, right? That might not be running on the same machine as the python script. (In the strange client/server application X11, the server is the machine you sit by, and the client is the (possibly remote) machine where your application is running.) In other words, it's only if DISPLAY indicates the local machine that checking for a local process makes sense. I'm not sure it's correct to have an environment set up to indicate a certain DISPLAY if that doesn't exist. I think a lot of Unix programs assume that DISPLAY actually indicates something that exists. It seems that the DISPLAY environment variable is a better indication of a present X Windows display capability in Unix that a certain process name...but I suppose we deviated a bit from Python now... -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From alan.gauld@blueyonder.co.uk Wed Jul 16 19:54:32 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 16 18:54:32 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> <5.2.1.1.0.20030716221151.01faea98@www.thinkware.se> Message-ID: <007501c34bed$26e12ed0$6401a8c0@xp> > 'X' would be the X server, right? That might not be running on the > same machine as the python script. (In the strange client/server > application X11, the server is the machine you sit by, and the > client is the (possibly remote) machine where your application is > running.) Good point. In the normal mode where you run the apps locally it would work, but if you were usingyour machine as an Xterminal then the python script could be elsewhere. > I'm not sure it's correct to have an environment set up to > indicate a certain DISPLAY if that doesn't exist. I think a lot > of Unix programs assume that DISPLAY actually indicates something > that exists. It hasn't caused me any problems in the last 13 years... but you could be right! It's just easier than setting DISPLAY everytime I start X. And ironically the reason I can't do it in the startx script is because one other user shares the X-server on my Unix box. (The DISPLAY env var is pointing at my PC...) Hmm, thinking further, how would that work? I run the X server on the PC(Thanks cygwin!) but set the DISPLAY on the Unix box where I run the applications. Now I can run a telnet sssion to that box from the PC without having X running and DISPLAY is still set but no X Server exists on my PC. To be certain you would need to look at the machine ID in DISPLAY then do a remote ps(using ssh or rsh) to see if X is running on that machine. This just gets more and more complicated... Alan G. From magnus@thinkware.se Wed Jul 16 20:32:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Wed Jul 16 19:32:01 2003 Subject: [Tutor] 500 (hit counter) In-Reply-To: <20030716213316.5F75973542@smtp.us2.messagingengine.com> Message-ID: <5.2.1.1.0.20030717012956.01ff3cd8@www.thinkware.se> What I see here is a Python script with no #! line in the beginning. If you try to execute that as a CGI script, it will run as a bourne shell script, yes? That's likely to cause errors... If you have a web server setup that manages to run this with python despite the lack of proper #!, make sure that you run Python unbuffered: "python -u". I'd also try putting "import cgitb; cgitb.enable()" in the beginning if Python was recent enough. At 16:33 2003-07-16 -0500, Kyle Babich wrote: >Pretty simple, it's a hit counter that gives me a 500... > >############################### >print "Content-type: text/html\r\n\r\n" > >import os >import stat >import string > >def increment () : > current = os.stat('/data.txt')[stat.ST_SIZE] > ip = os.environ['REMOTE_ADDR'] > > getHit = open('/ips.txt', 'r') > hitIps = getHit.readlines() > getHit.close() > > add = 1 > for each in hitIps: > each = string.strip(each) > if each == ip: > add = 0 > else: > pass > > if add == 1: > addIp = open('/ips.txt', 'a') > addIp.write("\n" . ip) > addIp.close() > > current += 1 > addHit = open('/data.txt', 'a') > addHit.write('k') > addHit.close() > > return current > >print increment() >############################### > >It is chmod'd to 755 and I also have ips.txt and data.txt that are both >777. Why the 500? I checked the error logs and it says 'Premature end >of script headers', which seems to be a standard error, except I didn't >do anything different with these headers than I do with headers in any >other program I've written. >-- >Kyle > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From python@kyle.sent.com Wed Jul 16 20:53:02 2003 From: python@kyle.sent.com (Kyle Babich) Date: Wed Jul 16 19:53:02 2003 Subject: [Tutor] 500 (hit counter) In-Reply-To: <5.2.1.1.0.20030717012956.01ff3cd8@www.thinkware.se> References: <5.2.1.1.0.20030717012956.01ff3cd8@www.thinkware.se> Message-ID: <20030716235235.6D3B8719F1@smtp.us2.messagingengine.com> On Thu, 17 Jul 2003 01:36:57 +0200, "Magnus Lyck=E5" said: > What I see here is a Python script with no #! line in the > beginning. If you try to execute that as a CGI script, it > will run as a bourne shell script, yes? That's likely to > cause errors... It's there, I just didn't copy and paste that part (by accident). >=20 > If you have a web server setup that manages to run this with > python despite the lack of proper #!, make sure that you > run Python unbuffered: "python -u". >=20 > I'd also try putting "import cgitb; cgitb.enable()" in the > beginning if Python was recent enough. I'll try this. I know for a fact that my admin is running an older version of python. It still uses open() instead of file(). >=20 > At 16:33 2003-07-16 -0500, Kyle Babich wrote: > >Pretty simple, it's a hit counter that gives me a 500... > > > >############################### > >print "Content-type: text/html\r\n\r\n" > > > >import os > >import stat > >import string > > > >def increment () : > > current =3D os.stat('/data.txt')[stat.ST_SIZE] > > ip =3D os.environ['REMOTE_ADDR'] > > > > getHit =3D open('/ips.txt', 'r') > > hitIps =3D getHit.readlines() > > getHit.close() > > > > add =3D 1 > > for each in hitIps: > > each =3D string.strip(each) > > if each =3D=3D ip: > > add =3D 0 > > else: > > pass > > > > if add =3D=3D 1: > > addIp =3D open('/ips.txt', 'a') > > addIp.write("\n" . ip) > > addIp.close() > > > > current +=3D 1 > > addHit =3D open('/data.txt', 'a') > > addHit.write('k') > > addHit.close() > > > > return current > > > >print increment() > >############################### > > > >It is chmod'd to 755 and I also have ips.txt and data.txt that are both > >777. Why the 500? I checked the error logs and it says 'Premature end > >of script headers', which seems to be a standard error, except I didn't > >do anything different with these headers than I do with headers in any > >other program I've written. > >-- > >Kyle > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor >=20 > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language=20 >=20 >=20 -- Kyle From himself@lafferty.de Wed Jul 16 21:16:03 2003 From: himself@lafferty.de (himself@lafferty.de) Date: Wed Jul 16 20:16:03 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not Message-ID: <20030717001936.142A3898C@carbon.pub.snx.de> > Personally, I'd use different scripts to start up the GUI and > console version of the application. Keep it simple. Well it depends on your GUI but maybe you'd like to have a look at the anygui project (http://angui.sf.net). It does all the checking for availiable GUI Toolkits (or none) and wrapping for you. If only a console is availiable it uses a curses interface (which is quite ok IMO). Well theres one HUGE drawback... it's not final yet. But maybe it solves your problems or you could design your wrapper after having looked at anygui's code. Greetings, Laff From idiot1@netzero.net Wed Jul 16 23:30:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Wed Jul 16 22:30:01 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer References: <3F155C41.7000800@icon.co.za> Message-ID: <3F15C487.7060706@netzero.net> actually, aI beleive that mailman does indeed offer this option, if the postmaster desires it; you will have to talk to the listdaddy about this, and beats me who that is. Quentin wrote: > All the lists I belong to have an auto reply address that will return > all replies back to the list, instead of to the original poster. Most > mailing list servers have this option. Is it possible for the Tutor list > to have it as well? > If this was a pre decided decision not to have a reply address, I'll > stand by it, else (elif? :) ), how do the other members feel about it? > > Quentin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From idiot1@netzero.net Wed Jul 16 23:30:10 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Wed Jul 16 22:30:10 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer References: <5.2.1.1.0.20030716170201.01f34940@www.thinkware.se> Message-ID: <3F15C560.7050902@netzero.net> This is not the first time I have onsidered such issues. It would be good if you could click one button to reply to the sender, and another to reply to the list. Alas, clicking REPLY ALL sends back to BOTH on netscape. Not sure how it works in the world of microsoft, as I believe it is a moral weakness to support evil institutions, but my impression is this is normal behavior in most email clients. Can anyone figure out a way to get tricky with headers to force one or the other, but not BOTH? Magnus Lyckå wrote: > At 16:08 2003-07-16 +0200, Quentin wrote: > >> All the lists I belong to have an auto reply address that will return >> all replies back to the list, instead of to the original poster. Most >> mailing list servers have this option. Is it possible for the Tutor >> list to have it as well? > > > We've been through this, it's somewhere in the archives. > The simple answer is that with most email clients, it's > easy to answer either to the list of to the sender if > it's set up as it is now. > > Just 'reply' will reply to the sender, and 'reply to all' > will also reply to the list. > > With 'reply-to' header set to the list, it requires some > manual labour to reply to the sender with most email clients. > > It's always good to prune the headers of an email manually, > just as you should prune the rest of the mail, for instance > removing uneeded quotes of previous mails. > > Also, if you have the 'reply-to' set to the mailing list, and > just use 'reply' in your email client, the attribution for > quotes will typically say "you wrote" instead of for instance > "Quentin wrote". > > I guess the best thing would be if every subscriber could set > up what they want 'reply-to' set to. Perhaps that is a reasonable > feature request for Mailman? Or can it be configured like that? > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From idiot1@netzero.net Wed Jul 16 23:30:25 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Wed Jul 16 22:30:25 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer References: <5.2.1.1.0.20030716170201.01f34940@www.thinkware.se> Message-ID: <3F15C560.7050902@netzero.net> This is not the first time I have onsidered such issues. It would be good if you could click one button to reply to the sender, and another to reply to the list. Alas, clicking REPLY ALL sends back to BOTH on netscape. Not sure how it works in the world of microsoft, as I believe it is a moral weakness to support evil institutions, but my impression is this is normal behavior in most email clients. Can anyone figure out a way to get tricky with headers to force one or the other, but not BOTH? Magnus Lyckå wrote: > At 16:08 2003-07-16 +0200, Quentin wrote: > >> All the lists I belong to have an auto reply address that will return >> all replies back to the list, instead of to the original poster. Most >> mailing list servers have this option. Is it possible for the Tutor >> list to have it as well? > > > We've been through this, it's somewhere in the archives. > The simple answer is that with most email clients, it's > easy to answer either to the list of to the sender if > it's set up as it is now. > > Just 'reply' will reply to the sender, and 'reply to all' > will also reply to the list. > > With 'reply-to' header set to the list, it requires some > manual labour to reply to the sender with most email clients. > > It's always good to prune the headers of an email manually, > just as you should prune the rest of the mail, for instance > removing uneeded quotes of previous mails. > > Also, if you have the 'reply-to' set to the mailing list, and > just use 'reply' in your email client, the attribution for > quotes will typically say "you wrote" instead of for instance > "Quentin wrote". > > I guess the best thing would be if every subscriber could set > up what they want 'reply-to' set to. Perhaps that is a reasonable > feature request for Mailman? Or can it be configured like that? > > > -- > Magnus Lycka (It's really Lyckå), magnus@thinkware.se > Thinkware AB, Sweden, www.thinkware.se > I code Python ~ The Agile Programming Language > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From klappnase@freenet.de Thu Jul 17 08:07:01 2003 From: klappnase@freenet.de (klappnase) Date: Thu Jul 17 07:07:01 2003 Subject: [Tutor] Problem recording large wav files with Snack Message-ID: <20030717130738.4f09e98d.klappnase@freenet.de> Hello, I am trying to develop some little sound applications for linux using the snack toolkit. (I am far from being a "professional" programmer, but just a beginner). I want to record large files to disk (whole sides of vinyl albums), so I do something like: s = tkSnack.Sound(encoding="Lin16", frequency=44100, channels=2, fileformat="WAV", byteorder="littleEndian,\ precision="double", file="xyz.wav") s.record() Now I have this strange problem that every time a screensaver starts (or other programs are launched) I get a loss of audio data, so that for example ten seconds of sound in the middle of the file are completely missing. I think that I should add some buffering for the recording, but the "buffersize" option does not seem to have any effect on this. If you have an idea what I could do about this I would be very thankful for any hints. Best regards Michael From shalehperry@comcast.net Thu Jul 17 10:51:36 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Thu Jul 17 09:51:36 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer In-Reply-To: <3F15C560.7050902@netzero.net> References: <5.2.1.1.0.20030716170201.01f34940@www.thinkware.se> <3F15C560.7050902@netzero.net> Message-ID: <200307170649.37312.shalehperry@comcast.net> On Wednesday 16 July 2003 14:36, Kirk Bailey wrote: > This is not the first time I have onsidered such issues. It would be good > if you could click one button to reply to the sender, and another to reply > to the list. Alas, clicking REPLY ALL sends back to BOTH on netscape. Not > sure how it works in the world of microsoft, as I believe it is a moral > weakness to support evil institutions, but my impression is this is normal > behavior in most email clients. Can anyone figure out a way to get tricky > with headers to force one or the other, but not BOTH? > The problem is a cultural one. Unix clients EXPECT you to be part of mailing lists, Windows clients think you are mailing your boss or your mother and a "reply to list" would just confuse you. This is definately something I have been struggling with over the last 3 weeks at work. Just transitioned over to IT so I spend part of my day staring at Windows. Still, you just learn to edit the outbound list. From john@rte.ie Thu Jul 17 11:04:02 2003 From: john@rte.ie (John Moylan) Date: Thu Jul 17 10:04:02 2003 Subject: [Tutor] trying to get md5sums of a list of files In-Reply-To: <20030716073420.9815.40576.Mailman@mail.python.org> References: <20030716073420.9815.40576.Mailman@mail.python.org> Message-ID: <1058450631.11743.1590.camel@localhost.localdomain> Hi, I have a list of the 1.5million filename with paths, on my NAS. I am going to compute md5sums for each file and sort them; check for duplicate files. This is relatively easy in bash: for i in `cat filelist` do; md5sum $i; done However, as an educational exercise, I want to do this in Python. So I coded up the following: #!/usr/local/bin/python import os, sys, md5 for path in open('filelist2'): myline = path.strip() f = open(myline, 'r') m = md5.new() for line in f.readlines(): m.update(line) f.close() md5sum = m.digest() print m However, the output does not make sense, where have I gone wrong? Thanks in Advance, John ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RTÉ may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From shalehperry@comcast.net Thu Jul 17 11:21:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Thu Jul 17 10:21:02 2003 Subject: [Tutor] trying to get md5sums of a list of files In-Reply-To: <1058450631.11743.1590.camel@localhost.localdomain> References: <20030716073420.9815.40576.Mailman@mail.python.org> <1058450631.11743.1590.camel@localhost.localdomain> Message-ID: <200307170719.35822.shalehperry@comcast.net> > So I coded up the following: > > #!/usr/local/bin/python > > import os, sys, md5 > > for path in open('filelist2'): > myline = path.strip() > f = open(myline, 'r') > m = md5.new() > for line in f.readlines(): > m.update(line) > f.close() > md5sum = m.digest() > print m > > However, the output does not make sense, where have I gone wrong? > you failed you read the docs fully (-: `digest()' Return the digest of the strings passed to the `update()' method so far. This is a 16-byte string which may contain non-ASCII characters, including null bytes. `hexdigest()' Like `digest()' except the digest is returned as a string of length 32, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. >>> import md5 >>> md5.new("Nobody inspects the spammish repetition").digest() '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9' >>> md5.new("Nobody inspects the spammish repetition").hexdigest() 'bb649c83dd1ea5c9d9dec9a18df0ffe9' From cybersamurai@mac.com Thu Jul 17 12:13:32 2003 From: cybersamurai@mac.com (Luiz Siqueira Neto) Date: Thu Jul 17 11:13:32 2003 Subject: [Tutor] u'=' ????? What is it? Message-ID: <200307171213.41311.cybersamurai@mac.com> What ---- u'=' ---- mean?? Ex: args = [u'='.join(k,safe_eval(v) for k, v in attrs.items()] From kalle@lysator.liu.se Thu Jul 17 12:20:02 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Thu Jul 17 11:20:02 2003 Subject: [Tutor] u'=' ????? What is it? In-Reply-To: <200307171213.41311.cybersamurai@mac.com> References: <200307171213.41311.cybersamurai@mac.com> Message-ID: <20030717151927.GC19374@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Luiz Siqueira Neto] > What > u'=' > mean?? u'=' is the Unicode literal string '='. Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE/Fr52dNeA1787sd0RAnE1AKDBDBcEhzXiFZn03xHmPcupjziJZwCgsn51 /lqXv1xqGRSk1FoXn9ZdCdc= =o+hF -----END PGP SIGNATURE----- From lsloan@umich.edu Thu Jul 17 12:23:06 2003 From: lsloan@umich.edu (Lance E Sloan) Date: Thu Jul 17 11:23:06 2003 Subject: [Tutor] Finding out if we can use a graphical environment or not In-Reply-To: References: <5.2.1.1.0.20030716171252.01f964f0@www.thinkware.se> Message-ID: <4107063.1058435984@141-213-238-90.umnet.umich.edu> --On Wednesday, July 16, 2003 12:18 -0300 Jorge Godoy wrote: >> Will you ever run your programs on a Microsoft platform with DOS >> prompt but no GUI available? What would that be? A toaster? > > Actually, I dunno. Probably not. Toasters wouldn't run DOS anyway. Maybe Java, though. ;) Seriously, though, the non-GUI version of the program could be run from DOS, though unlikely, or from a UNIX or Linux shell. So I think this is a good question. However, I think the suggestions others have made for running the program under different names ("proggy" and "Xproggy") make a lot of sense. It's possible that I'll run your program from an xterm window and although my "DISPLAY" environment variable is set and I do have X running, maybe I don't want to run the GUI version. -- Lance E Sloan U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From john@rte.ie Thu Jul 17 13:09:02 2003 From: john@rte.ie (John Moylan) Date: Thu Jul 17 12:09:02 2003 Subject: [Tutor] re: Problem recording large wav files with Snack In-Reply-To: <20030717160005.30133.44599.Mailman@mail.python.org> References: <20030717160005.30133.44599.Mailman@mail.python.org> Message-ID: <1058458081.11743.1702.camel@localhost.localdomain> This happens with most audio encoders. Encoding is a CPU intensive process. We encode real player content here all the time. Screen savers have to be disabled on encoding boxes because they can be too CPU hungry. JOhn ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RTÉ may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From andi@buxach.de Thu Jul 17 13:48:12 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Thu Jul 17 12:48:12 2003 Subject: [Tutor] sound volume Message-ID: <20030630121046.71b07643.andi@buxach.de> Hi i am working on a jukebox daemon currently (like cymbaline, julie, ...) Now i use pyogg and pymad with pyao for playback, now i'd like to modify the sound stream, especially the sound volume, because i don't want to use the oss-mixer. It should fade the songs into each other, so i must change the volume differently on different streams. Is there a library/module? So i could easily build it between pymad and pyao ? mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From magnus@thinkware.se Thu Jul 17 13:58:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Thu Jul 17 12:58:02 2003 Subject: [Tutor] trying to get md5sums of a list of files In-Reply-To: <1058450631.11743.1590.camel@localhost.localdomain> References: <20030716073420.9815.40576.Mailman@mail.python.org> <20030716073420.9815.40576.Mailman@mail.python.org> Message-ID: <5.2.1.1.0.20030717185008.020a8970@www.thinkware.se> At 15:03 2003-07-17 +0100, John Moylan wrote: > md5sum = m.digest() > print m > >However, the output does not make sense, where have I gone wrong? You have printed the md5 object instead of the digest. You assign the digest to the variable md5sum, and then you never use that... Simply do "print md5sum" instead of "print m" Note that the value returned by .digest() is a *binary* string though, you probably want a string of hex values: md5sum = m.hexdigest() print md5sum -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From jeff@ccvcorp.com Thu Jul 17 14:05:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 17 13:05:02 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer References: <5.2.1.1.0.20030716170201.01f34940@www.thinkware.se> <3F15C560.7050902@netzero.net> Message-ID: <3F16D731.6030000@ccvcorp.com> Kirk Bailey wrote: > This is not the first time I have onsidered such issues. It would be > good if you could click one button to reply to the sender, and another > to reply to the list. Alas, clicking REPLY ALL sends back to BOTH on > netscape. Not sure how it works in the world of microsoft, as I > believe it is a moral weakness to support evil institutions, but my > impression is this is normal behavior in most email clients. Can > anyone figure out a way to get tricky with headers to force one or the > other, but not BOTH? Yes, 'reply all' sends back to both parties, with pretty much any mailer. (That's why it's 'reply ALL'.) It is, however, fairly simple to delete undesired addresses from the email before it's sent -- especially since you're trimming the quoted email body anyhow. (You *are* trimming the email to only the most relevant quoted sections, right??) Deleting unwanted addresses is a *lot* easier than adding additional addresses. And it's rarely a problem for the email to go to an extra (private) address, anyhow. I certainly wouldn't mind if standard mailers grew a third 'reply to list' option, but given that the standard options are only 'reply to sender' and 'reply to all', I'm perfectly happy with manually trimming the reply list. This seems like much less of a problem than the weirdnesses that would likely be caused by getting "tricky with headers" -- as the link I posted mentions, header munging often leads to unpredictable results, and the less it's done the better. Jeff Shannon Technician/Programmer Credit International From mwagman@charter.net Thu Jul 17 14:35:02 2003 From: mwagman@charter.net (Mike Wagman) Date: Thu Jul 17 13:35:02 2003 Subject: [Tutor] Locking files on windows Message-ID: <1058463291.2461.3.camel@24-159-241-21.jvl.wi.charter.com> I need to lock files under windows using python. I've run into references to portalocker but can't find it. So can someone point me to it, and let me know if that is the best way to lock files. There is a chance that this will get run under linux so if there is a multiplatform locker that would be ideal (if portalocker is not one). Other wise locking files under window. I have looked as msvcrt and could use an example of how to use that in a practical application. From dyoo@hkn.eecs.berkeley.edu Thu Jul 17 14:47:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 17 13:47:01 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer In-Reply-To: <3F16D731.6030000@ccvcorp.com> Message-ID: On Thu, 17 Jul 2003, Jeff Shannon wrote: > Kirk Bailey wrote: > > > This is not the first time I have onsidered such issues. It would be > > good if you could click one button to reply to the sender, and another > > to reply to the list. Alas, clicking REPLY ALL sends back to BOTH on > > netscape. > > Yes, 'reply all' sends back to both parties, with pretty much any > mailer. (That's why it's 'reply ALL'.) Hi everyone, And in most cases, doing Reply to All is the right thing to do, especially on mailing lists that support Digest mode. There are some people who have turned off "list delivery" on their mailman settings, or in a less extreme case, are running in digest mode. Hypothetical situation: if you're in digest mode, and you ask a question on the Tutor list, do you want to wait for the next digest to see if someone has responded to your question? This is not actually such an uncommon situation: the majority of subscribers to Python-Tutor are on Digest mode! These folks may still like to occasionally post and get direct responses to their questions. Trimming the reply-to list to only the list, though, cuts them off and prevents them from getting timely answers. Anyway, let's get back to talking about Python. *grin* From dyoo@hkn.eecs.berkeley.edu Thu Jul 17 15:17:20 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 17 14:17:20 2003 Subject: [Tutor] trying to get md5sums of a list of files In-Reply-To: <200307170719.35822.shalehperry@comcast.net> Message-ID: On Thu, 17 Jul 2003, Sean 'Shaleh' Perry wrote: > > So I coded up the following: > > > > #!/usr/local/bin/python > > > > import os, sys, md5 > > > > for path in open('filelist2'): > > myline = path.strip() > > f = open(myline, 'r') > > m = md5.new() > > for line in f.readlines(): > > m.update(line) > > f.close() > > md5sum = m.digest() > > print m Hi everyone, One other potential bug: readlines() sucks in the whole file into memory at once, and treats it as a text file. For large files, this may impact memory, so a safer approach is to use a "chunked" read(): ### def md5file(f): """Returns an md5sum hex string of a file.""" m = md5.new() while 1: bytes = f.read(1024) if not bytes: break m.update(bytes) return m.hexdigest() ### I read a kilobyte arbitrary: dunno why, I guess it's a nice round number. *grin* The important thing is to avoid reading the whole file at once, but to do it progressively. md5's update() method is designed to be called many times precisely because it works on chunks at a time. With this md5file() approach, we can now deal with files of any size without running into a memory problem. Once we code up this md5file() utility function, John's original question: """ I am going to compute md5sums for each file and sort them; check for duplicate files. This is relatively easy in bash: for i in `cat filelist` do; md5sum $i; done """ has a cute translation in Python: ### for f in open('filelist'): print md5file(open(f, "rb")) ## Question: why "rb"? ### There's one other subtle point that deals with the inner file-open()ing loop. In particular, the "b" "binary" open() part in the loop is important. If we want to make sure we're getting the same results as our shell's "md5sum" utility, we must not treat newlines as special characters, since they too contribute to the md5 sum. Opening a file in binary mode will make sure newlines are treated such as any other byte in our file. Hope this helps! From mwagman@charter.net Thu Jul 17 15:27:52 2003 From: mwagman@charter.net (Mike Wagman) Date: Thu Jul 17 14:27:52 2003 Subject: [Tutor] Locking files on windows In-Reply-To: <1058463291.2461.3.camel@24-159-241-21.jvl.wi.charter.com> References: <1058463291.2461.3.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: <1058466271.4688.0.camel@24-159-241-21.jvl.wi.charter.com> found portalocker - Now to see if it does what I need. On Thu, 2003-07-17 at 12:34, Mike Wagman wrote: > I need to lock files under windows using python. > > I've run into references to portalocker but can't find it. > > So can someone point me to it, and let me know if that is the best way > to lock files. There is a chance that this will get run under linux so > if there is a multiplatform locker that would be ideal (if portalocker > is not one). > > Other wise locking files under window. I have looked as msvcrt and could > use an example of how to use that in a practical application. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From mwagman@charter.net Thu Jul 17 15:41:01 2003 From: mwagman@charter.net (Mike Wagman) Date: Thu Jul 17 14:41:01 2003 Subject: [Tutor] Portalocker Message-ID: <1058467236.4694.2.camel@24-159-241-21.jvl.wi.charter.com> Does not seem to be working. Can anyone send me a piece of code that will open a file, and when that file is open - I can't open it from another python program. From Sk8erguy2424@aol.com Thu Jul 17 16:03:04 2003 From: Sk8erguy2424@aol.com (Sk8erguy2424@aol.com) Date: Thu Jul 17 15:03:04 2003 Subject: [Tutor] Portalocker Message-ID: <90.3a0bc6c5.2c484ccb@aol.com> --part1_90.3a0bc6c5.2c484ccb_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Following the synopsis code, I ran into this problem: >>> import portalocker >>> file=open("C:\My Documents\log.txt", "r+") >>> portalocker.lock(file, portalocker.LOCK_EX) Traceback (most recent call last): File "", line 1, in ? portalocker.lock(file, portalocker.LOCK_EX) AttributeError: 'module' object has no attribute 'lock' I rechecked to see if I installed the module correctly and I did. Anyone know why this is happening? Thanks in advance. --part1_90.3a0bc6c5.2c484ccb_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable Following the synopsis code, I ran into this problem= :

>>> import portalocker
>>> file=3Dopen("C:\My Documents\log.txt", "r+")
>>> portalocker.lock(file, portalocker.LOCK_EX)
Traceback (most recent call last):
 File "<pyshell#13>", line 1, in ?
   portalocker.lock(file, portalocker.LOCK_EX)
AttributeError: 'module' object has no attribute 'lock'

I rechecked to see if I installed the module correctly and I did.  = Anyone know why this is happening?  Thanks in advance.
--part1_90.3a0bc6c5.2c484ccb_boundary-- From jdjames87@sbcglobal.net Thu Jul 17 18:27:01 2003 From: jdjames87@sbcglobal.net (Jordan James) Date: Thu Jul 17 17:27:01 2003 Subject: [Tutor] lots of Python errors Message-ID: <002e01c34be3$c907d920$0500a8c0@sbcglobal.net> This is a multi-part message in MIME format. ------=_NextPart_000_0027_01C34BA9.18E4A620 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I don't know why, but I seem to get a lot of errors running Python. How = I came to use Python was through Blender, a freeware 3D package (that = uses Python) that you've probably heard of. At first, I found that only = a few of the scripts that I downloaded for use in Blender worked, so I = thought it was a problem with Blender. So I got the actual python = command line and GUI. I still had lots of errors running scripts by = other people. For example, "os.system". When I say os.system("start notepad") ,it says=20 Traceback (most recent call last): File "C:/Program Files/Python/launch.py", line 1, in ? os.system("start notepad") NameError: name 'os' is not defined I'm pretty sure this isn't normal, because I read all of the tutor pages = by other people, and these things work for them. I am running Python = 2.3; is this possibly a really old version? Is there some major step = I'm not doing? I'm running Windows 98, does Python have problems with = Windows? Are there any other factors I need to consider? I know my problem is pretty broad, but if anyone knows what is going on, = I would appreciate it if you told me. Thanks. Jordan ------=_NextPart_000_0027_01C34BA9.18E4A620 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I don't know why, but I seem to get a = lot of errors=20 running Python.  How I came to use Python was through Blender, = a=20 freeware 3D package (that uses Python) that you've probably heard = of. =20 At first, I found that only a few of the scripts that I downloaded for = use in=20 Blender worked, so I thought it was a problem with = Blender.  So I got=20 the actual python command line and GUI.  I still had lots of errors = running=20 scripts by other people.  For example, =  "os.system".   When=20 I say
 
os.system("start notepad")
 
,it says
 
Traceback (most recent call = last):
  File=20 "C:/Program Files/Python/launch.py", line 1, in ?
   =20 os.system("start notepad")
NameError: name 'os' is not = defined
 
I'm pretty sure this isn't normal, = because I read=20 all of the tutor pages by other people, and these things work = for=20 them.  I am running Python 2.3; is this possibly a really old=20 version?  Is there some major step I'm not doing?  I'm running = Windows=20 98, does Python have problems with Windows?  Are there any other = factors I=20 need to consider?
 
I know my problem is pretty broad, but = if anyone=20 knows what is going on, I would appreciate it if you told = me.
 
Thanks.
 
Jordan
------=_NextPart_000_0027_01C34BA9.18E4A620-- From alex@caustic-creations.com Thu Jul 17 18:27:12 2003 From: alex@caustic-creations.com (Alex from Caustic Creations) Date: Thu Jul 17 17:27:12 2003 Subject: [Tutor] curses.wrapper() question Message-ID: <1058424268.942.9.camel@caustic.laptop> Hello, I'm trying to learn python because I would like to create a simple cash register application using curses. I read the curses howto and the reference manual and both refer to the curses.wrapper function. The advantages of using the wrapper are significant, yet I can't seem to call it up properly. I've included my "test.py" program - a compilation of all of the statements in the curses howto so I could see and play around with their effects. If anyone can find the time, could someone alter this little demo program using the curses wrapper to illustrate its correct use? Thanks so much in advance, Alex #### Begin Code #!/usr/bin/python # # Alex's first attemopts at writing a curses interface using python import curses stdscr = curses.initscr() curses.start_color() curses.noecho() curses.cbreak() stdscr.keypad(1) def newWindow(): begin_x = 20 ; begin_y = 7 height = 5 ; width = 40 win = curses.newwin(height, width, begin_y, begin_x) return stdscr.refresh() newWindow() # Windows and Pad test pad = curses.newpad(100,100) for y in range(0,100): for x in range(0,100): try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26) except curses.error: pass pad.refresh(0,0, 5,5, 20,75) # Display "Current Mode" line att he top of the screen stdscr.addstr(0, 0, "Current mode: Typing mode", curses.A_BOLD) stdscr.refresh() # Coloured text test stdscr.refresh() curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) stdscr.addstr( 0,80, "Pretty text", curses.color_pair(1) ) stdscr.refresh() # Keyboard input test while 1: c = stdscr.getch() if c == ord('p'): stdscr.addstr( 2,60, "You typed the letter p", curses.color_pair(1) ) elif c == ord('q'): break elif c == curses.KEY_HOME: x=y=0 # Ending curses politely curses.nocbreak(); stdscr.keypad(0); curses.echo() curses.endwin() #### End Code From exnihilo@myrealbox.com Thu Jul 17 18:47:39 2003 From: exnihilo@myrealbox.com (calvin) Date: Thu Jul 17 17:47:39 2003 Subject: [Tutor] lots of Python errors References: <002e01c34be3$c907d920$0500a8c0@sbcglobal.net> Message-ID: <3F171834.9020307@myrealbox.com> Jordan James wrote: > I don't know why, but I seem to get a lot of errors running Python. How > I came to use Python was through Blender, a freeware 3D package (that > uses Python) that you've probably heard of. At first, I found that only > a few of the scripts that I downloaded for use in Blender worked, so I > thought it was a problem with Blender. So I got the actual python > command line and GUI. I still had lots of errors running scripts by > other people. For example, "os.system". When I say > > os.system("start notepad") > > ,it says > > Traceback (most recent call last): > File "C:/Program Files/Python/launch.py", line 1, in ? > os.system("start notepad") > NameError: name 'os' is not defined > > I'm pretty sure this isn't normal, because I read all of the tutor pages > by other people, and these things work for them. I am running Python > 2.3; is this possibly a really old version? Is there some major step > I'm not doing? I'm running Windows 98, does Python have problems with > Windows? Are there any other factors I need to consider? > > I know my problem is pretty broad, but if anyone knows what is going on, > I would appreciate it if you told me. > > Thanks. > > Jordan Hi Jordan, The problem with your os.system line seems to be that you have not imported the module first. Python doesn't know what 'os' refers to (could be a module, a variable in another file, whatever), so it gives you the name error, because it doesn't recognize the name. If you import the os module first, then it knows what 'os' refers to, and will correctly call the function 'system' that is in that module: Python 2.2.1 (#1, Nov 10 2002, 18:40:13) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> os.system("ls") Traceback (most recent call last): File "", line 1, in ? NameError: name 'os' is not defined >>> import os >>> os.system("ls") afile.txt 0 >>> You have to import a module before you have access to anything in that module (like the 'system' function in the os module). -calvin btw, Python 2.3 is very new. I think the latest stable release is 2.2.3. From silviucc@home.ro Thu Jul 17 18:47:55 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Thu Jul 17 17:47:55 2003 Subject: [Tutor] test - sorry Message-ID: From alan.gauld@blueyonder.co.uk Thu Jul 17 19:33:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Thu Jul 17 18:33:01 2003 Subject: [Tutor] curses.wrapper() question References: <1058424268.942.9.camel@caustic.laptop> Message-ID: <006801c34cb3$5b3edfd0$6401a8c0@xp> No help on the curses wrapper stuff, in fact its existence was news to me! However... > #### Begin Code > > def newWindow(): > begin_x = 20 ; begin_y = 7 > height = 5 ; width = 40 > win = curses.newwin(height, width, begin_y, begin_x) > return You need to indent the function body(but that might just be an email wobbly) More significantly you don't need the empty return statement. By default Python functions return None. Also you might be better putting x,y,h and w in as parameters rather than variables. This will allow you to specify them when you call newWindow. Like this: def newWindow(begin_x=20, begin_y=7, height=5,width=40): win = curses.newwin(height, width, begin_y, begin_x) You can then call this like: newWin() # use the defaults specified newWin(7,5,3,4) # a very small window newWin(width=70) # defaults except for width > for y in range(0,100): > for x in range(0,100): > try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26) > except curses.error: pass Again I assume mail is messing up the necessary indentation? HTH even if not with your real problem, Alan G. From Janssen@rz.uni-frankfurt.de Thu Jul 17 19:37:03 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jul 17 18:37:03 2003 Subject: [Tutor] curses.wrapper() question In-Reply-To: <1058424268.942.9.camel@caustic.laptop> References: <1058424268.942.9.camel@caustic.laptop> Message-ID: On Thu, 17 Jul 2003, Alex from Caustic Creations wrote: > Hello, > > I'm trying to learn python because I would like to create a simple cash > register application using curses. I read the curses howto and the > reference manual and both refer to the curses.wrapper function. The > advantages of using the wrapper are significant, yet I can't seem to > call it up properly. > > I've included my "test.py" program - a compilation of all of the > statements in the curses howto so I could see and play around with their > effects. If anyone can find the time, could someone alter this little > demo program using the curses wrapper to illustrate its correct use? Hi Alex, curses.wrapper() is very easy to use :-) But you have to redesign your script for this.... curses.wrapper takes a function as argument. But what for a function? The "main" function for your curses application that does *all* the logic. By now you write your script much like a shell-script doing one step after another. This is a typical way to start, not that efficient (in terms of maintainable code) and unfortunatelly a no-go-way for curses.wrapper. A better design would be: 1. setting some global constants (if at all) 2. definining a "main" function (you can call it at wil, but "main" is often used) that does all the logic (mostly by calling subfunctions) 3. define subfunctions as you need 4. call "main": main() This should (should in the meanding of "for the sake of beauty") be the only piece of code that is called on top level (zero indentation). curses.wrapper is now simply used this way: curses.wrapper(main) Here I've got a piece of code that shows the non-wrapper way but with use of a "main" function (The "if __name__=='__main__':" part asures that the code is only excecuted when the file is excecuted as a script (not imported as a modul). You can ignore this when you can't see the benefit. try-finally asures the the finally-block is executed even if an exception occurs in main. You shouldn't ignore this ;-): if __name__=='__main__': try: stdscr=curses.initscr() curses.noecho() ; curses.cbreak() stdscr.keypad(1) main(stdscr) # Enter the main loop finally: stdscr.erase() stdscr.refresh() stdscr.keypad(0) curses.echo() ; curses.nocbreak() curses.endwin() # Terminate curses and the same (plus color activating) with the wrapper: if __name__=='__main__': curses.wrapper(main) When you absolutly have no idea how to break your code into subfunctions and call them by a main-function, then you can also add one level of indentation to the whole code and put a def main(): right in front of it. As a last resort ;-) cheers Michael From Janssen@rz.uni-frankfurt.de Thu Jul 17 19:45:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jul 17 18:45:02 2003 Subject: [Tutor] curses.wrapper() question In-Reply-To: References: <1058424268.942.9.camel@caustic.laptop> Message-ID: On Fri, 18 Jul 2003, Michael Janssen wrote: > Hi Alex, > > curses.wrapper() is very easy to use :-) But you have to redesign your > script for this.... > > curses.wrapper takes a function as argument. But what for a function? The > "main" function for your curses application that does *all* the logic. > > By now you write your script much like a shell-script doing one step after > another. This is a typical way to start, not that efficient (in terms of > maintainable code) and unfortunatelly a no-go-way for curses.wrapper. > > A better design would be: > > 1. setting some global constants (if at all) > > 2. definining a "main" function (you can call it at wil, but "main" is > often used) that does all the logic (mostly by calling subfunctions) I have forgotten one important thing: curses.wrapper will send the curses main window ("stdscr") to main as an argument. So you must write your main-function in that way, that it will *take* this argument. def main(stdscr): stdscr.addstr(0, 0, "Hello World!") # or what you want is nice. Michael From Janssen@rz.uni-frankfurt.de Thu Jul 17 19:51:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jul 17 18:51:02 2003 Subject: [Tutor] curses.wrapper() question In-Reply-To: <006801c34cb3$5b3edfd0$6401a8c0@xp> References: <1058424268.942.9.camel@caustic.laptop> <006801c34cb3$5b3edfd0$6401a8c0@xp> Message-ID: On Thu, 17 Jul 2003, Alan Gauld wrote: > [Alex] > > for y in range(0,100): > > for x in range(0,100): > > try: pad.addch(y,x, ord('a') + (x*x+y*y) % 26) > > except curses.error: pass > > Again I assume mail is messing up the necessary indentation? it was right for me but yet another proof of the saying that tabs are evil ;-) Michael From dyoo@hkn.eecs.berkeley.edu Thu Jul 17 21:31:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 17 20:31:02 2003 Subject: [Tutor] Problem recording large wav files with Snack In-Reply-To: <20030717130738.4f09e98d.klappnase@freenet.de> Message-ID: On Thu, 17 Jul 2003, klappnase wrote: > I am trying to develop some little sound applications for linux using > the snack toolkit. (I am far from being a "professional" programmer, but > just a beginner). > > I want to record large files to disk (whole sides of vinyl albums), so I > do something like: > > s = tkSnack.Sound(encoding="Lin16", frequency=44100, channels=2, > fileformat="WAV", byteorder="littleEndian,\ > precision="double", file="xyz.wav") > s.record() Hi klappnase, I'm not too familiar with the tkSnack module, and I'm not sure if any of us here can help diagnose the problem; it sounds more like an operating systems issue more than anything else. you may want to contact Snack's author, according to: http://www.speech.kth.se/snack/FAQ.html We can, at least, see Python syntax errors... *grin* Are you sure that's not missing a quote sign here? fileformat="WAV", byteorder="littleEndian,\ ^^^^^^^^^^^^^^^ [off-topic, sorta: If you are running on a Linux system, you may want to double check that your hard drive is tuned to performance: http://linux.oreillynet.com/pub/a/linux/2000/06/29/hdparm.html Most Linux systems are very conservative in the way they use their hard drives --- you may be running into a simple IO issue. ] Good luck! From saf@mail.scottfallin.com Thu Jul 17 23:53:02 2003 From: saf@mail.scottfallin.com (Scott Fallin) Date: Thu Jul 17 22:53:02 2003 Subject: [Tutor] parsing x is y statements from stdin Message-ID: <20030718025010.GA5868@localhost.localdomain> I'm trying to figure out how best to parse a string such as "It is hot today". I want to check for the existance of a predefined verb that will always be located in the middle of the sentence, and if the verb test passes, I want to chop the sentence up in to variables, var1 = 'It', var2 = 'is', and var3 = "hot today". I can do it in Perl but for some reason it is elluding me in Python. Any light shed would be much appreciated. s. From dyoo@hkn.eecs.berkeley.edu Fri Jul 18 00:43:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 17 23:43:02 2003 Subject: [Tutor] parsing x is y statements from stdin In-Reply-To: <20030718025010.GA5868@localhost.localdomain> Message-ID: On Thu, 17 Jul 2003, Scott Fallin wrote: > I'm trying to figure out how best to parse a string such as "It is hot > today". I want to check for the existance of a predefined verb that > will always be located in the middle of the sentence, and if the verb > test passes, I want to chop the sentence up in to variables, var1 = > 'It', var2 = 'is', and var3 = "hot today". > > I can do it in Perl but for some reason it is elluding me in Python. Hi Scott, Can you show us how you're doing it in Perl? We'll be happy to help you apply your knowledge of Perl to better understand how to do it in Python. By the way, you may be interested in a module called 'Monty Tagger': http://web.media.mit.edu/~hugo/research/montytagger.html You may not even need to write much code. *grin* Good luck to you! From lonetwin@yahoo.com Fri Jul 18 03:30:02 2003 From: lonetwin@yahoo.com (lonetwin) Date: Fri Jul 18 02:30:02 2003 Subject: [Tutor] Portalocker In-Reply-To: <90.3a0bc6c5.2c484ccb@aol.com> References: <90.3a0bc6c5.2c484ccb@aol.com> Message-ID: <200307181212.21502.lonetwin@yahoo.com> Hi there, Could you possibly post a URL for portalocker ?? At first glance I can hazard a guess, since I too have done such mistakes when playing in the interpreter. > >>> import portalocker > >>> file=open("C:\My Documents\log.txt", "r+") > >>> portalocker.lock(file, portalocker.LOCK_EX) > > Traceback (most recent call last): > File "", line 1, in ? > portalocker.lock(file, portalocker.LOCK_EX) > AttributeError: 'module' object has no attribute 'lock' The error message is pretty clear. You seem to be calling a non-existant method in the module 'portalocker' called 'lock' ('module' object has no attribute 'lock') Normally, for me, something like this happens in the interpreter when I stupidly try to use a method that belongs to a class with the same name is the module. What I mean is, look at the portalocker module and see if there is a class called 'portalocker' which you have to instantiate before calling the 'lock' method on the instance. Peace Steve -- It is easier to resist at the beginning than at the end. -- Leonardo da Vinci From exnihilo@myrealbox.com Fri Jul 18 04:07:02 2003 From: exnihilo@myrealbox.com (calvin) Date: Fri Jul 18 03:07:02 2003 Subject: [Tutor] simple threads program Message-ID: <3F179C23.7010504@myrealbox.com> hi, I am trying to create a simple threaded program, to learn how threads work. I would like to download and save a bunch of pages, and since the download is most of the time, it seems like a good candidate for speedup using threads. What I have so far is a simple program that I've adapted from thread examples that I've seen on the web: #!/usr/bin/python import thread, urllib pages = ['cnn.com', 'nytimes.com', 'slashdot.org', 'kuro5hin.org', 'news.google.com', 'berkeley.edu'] pages = pages * 3 def getPage(id, p): stdoutmutex.acquire() sock = urllib.urlopen('http://'+p) print "Downloaded", p htmlSource = sock.read() f = open(p+'.html', 'w') f.write(htmlSource) f.close() stdoutmutex.release() exitmutexes[id].acquire() # signal main thread stdoutmutex = thread.allocate_lock() exitmutexes = [] for i in range(len(pages)): exitmutexes.append(thread.allocate_lock()) thread.start_new(getPage, (i, pages[i])) print "Started thread", i for mutex in exitmutexes: while not mutex.locked(): pass print "Main thread exiting" This seems to be running as if everything is in one thread, since the pages always download in the exact order that they appear in the list of pages. Any hints at what I'm doing wrong? thanks, calvin From thomi@thomi.imail.net.nz Fri Jul 18 04:12:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Fri Jul 18 03:12:02 2003 Subject: [Tutor] simple threads program In-Reply-To: <3F179C23.7010504@myrealbox.com> References: <3F179C23.7010504@myrealbox.com> Message-ID: <20030718191147.2b04b3fd.thomi@thomi.imail.net.nz> > > I would like to download and save a bunch of pages, and since the > download is most of the time, it seems like a good candidate for > speedup using threads. > I'm not going to comment on the code (because i can't), but your example seems a little wierd... surely if the downloading take up most of the time, this would mean that you're on a fairly slow connection? perhaps dialup? If so, how would having multiple threads speed it up? OK, so there would be a slight speed increase, but you can't download 3 times as much by having 3 separate downloads; they'll just be coming down at 1/3 the speed.... When i used threads, i just followed the documentation in the threading module, and it worked just fine ;) -- Thomi Richards, thomi@thomi.imail.net.nz From john.moylan@rte.ie Fri Jul 18 04:54:01 2003 From: john.moylan@rte.ie (John Moylan) Date: Fri Jul 18 03:54:01 2003 Subject: [Tutor] trying to get md5sums of a list of files In-Reply-To: <20030717214755.25155.32458.Mailman@mail.python.org> References: <20030717214755.25155.32458.Mailman@mail.python.org> Message-ID: <1058514779.11743.1717.camel@localhost.localdomain> Thanks, that was embarrassingly simple solution. John ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RTÉ may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From john.moylan@rte.ie Fri Jul 18 05:59:01 2003 From: john.moylan@rte.ie (John Moylan) Date: Fri Jul 18 04:59:01 2003 Subject: [Tutor] re:md5sum In-Reply-To: <20030717214755.25155.32458.Mailman@mail.python.org> References: <20030717214755.25155.32458.Mailman@mail.python.org> Message-ID: <1058518721.11743.1730.camel@localhost.localdomain> Thanks, your code helped alot. I found that I still had to strip \n's from my filelist code with the following though: for path in open('filelist3'): f = path.strip() #strip \n's otherwise "file not found" type error print md5file(open(f, "rb")) > Hi everyone, > > > One other potential bug: readlines() sucks in the whole file into memory > at once, and treats it as a text file. For large files, this may impact > memory, so a safer approach is to use a "chunked" read(): > > ### > def md5file(f): > """Returns an md5sum hex string of a file.""" > m = md5.new() > while 1: > bytes = f.read(1024) > if not bytes: break > m.update(bytes) > return m.hexdigest() > ### > > > I read a kilobyte arbitrary: dunno why, I guess it's a nice round number. > *grin* The important thing is to avoid reading the whole file at once, but > to do it progressively. md5's update() method is designed to be called > many times precisely because it works on chunks at a time. With this > md5file() approach, we can now deal with files of any size without running > into a memory problem. > > > > Once we code up this md5file() utility function, John's original question: > > """ > I am going to compute md5sums for each file and sort them; check for > duplicate files. > This is relatively easy in bash: > for i in `cat filelist` do; md5sum $i; done > """ > > > has a cute translation in Python: > > ### > for f in open('filelist'): > print md5file(open(f, "rb")) ## Question: why "rb"? > ### > > > > There's one other subtle point that deals with the inner file-open()ing > loop. In particular, the "b" "binary" open() part in the loop is > important. If we want to make sure we're getting the same results as our > shell's "md5sum" utility, we must not treat newlines as special > characters, since they too contribute to the md5 sum. Opening a file in > binary mode will make sure newlines are treated such as any other byte in > our file. > > > Hope this helps! > > > ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RTÉ may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From Janssen@rz.uni-frankfurt.de Fri Jul 18 06:22:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jul 18 05:22:02 2003 Subject: [Tutor] curses.wrapper() question In-Reply-To: <1058487042.855.20.camel@caustic.laptop> References: <1058424268.942.9.camel@caustic.laptop> <1058487042.855.20.camel@caustic.laptop> Message-ID: [a copy to tutor@python.org FYI] On Fri, 17 Jul 2003, Alex from Caustic Creations wrote: > Hello Michael, > > Thanks a lot for taking the time to explain things to me. I must admit > that I was quite confused when I was able to call curses functions like > curses.addchr() yet had no success calling the curses.wrapper() > function. > > So, if I'm understanding things correctly, my simple cash register > program structure should look something like this: > > #! /usr/bin/python > > # Import the curses module and perhaps the math and time module > > import curses, math, time > > # Define the "main" function > > def main(stdscr): > stdscr.addstr(0, 0, "Hello World!") # or what you want > > # Define "clock" function as a sub-function of "main" (or perhaps > # import it as a separate module). > > def clock() > .... > Stuff that prints the time day. > .... Well, you've learned fast :-) That's the way to do it with curses.wrapper() and a much cleaner way to programm python (Although beginners have normally more time to learn this, but curses.wrapper pushes). One little hint: its completly okey to define functions inside other functions (like your clock-function) but this is seldom used (I can't remember any reason why to do it at all, but I've seen it in code). More convenient would be: def main(): # some stuff including call the clock function. def clock(): # some clock stuff The advantage is to keep the main-function small. Ideally "main" should act as the highest level programm-logic, representing the steps the programm takes in the most comprehensive way and call subfunction (I should have said "other function") any time it comes into details. This way other code-readers or you some month further will have little trubble to understand what your programm does. By the way: I've got a curses-programm that has got longish functions to get user-input. I still want this code a little more cleaner. The problem is, that you must do a lot of "if-else" to recognise the getch-input and for different purposes (input for the whole programm in contrast to input for a single field) i rewrite this function with a bit different if-elses and in the end I have three or four different input functions all doing nearly the same. A better approach would be to define a function, that has default bindings for all keys but the bindings can be overwritten. I don't know if you want to go into the realms of elaborate user input but in case we could possibly share our code and solutions? If you like, I can post you my code. regards Michael # Send the main function through the curses.wrapper() function if __name__ == '__main__': curses.wrapper(main) # End of code Would this be correct? You are right. My little script looks like a bash script. You are also right in saying that this is just for starting. It's how I learned to program PHP. I would write my intial PHP script in one big file and see how I could make things more efficient by chopping things up into includes, functions, and classes. This approach unfortunately didn't help me with the curses.wrapper() function. Thanks again for your time, Alex From silviucc@home.ro Fri Jul 18 06:51:35 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Fri Jul 18 05:51:35 2003 Subject: [Tutor] OT: Admin suggestion: Add reply address to mailer In-Reply-To: <3F155C41.7000800@icon.co.za> Message-ID: On Wed, 16 Jul 2003, Quentin wrote: > All the lists I belong to have an auto reply address that will return > all replies back to the list, instead of to the original poster. Most > mailing list servers have this option. Is it possible for the Tutor list > to have it as well? > If this was a pre decided decision not to have a reply address, I'll > stand by it, else (elif? :) ), how do the other members feel about it? If you happen to use procmail for mail filtering you could easily alter the rule that filters the mail for this list so a "Reply-To: tutor@python.org" can be added (or superseded) with formail. I have something like this that seems to do the job: :0: * ^X-BeenThere: tutor@python.org | /usr/bin/formail -i "Reply-To: tutor@python.org" >> IN-S-Python -- Your mind understands what you have been taught; your heart, what is true. From andi@buxach.de Fri Jul 18 07:29:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Fri Jul 18 06:29:01 2003 Subject: [Tutor] simple threads program In-Reply-To: <3F179C23.7010504@myrealbox.com> References: <3F179C23.7010504@myrealbox.com> Message-ID: <20030622110935.7a4c52d2.andi@buxach.de> I didn't really read your script, i must admit, but here is the shortest usage of threading i can think of: import thread def my_thread(): # do second thread things ... pass thread.start_new_thread(my_thread, ()) # do first thread things ... pass Note: start_new() is obsolete, use start_new_thread() I'm not very experienced, but it works for me this way :) mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From kalle@lysator.liu.se Fri Jul 18 07:57:01 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Fri Jul 18 06:57:01 2003 Subject: [Tutor] simple threads program In-Reply-To: <20030622110935.7a4c52d2.andi@buxach.de> References: <3F179C23.7010504@myrealbox.com> <20030622110935.7a4c52d2.andi@buxach.de> Message-ID: <20030718105607.GE19374@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Andreas Zwinkau] > I didn't really read your script, i must admit, but here is the > shortest usage of threading i can think of: > > import thread ... You shouldn't really use the thread module unless you have a good reason to. Use threading instead. import threading class Thread1(threading.Thread): def run(self): # do thread 1 stuff. class Thread2(threading.Thread): def run(self): # do thread 2 stuff. t1 = Thread1() t2 = Thread2() t1.start() t2.start() Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) iD8DBQE/F9I4dNeA1787sd0RAh6hAJ9KJckSj+nB7yRznGRN61VT+OW/pgCgztBn XbKgyylWBrm4+71e9US4xQw= =eAWJ -----END PGP SIGNATURE----- From Jan.Wilhelmsen@bilia.no Fri Jul 18 08:29:02 2003 From: Jan.Wilhelmsen@bilia.no (Wilhelmsen Jan) Date: Fri Jul 18 07:29:02 2003 Subject: [Tutor] newbie question Message-ID: <9DB3344EC407D311A0A500508B0963E401DE32CB@ex84701.cars.no.bilia.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C34D1F.710DA370 Content-Type: text/plain Hi! I'm fairly new to programming so I have to ask a simple question. I have a text file witch contains some constants that I will use later when parsing some other text files. File 1: 40 444 60 380 68 950 70 950 What I have to do is to check to values in column 1(v1) against a value in another a text string(v2), if match then v1 = v2. I know have to do this by opening the file and do a search and then close the file. But since this check will occur numerous times I thought maybe it's better too read the file in memory once and that's it. Can I make sort of a "table" (t1) with objects (column1) that has a value(column2). Then check this "table" when parsing the other text file? Hope someone can give me some tip about this. Regards Jan Wilhelmsen ------------------------------------------------------------------------------- This verifies that this e-mail has been scanned for virus and deemed virus-free according to F-secure Content Scanner 5.0 Fri, 18 Jul 2003 13:26:33 +0200 GMT ------------------------------------------------------------------------------- ------_=_NextPart_001_01C34D1F.710DA370 Content-Type: text/html Content-Transfer-Encoding: quoted-printable

 

Hi!

 

I'm fairly new to programming so I have to ask a simple question.

 <= /font>

 <= /font>

I have a text file witch contains some constants that I will use later when parsing some other text files.

 <= /font>

File 1:<= /font>

 

40            444

60            380

68            950

70            950

 

 

 <= /font>

What I have to do is to c= heck to values in column 1(v1) against a value in another a text string(v2), if match then v1 =3D v2.

 <= /font>

I know have to do this by= opening the file and do a search and then close the file.<= /p>

 <= /font>

But since this check will= occur numerous times I thought maybe it's better too read the file in memory once and that's it.

 <= /font>

Can I make sort of a "tab= le" (t1) with objects (column1) that has a value(col= umn2).

 <= /font>

Then check this "table" when parsing the other text file?

Hope someone can give me = some tip about this.

 <= /font>

 <= /font>

Regards=

 <= /font>

Jan Wilhelmsen

 =



---------------------------------------------------------------------------= ----
This verifies that this e-mail has been scanned for virus and deemed virus-= free
according to F-secure Content Scanner 5.0
Fri, 18 Jul 2003 13:26:33 +0200 GMT
---------------------------------------------------------------------------= ----
------_=_NextPart_001_01C34D1F.710DA370-- From andi@buxach.de Fri Jul 18 08:52:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Fri Jul 18 07:52:01 2003 Subject: [Tutor] simple threads program In-Reply-To: <20030718105607.GE19374@i92.ryd.student.liu.se> References: <3F179C23.7010504@myrealbox.com> <20030622110935.7a4c52d2.andi@buxach.de> <20030718105607.GE19374@i92.ryd.student.liu.se> Message-ID: <20030718135010.6f3abac6.andi@buxach.de> > You shouldn't really use the thread module unless you have a good > reason to. Use threading instead. What's the difference? threading.start_new_thread() is also available, may i use this? Any good tutorials/examples? mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From roypython@hotmail.com Fri Jul 18 08:56:35 2003 From: roypython@hotmail.com (roy ollis) Date: Fri Jul 18 07:56:35 2003 Subject: [Tutor] where to buy python books in phoenix az Message-ID:
i have been looking all over phoenix for python books.  i dont have a credit card so that prohibits online purchases.  can anyone tell me a good bookstore  for computerbooks in phoenix.  i have been directed to zooology every time i ask for python books at the major chains, and for b daltons sake i wont tell the name that when i said "its a computer language like java" they led me to cooking books.  i wish programming was as easy to learn as making coffee.  one scoop, a pot of water, and let the machine do the rest.  if anyone knows where i can get the books with cash (or a self programming and teaching computer, just kidding before i get told the obviouse) i will be grateful. i will even send money now and wait for the book if it's from a name i know like amazon.  thanks for any help you can give me. 


Protect your PC - Click here for McAfee.com VirusScan Online From saf@scottfallin.com Fri Jul 18 10:20:03 2003 From: saf@scottfallin.com (Scott Fallin) Date: Fri Jul 18 09:20:03 2003 Subject: [Tutor] parsing x is y statements from stdin Message-ID: Hi Danny, Thank you so much for your reply. Below are code snippets from the bot I wrote in Perl. I know that I should be ashamed to be using a lowly bot to help me better understand Python, but strangely, I am not ;) (Thank you for the tip on Monty Tagger. It looks neat.) Ok, here goes... #--- begin code snippet ----- sub parseChatter { my($msgType, $statement) = @_; $statement =~ s/\\(\s+)/\#$1\#/g; my($left, $middle, $right) foreach $thing (@verb) { if ($statement =~ /(^|\s)$thing(\s|$)/i) { ($left, $middle, $right) = ($`, $&, $'); $left =~ tr/Z-Z/a-z/l $left =~ s/^\s*(.*?)\s*$/$1/; $middle =~ s/^\s*(.*?)\s*$/$1/; $right =~ s/^\s*(.*?)\s*$/$1/; return '' unless ($left and $right); # some $msgType matching along with len checking # some more cartoon swearword-ish pattern matching is done to # to match verbs, strip of punctuation, etc. # e.g. if $middle is the verb "is", our entry gets queued up # to be put in the "is" database (eg. 'scott is a poor python' # programmer is inserted as 'scott => a poor python programmer') # and 'scott' is used as the key for future lookups } } } I want to do the same thing in Python, well, I want to achieve the same goal: parse stdin on an irc channel, do a bit of regex to pull out "she is ..."/"they are ..." statements. I've tried using: line = sys.stdin.readline() print line but of course the script never progresses past the readline() call. I'm rather certain all of stdin is being put into 'line' but it never gets to execute the print statement. I'm wondering if I can't treat each line of stdin as a list where list [0] is the key, list[1] is the verb, list[2] is the right hand side 'target'. I'm just completely unsure of how to go about doing that. Thank you for your time and consideration :) Scott. #--- end code snippet ---- >Hi Scott, >Can you show us how you're doing it in Perl? We'll be happy to help >you >apply your knowledge of Perl to better understand how to do it in >Python. >By the way, you may be interested in a module called 'Monty Tagger': >>On Thu, 17 Jul 2003, Scott Fallin wrote: >> I'm trying to figure out how best to parse a string such as "It is hot >> today". I want to check for the existance of a predefined verb that >> will always be located in the middle of the sentence, and if the verb >> test passes, I want to chop the sentence up in to variables, var1 = >> 'It', var2 = 'is', and var3 = "hot today". >> >> I can do it in Perl but for some reason it is elluding me in Python. From ATrautman@perryjudds.com Fri Jul 18 10:59:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri Jul 18 09:59:02 2003 Subject: [Tutor] where to buy python books in phoenix az Message-ID: <06738462136C054B8F8872D69DA140DB010851@corp-exch-1.pjinet.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C34D34.9AF4D2C0 Content-Type: text/plain; charset="iso-8859-1" I our local (central WI) Borders and B & N get out of the windows section of computers. The section you are looking for will have a huge number of JAVA books, some stuff I can't think of a good size Perl section and usually a dozen or so different Python books. I hate to say it but Perl is most reliable way to find Python:) Come to think about it, is was Perl that convinced me to pick Python...... HTH, Alan From: roy ollis [mailto:roypython@hotmail.com] Sent: Friday, July 18, 2003 6:55 AM To: tutor@python.org Subject: [Tutor] where to buy python books in phoenix az i have been looking all over phoenix for python books. i dont have a credit card so that prohibits online purchases. can anyone tell me a good bookstore for computerbooks in phoenix. i have been directed to zooology every time i ask for python books at the major chains, and for b daltons sake i wont tell the name that when i said "its a computer language like java" they led me to cooking books. i wish programming was as easy to learn as making coffee. one scoop, a pot of water, and let the machine do the rest. if anyone knows where i can get the books with cash (or a self programming and teaching computer, just kidding before i get told the obviouse) i will be grateful. i will even send money now and wait for the book if it's from a name i know like amazon. thanks for any help you can give me. _____ Protect your PC - Click here for McAfee.com VirusScan Online _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ------_=_NextPart_001_01C34D34.9AF4D2C0 Content-Type: text/html; charset="iso-8859-1"
I our local (central WI) Borders and B & N get out of the windows section of computers. The section you are looking for will have a huge number of JAVA books, some stuff I can't think of a good size Perl section and usually a dozen or so different Python books.
 
I hate to say it but Perl is most reliable way to find Python:) Come to think about it, is was Perl that convinced me to pick Python......
 
HTH,
Alan

 
 From: roy ollis [mailto:roypython@hotmail.com]
Sent: Friday, July 18, 2003 6:55 AM
To: tutor@python.org
Subject: [Tutor] where to buy python books in phoenix az

i have been looking all over phoenix for python books.  i dont have a credit card so that prohibits online purchases.  can anyone tell me a good bookstore  for computerbooks in phoenix.  i have been directed to zooology every time i ask for python books at the major chains, and for b daltons sake i wont tell the name that when i said "its a computer language like java" they led me to cooking books.  i wish programming was as easy to learn as making coffee.  one scoop, a pot of water, and let the machine do the rest.  if anyone knows where i can get the books with cash (or a self programming and teaching computer, just kidding before i get told the obviouse) i will be grateful. i will even send money now and wait for the book if it's from a name i know like amazon.  thanks for any help you can give me. 


Protect your PC - Click here for McAfee.com VirusScan Online _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
------_=_NextPart_001_01C34D34.9AF4D2C0-- From klappnase@freenet.de Fri Jul 18 11:10:23 2003 From: klappnase@freenet.de (klappnase@freenet.de) Date: Fri Jul 18 10:10:23 2003 Subject: [Tutor] parsing x is y statements from stdin Message-ID: DQotLS0gb3JpZ2luYWwgTmFjaHJpY2h0IEVuZGUgLS0tLQ0KDQoNCkknbSB0cnlpbmcgdG8gZmln dXJlIG91dCBob3cgYmVzdCB0byBwYXJzZSBhIHN0cmluZyBzdWNoIGFzICJJdCBpcyBob3QgdG9k YXkiLiAgSSB3YW50IHRvIGNoZWNrIGZvciB0aGUgZXhpc3RhbmNlIG9mIGEgcHJlZGVmaW5lZCB2 ZXJiIHRoYXQgd2lsbCBhbHdheXMgYmUgbG9jYXRlZCBpbiB0aGUgbWlkZGxlIG9mIHRoZSBzZW50 ZW5jZSwgYW5kIGlmIHRoZSB2ZXJiIHRlc3QgcGFzc2VzLCBJIHdhbnQgdG8gY2hvcCB0aGUgc2Vu dGVuY2UgdXAgaW4gdG8gdmFyaWFibGVzLCB2YXIxID0gJ0l0JywgdmFyMiA9ICdpcycsIGFuZCB2 YXIzID0gImhvdCB0b2RheSIuDQoNCkkgY2FuIGRvIGl0IGluIFBlcmwgYnV0IGZvciBzb21lIHJl YXNvbiBpdCBpcyBlbGx1ZGluZyBtZSBpbiBQeXRob24uDQoNCkFueSBsaWdodCBzaGVkIHdvdWxk IGJlIG11Y2ggYXBwcmVjaWF0ZWQuDQoNCnMuDQoNCkhpLA0KbWF5IGJlIHlvdSBjb3VsZCBkbyBz b21ldGhpbmcgbGlrZToNCg0KbXlzdHJpbmcgPSAiSXQgaXMgaG90IHRvZGF5Ig0KeCA9IG15c3Ry aW5nLnNwbGl0KCkNCmlmIHByZWRlZmluZWR2ZXJiIGluIHg6DQogICAgdmFyMSA9IHhbMF0NCiAg ICB2YXIyID0geFsxXQ0KICAgIHZhcjMgPSB4Wy0yXSArICIgIiArIHhbLTFdDQoNCk9yIGRvZXNu tCd0IHRoaXMgbWF0Y2ggeW91ciBwcm9ibGVtPw0KDQpNaWNoYWVsDQoNCl9fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fDQpUdXRvciBtYWlsbGlzdCAgLSAgVHV0 b3JAcHl0aG9uLm9yZw0KPGEgaHJlZj0naHR0cDovL21haWwucHl0aG9uLm9yZy9tYWlsbWFuL2xp c3RpbmZvL3R1dG9yJyB0YXJnZXQ9J19ibGFuayc+PHU+aHR0cDovL21haWwucHl0aG9uLm9yZy9t YWlsbWFuL2xpc3RpbmZvL3R1dG9yPC91PjwvYT4NCgoKCi0tIAplQmF5IC0gSmV0enQgYmVzc2Vy IGVpbmthdWZlbiEKVWViZXIgMS4gTWlvLiBBbmdlYm90ZS4gU3RhcnRwcmVpc2UgYWIgPyAxLC0K aHR0cDovL3d3dy5mcmVlbmV0LmRlL3RpcHAvc2hvcHBpbmcvZWJheQ== From bwinton@latte.ca Fri Jul 18 11:17:00 2003 From: bwinton@latte.ca (Blake Winton) Date: Fri Jul 18 10:17:00 2003 Subject: [Tutor] parsing x is y statements from stdin In-Reply-To: Message-ID: <000001c34d37$4c5d9f90$6401a8c0@phantomfiber.com> > I'm wondering if I can't treat each line of stdin as a list where list > [0] is the key, list[1] is the verb, list[2] is the right hand > side 'target'. I'm just completely unsure of how to go about doing > that. Here's what I did, so that you can see my train of thought. (If you're using an earlier version of Python, and you can't copy the following example, email me, and I'll show you the backwards- compatible way to do it.) Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x = "He is a python programmer" >>> help( x.split ) Help on built-in function split: split(...) S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. >>> x.split( 3 ) Traceback (most recent call last): File "", line 1, in ? TypeError: expected a character buffer object >>> x.split( None, 3 ) ['He', 'is', 'a', 'python programmer'] >>> x.split( None, 2 ) ['He', 'is', 'a python programmer'] >>> import sys >>> x = sys.stdin.readline() You get the idea now. >>> x.split( None, 2 ) ['You', 'get', 'the idea now.\n'] >>> help( x.strip ) Help on built-in function strip: strip(...) S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping >>> x.strip().split( None, 2 ) ['You', 'get', 'the idea now.'] How does that look to you? Mostly what you wanted? Later, Blake. From sigurd@12move.de Fri Jul 18 12:17:02 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Jul 18 11:17:02 2003 Subject: [Tutor] newbie question In-Reply-To: <9DB3344EC407D311A0A500508B0963E401DE32CB@ex84701.cars.no.bilia.net> (Wilhelmsen Jan's message of "Fri, 18 Jul 2003 13:26:33 +0200") References: <9DB3344EC407D311A0A500508B0963E401DE32CB@ex84701.cars.no.bilia.net> Message-ID: On 18 Jul 2003, Wilhelmsen Jan <- Jan.Wilhelmsen@bilia.no wrote: > I have a text file witch contains some constants that I will use later when > parsing some other text files. > File 1: > 40 444 > 60 380 > 68 950 > 70 950 > What I have to do is to check to values in column 1(v1) against a value in > another a text string(v2), if match then v1 = v2. Can you show with a littlem example what you exactly want to achieve. Are the values in v2 strings which contain v1 as substring? What happens with column 2 of your example? You don't semm to need it; you mention only column1 (== v1) and the value in the second text file (== v2). Is that value also in column 1? > I know have to do this by opening the file and do a search and then close > the file. > But since this check will occur numerous times I thought maybe it's better > too read the file in memory once and that's it. > Can I make sort of a "table" (t1) with objects (column1) that has a > value(column2). Yes. > Then check this "table" when parsing the other text file? > Hope someone can give me some tip about this. Python has a builtin sequence type called dictionary (a hash table). Perhaps you could use it (you don't say if the order of the entries matters (if yes a dictionary won't help)). To build the dictionary you could simple open the file read the lines and use the first value as key and the second as value of the dictionary. Like that eg: >>> table = {} >>> f = open("file", "r") >>> for line in f: ... line = line.split() ... table[line[0]] = line[1] ... >>> table {'60': '380', '68': '950', '40': '444', '70': '950'} >>> Now you have a dictionary where column 1 of your file acts as key and column 2 is the value. Now to the check You should give a little example first what you exactly like to achieve otherwise it's not easy to help you. Karl -- Please do *not* send copies of replies to me. I read the list From SWidney@ci.las-vegas.nv.us Fri Jul 18 13:20:03 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Jul 18 12:20:03 2003 Subject: [Tutor] where to buy python books in phoenix az Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86B1@sovereign.ci.las-vegas.nv.us> > i have been looking all over phoenix for python books. i > dont have a credit card so that prohibits online purchases. > can anyone tell me a good bookstore for computerbooks in > phoenix. i have been directed to zooology every time i ask > for python books at the major chains, and for b daltons sake > i wont tell the name that when i said "its a computer > language like java" they led me to cooking books. i wish > programming was as easy to learn as making coffee. one > scoop, a pot of water, and let the machine do the rest. if > anyone knows where i can get the books with cash (or a self > programming and teaching computer, just kidding before i get > told the obviouse) i will be grateful. i will even send money > now and wait for the book if it's from a name i know like > amazon. thanks for any help you can give me. You're looking for computer books and you mention book stores you've visited. Have you tried any coputer stores? It looks like CompUSA has five stores in the area; one of them may have what you're looking for. Also, if you go into a book store with a title in hand, at the very least, they can order it for you. You don't have to pay anything until the book arrives. And if you change your mind, most places just put the book on a shelf for someone else to pick up. Research your purchase online (you don't need a credit card to browse) then take your choice(s) to the brick-and-mortar. From saf@scottfallin.com Fri Jul 18 13:42:02 2003 From: saf@scottfallin.com (Scott Fallin) Date: Fri Jul 18 12:42:02 2003 Subject: [Tutor] parsing x is y statements from stdin Message-ID: Michael and Blake, Thank you both for your suggestions. They'll do the trick! I appreciate it very much. s. > > I'm wondering if I can't treat each line of stdin as a list where list > > [0] is the key, list[1] is the verb, list[2] is the right hand > > side 'target'. I'm just completely unsure of how to go about doing > > that. > > Here's what I did, so that you can see my train of thought. > (If you're using an earlier version of Python, and you can't copy > the following example, email me, and I'll show you the backwards- > compatible way to do it.) > > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> x = "He is a python programmer" > >>> help( x.split ) > Help on built-in function split: > > split(...) > S.split([sep [,maxsplit]]) -> list of strings > > Return a list of the words in the string S, using sep as the > delimiter string. If maxsplit is given, at most maxsplit > splits are done. If sep is not specified or is None, any > whitespace string is a separator. > > >>> x.split( 3 ) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: expected a character buffer object > >>> x.split( None, 3 ) > ['He', 'is', 'a', 'python programmer'] > >>> x.split( None, 2 ) > ['He', 'is', 'a python programmer'] > > > >>> import sys > >>> x = sys.stdin.readline() > You get the idea now. > >>> x.split( None, 2 ) > ['You', 'get', 'the idea now.\n'] > >>> help( x.strip ) > Help on built-in function strip: > > strip(...) > S.strip([chars]) -> string or unicode > > Return a copy of the string S with leading and trailing > whitespace removed. > If chars is given and not None, remove characters in chars instead. > If chars is unicode, S will be converted to unicode before stripping > >>> x.strip().split( None, 2 ) > ['You', 'get', 'the idea now.'] > > How does that look to you? Mostly what you wanted? > > Later, > Blake. > > > -- From jeff@ccvcorp.com Fri Jul 18 13:42:15 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Jul 18 12:42:15 2003 Subject: [Tutor] simple threads program References: <3F179C23.7010504@myrealbox.com> <20030622110935.7a4c52d2.andi@buxach.de> <20030718105607.GE19374@i92.ryd.student.liu.se> <20030718135010.6f3abac6.andi@buxach.de> Message-ID: <3F18234B.1090202@ccvcorp.com> Andreas Zwinkau wrote: >>You shouldn't really use the thread module unless you have a good >>reason to. Use threading instead. >> >> >What's the difference? >threading.start_new_thread() is also available, may i use this? >Any good tutorials/examples? > The difference is the threading.Thread class, which handles most of the low-level thread management work for you. Multithreading using threading.Threads is typically a matter of creating a subclass of Thread which has a run() function that does your work, creating an instance of that subclass, and calling that instance's start() method. You should also look into using Queue.Queue for any inter-thread communication. Queues are a dead-simple and thread-safe way to pass data back and forth. Read the docstrings in the threading and Queue modules for a little more detail. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Fri Jul 18 15:31:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 18 14:31:02 2003 Subject: [Tutor] simple threads program In-Reply-To: <20030718191147.2b04b3fd.thomi@thomi.imail.net.nz> References: <3F179C23.7010504@myrealbox.com> <3F179C23.7010504@myrealbox.com> Message-ID: <5.2.1.1.0.20030718203404.020d0528@www.thinkware.se> At 19:11 2003-07-18 +1200, Thomas CLive Richards wrote: >surely if the downloading take up most of the time, this would mean that >you're on a fairly slow connection? I have a fast connection (10Mbps) and for me, downloads are always slower than my local connection would allow. Parallel downloads certainly makes sense. -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From magnus@thinkware.se Fri Jul 18 15:33:01 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 18 14:33:01 2003 Subject: [Tutor] simple threads program In-Reply-To: <20030718135010.6f3abac6.andi@buxach.de> References: <20030718105607.GE19374@i92.ryd.student.liu.se> <3F179C23.7010504@myrealbox.com> <20030622110935.7a4c52d2.andi@buxach.de> <20030718105607.GE19374@i92.ryd.student.liu.se> Message-ID: <5.2.1.1.0.20030718203823.020be1b0@www.thinkware.se> At 13:50 2003-07-18 +0200, Andreas Zwinkau wrote: >What's the difference? >threading.start_new_thread() is also available, may i use this? >Any good tutorials/examples? http://starship.python.net/crew/aahz/OSCON2001/index.html -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From gyromagnetic@excite.com Fri Jul 18 15:38:05 2003 From: gyromagnetic@excite.com (gyro funch) Date: Fri Jul 18 14:38:05 2003 Subject: [Tutor] word challenge Message-ID: <20030718183717.4C29D133F5@xmxpita.excite.com> Hi, I thought that this might be an interesting challenge for those of you with a 'puzzling' disposition. ;-) Suppose I have a phrase from which I want to extract a word made up of at least one letter from each of the words (more than one letter may be taken from each word if desired). The letters must be aligned in the order in which they were taken from the words. For instance, if I have the phrase: "handy cool phrase" I might extract the "h" from "handy", one "o" from "cool", and the "r","s",and "e" from "phrase" to give "horse". Each word must exist in some defined dictionary or word list. I'm looking for an efficient (and/or clever) implementation in Python of some algorithm satisfying these requirements. I am coding my own solution, but I am interested in what other people come up with as well. Thanks and have fun. -g _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From silviucc@home.ro Fri Jul 18 15:58:05 2003 From: silviucc@home.ro (Silviu Cojocaru) Date: Fri Jul 18 14:58:05 2003 Subject: [Tutor] word challenge In-Reply-To: <20030718183717.4C29D133F5@xmxpita.excite.com> Message-ID: On Fri, 18 Jul 2003, gyro funch wrote: > I am coding my own solution, but I am interested in what other people > come up with as well. Well, you could have a file with all (or a lot of) words from a dictionary and then use some kind of backtracking algo to generate words and compare them to what you have in the dictionary file. Or, to make it faster (and more RAM hungry :) you put all the words (or the most common ones) from the dictionary in a list o strings. Sort that list. Take a letter from the first word, try to match words that are in the dictionary that begin with that letter. The a letter from the second word, and match a word in the dictionary that starts with these two letters and so on. Just an idea (slow one ? :) -- There are twenty-five people left in the world, and twenty-seven of them are hamburgers. -- Ed Sanders From zak@harlekin-maus.com Fri Jul 18 16:10:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Jul 18 15:10:02 2003 Subject: [Tutor] word challenge In-Reply-To: <20030718183717.4C29D133F5@xmxpita.excite.com> References: <20030718183717.4C29D133F5@xmxpita.excite.com> Message-ID: <2314.192.206.201.106.1058555354.squirrel@mail.harlekin-maus.com> > Suppose I have a phrase from which I want to extract a word made up of > at least one letter from each of the words (more than one letter may be > taken from each word if desired). The letters must be aligned in the > order in which they were taken from the words. > -g * Which word do we pick from the phrase? All valid words in the word list? * Verification: Each word in the phrase must provide one or more letters, in the order that they appear in the phrase, to the found word? --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From vicki@thepenguin.org Fri Jul 18 16:15:02 2003 From: vicki@thepenguin.org (Vicki Stanfield) Date: Fri Jul 18 15:15:02 2003 Subject: [Tutor] General object-oriented procedure question Message-ID: <49551.206.53.226.4.1058555696.squirrel@www.thepenguin.org> I have a program that has several classes, each with multiple functions defined. I have mapped my way through enough to basically understand the flow of things, but I am not sure what happens when it finishes the mainloop (standard garden-variety mainloop). Say for instance that one of the classes includes a button that I press to initiate some sequence of activities. I finish the sequence fine, but then I get back to the class and the program hangs. I have a pulldown menu which includes an exit, and that works, but what if I simply want to end after the button activity ceases. How do I do that? I've inserted print statements after the mainloop call, but they are never reached unless I exit from the menu. I need to add something to the end of the mainloop to end when finished, but I am unsure where to insert it or exactly what to insert. I tried "return true", but that didn't work. --vicki From gyromagnetic@excite.com Fri Jul 18 16:23:01 2003 From: gyromagnetic@excite.com (gyro funch) Date: Fri Jul 18 15:23:01 2003 Subject: [Tutor] word challenge Message-ID: <20030718192228.641E21E413@xmxpita.excite.com> Hi Zak, >>* Which word do we pick from the phrase? All valid words in the >>word list? All words from the phrase must be used to 'donate' letters. The words in the phrase don't have to be in the wordlist. >>* Verification: Each word in the phrase must provide one or more >>letters, >>in the order that they appear in the phrase, to the found word? Yes. Thanks for responding. -g _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From zak@harlekin-maus.com Fri Jul 18 16:57:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Jul 18 15:57:01 2003 Subject: [Tutor] word challenge In-Reply-To: <20030718192228.641E21E413@xmxpita.excite.com> References: <20030718192228.641E21E413@xmxpita.excite.com> Message-ID: <2842.192.206.201.106.1058558169.squirrel@mail.harlekin-maus.com> > Hi Zak, > >>>* Which word do we pick from the phrase? All valid words in the >>word >>> list? > > All words from the phrase must be used to 'donate' letters. The words in > the phrase don't have to be in the wordlist. > > -g Oops. I meant to ask: * Of all possible discovered words from the phrase's own words, which do we pick? All of them? --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From abli@freemail.hu Fri Jul 18 17:03:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Fri Jul 18 16:03:02 2003 Subject: [Tutor] General object-oriented procedure question In-Reply-To: <49551.206.53.226.4.1058555696.squirrel@www.thepenguin.org> References: <49551.206.53.226.4.1058555696.squirrel@www.thepenguin.org> Message-ID: <20030718200204.GA10207@hooloovoo> > I have a program that has several classes, each with multiple functions > defined. I have mapped my way through enough to basically understand the > flow of things, but I am not sure what happens when it finishes the > mainloop (standard garden-variety mainloop). You mean tkinter mainloop? Please explicitly mention tkinter when your problem has something to do with it, as there are several graphical bindings for python, and most likely several modules that have mainloops. I'll assume that you are using tkinter. > Say for instance that one of > the classes includes a button that I press to initiate some sequence of > activities. I finish the sequence fine, but then I get back to the class > and the program hangs. Hangs in what sence? The gui becomes unresponsive, you can't click on any widget, and if you cover the window with something else ad re-expose it it doesn't get redrawn? Post a 'working' example. (where 'working' means shows the problem, so it might be better to call it 'broken' :) ) > I have a pulldown menu which includes an exit, and > that works, but what if I simply want to end after the button activity > ceases. How do I do that? What do you mean 'button activity ceases'? After you release a button on the keyboard? Then bind to the KeyRelease event, and call the quit() method of a widget from the event callback. > I've inserted print statements after the > mainloop call, but they are never reached unless I exit from the menu. In tkinter you set up your app, call mainloop, and from then on most of the time is spent in the mainloop which does all the houskeeping stuff (reedrawing the screen when needed, handling keypresses, etc.) and calls your event callbacks occasionally. Your event callbacks return to the mainloop. When you exit the mainloop, the gui is teared down, and your graphical widgets are gone. Most likely you don't want to do anything after the mainloop. What are you trying to achieve? > I need to add something to the end of the mainloop to end when finished, > but I am unsure where to insert it or exactly what to insert. I think the mainloop can be ended by two things: you explicitly end it, with, say the .quit() method of a widget or the window manager closes the app down. (The user closes the window by clicking the icon in the titlebar.) In the first case, you simply add your code to immedatelly before that call to the .quit() method. In the second case, the app is actually sent a message from the windowmanager to close itself. (At least thats my understanding of who the thing works.) You can 'intercept' this by using the .protocol() method of the root window. See http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm (near the bottom) Abel Daniel From gyromagnetic@excite.com Fri Jul 18 17:04:03 2003 From: gyromagnetic@excite.com (gyro funch) Date: Fri Jul 18 16:04:03 2003 Subject: [Tutor] word challenge Message-ID: <20030718200309.0A4B9F699@xmxpita.excite.com> Hi Zak, >>Oops. I meant to ask: >>* Of all possible discovered words from the >> phrase's own words, which do we pick? All of them? Yes, we want a list of all of them. This list can then be paired down based on some criterion (shortest, longest, etc.) -g _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From exnihilo@myrealbox.com Fri Jul 18 17:19:18 2003 From: exnihilo@myrealbox.com (calvin) Date: Fri Jul 18 16:19:18 2003 Subject: [Tutor] simple threads program In-Reply-To: <20030718191147.2b04b3fd.thomi@thomi.imail.net.nz> References: <3F179C23.7010504@myrealbox.com> <20030718191147.2b04b3fd.thomi@thomi.imail.net.nz> Message-ID: <3F18559F.8070506@myrealbox.com> Thomas CLive Richards wrote: >>I would like to download and save a bunch of pages, and since the >>download is most of the time, it seems like a good candidate for >>speedup using threads. >> >> >> > >I'm not going to comment on the code (because i can't), but your example >seems a little wierd... > >surely if the downloading take up most of the time, this would mean that >you're on a fairly slow connection? perhaps dialup? If so, how would >having multiple threads speed it up? OK, so there would be a slight >speed increase, but you can't download 3 times as much by having 3 >separate downloads; they'll just be coming down at 1/3 the speed.... > No. I mean that downloading takes most of the time, because the cpu work is very little. I have broadband, and I rarely use close to my download capacity for any 1 single download, so downloading simultaneously is indeed faster than downloading sequentially. > >When i used threads, i just followed the documentation in the threading >module, and it worked just fine ;) > > > thanks, that's helpful ;-) -calvin From magnus@thinkware.se Fri Jul 18 17:44:02 2003 From: magnus@thinkware.se (Magnus =?iso-8859-1?Q?Lyck=E5?=) Date: Fri Jul 18 16:44:02 2003 Subject: [Tutor] parsing x is y statements from stdin In-Reply-To: Message-ID: <5.2.1.1.0.20030718221929.020b9ec0@www.thinkware.se> At 13:19 2003-07-18 +0000, Scott Fallin wrote: >I want to do the same thing in Python, well, I want to achieve the same >goal: parse stdin on an irc channel, do a bit of regex to pull out "she >is ..."/"they are ..." statements. This works for me: import sys verbs = "is am are have has feel feels".split() d = {} for line in sys.stdin: line = line.lower() for verb in verbs: space_verb = " %s " % verb if space_verb in line: who, what = line.split(space_verb, 2) d.setdefault(verb, {}).setdefault( who.strip(), []).append(what.strip()) for verb in d: for who in d[verb]: print who, verb for what in d[verb][who]: print '\t%s' % what print I'll go through it in some detail: import sys # Needed to access sys.stdin verbs = "is am are have has feel feels".split() # A bit more conveinent to type than # verbs = ["is", "am", ...] d = {} # I magine this dictionary will eventually contain # something like: # d = {'is': {'dog': ['lazy', 'stupid'], 'cat': ['sleepy']}, # 'has': {'bill': ['money'], 'linus': ['respect']} } # Note the lists! They are needed to allow several sentences # with the same subject and verb. for line in sys.stdin: # Iterating directly over a file object is the same as readline() # in recent Python versions line = line.lower() # Make it all lower case. If you don't want this, the splitting will # probably be a little more complicated. for verb in verbs: # Iterate over the list of verbs space_verb = " %s " % verb # I assume the verbs are surrounded by space, and I don't want # to find the "is" in "disk" when I look for verbs. if space_verb in line: #Ok, we found the current verb in this sentence who, what = line.split(space_verb, 2) # Split the line on the verb, but don't split in more # than two parts. E.g. "he is what he is" should return # ('he', 'what he is'), not ('he', 'what he', '') d.setdefault(verb, {}).setdefault( who.strip(), []).append(what.strip()) # This is obviously the tricky part... # First of all, it could be rewritten like: # who = who.strip() # remove leading/trailing whitespace # what = what.strip() # remove leading/trailing whitespace # d_verb = d.setdefault(verb, {}) # d_verb_who = d_verb.setdefault(who, []) # d_verb_who.append(what) # but if you don't understand .setdefault(), that won't make # you a lot wiser... # d.setdefault(x,y) means: Return d[x] if it exists, otherwise # let d[x] = y and then return d[x]. This methods was created # since code like the following was so common in Python code # if not d.has_key(x): # d[x] = [] # d[x].append(y) # I think you figure out the rest... for verb in d: for who in d[verb]: print who, verb for what in d[verb][who]: print '\t%s' % what print -- Magnus Lycka (It's really Lyckå), magnus@thinkware.se Thinkware AB, Sweden, www.thinkware.se I code Python ~ The Agile Programming Language From hall@ouhep1.nhn.ou.edu Fri Jul 18 18:46:35 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Fri Jul 18 17:46:35 2003 Subject: [Tutor] word challenge In-Reply-To: <20030718200309.0A4B9F699@xmxpita.excite.com> Message-ID: Ok, so I can think of a couple of ways of going about this. They would probably vary in speed depending on the length of the dictionary file, and the phrase. 1)loop over every letter in the phrase. Inside this loop, loop over all dictionary words beginning with this letter. first check that the letters after the current letter are enough to make the current word, if that passes, check that all the letters in the current word are after the current letter. if that passes, check that they are in the correct order, if so, we have a word that works. 2)check every possible combination that COULD be a word against the dictionary. This method would grow VERY fast with length of phrase I think however. Ike On Fri, 18 Jul 2003, gyro funch wrote: > > Hi Zak, > > >>Oops. I meant to ask: > >>* Of all possible discovered words from the > >> phrase's own words, which do we pick? All of them? > > Yes, we want a list of all of them. > This list can then be paired down based on some criterion (shortest, longest, etc.) > > -g > > _______________________________________________ > Join Excite! - http://www.excite.com > The most personalized portal on the Web! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From sigurd@12move.de Fri Jul 18 19:07:01 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Jul 18 18:07:01 2003 Subject: [Tutor] word challenge In-Reply-To: <20030718183717.4C29D133F5@xmxpita.excite.com> (gyro funch's message of "Fri, 18 Jul 2003 14:37:17 -0400 (EDT)") References: <20030718183717.4C29D133F5@xmxpita.excite.com> Message-ID: On 18 Jul 2003, gyro funch <- gyromagnetic@excite.com wrote: > Hi, I thought that this might be an interesting challenge for those of > you with a 'puzzling' disposition. ;-) Yes it was very funny. I have a possible solution. Don't know if it's very pythonesque but I like it. > Suppose I have a phrase from which I want to extract a word made up of > at least one letter from each of the words (more than one letter may > be taken from each word if desired). The letters must be aligned in > the order in which they were taken from the words. > For instance, if I have the phrase: "handy cool phrase" I might > extract the "h" from "handy", one "o" from "cool", and the "r","s",and > "e" from "phrase" to give "horse". > Each word must exist in some defined dictionary or word list. I started playing like that: phrase = 'handy cool phrase' phrasewos = ''.join(phrase.split()).split() seq = range(len(phrasewos)) So I had now a sequence where each digit represented an index to our word list. To shuffle it I used list comprehension: [[x,y,z] \ for x in seq \ for y in seq[x+1:] \ for z in seq[y+1:]] So far so good but how could I build a function for a arbitrary number of chars? I let Python write it. So here comes my solution: --8<---------------cut here---------------start------------->8--- def shuffle_words(number, phrase): phrase = ''.join(phrase.split()) seq = range(len(phrase)) seq = eval(build_fun(number)) words = [] for word in seq: wort = '' for index in word: wort += phrase[index] words.append(wort) return words def build_fun(number): vals = '[[a0, ' fun = 'for a0 in seq ' for i in range(1, number): vals += 'a' + str(i) + ', ' fun += 'for ' 'a' + str(i) + ' in seq[' + 'a' + str(i-1) + '+1:]' vals += '] ' fun += ']' return vals + fun def filter_words(seq, dict): filter(lambda x: dict.has_key(x), seq) --8<---------------cut here---------------end--------------->8--- `build_fun' is a function which creates a string (our list comprehension) `shuffle_words' takes our phrase and a number (the length of our words) and builds all possible combinations according to our rules and returns them in a list. `filter_words' takes that list and a dictionary (the dictionary has existing words as keys) and returns a list with the words found in the dictionary. Here an example: >>> d = {'has': None, 'had': None} >>> seq = shuffle_words(3, phrase) >>> filter(lambda x: d.has_key(x), seq) ['had', 'has', 'has', 'has'] >>> As we see at the moment words which are multiple times in the list are also multiple times returned; this may be what we want or not. But that's easy to change. Karl -- Please do *not* send copies of replies to me. I read the list From python@rcn.com Sat Jul 19 03:35:02 2003 From: python@rcn.com (Raymond Hettinger) Date: Sat Jul 19 02:35:02 2003 Subject: [Tutor] word challenge References: <20030718183717.4C29D133F5@xmxpita.excite.com> Message-ID: <00cc01c34dba$5b2038c0$8bb82c81@oemcomputer> ----- Original Message ----- From: "gyro funch" To: Sent: Friday, July 18, 2003 2:37 PM Subject: [Tutor] word challenge > > Hi, > I thought that this might be an interesting challenge for those of you with a 'puzzling' disposition. ;-) > > Suppose I have a phrase from which I want to extract a word made up of at least one letter from each of the words (more than one letter may be taken from each word if desired). The letters must be aligned in the order in which they were taken from the words. > > For instance, if I have the phrase: "handy cool phrase" > I might extract the "h" from "handy", one "o" from "cool", and the "r","s",and "e" from "phrase" to give "horse". Since the number of paths through the phrase is very large, a good bet is to start with a dictionary of available words and test to see if they can be found in the phrase (while paying attention to letter order and the requirement that each group be represented). For speed, there are three quick tests to narrow down the field: * the first letter should be in the first group * the last letter should be in the last group * each letter must be in the set of letters in the groups After ruling out words that don't pass the three tests, the next step is to find possible paths through phrase. Some of the complexities and backtracking are illustrated by the test: "hot" in "hoo ot otel" A recursive algorithm is used. To find where a word is in the remaining phrase starting from a given position and group, only the first letter is checked to see if it is in the current group or next group. If so, the remainder of the word is checked starting at the next matching group and position. If that doesn't word out, other instances of the first letter are checked for until there are no more in the current or next group. class Phrase: def __init__(self, s): self.words = s.split() self.first = dict.fromkeys(self.words[0]) self.last = dict.fromkeys(self.words[-1]) self.charmap = {} self.conseq = [] self.group = [] for i, word in enumerate(self.words): for char in word: self.charmap.setdefault(char, []).append(i) self.conseq.append(char) self.group.append(i) self.conseq = ''.join(self.conseq) self.topgroup = len(self.words)-1 def __contains__(self, word): if word[0] not in self.first: return False if word[-1] not in self.last: return False for char in word[1:-1]: if char not in self.charmap: return False return self.paths(word) def paths(self, word, startpos=0, group=0): #print word, startpos, group if not word: return group == self.topgroup char = word[0] i = startpos-1 while 1: i = self.conseq.find(char, i+1) if i < 0: return False g = self.group[i] if g > group + 1: return False if g == group and self.paths(word[1:], i+1, group): return True if g == group+1 and self.paths(word[1:], i+1, group+1): return True P = Phrase("handy cool phrase") print 'horse' in P print 'jump' in P for word in open('mydictionary.txt'): if word in P: print word Raymond Hettinger P.S. Nice puzzle! From jpaish@freenet.edmonton.ab.ca Sat Jul 19 10:44:02 2003 From: jpaish@freenet.edmonton.ab.ca (Joseph Paish) Date: Sat Jul 19 09:44:02 2003 Subject: [Tutor] is it possible to embed data inside a script? Message-ID: <03071907470600.01312@localhost.localdomain> can a person include the data that a script processes inside the script=20 itself? =20 i am in the process of converting a short perl script that processes=20 everything following __DATA__ instead of processing the contents of a=20 separate (very small) file. stripped down perl code follows : # ------------- my @lines =3D ; foreach (@lines) { # do stripped out processing of stuff following __DATA__ } __DATA__ abc 123 def 456 ghi 789 # -------- is there some way to achieve the same thing in python? thanks joe From pythontutor@venix.com Sat Jul 19 11:58:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat Jul 19 10:58:02 2003 Subject: [Tutor] is it possible to embed data inside a script? In-Reply-To: <03071907470600.01312@localhost.localdomain> References: <03071907470600.01312@localhost.localdomain> Message-ID: <3F195C50.3040507@venix.com> There is no read data ability in Python as there is in Basic and Perl. You can certainly imbed the data into a python script and process it. One approach: DATA = '''abc 123 def 456 ghi 789''' DATA_lines = DATA.split('\n') DATA_items = [line.split() for line in DATA_lines] for x,y in DATA_items: # do your thing here If you prefer to keep things compact: for x,y in [line.split() for line in DATA.split('\n')]: Joseph Paish wrote: > can a person include the data that a script processes inside the script > itself? > > i am in the process of converting a short perl script that processes > everything following __DATA__ instead of processing the contents of a > separate (very small) file. > > > stripped down perl code follows : > > # ------------- > my @lines = ; > > foreach (@lines) { > # do stripped out processing of stuff following __DATA__ > } > > __DATA__ > abc 123 > def 456 > ghi 789 > > # -------- > > > is there some way to achieve the same thing in python? > > thanks > > joe > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From bgailer@alum.rpi.edu Sat Jul 19 12:10:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Sat Jul 19 11:10:01 2003 Subject: [Tutor] is it possible to embed data inside a script? In-Reply-To: <03071907470600.01312@localhost.localdomain> Message-ID: <5.2.1.1.0.20030719083457.01c3fc68@66.28.54.253> --=======12A77CC======= Content-Type: text/plain; x-avg-checked=avg-ok-1F3C594D; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:47 AM 7/19/2003 -0600, Joseph Paish wrote: >can a person include the data that a script processes inside the script >itself? > >i am in the process of converting a short perl script that processes >everything following __DATA__ instead of processing the contents of a >separate (very small) file. > >stripped down perl code follows : > ># ------------- >my @lines = ; > >foreach (@lines) { > # do stripped out processing of stuff following __DATA__ > } > >__DATA__ >abc 123 >def 456 >ghi 789 > ># -------- > >is there some way to achieve the same thing in python? Easiest IMHO is to use Python's triple quote to create a literal that spans multiple lines. data = """abc 123 def 456 ghi 789 """ This cannot be the last thing in the script. It must be followed by (at minimum) a function call to run your code. Note that the result includes a newline (\n) character at the end of each line. To convert this into a list: lines = data.split('\n') An alternate approach: put the data in triple quotes at the end preceded by the __DATA__ flag, then use this code to read the script and extract the data. This code assumes the module was run as a script, not imported. If it were imported then we'd need to examine the module's __file__ property to get the source file path. # retrieve lines following __DATA__ import sys lines = file(sys.argv[0]).readlines() start = lines.index('__DATA__\n') lines = [line.strip('\n') for line in lines[start+1:-1]] # process the lines print lines # define the data """ __DATA__ abc 123 def 456 ghi 789 """ Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======12A77CC======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1F3C594D Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======12A77CC=======-- From gyromagnetic@excite.com Sat Jul 19 13:48:03 2003 From: gyromagnetic@excite.com (gyro funch) Date: Sat Jul 19 12:48:03 2003 Subject: [Tutor] word challenge Message-ID: <20030719164714.CAE1B3DE6@xmxpita.excite.com> Raymond Hettinger wrote: >>Since the number of paths through the phrase is very large, >>a good bet is to start with a dictionary of available words >>and test to see if they can be found in the phrase (while >>paying attention to letter order and the requirement that >>each group be represented). Excellent Raymond! Thanks for the great analysis and well though out code. On the other end of the spectrum is my code below. This uninspiring, brute-force code relies on the 'batteries included' aspect of Python and makes the regular expression engine do all of the work. We basically construct a regular expression satisfying the criteria outlined earlier and 'let it rip' on the word list. As Raymond and others pointed out, the word list could be pre-processed to eliminate words clearly not satisfying the criteria. Thanks to all for your great code and efforts! -g My apologies if my mailer screws up the code formatting. class FindWords(object): def __init__(self, wfile = '/usr/dict/words'): self.wfile = wfile self.wlist = [] self._make_word_list() def _make_word_list(self): import re wrd_re = re.compile(r'^[a-z]+$') fh = open(self.wfile,'r') all_lines = fh.readlines() fh.close() for line in all_lines: word = line.strip().lower() if wrd_re.search(word): self.wlist.append(word) return self.wlist def _build_regex(self, phrase): mlist = [] for word in phrase.split(): wr,wlist = range(len(word)),[] for j in wr: wre = '' for i in wr: if i == j: char = '' else: char = '?' wre += '%s%s' % (word[i],char) wlist.append(wre) mlist.append('(%s)' % '|'.join(wlist)) full_re = '^%s$' % ''.join(mlist) return full_re def get_words(self, phrase): import re found_words = [] p_regex = re.compile(self._build_regex(phrase)) for word in self.wlist: if p_regex.search(word): found_words.append(word) return found_words def main(): mw = FindWords() phrase = 'handy cool phrase' wl = mw.get_words(phrase) # let's get the longest and shortest words wdict = {} for word in wl: wdict.setdefault(len(word),[]).append(word) wrds = wdict.keys() mn,mx = min(wrds),max(wrds) print wdict[mn] print wdict[mx] return _______________________________________________ Express Yourself - Share Your Mood in Emails! Visit www.SmileyCentral.com - the happiest place on the Web. From alan.gauld@blueyonder.co.uk Sat Jul 19 17:08:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat Jul 19 16:08:02 2003 Subject: [Tutor] is it possible to embed data inside a script? References: <03071907470600.01312@localhost.localdomain> Message-ID: <001d01c34e31$8d962fe0$6401a8c0@xp> > can a person include the data that a script processes > inside the script itself? Sure just create a variable assignment. > i am in the process of converting a short perl script that > processes everything following __DATA__ instead of processing > the contents of a separate (very small) file. You can use sinple text strings to hold the data, in which case it looks just like a file, but more sensible and sophisticated is to hold the data as a Python data structure. A list of tuples might work, or a dictionary. This avoids all the text processing stuff and lets you get right to work while the data is still held in text form within the file for easy modification between runs. I often do this for test scripts when using Python for volume tests. Of course its usually better to separate the two and this can be done easily by defining an import and functon call after the data and putting all the processing code in a separate file: #### trivial case #### # file = foo.py def process(data): for s in data: print s ######################### # file = data.py data = """ some data here some more and still more """ import foo foo.process(data) ######################### HTH, Alan G. Alan G. From klappnase@freenet.de Sat Jul 19 21:04:01 2003 From: klappnase@freenet.de (klappnase@freenet.de) Date: Sat Jul 19 20:04:01 2003 Subject: [Tutor] General object-oriented procedure question Message-ID: DQotLS0gb3JpZ2luYWwgTmFjaHJpY2h0IEVuZGUgLS0tLQ0KDQoNCkkgaGF2ZSBhIHByb2dyYW0g dGhhdCBoYXMgc2V2ZXJhbCBjbGFzc2VzLCBlYWNoIHdpdGggbXVsdGlwbGUgZnVuY3Rpb25zDQpk ZWZpbmVkLiBJIGhhdmUgbWFwcGVkIG15IHdheSB0aHJvdWdoIGVub3VnaCB0byBiYXNpY2FsbHkg dW5kZXJzdGFuZCB0aGUNCmZsb3cgb2YgdGhpbmdzLCBidXQgSSBhbSBub3Qgc3VyZSB3aGF0IGhh cHBlbnMgd2hlbiBpdCBmaW5pc2hlcyB0aGUNCm1haW5sb29wIChzdGFuZGFyZCBnYXJkZW4tdmFy aWV0eSBtYWlubG9vcCkuIFNheSBmb3IgaW5zdGFuY2UgdGhhdCBvbmUgb2YNCnRoZSBjbGFzc2Vz IGluY2x1ZGVzIGEgYnV0dG9uIHRoYXQgSSBwcmVzcyB0byBpbml0aWF0ZSBzb21lIHNlcXVlbmNl IG9mDQphY3Rpdml0aWVzLiBJIGZpbmlzaCB0aGUgc2VxdWVuY2UgZmluZSwgYnV0IHRoZW4gSSBn ZXQgYmFjayB0byB0aGUgY2xhc3MNCmFuZCB0aGUgcHJvZ3JhbSBoYW5ncy4gSSBoYXZlIGEgcHVs bGRvd24gbWVudSB3aGljaCBpbmNsdWRlcyBhbiBleGl0LCBhbmQNCnRoYXQgd29ya3MsIGJ1dCB3 aGF0IGlmIEkgc2ltcGx5IHdhbnQgdG8gZW5kIGFmdGVyIHRoZSBidXR0b24gYWN0aXZpdHkNCmNl YXNlcy4gSG93IGRvIEkgZG8gdGhhdD8gSSd2ZSBpbnNlcnRlZCBwcmludCBzdGF0ZW1lbnRzIGFm dGVyIHRoZQ0KbWFpbmxvb3AgY2FsbCwgYnV0IHRoZXkgYXJlIG5ldmVyIHJlYWNoZWQgdW5sZXNz IEkgZXhpdCBmcm9tIHRoZSBtZW51LiBJDQpuZWVkIHRvIGFkZCBzb21ldGhpbmcgdG8gdGhlIGVu ZCBvZiB0aGUgbWFpbmxvb3AgdG8gZW5kIHdoZW4gZmluaXNoZWQsIGJ1dA0KSSBhbSB1bnN1cmUg d2hlcmUgdG8gaW5zZXJ0IGl0IG9yIGV4YWN0bHkgd2hhdCB0byBpbnNlcnQuIEkgdHJpZWQgInJl dHVybg0KdHJ1ZSIsIGJ1dCB0aGF0IGRpZG4ndCB3b3JrLg0KDQotLXZpY2tpDQoNCkhpLA0KDQpJ J20gbm90IHJlYWxseSBzdXJlIGlmIEkgdW5kZXJzdG9vZCB5b3VyIHByb2JsZW0sIGl0IHNlZW1z IHRvIG1lIGxpa2UgeW91DQp3YW50IHRvIHNodXQgZG93biB0aGUgbWFpbiB3aW5kb3cgb2YgeW91 ciBwcm9ncmFtIGFmdGVyIHRoZSBmdW5jdGlvbiB5b3UgY2FsbCB3aXRoIGEgQnV0dG9uLVByZXNz IGhhcyBjb21lIHRvIGFuIGVuZDsgaW4gdGhpcyBjYXNlIHlvdSBzaG91bGQgYWRkDQphIHN5cy5l eGl0KDApIHRvIHRoZSBlbmQgb2YgeW91ciBmdW5jdGlvbi4gTWF5YmUgdGhhdCdzIG5vdCByZWFs bHkgd2hhdCB5b3Ugd2FudGVkLiBIb3dldmVyIHlvdSBjYW4gbm90IGVuZCB0aGUgbWFpbmxvb3Ag d2l0aCBhIGxpbmUgYWZ0ZXIgdGhlIG1haW5sb29wLHRoYXQncyB0aGUgdXNlIG9mIHRoZSBtYWlu bG9vcCB0aGF0IGl0IG5ldmVyIGVuZHMgdW50aWwgeW91IGV4cGxpY2l0bHkgY2FsbCBzb21ldGhp bmcgdG8gZW5kIGl0Lg0KDQpNaWNoYWVsDQoNCg0KDQoNCg0KDQoNCl9fX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fDQpUdXRvciBtYWlsbGlzdCAgLSAgVHV0b3JA cHl0aG9uLm9yZw0KPGEgaHJlZj0naHR0cDovL21haWwucHl0aG9uLm9yZy9tYWlsbWFuL2xpc3Rp bmZvL3R1dG9yJyB0YXJnZXQ9J19ibGFuayc+PHU+aHR0cDovL21haWwucHl0aG9uLm9yZy9tYWls bWFuL2xpc3RpbmZvL3R1dG9yPC91PjwvYT4NCgoKCi0tIAplQmF5IC0gSmV0enQgYmVzc2VyIGVp bmthdWZlbiEKVWViZXIgMS4gTWlvLiBBbmdlYm90ZS4gU3RhcnRwcmVpc2UgYWIgPyAxLC0KaHR0 cDovL3d3dy5mcmVlbmV0LmRlL3RpcHAvc2hvcHBpbmcvZWJheQ== From alex@gabuzomeu.net Sun Jul 20 08:08:03 2003 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Sun Jul 20 07:08:03 2003 Subject: [Tutor] Re: [quicky intro to vector search engines] In-Reply-To: <20030701193109.17977.82811.Mailman@mail.python.org> Message-ID: <4.3.2.7.2.20030709164311.00bb5e58@mail.poulpe.net> Hello Danny and All, >Date: Tue, 1 Jul 2003 12:30:12 -0700 (PDT) >From: Danny Yoo >Subject: Re: [Tutor] writing a search engine [quicky intro to vector >search engines] Vector search engines looked fun; I just had to give it a try :-) I uploaded a basic implementation to: http://www.gabuzomeu.net/alex/py/vsse/SearchEngine.zip Feedback is welcome. >The general idea is to turn each document in our collection into a vector >in N-dimensional space. And N can be potentially really large: it's the >number of unique words in our whole document collection. I used Numeric arrays to store these data. Individual arrays are stored in a dictionary keyed by file names. As a test, I indexed the Linux Howto collection (text-only version). That's 304 files; about 25 MB of data. When searching the collection, the result I get look reasonable: >>> app.search("apache", 0.15) Searching in 304 files... --------------------- Apache-Overview-HOWTO.txt 60.68% Apache-Compile-HOWTO.txt 34.38% Apache-WebDAV-LDAP-HOWTO.txt 33.25% WWW-HOWTO.txt 16.82% >>> app.search("beowulf cluster", 0.1) Searching in 304 files... --------------------- Beowulf-HOWTO.txt 34.56% SSI-UML-HOWTO.txt 26.92% openMosix-HOWTO.txt 18.16% Cluster-HOWTO.txt 12.80% Parallel-Processing-HOWTO.txt 11.69% CPU-Design-HOWTO.txt 10.59% Memory usage is quite high (about 100 MB for the PythonWin process). When saving the index instance to a file as a binary pickle, the file is quite large too (70 MB). >With this numbering, we can now transform our documents into vectors in >13-dimensional space. > >### > >>> def transformIntoVector(words): >... vector = [0] * 13 >... for w in words: >... vector[d[w]] = 1 >... return vector We may have a problem when a query word is not included in the index. For now, I just drop it, print out a message and query the index with the remaining query words. >And once we do this, then we can do a search by finding the vectors in our >document collection that are most "similar" to our query vector. One cute >way to do a simliarity check is to simply "multiply" a query vector, >componentwise, against our document vectors. >### > >>> def v_multiply(v1, v2): >... sum = 0 >... for x, y in zip(v1, v2): >... sum += x * y >... return sum >### Here, I just used the formula in the Perl article you quoted*. One difference with your exemple is that I store the number of instances of a word (or stem) in the document vector. * http://www.perl.com/lpt/a/2003/02/19/engine.html >Since our query was the word "emergency", we matched against our first >document, but got no hits in our second document. >self.matrix is a 'pysparse' matrix of all my document vectors, using some >libraries from the PySparse project, > > http://www.python.org/pycon/papers/pysparse.html I haven't tried using pysparse yet. >(The real reason I'm working on this code is to do document clustering for >a digital library While looking for a pure-python stemmer, I came across this reference: Machine Learning: Text classification report, Ludvig Omholt, 2001/06/01: http://ludde.net/ml/index.html Some Python code is included: http://ludde.net/ml/implementation.html Cheers. Alexandre From andi@buxach.de Sun Jul 20 10:21:35 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Sun Jul 20 09:21:35 2003 Subject: [Tutor] pcm -> seconds Message-ID: <20030720151958.3d5eb267.andi@buxach.de> ave I am programming a JukeBox, currently i try to figur out how to make a song fade out? I can change the sound volume no problem (audioop module), but the problem is the timing. There is a threaded class, which streams the data as long a variable is set. Now i would have to let a counter tick in the background to see how much of the song is played. The stream is a 16bit stereo PCM stream. Is the amount of time 4kb of that stream need to play fix? So can i count 4kb = 1,4314 (value just imagined) seconds? Or should i figure out the amount of stream data i get from a mp3? Or should i just implement yet another thread to count the seconds? All suggestions are welcome for this problem :) mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From alan.gauld@blueyonder.co.uk Sun Jul 20 16:51:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sun Jul 20 15:51:01 2003 Subject: [Tutor] pcm -> seconds References: <20030720151958.3d5eb267.andi@buxach.de> Message-ID: <004001c34ef8$303d1030$6401a8c0@xp> > Or should i just implement yet another thread to count the seconds? Since you are dealing with time I would stick with that and use another thread. However if performance starts to suffer then you might have to do some clever bytes->time approximations. However with the compression involved it may not be too easy. Alan G From Sk8erguy2424@aol.com Sun Jul 20 17:06:02 2003 From: Sk8erguy2424@aol.com (Sk8erguy2424@aol.com) Date: Sun Jul 20 16:06:02 2003 Subject: [Tutor] Portalocker Message-ID: <43.1fe3e3f9.2c4c4ffb@aol.com> --part1_43.1fe3e3f9.2c4c4ffb_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit The URL for the portalocker module is: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203 --part1_43.1fe3e3f9.2c4c4ffb_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable The URL for the portalocker module is:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65203
--part1_43.1fe3e3f9.2c4c4ffb_boundary-- From cybersamurai@mac.com Sun Jul 20 23:21:03 2003 From: cybersamurai@mac.com (cybersamurai@mac.com) Date: Sun Jul 20 22:21:03 2003 Subject: [Tutor] XML documentation Message-ID: <359178A8-BB22-11D7-B454-000393B10A78@mac.com> I need know here I can find documentation about XML and Python. I know How read and write a new XML file but I don't know edit. From idiot1@netzero.net Mon Jul 21 00:18:03 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sun Jul 20 23:18:03 2003 Subject: [Tutor] is it possible to embed data inside a script? In-Reply-To: <03071907470600.01312@localhost.localdomain> References: <03071907470600.01312@localhost.localdomain> Message-ID: <3F1B5B5B.7090302@netzero.net> Sure thing. domainname="tinylist.org" password="swordfish" id="idiot1@netzero.net" simple enough, but wait, there's more! array1()='2','3','3','4','4','4','5','5','5','5','6','6','6','6','6','7','7','7','7','7','7',... (2dice, 6 sides, in a matrix. Use ramdom.choice to pick one of them. Weighted correctly for 2s6) These are simplistic examples, but sure, data is just data. You can assign it to any variable type in a declaration whenever you like. Now, when this means a LOT of data, thing can get boring and real easy to get mixed up in the programmer's mind. Ever see a program with several HUNDRED DATA statements, read by a READ statement? When you go in to change something, it is EASY to get totally lost, espically when it is a program which does not number lines. Why is it important to store a lot of data IN the program? Joseph Paish wrote: > can a person include the data that a script processes inside the script > itself? > > i am in the process of converting a short perl script that processes > everything following __DATA__ instead of processing the contents of a > separate (very small) file. > > > stripped down perl code follows : > > # ------------- > my @lines = ; > > foreach (@lines) { > # do stripped out processing of stuff following __DATA__ > } > > __DATA__ > abc 123 > def 456 > ghi 789 > > # -------- > > > is there some way to achieve the same thing in python? > > thanks > > joe > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From vvernon@earthlink.net Mon Jul 21 02:36:02 2003 From: vvernon@earthlink.net (Vernon Miller) Date: Mon Jul 21 01:36:02 2003 Subject: [Tutor] PIL Message-ID: <000b01c34f5a$a235ed80$b99780d1@net> I have a question, may seem dumb, but I imported the Image module and opened a gif image. The question is this, it opened up into my windows paint program. Is that what it is supposed to do, and if so how can you get it to open with or in another graphic program. Thanks Vernon Miller P.S. I have started the Visual C ++ course, so I won't have as much time to work on python until I learn the C++, but I am going to keep trying to give as much effort as possible to learning Python also. Thanks once again to everyone for your advice about which program to study. Your comments helped very much and caused me to look closer at each one of the program before I decided which to take. From andi@buxach.de Mon Jul 21 08:38:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Mon Jul 21 07:38:01 2003 Subject: [Tutor] pcm -> seconds In-Reply-To: <004001c34ef8$303d1030$6401a8c0@xp> References: <20030720151958.3d5eb267.andi@buxach.de> <004001c34ef8$303d1030$6401a8c0@xp> Message-ID: <20030721133710.45766692.andi@buxach.de> Solved ... The raw pcm stream is 44.1 kHz 16bit stereo, which means 176400 bytes (44100*16*2/8) are one second. the raw stream bytes are counted after decode, before pushing them to the output. The playing is a thread already, so the main thread can change the volume at the right moment. mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From Jan.Wilhelmsen@bilia.no Mon Jul 21 11:12:50 2003 From: Jan.Wilhelmsen@bilia.no (Wilhelmsen Jan) Date: Mon Jul 21 10:12:50 2003 Subject: SV: [Tutor] newbie question Message-ID: <9DB3344EC407D311A0A500508B0963E401DE32D5@ex84701.cars.no.bilia.net> OK I try to explain a little more detailed. First of all I have 2 text files witch we want to user for reference = and translations. File 1 looks like this: 40 444 60 380 68 950 70 950 kjeu 847 mnsy 342 kjeu I 984 M=E9g 273 etc... File 2 is just the same structure as file 1,But of course other values. Then I have a third file called dataf1.txt One part of each record in this dataf1.txt looks like this: 00120024311011655 0304 1211 M=E9g 5529260=20 In this case in need to replace M=E9g with 273 and create a new = datafile and write the new string in this one. This is just one of the modifications I have to do but the others are = pretty much the same as this. So if I learn how to do one, the rest will be easier. I tried too create a dictionary like this: def t1(): f =3D open("filename","r") for line in f: line =3D line.split() table[line[0]] =3D line[1] print table But here I get only one dictionary item for both: Kjeu And=20 Kjeu I Does this mean that I can't use the line.split? When I print out the M=E9g post I get M\xe9g , how can I deal with = this? This might not a problem if only the output to the new file is ok. Regards Jan Wilhelmsen IT-Technician Bilia Personbil as -----Opprinnelig melding----- Fra: sigurd@12move.de [mailto:sigurd@12move.de]=20 Sendt: 18. juli 2003 17:12 Til: tutor@python.org Emne: Re: [Tutor] newbie question On 18 Jul 2003, Wilhelmsen Jan <- Jan.Wilhelmsen@bilia.no wrote: > I have a text file witch contains some constants that I will use = later when > parsing some other text files. > File 1: > 40 444 > 60 380 > 68 950 > 70 950 > What I have to do is to check to values in column 1(v1) against a = value in > another a text string(v2), if match then v1 =3D v2. Can you show with a littlem example what you exactly want to achieve. Are the values in v2 strings which contain v1 as substring? What = happens with column 2 of your example? You don't semm to need it; you mention only column1 (=3D=3D v1) and the value in the second text file (=3D=3D = v2). Is that value also in column 1? > I know have to do this by opening the file and do a search and then = close > the file. > But since this check will occur numerous times I thought maybe it's = better > too read the file in memory once and that's it. > Can I make sort of a "table" (t1) with objects (column1) that has a > value(column2).=20 Yes. > Then check this "table" when parsing the other text file? > Hope someone can give me some tip about this. Python has a builtin sequence type called dictionary (a hash table). Perhaps you could use it (you don't say if the order of the entries matters (if yes a dictionary won't help)). To build the dictionary you could simple open the file read the lines and use the first value as key and the second as value of the dictionary. Like that eg: >>> table =3D {} >>> f =3D open("file", "r") >>> for line in f: ... line =3D line.split() ... table[line[0]] =3D line[1] ...=20 >>> table {'60': '380', '68': '950', '40': '444', '70': '950'} >>>=20 Now you have a dictionary where column 1 of your file acts as key and column 2 is the value. Now to the check You should give a little example first what you exactly like to achieve otherwise it's not easy to help you. Karl --=20 Please do *not* send copies of replies to me. I read the list _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------------------------------------------------= ---- --- This verifies that this e-mail has been scanned for virus and deemed virus-free=20 according to F-secure Content Scanner 5.0 Fri, 18 Jul 2003 17:11:59 +0200 GMT ------------------------------------------------------------------------= ---- --- From godoy@metalab.unc.edu Mon Jul 21 11:46:02 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Mon Jul 21 10:46:02 2003 Subject: [Tutor] Best approach to sort data based on several criteria Message-ID: Hi. I have a huge amount of data that's stored in a file where each record is in a line made of 22 columns, and each column is separated from the other by a ';'. I need to show this data (some columns each time) sorted out accordingly to some columns (e.g. columns zero, one, five and six, each on a different view and in one of these views, I need to sort based on multiple keys). What's the best way to handle this situation? I thought about splitting these columns and sorting them, but maybe there's a more efficient way... Not to mention that some columns are strings and other are dates or numbers. TIA, -- Godoy. From Adam Vardy Mon Jul 21 11:58:10 2003 From: Adam Vardy (Adam Vardy) Date: Mon Jul 21 10:58:10 2003 Subject: [Tutor] where to buy python books in phoenix az In-Reply-To: References: Message-ID: <17296451875.20030721122628@roadrunner.nf.net> Friday, July 18, 2003, 9:24:36 AM, you wrote: >> i have been looking all over phoenix for python books.=A0 i dont have >> a credit card so that prohibits online purchases.=A0 There are a lot of online bookstores. But anyway, take Amazon.com for example. Here is their payment types they accept page: http://www.amazon.com/exec/obidos/tg/browse/-/513058/ref=3Dhp_hp_ls_2_4/1= 02-1503671-1058532 Not terribly restricting. >> can anyone tell >> me a good bookstore=A0 for computerbooks in phoenix.=A0 I'm not near there, so someone in that area can comment. >> i have been >> directed to zooology every time i ask for python books at the major >> chains, and for b daltons sake i wont tell the name that when i >> said "its a computer language like java" they led me to cooking >> books.=A0 :-) >> i wish programming was as easy to learn as making coffee.=A0 >> one scoop, a pot of water, and let the machine do the rest.=A0 if >> anyone knows where i can get the books with cash (or a self >> programming and teaching computer, just kidding before i get told >> the obviouse) hmmm.. if you look up computer lessons on various topics, sometimes you find that you can get videos, or CD's with lessons on programming language x or whatever topic. Maybe it might say live videos from some expert, or interactive lessons. So maybe you find it on a website or in a magazine. But, you always seemed to find this in one of two forms. Either it was real cheap, or it was terribly expensive. Like maybe $800 US for a few CD's, or a few VHS videos. And often, it seemed like it could just be covering the same topics in some book. And then, other times you might locate something like 1001 interactive lessons on C++ on a CD, plus 200 other topics, CD for $10. You might suppose that there's stuff out there of that type that would benefit some, differently than reading prose. But more often it's too much to spend to find out what is out there may actually consist of. --=20 Adam Vardy From qsc@icon.co.za Mon Jul 21 12:21:56 2003 From: qsc@icon.co.za (Quentin) Date: Mon Jul 21 11:21:56 2003 Subject: [Tutor] Best approach to sort data based on several criteria In-Reply-To: References: Message-ID: <3F1C04B1.9000907@icon.co.za> OK, I am not going to give you a Python answer, but some ways to consider, I've done similar things the past few months (I used VB, and hope to do it with Python in the future): Main thing I would do is to convert the file into a data base. This will give you so much more control over reading and editing the data. And so much easier to program an app to read and sort a database than a large text file. I use MySQL database (another opensource project, and it is also supported by Python). You can use MySQL admin to create a data base and then write a small Python app to read your file data in. ( you can even use Python to create a database direct). If you are not to up too speed with Python (like me) you can: Use a spreadsheet program to open the (txt, I presume, or CSV) file and set it to parse your data into spreadsheet columns based on the deliminator (You said ";"), then, either: 1. Export it direct to a database. 2. Save it as a text file that MySQL will understand and use to import data. Read the MySQL tutorial that is in the docs, and you will understand a lot of what I've said. http://www.mysql.com/ Quentin From bgailer@alum.rpi.edu Mon Jul 21 12:58:02 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Mon Jul 21 11:58:02 2003 Subject: [Tutor] Best approach to sort data based on several criteria In-Reply-To: Message-ID: <5.2.1.1.0.20030721095208.058f9af0@66.28.54.253> --=======538489======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-62E017AB; boundary="=====================_16454500==.ALT" --=====================_16454500==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-62E017AB; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:44 AM 7/21/2003 -0300, Jorge Godoy wrote: >I have a huge amount of data >[snip] >I need to show this data (some columns each time) sorted out >accordingly to some columns (e.g. columns zero, one, five and six, >each on a different view and in one of these views, I need to sort >based on multiple keys). Consider using the sqlite database. Unlike most other RDBMS, sqlite is loaded as part of your python session, so is very fast. http://www.sqlite.org for the database. http://pysqlite.sourceforge.net/ for the Python wrapper. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_16454500==.ALT Content-Type: text/html; x-avg-checked=avg-ok-62E017AB; charset=us-ascii Content-Transfer-Encoding: 8bit At 11:44 AM 7/21/2003 -0300, Jorge Godoy wrote:
I have a huge amount of data
[snip]
I need to show this data (some columns each time) sorted out
accordingly to some columns (e.g. columns zero, one, five and six,
each on a different view and in one of these views, I need to sort
based on multiple keys).

Consider using the sqlite database. Unlike most other RDBMS, sqlite is loaded as part of your python session, so is very fast.
http://www.sqlite.org for the database.
http://pysqlite.sourceforge.net/ for the Python wrapper.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_16454500==.ALT-- --=======538489======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-62E017AB Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======538489=======-- From rick@niof.net Mon Jul 21 13:00:03 2003 From: rick@niof.net (Rick Pasotto) Date: Mon Jul 21 12:00:03 2003 Subject: [Tutor] Best approach to sort data based on several criteria In-Reply-To: References: Message-ID: <20030721160243.GR26665@niof.net> On Mon, Jul 21, 2003 at 11:44:44AM -0300, Jorge Godoy wrote: > > Hi. > > I have a huge amount of data that's stored in a file where each record > is in a line made of 22 columns, and each column is separated from the > other by a ';'. > > I need to show this data (some columns each time) sorted out > accordingly to some columns (e.g. columns zero, one, five and six, > each on a different view and in one of these views, I need to sort > based on multiple keys). > > What's the best way to handle this situation? > > I thought about splitting these columns and sorting them, but maybe > there's a more efficient way... > > Not to mention that some columns are strings and other are dates or > numbers. As another poster said, the easiest way is to convert to a database. For that you might want to consider SQLite. There's a python module. http://sourceforge.net/projects/pysqlite/ This would be much simpler and more portable than the heavier duty databases like MySql. On the other hand, awk may be all you need! :-) -- "If you speak the truth, have a foot in the stirrup." -- Turkish proverb Rick Pasotto rick@niof.net http://www.niof.net From godoy@metalab.unc.edu Mon Jul 21 13:03:03 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Mon Jul 21 12:03:03 2003 Subject: [Tutor] Best approach to sort data based on several criteria In-Reply-To: <3F1C04B1.9000907@icon.co.za> (qsc@icon.co.za's message of "Mon, 21 Jul 2003 17:20:17 +0200") References: <3F1C04B1.9000907@icon.co.za> Message-ID: Quentin writes: > OK, I am not going to give you a Python answer, but some ways to Thank you. I'm not willing to loose all the fun doing things myself. Any indications on what I can read or how's the most effective pythonic way of doing things is great. > consider, I've done similar things the past few months (I used VB, and > hope to do it with Python in the future): > Main thing I would do is to convert the file into a data base. This > will give you so much more control over reading and editing the > data. And so much easier to program an app to read and sort a database > than a large text file. I use MySQL database (another opensource > project, and it is also supported by Python). I'm going to do that later with the database, but this is just a temporary solution until we have the definitive thing implemented. There we are using PostgreSQL. > You can use MySQL admin to create a data base and then write a small > Python app to read your file data in. ( you can even use Python to > create a database direct). I was considering that -- in the very beginning --, but I'm not willing to use it if it can be avoided. On the other hand, using a database will solve a lot of problems and it can do the hard job on sorting and all the rest to me... I'll reconsider using it. Maybe my quick hack will be a bit more elaborated than I was willing... Thanks again, -- Godoy. From godoy@metalab.unc.edu Mon Jul 21 13:06:42 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Mon Jul 21 12:06:42 2003 Subject: [Tutor] Best approach to sort data based on several criteria In-Reply-To: <5.2.1.1.0.20030721095208.058f9af0@66.28.54.253> (Bob Gailer's message of "Mon, 21 Jul 2003 09:55:49 -0600") References: <5.2.1.1.0.20030721095208.058f9af0@66.28.54.253> Message-ID: Bob Gailer writes: > Consider using the sqlite database. Unlike most other RDBMS, sqlite is > loaded as part of your python session, so is very fast. > http://www.sqlite.org for the database. > http://pysqlite.sourceforge.net/ for the Python wrapper. This seems to be the best approach as recommended before and since I can let the database handle all the data sorting... This has the increased advantage of having a Windows port --- that's where my temporary solution will run. Thanks for the links. -- Godoy. From cybersamurai@mac.com Mon Jul 21 14:00:05 2003 From: cybersamurai@mac.com (Luiz Siqueira Neto) Date: Mon Jul 21 13:00:05 2003 Subject: [Tutor] importing modules Message-ID: <200307211400.15463.cybersamurai@mac.com> How can I import modules inside of a directory in a root of my project? in java I use import dir.package.* From glingl@aon.at Mon Jul 21 14:09:05 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jul 21 13:09:05 2003 Subject: [Tutor] Re: newbie question Message-ID: <3F1C1E78.5080106@aon.at> Hi Jan! Two short remarks to your problems: (1) >But here I get only one dictionary item for both: > > >Kjeu > >And=20 > >Kjeu I > You get this because here line is "kjeu I 984" and thus line.split() has three items: >>> line ="kjeu I 984" >>> line.split() ['kjeu', 'I', '984'] >>> One way to handle this problem could be: >>> line.rfind(" ") 13 >>> sep = line.rfind(" ") >>> line[:sep] 'kjeu I ' >>> line[:sep].strip() 'kjeu I' >>> line[sep:] ' 984' >>> line[sep:].strip() '984' >>> table = {} >>> table[line[:sep].strip()] = line[sep:].strip() >>> table {'kjeu I': '984'} >>> (2) >When I print out the M=E9g post I get M\xe9g , how can I deal with = >this? This >might not a problem if only the output to the new file is ok. >>> print "M\xe9g" Még >>> ord("\xe9") 233 This shows, that "\xe9" is the internal (hex-) representation of a character with ascii-code > 127, namely an e with some accent and ascii-code 233. If you feed it directly into a print-statement it will be displayed correctly. HTH Gregor From dyoo@hkn.eecs.berkeley.edu Mon Jul 21 14:37:19 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 21 13:37:19 2003 Subject: [Tutor] Re: [quicky intro to vector search engines] In-Reply-To: <4.3.2.7.2.20030709164311.00bb5e58@mail.poulpe.net> Message-ID: On Sun, 20 Jul 2003, Alexandre Ratti wrote: > Vector search engines looked fun; I just had to give it a try :-) I > uploaded a basic implementation to: > > http://www.gabuzomeu.net/alex/py/vsse/SearchEngine.zip Hi Alexandre, Very cool; I will have to take a look at this! > >>> app.search("beowulf cluster", 0.1) > Searching in 304 files... > --------------------- > Beowulf-HOWTO.txt 34.56% > SSI-UML-HOWTO.txt 26.92% > openMosix-HOWTO.txt 18.16% > Cluster-HOWTO.txt 12.80% > Parallel-Processing-HOWTO.txt 11.69% > CPU-Design-HOWTO.txt 10.59% > > Memory usage is quite high (about 100 MB for the PythonWin process). > When saving the index instance to a file as a binary pickle, the file is > quite large too (70 MB). I've been reading a little more about Maciej Ceglowski's work on vector search engines; I've been collecting some of my notes here: http://hkn.eecs.berkeley.edu/~dyoo/python/svd/ The "Latent Semantic Analysis" technique that Maciej briefly mentions at the end of his article talks about ways of compressing the vector space using some vector techniques. At the moment, I don't yet feel comfortable enough with the linear algebra to understand SVD yet, but I can collect links pretty well. *grin* If I have time, I'll see if I can cook up a wrapper module for SVDPACK. Talk to you later! From DORSEY_EDMUND_K@LILLY.COM Mon Jul 21 16:38:01 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Mon Jul 21 15:38:01 2003 Subject: [Tutor] File reading problem Message-ID: This is a multipart message in MIME format. --=_alternative 006BB95605256D6A_= Content-Type: text/plain; charset="us-ascii" I'm trying to read in some files and for some reason python keeps telling me IOError: [Errno 2] No such file or directory: 'c:\\models\tiny.vff' The code is as follows from vffReader import * from vffWriter import * import array as A reader = vffReader() reader.readFile(filename = "c:\models\tiny.vff") writer = vffWriter(reader.getHeader(), reader.getData()) writer.write(filename = "c:\models\tiny_out.vff") print "Done" The odd thing is if I change the code to the below it works. The only difference is which file I try to open. (This is how I ran the program originally before changing the file to the above) from vffReader import * from vffWriter import * import array as A reader = vffReader() reader.readFile(filename = "c:\models\super_tiny.vff") #different file name writer = vffWriter(reader.getHeader(), reader.getData()) writer.write(filename = "c:\models\super_tiny_out.vff") #different file name print "Done" The above works okay. Both tiny.vff and super_tiny.vff exist. I'm staring at them in windows explorer and I can even open both of them. Why can python find one but it can't find the other. I originally programmed it with super_tiny but wanted to change it to a different file. Thats when the problem arose. Thanks for any help. --=_alternative 006BB95605256D6A_= Content-Type: text/html; charset="us-ascii"
I'm trying to read in some files and for some reason python keeps telling me  IOError: [Errno 2] No such file or directory: 'c:\\models\tiny.vff'

The code is as follows

from vffReader import *
from vffWriter import *
import array as A

reader = vffReader()
reader.readFile(filename = "c:\models\tiny.vff")
writer = vffWriter(reader.getHeader(), reader.getData())
writer.write(filename = "c:\models\tiny_out.vff")
print "Done"


The odd thing is if I change the code to the below it works.  The only difference is which file I try to open.  (This is how I ran the program originally before changing the file to the above)

from vffReader import *
from vffWriter import *
import array as A

reader = vffReader()
reader.readFile(filename = "c:\models\super_tiny.vff") #different file name
writer = vffWriter(reader.getHeader(), reader.getData())
writer.write(filename = "c:\models\super_tiny_out.vff") #different file name
print "Done"

The above works okay.  Both tiny.vff and super_tiny.vff exist.  I'm staring at them in windows explorer and I can even open both of them.  Why can python find one but it can't find the other.  I originally programmed it with super_tiny but wanted to change it to a different file.  Thats when the problem arose.  Thanks for any help. --=_alternative 006BB95605256D6A_=-- From jeff@ccvcorp.com Mon Jul 21 17:08:08 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 21 16:08:08 2003 Subject: [Tutor] File reading problem References: Message-ID: <3F1C483C.7040402@ccvcorp.com> DORSEY_EDMUND_K@LILLY.COM wrote: > > I'm trying to read in some files and for some reason python keeps > telling me IOError: [Errno 2] No such file or directory: > 'c:\\models\tiny.vff' You need to escape your backslashes. '\t' is a tab, not a backslash and the letter 't'. It works with the super_tiny.vff file, because \s (like \m) happens to not indicate a control character. You can fix this by changing this line (and any other lines that use filenames): > reader.readFile(filename = "c:\models\tiny.vff") to look like either one of the following: reader.readFile(filename = "c:\\models\\tiny.vff") reader.readFile(filename = r"c:\models\tiny.vff") reader.readFile(filename = "c:/models/tiny.vff") In the first one, I've used double backslashes. This indicates that the backslash should be interpreted literally, rather than potentially interpreted as a control character. In the second one, I've preceded the string with an 'r', which indicates that this is to be a raw string. In raw strings, no control character interpretation is done. In the last case, I've used forward slashes instead of backslashes. This isn't Windows-standard, but it will work for (AFAIK) every system call that's passed through Python. (It doesn't work in the Windows command shell, but it works pretty much everywhere else.) You can also import the os module and use os.path.join() to construct your filename. Jeff Shannon Technician/Programmer Credit International From alan.gauld@blueyonder.co.uk Mon Jul 21 17:38:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Jul 21 16:38:02 2003 Subject: [Tutor] pcm -> seconds References: <20030720151958.3d5eb267.andi@buxach.de><004001c34ef8$303d1030$6401a8c0@xp> <20030721133710.45766692.andi@buxach.de> Message-ID: <008101c34fc7$d7ba8fc0$6401a8c0@xp> > The raw pcm stream is 44.1 kHz 16bit stereo, which means 176400 bytes > (44100*16*2/8) are one second. So it isn't MP3 then. That's CD type sound but in your message you referred to MP3 which is compressed... Alan G. From vvernon@earthlink.net Mon Jul 21 18:15:02 2003 From: vvernon@earthlink.net (Vernon Miller) Date: Mon Jul 21 17:15:02 2003 Subject: [Tutor] read, write to file Message-ID: <002e01c34fdd$e08539a0$859780d1@net> I spend all day trying to get this to work f=open('C:/Python22/Tools/tmp/workfile.txt', 'w') f.write('This is the first line of the file') after it finally seemed to work I tried to read the line with readline() What I got was several hundred lines of x's and o's, but nothing was written to the file last week I went through the same thing and after rebooting several times it finally decided to work, it seems to me that there is something fundamentally wrong with the read, write to file functions in this latest version of python. Vernon Miller vvernon@earthlink.net From vicki@thepenguin.org Mon Jul 21 18:22:52 2003 From: vicki@thepenguin.org (Vicki Stanfield) Date: Mon Jul 21 17:22:52 2003 Subject: [Tutor] General object-oriented procedure question Message-ID: <27794.206.53.226.4.1058542773.squirrel@www.thepenguin.org> I have a program that has several classes, each with multiple functions defined. I have mapped my way through enough to basically understand the flow of things, but I am not sure what happens when it finishes the mainloop (standard garden-variety mainloop). Say for instance that one of the classes includes a button that I press to initiate some sequence of activities. I finish the sequence fine, but then I get back to the class and the program hangs. I have a pulldown menu which includes an exit, and that works, but what if I simply want to end after the button activity ceases. How do I do that? I've inserted print statements after the mainloop call, but they are never reached unless I exit from the menu. I need to add something to the end of the mainloop to end when finished, but I am unsure where to insert it or exactly what to insert. I tried "return true", but that didn't work. --vicki From alex@caustic-creations.com Mon Jul 21 18:23:12 2003 From: alex@caustic-creations.com (Alex from Caustic Creations) Date: Mon Jul 21 17:23:12 2003 Subject: [Tutor] Stopping a loop with user input in curses Message-ID: <1058652249.1685.0.camel@caustic.laptop> Hello all, I've written a small clock program in curses that I would like to have end when someone presses 'q'. I've included the code below. I'm *very* new to python so I apologize in advance if this seems like a horribly obvious problem. I've spent all day trying various structures but none of them have worked out. Any help would be greatly appreciated. Thanks, Alex #! /usr/bin/python # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() while 1: t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() time.sleep(1) def main(stdscr): # Bring up the clock function theClock() # If 'q' is pressed, exit while 2: c = stdscr.getch() if c == ord('q'): curses.beep() break if __name__ == '__main__': curses.wrapper(main) From anna@aleax.it Mon Jul 21 18:23:38 2003 From: anna@aleax.it (Anna Ravenscroft) Date: Mon Jul 21 17:23:38 2003 Subject: [Tutor] mailman on website Message-ID: <200307201523.22803.anna@aleax.it> Does anyone here know how to get mailman setup on a website? We're trying to do it for a non-profit community group and feeling very overwhelmed.... I realize this is only peripherally python=related but I hang out here and I know folks here so I'm hoping someone can help... If anyone has experience on this, let me know what we would do as a first step... Um - we have a website, that is on a server donated by someone in the group. We ftp files there for the website. Does the owner of the server machine have to install mailman? or can we somehow do it ourselves? and how do we set up our list? HELP?! Thank you. Anna From alex@caustic-creations.com Mon Jul 21 18:24:04 2003 From: alex@caustic-creations.com (Alex from Caustic Creations) Date: Mon Jul 21 17:24:04 2003 Subject: [Tutor] Flat file to associative array... Message-ID: <1058773486.1145.1.camel@caustic.laptop> Hello, What would be the best way to convert a flat file of products into a multi-dimensional array? The flat file looks like this: Beer|Molson|Dry|4.50 Beer|Molson|Export|4.50 Shot|Scotch|Macallan18|18.50 Shot|Regular|Jameson|3.00 I've managed to read the file properly and get the individual lines into a list, but I've got to turn this list into something that can be stored in memory like a dictionary / associative array so I can properly display the data. Here's the code I have so far: [Code] #! /usr/bin/python import string file = open("definitions", "r") while 1: line = file.readline() if not line: break else: data = string.split(line, '|') item = dict([('product', data[0])]) print "You want a " + item['product'] + ". What kind? " + data[1] + " for $" + data[3] + " ... right?" file.close() [/Code] Thanks in advance, Alex From dyoo@hkn.eecs.berkeley.edu Mon Jul 21 18:35:15 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 21 17:35:15 2003 Subject: [Tutor] read, write to file In-Reply-To: <002e01c34fdd$e08539a0$859780d1@net> Message-ID: On Mon, 21 Jul 2003, Vernon Miller wrote: > I spend all day trying to get this to work > > f=open('C:/Python22/Tools/tmp/workfile.txt', 'w') > f.write('This is the first line of the file') Hi Vernon, Oh! Don't forget to close() the file. This actually is important, because some operating systems will delay from actually writing the bits to disk until the file is explicitely closed. With the fix, your code might look like this: ### f = open('C:/Python22/Tools/tmp/workfile.txt', 'w') f.write('This is the first line of the file') f.close() ### Hope this fixes the problem! From mike@daboyz.org Mon Jul 21 18:49:02 2003 From: mike@daboyz.org (Michael Barrett) Date: Mon Jul 21 17:49:02 2003 Subject: [Tutor] importing modules In-Reply-To: <200307211400.15463.cybersamurai@mac.com> References: <200307211400.15463.cybersamurai@mac.com> Message-ID: <20030721214719.GA86130@daboyz.org> Assuming your project is in directory /path/to/project and the module is called 'mymodule.py' then you can do the following in your script: import sys sys.path.append('/path/to/project') import mymodule ===== Hope that helps. On Mon, Jul 21, 2003 at 02:00:15PM -0300, Luiz Siqueira Neto wrote: > How can I import modules inside of a directory in a root of my project? > > in java I use import dir.package.* > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ________________________________________________________________________ Mike Barrett | "We have veggie bacon, why don't we have mike@daboyz.org | meat fruit?" www.daboyz.org | -- My co-worker, Ben ------------------------+----------------------------------------------- From mike@daboyz.org Mon Jul 21 18:57:09 2003 From: mike@daboyz.org (Michael Barrett) Date: Mon Jul 21 17:57:09 2003 Subject: [Tutor] Stopping a loop with user input in curses In-Reply-To: <1058652249.1685.0.camel@caustic.laptop> References: <1058652249.1685.0.camel@caustic.laptop> Message-ID: <20030721215511.GB86130@daboyz.org> It looks to me like the problem is that you call 'theClock' which has a while loop inside it that never ends. I tried throwing your check for the button press of q in the while loop inside theClock but it looks like stdscr.getch() blocks until a button is pressed. This is because you don't have it set in no_delay mode. To set it in no_delay mode, use the nodelay method. Here's my edit to your code that seems to do what you want. No guarantee this is the best way to do it (i'm sure it's not) but it works for me. Hope this helps: #! /usr/bin/python # Import curses module import curses, time stdscr = curses.initscr() def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() while 1: t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() stdscr.nodelay(1) c = stdscr.getch() if c == ord('q'): curses.beep() break time.sleep(1) def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) ==== On Sat, Jul 19, 2003 at 06:04:10PM -0400, Alex from Caustic Creations wrote: > Hello all, > > I've written a small clock program in curses that I would > like to have end when someone presses 'q'. I've included the > code below. I'm *very* new to python so I apologize in advance if > this seems like a horribly obvious problem. I've spent all day > trying various structures but none of them have worked out. > > Any help would be greatly appreciated. > > Thanks, > > Alex > > > #! /usr/bin/python > > # Import curses module > > import curses, time > stdscr = curses.initscr() > > def theClock(): > > # Define global colour scheme > curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) > > # Get the screen size > max_y, max_x = stdscr.getmaxyx() > > # Calculate the clock position relative to the screen size > clock_x = max_x - 28 > > # Draw the clock > clockWindow = curses.newwin(3, 26, 1, clock_x) > clockWindow.bkgd(' ', curses.color_pair(1)) > clockWindow.box() > clockWindow.refresh() > > while 1: > t = time.asctime() > clockWindow.addstr(1, 1, t) > clockWindow.refresh() > time.sleep(1) > > > def main(stdscr): > > # Bring up the clock function > > theClock() > > # If 'q' is pressed, exit > while 2: > c = stdscr.getch() > if c == ord('q'): > curses.beep() > break > > > if __name__ == '__main__': > curses.wrapper(main) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ________________________________________________________________________ Mike Barrett | "We have veggie bacon, why don't we have mike@daboyz.org | meat fruit?" www.daboyz.org | -- My co-worker, Ben ------------------------+----------------------------------------------- From pythontutor@venix.com Mon Jul 21 19:18:03 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon Jul 21 18:18:03 2003 Subject: [Tutor] Stopping a loop with user input in curses In-Reply-To: <1058652249.1685.0.camel@caustic.laptop> References: <1058652249.1685.0.camel@caustic.laptop> Message-ID: <3F1C6661.80400@venix.com> You have two loops in your program. The first begins: while 1: and is in the theClock function. This loop will continue forever (1 represents True). To terminate this loop you need a break within it. The send loop is in the main body and begins: while 2: This loop is NEVER executed because you are still executing the first loop. You need to move the getch() call into the first loop. HOWEVER, this will cause the loop to pause until a key is pressed which is not what you want. If you call nodelay(1), then getch() will no longer wait for the keystroke. However, now getch() will raise an exception if there is no keystroke to "get". The following should help: stdscr.nodelay(1) # do not wait for a key press while 1: t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() try: c = stdscr.getch() if c == ord('q'): curses.beep() break except : # might be stdscr.error time.sleep(1) Attempt stdscr.error for the exception name. If that's wrong, Python will give you a traceback with the correct name. There's a tutorial at this link: http://www.python.org/doc/howto/curses/curses.html Alex from Caustic Creations wrote: > Hello all, > > I've written a small clock program in curses that I would > like to have end when someone presses 'q'. I've included the > code below. I'm *very* new to python so I apologize in advance if > this seems like a horribly obvious problem. I've spent all day > trying various structures but none of them have worked out. .... > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From jeff@ccvcorp.com Mon Jul 21 19:32:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 21 18:32:01 2003 Subject: [Tutor] Stopping a loop with user input in curses References: <1058652249.1685.0.camel@caustic.laptop> <3F1C6661.80400@venix.com> Message-ID: <3F1C69D7.1050706@ccvcorp.com> Lloyd Kvam wrote: > The following should help: > stdscr.nodelay(1) # do not wait for a key press > while 1: > t = time.asctime() > clockWindow.addstr(1, 1, t) > clockWindow.refresh() > try: > c = stdscr.getch() > if c == ord('q'): > curses.beep() > break > except : # might be stdscr.error > time.sleep(1) This isn't quite right -- as written, the 'try:' block won't be executed until *after* the 'while 1:' loop ends (i.e., never). To fix this, the entire try/except segment needs to be indented to the same level as the rest of the loop contents, instead of the level of the while statement, i.e. : stdscr.nodelay(1) # do not wait for a key press while 1: t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() try: c = stdscr.getch() if c == ord('q'): curses.beep() break except : # might be stdscr.error time.sleep(1) This may have been caused by a mailer error or some such, but indentation matters... Jeff Shannon Technician/Programmer Credit International From alan.gauld@blueyonder.co.uk Mon Jul 21 19:49:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Jul 21 18:49:02 2003 Subject: [Tutor] read, write to file References: <002e01c34fdd$e08539a0$859780d1@net> Message-ID: <00ca01c34fda$490931b0$6401a8c0@xp> > f=open('C:/Python22/Tools/tmp/workfile.txt', 'w') > f.write('This is the first line of the file') > > after it finally seemed to work I tried to read the line with readline() You don't show us that code so its hard to be sure, however you should close the file between writing and reading, or if you open it for both you need to remember to reset the file pointer back to the beginning with f.seek(0), you might also need to force the write with f.flush() > What I got was several hundred lines of x's and o's, but nothing was written > to the file Did you actually check the file by opening it in wordpad or some other text editor? Or are you just assuming that because you didn't see it in the output that it wasn't written? If you checked in wordpad then its probably a missing close/flush(). If you only looked at the output it could be there but you didn't reset the file pointer to the beginning... > last week I went through the same thing and after rebooting several times it > finally decided to work, This sounds like a missing flush/close issue, the OS eventually writes the buffered data and one time you got lucky in your timing... > it seems to me that there is something > fundamentally wrong with the read, write to file functions in this latest > version of python. Nope, all versions of Python(and most other languages) work the same way with buffered file I/O. Its actually a good thing because it significantly improves the speed of file operations, but it does require a little bit of good housekeeping on occasion. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pythontutor@venix.com Mon Jul 21 19:53:01 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon Jul 21 18:53:01 2003 Subject: [Tutor] Stopping a loop with user input in curses In-Reply-To: <3F1C69D7.1050706@ccvcorp.com> References: <1058652249.1685.0.camel@caustic.laptop> <3F1C6661.80400@venix.com> <3F1C69D7.1050706@ccvcorp.com> Message-ID: <3F1C6E77.30501@venix.com> It looked OK on my screen, but it was a mixture of spaces and tabs. (And again, I believe the try / except stuff is wrong.) (And I still recommend "Python in a Nutshell") Jeff Shannon wrote: .... > This may have been caused by a mailer error or some such, but > indentation matters... -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From glingl@aon.at Mon Jul 21 19:55:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Jul 21 18:55:01 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) Message-ID: <3F1C6F8B.5030209@aon.at> Hi! The problem, that makes me angry, upset and depressed ocurred for the first time, when I installed and tried to use Python 2.3 on a Windows2000 machine. It goes like this: When I try to run a program from the new IDLE an error occurs: Warning: HOME environment variable points to c:\epacris\tinyfugue\home but the path does not exist. ================================ RESTART ================================ At the same time Python seems to report this to ... hmmm ... to whom? (Also annoying! I'd like to be informed about messages going from my computer to whom ever ... Whoever it may be, the adressee willnot be happy with error wessages like this. ) The situation on my machine is as follows: I have an old installation of Windows NT on drive C. This I still use only for very special purposes. Two or more years ago there I had installed "epacris", but I deleted it long ago. Now I use an installation of Windows 2000 Prof on drive H, with Python installed on drive I. When I thought about the mentioned error, I had the idea that there was a home environment variable in the old NT-installation pointing to "C:\epacris ... " And indeed, it was. I deleted it. But the error didn't go away! I tried to use regedit to search for "home" in the registry of both installations, without success. (I am NOT an experienced user of regedit!) Now I have no clue of how to proceed. In the meantime the same error was the reason, that the drpython-editor dosn't work. Searching for the reason, I fond out, that: >>> os.path.expanduser("~") 'c:\\epacris\\tinyfugue\\home' >>> I don't understand how this comes? I have no environment variable HOME defined on both installations - or I don't know how to locate them, if they are created automatically. I don't even understand, why win2000, installed in H: searches for something in C: ? I believe, that this is a Windows-Problem, but it never occured with any other program except of Python or Python-apps. Maybe there is a very simple solution to this. Maybe there is a knowledgable women or man out there, who can help? Or is it time to make a change, just relax, take it easy ... and install Linux? With very unhappy greetings Gregor P.S.: Next time I hope to be in a better mood ;-( From dyoo@hkn.eecs.berkeley.edu Mon Jul 21 21:37:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 21 20:37:01 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) In-Reply-To: <3F1C6F8B.5030209@aon.at> Message-ID: On Tue, 22 Jul 2003, Gregor Lingl wrote: > Now I have no clue of how to proceed. In the meantime the same error > was the reason, that the drpython-editor dosn't work. Searching for the > reason, I fond out, that: > > >>> os.path.expanduser("~") > 'c:\\epacris\\tinyfugue\\home' Hi Gregor, Ok, let's just double check something... Ok, the guilty code is probably in 'ntpath.py'. Let's take a look. ### def expanduser(path): """Expand ~ and ~user constructs. If user or $HOME is unknown, do nothing.""" if path[:1] != '~': return path i, n = 1, len(path) while i < n and path[i] not in '/\\': i = i + 1 if i == 1: if os.environ.has_key('HOME'): userhome = os.environ['HOME'] elif not os.environ.has_key('HOMEPATH'): return path else: try: drive = os.environ['HOMEDRIVE'] except KeyError: drive = '' userhome = join(drive, os.environ['HOMEPATH']) else: return path return userhome + path[i:] ### Hmmm. Not only does it look at HOME, but Python will try to go for HOMEDRIVE and HOMEPATH too! Wow, that's thorough. *grin* Gregor, can you drop down to the DOS prompt and try: echo $HOME echo $HOMEPATH echo $HOMEDRIVE and tell us what you get? I do get the feeling that there's some lingering environmental variables in your NT installation that's doing funny things. Let's double check to see if those variables are initialized. > Or is it time to make a change, just relax, take it easy ... Take it easy. *grin* Don't worry, we'll get to the bottom of this. Good luck! From shalehperry@comcast.net Mon Jul 21 21:37:14 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Mon Jul 21 20:37:14 2003 Subject: [Tutor] mailman on website In-Reply-To: <200307201523.22803.anna@aleax.it> References: <200307201523.22803.anna@aleax.it> Message-ID: <200307211735.41010.shalehperry@comcast.net> On Sunday 20 July 2003 06:23, Anna Ravenscroft wrote: > Does anyone here know how to get mailman setup on a website? We're trying > to do it for a non-profit community group and feeling very overwhelmed.... > I realize this is only peripherally python=related but I hang out here and > I know folks here so I'm hoping someone can help... > > If anyone has experience on this, let me know what we would do as a first > step... > > Um - we have a website, that is on a server donated by someone in the > group. We ftp files there for the website. Does the owner of the server > machine have to install mailman? or can we somehow do it ourselves? and how > do we set up our list? > you have to have login access to the host. If it is a Unix-like machine (Sun, BSD, Linux, etc) ssh will work. However, if you do not know what you are doing the install can be tricky. You might be better off paying them for the 2 - 3 hours of time they are likely to charge you. From shalehperry@comcast.net Mon Jul 21 21:49:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Mon Jul 21 20:49:02 2003 Subject: [Tutor] Flat file to associative array... In-Reply-To: <1058773486.1145.1.camel@caustic.laptop> References: <1058773486.1145.1.camel@caustic.laptop> Message-ID: <200307211748.24799.shalehperry@comcast.net> On Monday 21 July 2003 00:44, Alex from Caustic Creations wrote: > Hello, > > What would be the best way to convert a flat file of products into > a multi-dimensional array? The flat file looks like this: > > Beer|Molson|Dry|4.50 > Beer|Molson|Export|4.50 > Shot|Scotch|Macallan18|18.50 > Shot|Regular|Jameson|3.00 > #!/usr/bin/python2.3 import csv class PipeDialect(csv.Dialect): delimiter = '|' quotechar = '"' escapechar = None doublequote = True skipinitialspace = False lineterminator = '\n' quoting = csv.QUOTE_MINIMAL csv.register_dialect('pipe-based', PipeDialect) fp = open('/tmp/test.csv') reader = csv.reader(fp, 'pipe-based') for row in reader: print row why right parsers when you don't have to (-: As for the real question you asked, just play arond a little more, you'll get it. From tutor@python.org Mon Jul 21 22:52:02 2003 From: tutor@python.org (Tim Peters) Date: Mon Jul 21 21:52:02 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) In-Reply-To: <3F1C6F8B.5030209@aon.at> Message-ID: [Gregor Lingl] > The problem, that makes me angry, upset and depressed ocurred > for the first time, when I installed and tried to use Python 2.3 on a > Windows2000 machine. > > It goes like this: > > When I try to run a program from the new IDLE an error > occurs: > > Warning: HOME environment variable points to > c:\epacris\tinyfugue\home > but the path does not exist. > ================================ RESTART > ================================ Use the source, Gregor. Searching for HOME shows the source of this msg in Lib/idlelib/configHandler.py. The docstring for method GetUserCfgDir() is """ Creates (if required) and returns a filesystem directory for storing user config files. """ That's all it's trying to do. > At the same time Python seems to report this to ... hmmm ... to whom? There's no such code anywhere near the bit that displays this warning. > (Also annoying! I'd like to be informed about messages going from my > computer to whom ever ... Whoever it may be, the adressee willnot be > happy with error wessages like this. ) Why is it that you think IDLE is reporting this to someone? Note that the new IDLE *does* use sockets, but only on localhost. It needs to do this in order to implement the most-often requested of all features for IDLE: running code in a separate process, in order to avoid unbreakable infinite loops, and impossibly difficult by-hand reload() sequences. Socket activity may look like "network activity" to you (for example, if you're running ZoneAlarm, it will ask whether you want to allow this traffic), but it's all just your machine talking to itself. These new (for IDLE) uses of sockets can be found in Lib/idlelib/PyShell.py. > ... > Or is it time to make a change, > just relax, > take it easy > ... > and install Linux? IDLE will use sockets there too . From glingl@aon.at Tue Jul 22 03:41:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 22 02:41:01 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) References: Message-ID: <3F1CDCCA.4050104@aon.at> Danny Yoo schrieb: >On Tue, 22 Jul 2003, Gregor Lingl wrote: > > > >>'c:\\epacris\\tinyfugue\\home' >> >> > > >Hi Gregor, > > > >Ok, let's just double check something... Ok, the guilty code is probably >in 'ntpath.py'. Let's take a look. > >### >def expanduser(path): > """Expand ~ and ~user constructs. > > If user or $HOME is unknown, do nothing.""" > .... >### > > >Hmmm. Not only does it look at HOME, but Python will try to go for >HOMEDRIVE and HOMEPATH too! Wow, that's thorough. *grin* > > >Gregor, can you drop down to the DOS prompt and try: > > echo $HOME > echo $HOMEPATH > echo $HOMEDRIVE > I tried this yesterday, and indeed at the DOS prompt HOME had the value "C:\epacris....", although it didn't show up as an environment variable in 'system' of the control panel any more. I was not able to delete it, so I created a new (dummy - hmm?) directory I:\home and set HOME = I:\home This now showed up in control panel's system. When I tried to delete it there, it's old value was surprisingly and silently restored. I can live with my new HOME, and even if this in my view at first was a "work-around", the new IDLE immediately used it to store it's .idlerc directory and there it's recent file list. So it turned out not only to be a workaround, but also useful. Nevertheless I feel a bit uneasy, as this old HOME "C:\epacris\..." is apparently stored somewhere in the system, and I can't find out where nor why it is restored automatically when I delete the HOME environment variable. >and tell us what you get? I do get the feeling that there's some >lingering environmental variables in your NT installation that's doing >funny things. > So you see, that your feelings meet exactly what's going on! >Let's double check to see if those variables are >initialized. > > >>Or is it time to make a change, just relax, take it easy ... >> >> > >Take it easy. *grin* Don't worry, we'll get to the bottom of this. > > Hmmm..., I'm not sure if we'll really get to the VERY bottom of this Many thanks for your quick response (indeed I feel better now) Gregor > >Good luck! > > > > > From glingl@aon.at Tue Jul 22 03:55:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 22 02:55:03 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) References: Message-ID: <3F1CE027.8040608@aon.at> Tim Peters schrieb: >[Gregor Lingl] > > >>The problem, that makes me angry, upset and depressed ocurred >>for the first time, when I installed and tried to use Python 2.3 on a >>Windows2000 machine. >> >>It goes like this: >> >>When I try to run a program from the new IDLE an error >>occurs: >> >> Warning: HOME environment variable points to >> c:\epacris\tinyfugue\home >> but the path does not exist. >>================================ RESTART >>================================ >> >> > >Use the source, Gregor. Searching for HOME shows the source of this msg in >Lib/idlelib/configHandler.py. The docstring for method GetUserCfgDir() is > > """ > Creates (if required) and returns a filesystem directory for > storing user config files. > """ > >That's all it's trying to do. > > Yes, I see. The problem, however, lies apparently in the way window treats it's environment variables. > > >>At the same time Python seems to report this to ... hmmm ... to whom? >> >> > >There's no such code anywhere near the bit that displays this warning. > > Ah! This apparently was a bad shortcut ... >>(Also annoying! I'd like to be informed about messages going from my >>computer to whom ever ... Whoever it may be, the adressee willnot be >>happy with error wessages like this. ) >> >> > >Why is it that you think IDLE is reporting this to someone? Note that the >new IDLE *does* use sockets, but only on localhost. It needs to do this in >order to implement the most-often requested of all features for IDLE: >running code in a separate process, in order to avoid unbreakable infinite >loops, and impossibly difficult by-hand reload() sequences. Socket activity >may look like "network activity" to you (for example, if you're running >ZoneAlarm, it will ask whether you want to allow this traffic), but it's all >just your machine talking to itself. > > I use Norton's Internet security and this reports: I:\Python23\pythonw.exe is going to access the internet ... (or something like this). I apparently did misinterpret this. (For me this raises the question, if it were impossible for programs like ZoneAlarm, Norton's... etc, to find out (e.g. via the IP adress) if such traffic is just adressing the own machine?) So thanks, Tim, for your explanations. Gregor >These new (for IDLE) uses of sockets can be found in Lib/idlelib/PyShell.py. > > > >>... >>Or is it time to make a change, >>just relax, >>take it easy >>... >>and install Linux? >> >> > >IDLE will use sockets there too . > > > > > From thomi@thomi.imail.net.nz Tue Jul 22 04:34:00 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Tue Jul 22 03:34:00 2003 Subject: [Tutor] how to call "~wxDialog()" in python? Message-ID: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> Hey, when trying to destroy a (WxWindows) window, I have to call a function called "self.~wxDialog()" However, python complains about the '~' character: thomi@Julie:~/work/python sources/wxPython$ ./wedderburn.py File "./wedderburn.py", line 146 EVT_BUTTON(self,ID_PREFS_CLOSEBUTTON,self.~wxDialog) ^ SyntaxError: invalid syntax I tried escaping it with a '\' character, like you can do in some other languages, but that didn't seem to work either. I also thought that maybe the python wrapper to the wxWindows library had changed thename of this function, but i couldn't see any mention of it in the latest documentation. ummm... "HELP!"... I'm kinda stuck now..... *hides under desk* thanks, -- Thomi Richards, thomi@thomi.imail.net.nz From thomi@thomi.imail.net.nz Tue Jul 22 04:46:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Tue Jul 22 03:46:02 2003 Subject: [Tutor] how to call "~wxDialog()" in python? In-Reply-To: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> References: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> Message-ID: <20030722194503.6afb3d3a.thomi@thomi.imail.net.nz> I guess i should append to that: I expected to see some kind of close method for things like dialog boxes, but the documentation here: http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin111.htm#topic189 doesn't mention there being any such thing. Am i using the wrong documentation? or is it not complete? or (most likely) am I just a complete Idiot ;) -- Thomi Richards, thomi@thomi.imail.net.nz From dhanvik@gmx.net Tue Jul 22 07:58:01 2003 From: dhanvik@gmx.net (K Dhanvi) Date: Tue Jul 22 06:58:01 2003 Subject: [Tutor] Final de-allocation before the application exists Message-ID: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> This is a multi-part message in MIME format. ------=_NextPart_000_00F7_01C3506E.8240DF20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi friends,=20 =20 I am developing an module where I allocate certain threads and memory = in the module and an application would use this allocated resources. I = would like to know whether Python provides any function which would be = called at the end of the life cycle of the application or just before = the application exits. =20 =20 I would like to know whether to know since, I would like to hide this = function in my module and not force the user to call the function. This = would remove the dependency on the user to specifically call the = function. Also if there is such a function , I can make sure that the my = module resources are de-allocated gracefully.=20 Please let me know incase this can be possible. with regards,=20 K Dhanvi ------=_NextPart_000_00F7_01C3506E.8240DF20 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi friends,
 
  I am developing an module where I allocate = certain=20 threads and memory in the module and an application would use this=20 allocated resources. I would like to know whether Python provides = any=20 function which would be called at the end of the life cycle of the=20 application or just before the application exits.  =
 
  I would like to know whether to know = since, =20 I would like to hide this function in my module and not = force the=20 user to call the function. This would remove the dependency on the = user to=20 specifically call the function. Also if there is such a function , I can = make=20 sure that the my module resources are de-allocated gracefully.=20
 
    Please let me know incase this can be=20 possible.
 
with regards,
K=20 Dhanvi
------=_NextPart_000_00F7_01C3506E.8240DF20-- From dhanvik@gmx.net Tue Jul 22 08:26:02 2003 From: dhanvik@gmx.net (K Dhanvi) Date: Tue Jul 22 07:26:02 2003 Subject: [Tutor] Final de-allocation before the application exists References: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> Message-ID: <011801c35044$533cfd50$0d001eac@ud.cybage.com> This is a multi-part message in MIME format. ------=_NextPart_000_0115_01C35072.6A148790 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Sorry about my english in the previous mail.=20 I re-state my question in this mail :=20 I would like to know whether Python has a function which would be = called just before the end of the application. I cannot use destructors = in my application because I have some static data in my application that = is modified during the life cycle of the application. If I have any = function like this , then I could hide the gory details of de-allocation = of resources completely from the user. This way, what he ( user ) does = not know, he need not be bothered about :)..=20 ( I am allocating the resources and threads in my module which is used = by an application. I would like to de-allocate resources in the = application ) well thats my query.. incase theres something I am missing in my = approach please point me out .. thanks a lot for your time and help. with regards,=20 K Dhanvi ----- Original Message -----=20 From: K Dhanvi=20 To: tutor@python.org=20 Sent: Tuesday, July 22, 2003 4:30 PM Subject: [Tutor] Final de-allocation before the application exists Hi friends,=20 =20 I am developing an module where I allocate certain threads and = memory in the module and an application would use this allocated = resources. I would like to know whether Python provides any function = which would be called at the end of the life cycle of the application or = just before the application exits. =20 =20 I would like to know whether to know since, I would like to hide = this function in my module and not force the user to call the function. = This would remove the dependency on the user to specifically call the = function. Also if there is such a function , I can make sure that the my = module resources are de-allocated gracefully.=20 Please let me know incase this can be possible. with regards,=20 K Dhanvi ------=_NextPart_000_0115_01C35072.6A148790 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Sorry about my english in the previous mail. =
 
I re-state my question in this mail :
 
  I would like to know whether Python has a = function=20 which would be called just before the end of the application. I cannot = use=20 destructors in my application because I have some static data in my = application=20 that is modified during the life cycle of the application.  If I = have any=20 function like this , then I could hide the gory details of de-allocation = of=20 resources completely from the user. This way, what he ( = user ) does=20 not know, he need not be bothered about :)..
  ( I am allocating the resources and threads = in my=20 module which is used by an application. I would like to de-allocate = resources in the application  )
 
well thats my query.. incase theres something I am = missing in=20 my approach please point me out .. thanks a lot for your time and=20 help.
 
with regards,
K Dhanvi
----- Original Message -----
From:=20 K = Dhanvi
Sent: Tuesday, July 22, 2003 = 4:30=20 PM
Subject: [Tutor] Final = de-allocation=20 before the application exists

Hi friends,
 
  I am developing an module where I allocate = certain=20 threads and memory in the module and an application would use = this=20 allocated resources. I would like to know whether Python provides = any=20 function which would be called at the end of the life cycle of = the=20 application or just before the application exits.  =
 
  I would like to know whether to know = since, =20 I would like to hide this function in my module and not = force=20 the user to call the function. This would remove the dependency = on the=20 user to specifically call the function. Also if there is such a = function , I=20 can make sure that the my module resources are de-allocated = gracefully.=20
 
    Please let me know incase this can = be=20 possible.
 
with regards,
K=20 Dhanvi
------=_NextPart_000_0115_01C35072.6A148790-- From klappnase@freenet.de Tue Jul 22 08:29:02 2003 From: klappnase@freenet.de (klappnase) Date: Tue Jul 22 07:29:02 2003 Subject: [Tutor] Problem recording large wav files with Snack In-Reply-To: References: <20030717130738.4f09e98d.klappnase@freenet.de> Message-ID: <20030722132933.3c3a99ac.klappnase@freenet.de> On Thu, 17 Jul 2003 17:30:13 -0700 (PDT) Danny Yoo wrote: > > > On Thu, 17 Jul 2003, klappnase wrote: > > > I am trying to develop some little sound applications for linux using > > the snack toolkit. (I am far from being a "professional" programmer, but > > just a beginner). > > > > I want to record large files to disk (whole sides of vinyl albums), so I > > do something like: > > > > s = tkSnack.Sound(encoding="Lin16", frequency=44100, channels=2, > > fileformat="WAV", byteorder="littleEndian,\ > > precision="double", file="xyz.wav") > > s.record() > > > Hi klappnase, > > > I'm not too familiar with the tkSnack module, and I'm not sure if any of > us here can help diagnose the problem; it sounds more like an operating > systems issue more than anything else. you may want to contact Snack's > author, according to: > > http://www.speech.kth.se/snack/FAQ.html > Thanks, I think I'll should try that. > > We can, at least, see Python syntax errors... *grin* Are you sure that's > not missing a quote sign here? > > fileformat="WAV", byteorder="littleEndian,\ > ^^^^^^^^^^^^^^^ Oops! Just a typo in the mail of course. > > > [off-topic, sorta: > > If you are running on a Linux system, you may want to double check > that your hard drive is tuned to performance: > > http://linux.oreillynet.com/pub/a/linux/2000/06/29/hdparm.html > > Most Linux systems are very conservative in the way they use their > hard drives --- you may be running into a simple IO issue. > ] udma2, I think that should be sufficient, more is not possible anyway. > > Good luck! > Thanks again Regards Michael From klappnase@freenet.de Tue Jul 22 08:29:15 2003 From: klappnase@freenet.de (klappnase) Date: Tue Jul 22 07:29:15 2003 Subject: [Tutor] Re: Using PMW? In-Reply-To: <000601c34fde$cb9f61e0$0300a8c0@hobie3> References: <9a410299.0307191709.28fcbdf6@posting.google.com> <000601c34fde$cb9f61e0$0300a8c0@hobie3> Message-ID: <20030722133006.3ace13a5.klappnase@freenet.de> On Mon, 21 Jul 2003 16:21:20 -0700 "Ken Erickson" wrote: > One thing that I have noticed is that when I start the IDLE program and type > "import pmw" I get: > > >>> import pmw > Traceback (most recent call last): > File "", line 1, in ? > import pmw > ImportError: No module named pmw Seems like there is a typo here; the module's name Is Pmw. > I did a search for "pmw.py" and found nothing on my system. I'm new to > Python so I'm not sure if I'm suppose to build this module or what? Do you > have any ideas? > I have no such file, too; I must admit that I don't know much about Pmw, but that is obviousliy o.k. The best you try it again with "import Pmw" and see what happens. Regards Michael From godoy@metalab.unc.edu Tue Jul 22 08:41:01 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Tue Jul 22 07:41:01 2003 Subject: [Tutor] how to call "~wxDialog()" in python? In-Reply-To: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> (Thomas CLive Richards's message of "Tue, 22 Jul 2003 19:33:04 +1200") References: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> Message-ID: Thomas CLive Richards writes: > when trying to destroy a (WxWindows) window, I have to call a function > called "self.~wxDialog()" However, python complains about the '~' > character: > > thomi@Julie:~/work/python sources/wxPython$ ./wedderburn.py > File "./wedderburn.py", line 146 > EVT_BUTTON(self,ID_PREFS_CLOSEBUTTON,self.~wxDialog) > ^ > SyntaxError: invalid syntax I use the following to close my dialogs: ====================================================================== class About(wxDialog): def __init__(self, *args, **kwds): # begin wxGlade: About.__init__ (...) self.button_4 = wxButton(self.panel_5, -1, "Fechar") (...) # end wxGlade (...) EVT_BUTTON(self, -1, self.OnExit) (...) def OnExit(self, event): self.Close(True) ====================================================================== I.e., I let the only button on the dialog with the standard ID of '-1' and associate it to a function 'OnExit' in the same class. See you, -- Godoy. From Jan.Wilhelmsen@bilia.no Tue Jul 22 11:02:22 2003 From: Jan.Wilhelmsen@bilia.no (Wilhelmsen Jan) Date: Tue Jul 22 10:02:22 2003 Subject: [Tutor] sorting a 'large' datafile Message-ID: <9DB3344EC407D311A0A500508B0963E401DE32DB@ex84701.cars.no.bilia.net> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C35059.8A329CB0 Content-Type: text/plain I need to sort records in a datafile by specific positions in the file. The records in the datafile look like this: 3000010711004943 200211052002110520021120015980050378 3000010711004943 200211052002110520021120015980050378 3200010711004943 200211052002110520021120015980050378 3100010711004943 200211052002110520021120015980050378 3000010711004943 200211052002110520021120015980050378 3000014211015894 200211052002110520021205030700161 3200014211015894 000000000451606+24 BD30599 3200014211015894 000000000158000+24 BD30599 3200014211015894 000000000033600+24 BD30599 3200014211015894 000000000025900+24 BD30599 3100014211015894 000000000038400+24 BD30599 I've created two variables for the fields I want to sort by: rt = line[:2] dok = line[6:16] First I want to sort by 'dok' then by 'rt'. Do I have to read the whole file into memory before I can begin sorting the records? I tried to read in all the lines but everything crashes when I do. The file is only 250kb so this should be possibly, or I'm I wrong? Can anyone give me some tips? Thanks in advance Jan Wilhelmsen IT-Technician Bilia Personbil as ------------------------------------------------------------------------------- This verifies that this e-mail has been scanned for virus and deemed virus-free according to F-secure Content Scanner 5.0 Tue, 22 Jul 2003 15:59:59 +0200 GMT ------------------------------------------------------------------------------- ------_=_NextPart_001_01C35059.8A329CB0 Content-Type: text/html Content-Transfer-Encoding: quoted-printable

I need to sort records in= a datafile by specific positions in the file.

 <= /font>

The records in the datafile look like this:

 <= /font>

3000010711004943      200211052002110520021120015980050378

3000010711004943      200211052002110520021120015980050378

3200010711004943      200211052002110520021120015980050378

3100010711004943      200211052002110520021120015980050378

3000010711004943      200211052002110520021120015980050378

3000014211015894      200211052002110520021205030700161   

3200014211015894      000000000451606+24        =      BD30599        =             

3200014211015894      000000000158000+24        =      BD30599        =             

3200014211015894      000000000033600+24        =      BD30599        =             

3200014211015894      000000000025900+24        =      BD30599        =             

3100014211015894      000000000038400+24        =      BD30599    &nbs= p;            &= nbsp;  

 

I've created two variables for the fields I want to sort by:

 <= /font>

        rt =3D line[:2]=

        dok =3D line[6:16]

 <= /font>

First I want to sort by '= dok' then by 'rt'.

 <= /font>

Do I have to read the who= le file into memory before I can begin sorting the records?<= /font>

 <= /font>

I tried to read in all th= e lines but everything crashes when I do.

 <= /font>

The file is only 250kb so= this should be possibly, or I'm I wrong?

 <= /font>

Can anyone give me some t= ips?

 <= /font>

Thanks in advance

 <= /font>

Jan Wilhelmsen

IT-Tech= nician

Bilia Personbil as

 =



---------------------------------------------------------------------------= ----
This verifies that this e-mail has been scanned for virus and deemed virus-= free
according to F-secure Content Scanner 5.0
Tue, 22 Jul 2003 15:59:59 +0200 GMT
---------------------------------------------------------------------------= ----
------_=_NextPart_001_01C35059.8A329CB0-- From jeff@ccvcorp.com Tue Jul 22 13:35:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 22 12:35:01 2003 Subject: [Tutor] how to call "~wxDialog()" in python? References: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> Message-ID: <3F1D6779.2070404@ccvcorp.com> Thomas CLive Richards wrote: > when trying to destroy a (WxWindows) window, I have to call a function > called "self.~wxDialog()" However, python complains about the '~' > character: > > thomi@Julie:~/work/python sources/wxPython$ ./wedderburn.py > File "./wedderburn.py", line 146 > EVT_BUTTON(self,ID_PREFS_CLOSEBUTTON,self.~wxDialog) > ^ > SyntaxError: invalid syntax You're looking at the wxWindows docs, which are for C++. As of yet, there aren't any wxPython-specific docs, just annotations in the C++ docs. So, in many cases, it's necessary to translate the C++ in the docs into Python. In this particular case, the ~wxDialog() is a C++ destructor. C++ requires you to specify exactly how to destroy an object and free any memory that it's allocated; in most cases Python handles that sort of thing for you. So, you really *don't* need to call a destructor for Python. The method that you need to call in order to destroy a wxPython window (whether frame, dialog, or whatever) is Destroy(). However, you probably want to do that from an OnClose() handler. In your __init__() (or wherever you're hooking events), you'll want to add a line to hook EVT_CLOSE: EVT_CLOSE(self, self.OnCloseWindow) The event handler for it is pretty simple: def OnCloseWindow(self, event): self.Destroy() return true Now, anything that causes your window to close should go through this event, which is triggered by the Close() method on all wxWindows. Thus, your above button event looks like this: EVT_BUTTON(self,ID_PREFS_CLOSEBUTTON,self.Close()) The real advantage here comes when there's something that needs done any time that you close the window; you can put that code in OnCloseWindow(), and it will be run regardless of the method used to close the window, whether it's by a button, from a menu, or from the close-button (the [X]) in the corner of the title bar. Jeff Shannon Technician/Programmer Credit International From bgailer@alum.rpi.edu Tue Jul 22 13:41:49 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Tue Jul 22 12:41:49 2003 Subject: [Tutor] sorting a 'large' datafile In-Reply-To: <9DB3344EC407D311A0A500508B0963E401DE32DB@ex84701.cars.no.b ilia.net> Message-ID: <5.2.1.1.0.20030722103639.0271a9f0@66.28.54.253> --=======516411C5======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6751694E; boundary="=====================_8123250==.ALT" --=====================_8123250==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6751694E; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:59 PM 7/22/2003 +0200, Wilhelmsen Jan wrote: >I need to sort records in a datafile by specific positions in the file. >The records in the datafile look like this: > >3000010711004943 200211052002110520021120015980050378 >3000010711004943 200211052002110520021120015980050378 >3200010711004943 200211052002110520021120015980050378 >3100010711004943 200211052002110520021120015980050378 >3000010711004943 200211052002110520021120015980050378 >3000014211015894 200211052002110520021205030700161 >3200014211015894 000000000451606+24 BD30599 > >3200014211015894 000000000158000+24 BD30599 > >3200014211015894 000000000033600+24 BD30599 > >3200014211015894 000000000025900+24 BD30599 > >3100014211015894 000000000038400+24 BD30599 > > >I've created two variables for the fields I want to sort by: > rt = line[:2] > dok = line[6:16] >First I want to sort by 'dok' then by 'rt'. >Do I have to read the whole file into memory before I can begin sorting >the records? >I tried to read in all the lines but everything crashes when I do. >The file is only 250kb so this should be possibly, or I'm I wrong? >Can anyone give me some tips? Consider using the sqlite database. It will handle large files and sort very efficiently. http://www.sqlite.org for the database. http://pysqlite.sourceforge.net/ for the Python wrapper. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_8123250==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6751694E; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:59 PM 7/22/2003 +0200, Wilhelmsen Jan wrote:

I need to sort records in a datafile by specific positions in the file.
The records in the datafile look like this:

3000010711004943      200211052002110520021120015980050378
3000010711004943      200211052002110520021120015980050378
3200010711004943      200211052002110520021120015980050378
3100010711004943      200211052002110520021120015980050378
3000010711004943      200211052002110520021120015980050378
3000014211015894      200211052002110520021205030700161   
3200014211015894      000000000451606+24             BD30599                    
3200014211015894      000000000158000+24             BD30599                    
3200014211015894      000000000033600+24             BD30599                    
3200014211015894      000000000025900+24             BD30599                    
3100014211015894      000000000038400+24             BD30599                    

I've created two variables for the fields I want to sort by:
        rt = line[:2]
        dok = line[6:16]
First I want to sort by 'dok' then by 'rt'.
Do I have to read the whole file into memory before I can begin sorting the records?
I tried to read in all the lines but everything crashes when I do.
The file is only 250kb so this should be possibly, or I'm I wrong?
Can anyone give me some tips?

Consider using the sqlite database. It will handle large files and sort very efficiently.
http://www.sqlite.org for the database.
http://pysqlite.sourceforge.net/ for the Python wrapper.

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_8123250==.ALT-- --=======516411C5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6751694E Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======516411C5=======-- From jeff@ccvcorp.com Tue Jul 22 13:46:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 22 12:46:02 2003 Subject: [Tutor] Final de-allocation before the application exists References: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> <011801c35044$533cfd50$0d001eac@ud.cybage.com> Message-ID: <3F1D6A4F.4010004@ccvcorp.com> K Dhanvi wrote: > I would like to know whether Python has a function which would be > called just before the end of the application. I cannot use > destructors in my application because I have some static data in my > application that is modified during the life cycle of the > application. If I have any function like this , then I could hide the > gory details of de-allocation of resources completely from the user. > This way, what he ( user ) does not know, he need not be bothered > about :).. This depends a bit on just what you're thinking of de-allocating. In most cases, when Python closes, it will automatically clean up after itself. This includes freeing memory, closing open files, releasing sockets, etc, etc. So, you *probably* don't actually need to do this yourself. The big exception would be if that static data you mention needs to be written to disk before the application exits. (Threads cannot be closed from outside that thread, they must stop themselves, but they do so automatically when the application closes unless the thread has been marked as a daemon, in which case they prevent the app from closing.) The best way to do that depends very much on the structure of your program. Most (all?) GUI toolkits allow you to hook into window-closing and application-closing events; a text menu-driven app would probably have an exit option that could be expanded on. Tell us a bit more about what you need to do at closing, and how your program operates, and we can probably give a little bit better advice... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Tue Jul 22 14:19:09 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 22 13:19:09 2003 Subject: [Tutor] sorting a 'large' datafile References: <9DB3344EC407D311A0A500508B0963E401DE32DB@ex84701.cars.no.bilia.net> Message-ID: <3F1D722B.9010902@ccvcorp.com> Wilhelmsen Jan wrote: > I need to sort records in a datafile by specific positions in the file. > > [...] > > I've created two variables for the fields I want to sort by: > > > > rt = line[:2] > > dok = line[6:16] > > > > First I want to sort by 'dok' then by 'rt'. > > > > Do I have to read the whole file into memory before I can begin > sorting the records? > > > > I tried to read in all the lines but everything crashes when I do. > > > > The file is only 250kb so this should be possibly, or I'm I wrong? > 250kB should indeed fit into memory with no problem, provided you have a reasonable amount of memory in your computer. (If your computer is old enough to have less than 100 times that much memory, you've probably got bigger problems than just memory size.) You probably will need to read the entire file into memory before you can sort it. There are ways to avoid doing so, including dumping the contents into a database, but this is a simple enough problem on a small enough data set that doing this the simple way should be easy enough. You didn't specify the exact cause of the crash (cutting and pasting the traceback into your email is a good idea), so I can't see what your problem was before, but I'll show you how it should work. The best approach here varies somewhat depending on what exactly it is that you want to do with your data once you've sorted it. In all likelihood, though, you're going to want to end up with a list of records in the appropriate order. There's a couple of options on how to store the records -- you can write a simple class and create an instance of that class for each record, or you can just convert each record into a tuple (or list). I'll use tuples here for simplicity's sake. The first thing you need to do is read in the contents of your file. Since you have one line per record, it's pretty easy to get a basic list of records -- datafile = file('myfile.dat','r') lines = datafile.readlines() You now have a list of lines, and you want to sort that list, but you need to sort it based on specific subfields. Lists have a sort() method, but you need to arrange things so that the right subfields will be sorted on in the right order. The easiest way to do this is to convert each line into a tuple -- sort() automatically sorts tuples (and lists) based on the first element, and if those match it sorts based on the second element, and so on. So if we turn each line into a tuple like (dok, rt, entire_line), it should get sorted in just the way that you want. We can write a quick function that'll do this for a single line, and then apply that function to each element in our list of lines. The function should look something like this: def make_tuple(line): dok = line[6:16] rt = line[:2] return (dok, rt, line) Actually, you could do it as a single line, depending on your preferences for succinctness-- def make_tuple(line): return (line[6:16], line[:2], line) The first version may make it a little easier to understand your intent in another six months presuming that it's clear from context what 'dok' and 'rt' stand for ;) but the second version is a bit shorter and infinitessimally quicker. There's a couple of ways to do the same operation on every item in a list, but my preference in this sort of situation is to use a list comprehension -- data = [make_tuple(line) for line in lines] So now you have your list of tuples, and you can sort them. data.sort() Be aware that this sorts the list in place -- it's easy to be tempted to write something like sorted_list = data.sort() but this will not work -- the list pointed to by data will be sorted, and the name sorted_list will point to None. (Lists use an in-place sort instead of returning a sorted copy to conserve memory in case the list is very large, and sort() returns None to make it very clear that the sort is done in-place.) So now data is a sorted list of tuples. If you now want to have just the raw lines again, but in this sorted order, you can use another list comprehension to strip that out -- data = [line[-1] for line in data] This will make a list of only the last element of each tuple, but will preserve order. You may also want to keep the tuples, and simply refer to 'tok' as item[0], 'rt' as item[1], and the entire line as item[2]. Jeff Shannon Technician/Programmer Credit International From lsloan@umich.edu Tue Jul 22 15:07:01 2003 From: lsloan@umich.edu (Lance E Sloan) Date: Tue Jul 22 14:07:01 2003 Subject: [Tutor] Final de-allocation before the application exists In-Reply-To: <011801c35044$533cfd50$0d001eac@ud.cybage.com> References: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> <011801c35044$533cfd50$0d001eac@ud.cybage.com> Message-ID: <12090561.1058882769@141-213-238-90.umnet.umich.edu> --On Tuesday, July 22, 2003 16:58 +0530 K Dhanvi wrote: > I would like to know whether Python has a function which would be > called just before the end of the application. I cannot use destructors > in my application because I have some static data in my application that > is modified during the life cycle of the application. If I have any > function like this , then I could hide the gory details of de-allocation > of resources completely from the user. This way, what he ( user ) does > not know, he need not be bothered about :).. How about just catching the SystemExit exception? >>> import sys >>> try: ... # Your program goes here ... sys.exit() ... except SystemExit: ... print "we exited" ... we exited Of course you could trap other specific exceptions or all exceptions for that matter. See section 8 of the Python Tutorial at . -- Lance E Sloan U-M WATS: Web Applications, Technologies, and Solutions Full-service web and database design, development, and hosting. http://websvcs.itd.umich.edu/ - "Putting U on the Web" From tim.one@comcast.net Tue Jul 22 16:07:01 2003 From: tim.one@comcast.net (Tim Peters) Date: Tue Jul 22 15:07:01 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) In-Reply-To: <3F1CE027.8040608@aon.at> Message-ID: [Gregor Lingl] > ... > I use Norton's Internet security and this reports: > I:\Python23\pythonw.exe is going to access the internet ... (or > something like this). > > I apparently did misinterpret this. (For me this raises > the question, if it were impossible for programs like > ZoneAlarm, Norton's... etc, to find out (e.g. via the > IP adress) if such traffic is just adressing the own machine?) It seems odd to me too, but I haven't written such a program so really don't know what their problems might be. The localhost network address (127.0.0.1) sure doesn't *seem* like a hard thing to recognize! Then again, the fewer special cases in a firewall app, the fewer things it can get wrong. From alan.gauld@blueyonder.co.uk Tue Jul 22 17:48:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Tue Jul 22 16:48:02 2003 Subject: [Tutor] Final de-allocation before the application exists References: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> <011801c35044$533cfd50$0d001eac@ud.cybage.com> Message-ID: <011301c35092$8d28e260$6401a8c0@xp> Hi, > I cannot use destructors in my application because I have > some static data in my application that is modified during > the life cycle of the application. More to the point Python does not really have destructors in the sense that you seem to mean. Python controls the release of resources not the programmer. > I am allocating the resources and threads in my module I'm not sue what you mean by this? I assume you are creating objects and assigning variables to them? And those variables have global scope? If so when the application exits Python will garbage collect the objects to which they refer. The only clear up you should need to do is close open files etc (and Python actually does that too on exit, but its considered polite for the programmer to do it expliicitly). > I would like to de-allocate resources in the application If you call the del() function you will decrement the reference count on the object to effectively suggest to Python that the resource can be garbage collected at a suitable time. If the object has a __del__ method then when the garbage collector eventually kicks in it will call the method. Beyond that what do you perceive is needed? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From idiot1@netzero.net Tue Jul 22 18:37:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Tue Jul 22 17:37:02 2003 Subject: [Tutor] Feature quest Message-ID: <3F1DAE34.70404@netzero.net> I am considering adding a feature to optionally offer a link to send a message to the owner of a list. I seek suggestions on how to best implement this function. Please email me directly, off list. I can do it as: *optional plain vanilla email link on the management page for a list *A seperate menu of available listowners addresses *A optional link on that list's membership management page to a script which sends a message. Said second script reads the listowner file and sends a message to the owner, never revealing the owner's actual email address. This is most secure, and most complex, but certainly reasonably doable. -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From SWidney@ci.las-vegas.nv.us Tue Jul 22 19:30:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Tue Jul 22 18:30:02 2003 Subject: [Tutor] Get me out of the blue (help urgently needed!) Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86C8@sovereign.ci.las-vegas.nv.us> Sorry to jump into this so late (I've been off for a few days). > At the same time Python seems to report this to ... hmmm ... to whom? > (Also annoying! I'd like to be informed about messages going from my > computer to whomever ... Whoever it may be, the addressee will not be > happy with error messages like this. ) Beside what has already been mentioned, another possibility is that Windows 2000 might be invoking its error reporting dialog box. It used to be that it was only launched when a Microsoft product died, but now it seems any crashed application will bring it up. If a dialog box popped up giving you the chance to report or not send information about the erro, then it probably was a Microsoft "feature". > I tried to use regedit to search for "home" in the registry of both > installations, without success. (I am NOT an experienced user of > regedit!) In regedit, look under HKEY_CURRENT_USER\Environment. You probably have a REG_SZ or REG_EXPAND_SZ value named HOME. Some applications use the %HOME% environment variable as a base path for storing configuration information, temp files, etc. You are safe setting it to any directory that exists. Since you have Windows 2000 installed on H:, why not set HOME to H:\ ? As an aside, the other two variables that Danny mentions (HOMEDRIVE & HOMEPATH) are mostly used in corporate networks. In a User Profile, you can specify that a drive letter be mapped to a network location and this location is "home". As an example, say it was set with F: = "\\server\sharename\path\to\profiles". When that account logs on, three network environment variables are created. %HOMESHARE% is set to "\\server\sharename" and %HOMEPATH% to "\path\to\profiles". The F: drive gets mapped to the concatenation: %HOMESHARE%%HOMEPATH%. And then %HOMEDRIVE% is set to "F:". The network environment variables can be overridden by the user by creating a user environment variable named HOME, which can point to any arbitrary (but existing) location. > I don't understand how this comes? I have no environment > variable HOME defined on both installations - or I don't know > how to locate them, if they are created automatically. > I don't even understand, why win2000, installed in H: > searches for something in C: ? Most Windows applications these days store their configuration information in the Registry. That's why you don't come across this very often. Python, being multi-platform, uses the closest thing Windows provides to ~ which is %HOME% I hope this has helped. Scott From vvernon@earthlink.net Tue Jul 22 23:03:02 2003 From: vvernon@earthlink.net (Vernon Miller) Date: Tue Jul 22 22:03:02 2003 Subject: [Tutor] (no subject) Message-ID: <001501c350cf$46390460$cc9780d1@net> I'm sorry for not giving more info, of course I closed the file after each time I got through trying to write the input, but it still never wrote anything to the file until after about 20 to 30 tries but each time that I went down to the next part and wrote f.readline() it printed out millions of x's and o's and locked up the system. I had problems all day today so I finally uninstalled the python and lost everything I was working on. But, and this is the important thing, after reinstalling python, it now seems to be working. Perhaps there was something wrong with the way I had installed python. I don't know, but I do know that I spent 3 hrs trying to get a program to run, after I reinstalled python, it only took one try to get it to run. Of course I did have to spend 15 minutes rewriting the file. Thanks for your input. Vernon Miller vvernon@earthlink.net From vvernon@earthlink.net Tue Jul 22 23:13:05 2003 From: vvernon@earthlink.net (Vernon Miller) Date: Tue Jul 22 22:13:05 2003 Subject: [Tutor] Yes I checked Message-ID: <002d01c350d0$ab3b0f60$cc9780d1@net> Yes I opened the file to see if it had been written to the file, nothing was written out of the 20 or 30 times I tried, I thought I was doing something wrong so I tried everything I could think of to make it work. I also closed python and restarted my computer several times. But, nothing worked, however today after having problems all day, I uninstalled python and went to the website and downloaded it again, reinstalled it just a few minutes ago now it works just fine. I finally got fed up with all the problems and got every diagnostic tool I have out and went through everything on my computer to try and find where the problem was. There was no problem anywhere else. So I concluded that either I had installed python wrong, or something had gone wrong with the installation. I should have known, because it happened once before after I had installed python it would'nt work properly. Apparently that was the problem because it works fine now. Thanks for your help Vernon Miller vvernon@earthlink.net From vvernon@earthlink.net Tue Jul 22 23:23:02 2003 From: vvernon@earthlink.net (Vernon Miller) Date: Tue Jul 22 22:23:02 2003 Subject: [Tutor] Good ole mule Message-ID: <006c01c350d1$fd939380$cc9780d1@net> Good ole mule An old hillbilly farmer had a wife who nagged him unmercifully. From morning til night (and sometimes later), she was always complaining about something. The only time he got any relief was when he was out plowing with his old mule. He tried to plow a lot. One day, when he was out plowing, his wife brought him lunch in the field. He drove the old mule into the shade, sat down on a stump, and began to eat his lunch. Immediately, his wife began nagging him again. Complain, nag, complain, nag; it just went on and on. All of a sudden, the old mule lashed out with both hind feet; caught her smack in the back of the head. Killed her dead on the spot. At the funeral several days later, the minister noticed something rather odd. When a woman mourner would approach the old farmer, he would listen for a minute, then nod his head in agreement; but when a man mourner approached him, he would listen for a minute, then shake his head in disagreement. This was so consistent, the minister decided to ask the old farmer about it. So after the funeral, the minister spoke to the old farmer, and asked him why he nodded his head and agreed with the women, but always shook his head and disagreed with all the men. The old farmer said, "Well, the women would come up and say something about how nice my wife looked, or how pretty her dress was, so I'd nod my head in agreement." "And what about the men?" the minister asked. "They wanted to know if the mule was for sale." From dhanvik@gmx.net Wed Jul 23 01:56:02 2003 From: dhanvik@gmx.net (K Dhanvi) Date: Wed Jul 23 00:56:02 2003 Subject: [Tutor] Final de-allocation before the application exists References: <00fe01c35040$6b8393a0$0d001eac@ud.cybage.com> <011801c35044$533cfd50$0d001eac@ud.cybage.com> <011301c35092$8d28e260$6401a8c0@xp> Message-ID: <006601c350d7$17e748d0$0d001eac@ud.cybage.com> This is a multi-part message in MIME format. ------=_NextPart_000_0058_01C35105.26CF6C00 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi Friends, =20 Thanks for the replies on my query.. the suggestion of systemExit = exception could be what I want...but I have to check whether I can catch = the exception in a module. I would like to clarify my application. I have a custom designed thread = pool which maintains a stack of currently allocated threads and some = details about them. There is also a list which maintains all the = resources from which the threads are allocated ( or rather marked for = allocation ) . when an application requests for a thread, the stack top = pointer would point to next free resource ( or a thread here ) and an = unique id for the thread is returned to the actual application. = Whenever the application needs to use the thread, the application would = call the function from the threadPool with the unique ID and the = threadPool would start the thread as per the data provied by the = application.=20 Now I want to make sure that all the threads have completed execution = before the main application exists and since I keep track of the = allocated threads in the application in my ThreadPool module, I would = like to have function here, that I am sure would be called whenever the = main application exists. This function should be most preferably called = without the knowledge of the actual application developer. since this = would remove a overhead on his behalf of actually remembering to call = the function.=20 The ThreadPool and the stack are static members of the ThreadPool = class and which is subclass of Threading class.=20 I hope now that my question can be more easily understood.=20 I have another class where I would be doing connection pooling for a = networking application which would be very network intensive. Its is = supposed to replicate thousands of clients to connect to a server. Hence = a connection pooling class makes more sense .. thus if I have a function = that can be called at the exit of an application in which the module is = used, then I could politely close all my open handles ,sockets, = threads.,etc. instead of relying on Python. I am a core C programmer = and thus have the habit of cleaning up my mess :)..This way I am sure = that I have clean exit.. Friends.. lemme know, whether I am on the right track ... I would = really appreciate help from you all.=20 thanks K Dhanvi ------=_NextPart_000_0058_01C35105.26CF6C00 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

Hi Friends,
    
 Thanks for the replies on my query.. the = suggestion of=20 systemExit exception could be what I want...but I have to check = whether I=20 can catch the exception in a module.
 
 I would like to clarify my application. I have = a custom=20 designed thread pool which maintains a stack of currently allocated = threads and=20 some details about them. There is also a list which maintains all = the=20 resources from which the threads are allocated ( or rather marked for = allocation=20 ) . when an application requests for a thread, the stack top pointer = would point=20 to next free resource ( or a thread here ) and  an unique id = for the=20 thread is returned to the actual application.  Whenever the = application=20 needs to use the thread, the application would call the function from = the=20 threadPool with the unique ID and the threadPool would start the thread = as per=20 the data provied by the application.
 
  Now I want to make sure that all the = threads have=20 completed execution before the main application exists and since I keep = track of=20 the allocated threads in the application in my ThreadPool module, I = would like=20 to have function here, that I am sure would be called whenever the main=20 application exists. This function should be most preferably called = without the=20 knowledge of the actual application developer. since this would remove a = overhead on his behalf of actually remembering to call the function.=20
 
  The ThreadPool and the stack are static = members of the=20 ThreadPool class and which is subclass of Threading class.
 
  I hope now that my question can be more = easily=20 understood.
 
  I have another class where I would be doing = connection=20 pooling for a networking application which would be very network = intensive. Its=20 is supposed to replicate thousands of clients to connect to a server. = Hence a=20 connection pooling class makes more sense .. thus if I have a function = that can=20 be called at the exit of an application in which the module is used, = then I=20 could politely close all my open handles ,sockets, threads.,etc. = instead of=20 relying on Python.  I am a  core C programmer and thus have = the habit=20 of cleaning up my mess :)..This way I am sure that I have clean=20 exit..
 
  Friends.. lemme know, whether I am on the = right track=20 ... I would really appreciate help from you all.
 
thanks
K Dhanvi
------=_NextPart_000_0058_01C35105.26CF6C00-- From idiot1@netzero.net Wed Jul 23 02:06:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Wed Jul 23 01:06:02 2003 Subject: [Tutor] whacked up a wiki Message-ID: <3F1E1780.30609@netzero.net> actually, I installed piki, the all python wiki. WOW. This sort of thing has HUGE potential. Yers, I went over and looked at the wiki encyclopedia. FANTASTIC. The manual could have been better, and commenting in the script was pretty scarce indeed, but I skullcracked it, and it works. Viddie the thing at http://www.tinylist.org.cgi-bin/piki.py my good droogs! -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From lonetwin@yahoo.com Wed Jul 23 04:32:02 2003 From: lonetwin@yahoo.com (lonetwin) Date: Wed Jul 23 03:32:02 2003 Subject: [Tutor] importing modules In-Reply-To: <20030721214719.GA86130@daboyz.org> References: <200307211400.15463.cybersamurai@mac.com> <20030721214719.GA86130@daboyz.org> Message-ID: <200307231313.17236.lonetwin@yahoo.com> Hi there, Also read the documentation at (url may wrap) http://www.python.org/doc/current/tut/node8.html#SECTION008400000000000000000 HTH Peace Steve On Tuesday 22 Jul 2003 3:17 am, Michael Barrett wrote: > Assuming your project is in directory /path/to/project and the module is > called 'mymodule.py' then you can do the following in your script: > > import sys > sys.path.append('/path/to/project') > > import mymodule > > ===== > > Hope that helps. > > On Mon, Jul 21, 2003 at 02:00:15PM -0300, Luiz Siqueira Neto wrote: > > How can I import modules inside of a directory in a root of my project? > > > > in java I use import dir.package.* > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor -- One does not thank logic. -- Sarek, "Journey to Babel", stardate 3842.4 From thomi@thomi.imail.net.nz Wed Jul 23 05:40:04 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed Jul 23 04:40:04 2003 Subject: [Tutor] question regarding windows extensions and excel spreadhseets. Message-ID: <20030723203933.201aa781.thomi@thomi.imail.net.nz> Hi again ;) I've been putting this off for too long now, but I need to do some python/windows programming. the only trouble is that I have no idea about where to start. I have a program which generate some eight data every now and again. What i need to do is to be able to append this to an excel spreadsheet, while the spreadsheet is open on the users desktop. I have heard that you can do this with Visual Basic, So I'm guessing you can do it with the windows extensions too, right? When looking at www.python.org/windows/ I ran into my first problem... what's the difference between the win32 and win32com packages? which one should i use for my application? Ideally i should be able to write a smallish function which takes numerical input, and spits it at the excel spreadsheet.. can this be done easily? what packages/modules/functions should I be investigating? I can't remember the last time i used windows, and ideally I'd like to keep my time using windows as short as possible... finally, although as a bit of an "aside", is there a module which performs a similar task to the above, but under Linux? I'm guessing it'd be application specific, so you'd have to do things differently depending on whether you were using gnumeric, kspread or openoffice, right? thanks for the tips ;) -- Thomi Richards, thomi@thomi.imail.net.nz From thomi@thomi.imail.net.nz Wed Jul 23 06:01:02 2003 From: thomi@thomi.imail.net.nz (Thomas CLive Richards) Date: Wed Jul 23 05:01:02 2003 Subject: [Tutor] question regarding windows extensions and excel spreadhseets. In-Reply-To: References: Message-ID: <20030723205957.359e2713.thomi@thomi.imail.net.nz> Hi, On Wed, 23 Jul 2003 10:46:32 +0200 Thus spake "Jaco Smuts (ZA)" : > Hi there > > O'Reilly has published a book on Python programming on win32 that > should go a long way to answering your questions. I did see that. unfortunately, books cost money, which is something that i don't have ;) -- Thomi Richards, thomi@thomi.imail.net.nz From dyoo@hkn.eecs.berkeley.edu Wed Jul 23 06:13:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 23 05:13:01 2003 Subject: [Tutor] importing modules [from [module] import * is evil] In-Reply-To: <200307211400.15463.cybersamurai@mac.com> Message-ID: On Mon, 21 Jul 2003, Luiz Siqueira Neto wrote: > How can I import modules inside of a directory in a root of my project? > > in java I use import dir.package.* Hi Luiz, Let's clarify one point: your question is actually two separate questions. *grin* > How can I import modules inside of a directory in a root of my project? Python searches for modules that it can find within the 'sys.path' variable, so you can alter sys.path to include the root of your project directory. In Java, we deal with an environmental variable called the "CLASSPATH". In Python, the analogous variable is "PYTHONPATH", but by default, it includes the current directory already. If you need to add a hardcoded path, you can modify sys.path as Michael recommends. > in java I use import dir.package.* This second question is different because it asks: "How do I pull the contents of a package into my namespace?" For that, see: http://www.python.org/doc/current/tut/node8.html#SECTION008410000000000000000 Warning: using 'from [module] import *' is often not a good idea --- it works best only if a module is specifically designed to support it. It can be potentially problematic because it pulls everything from the module into our namespace, including names that can conflict with builtins. Java programmers will run into this problem too, but it's slightly less of an issue because the problem pops up at compile time rather than runtime. Since you have experience in Java, let's talk Java. *grin* Let's say we're dealing with two classes in separate packages: 'A/Foo' and 'B/Foo': /*** * A/Foo.java **/ package A; public class Foo { public void sayHello() { System.out.println("foo!"); } } /***/ /*** * B/Foo.java **/ package B; public class Foo { public void sayHello() { System.out.println("foo?"); } } /***/ Ok, the stage is set. What happens if we do something like this? /*** * Test.java */ import A.*; import B.*; public class Test { public static void main(String[] args) { Foo f = new Foo(); f.sayHello(); } } /***/ Java will (or had better!) detect this as a compile-time error. Here's what it looks like on my end: ###### bash-2.05a$ javac Test.java Test.java:5: reference to Foo is ambiguous, both class B.Foo in B and class A.Foo in A match Foo f = new Foo(); ^ Test.java:5: reference to Foo is ambiguous, both class B.Foo in B and class A.Foo in A match Foo f = new Foo(); ^ 2 errors ###### That's the important thing to realise: doing a "glob" of our modules can result in collisions. But Java opts to trigger a compile time error to force the programmer to deal with this. Not a good thing if you're the author of B, but not the original designer of the A package, but it's still should be managable in Java. Ok, let's put on our Python hat now. We need to get an analogous situation going. ### bash-2.05a$ cat A.py def sayHello(): print "Hello, this is A!" bash-2.05a$ cat B.py def sayHello(): print "Hello, this is B" bash-2.05a$ python Python 2.2 (#1, 11/12/02, 23:31:59) [GCC Apple cpp-precomp 6.14] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from A import * >>> from B import * >>> sayHello() Hello, this is B ### Rather than conflict with an error, Python will allow one 'import *' to override the other. This might be what the programmer expects... but then again, maybe not. So it's not a SyntaxError --- it's a bit more insidious in Python, so not such a nice thing to deal with. Consequently, most Python programmers will recommend the avoidance of 'import *' unless the package has been really designed with these issues in mind. ('Tkinter' and 'pygame', for example.) Otherwise, it's better to either fully qualify module imports, or to be be more specific: ### import A from B import sayHello A.sayHello() sayHello() ### That way, we can avoid the variable name collision altogether. Anyway, hope this helps! From knguyen@seri.co.uk Wed Jul 23 07:37:02 2003 From: knguyen@seri.co.uk (Khai Nguyen) Date: Wed Jul 23 06:37:02 2003 Subject: [Tutor] write into a file Message-ID: <341710540F08E34498A057DEE04DAAD7DFF1B1@ex1.seri.co.uk> Hi, Use writeline or writelines (please see doc) This script below works fine " f=3Dopen('C:/Python22/Tools/tmp/workfile.txt', 'w') f.writeline('This is the first line of the file') " Kind regards -----Original Message----- From: Vernon Miller [mailto:vvernon@earthlink.net]=20 Sent: Wednesday, July 23, 2003 5:03 AM To: Tutor@python.org Subject: [Tutor] (no subject) I'm sorry for not giving more info, of course I closed the file after each time I got through trying to write the input, but it still never wrote anything to the file until after about 20 to 30 tries but each time that I went down to the next part and wrote f.readline() it printed out millions of x's and o's and locked up the system. I had problems all day today so I finally uninstalled the python and lost everything I was working on. But, and this is the important thing, after reinstalling python, it now seems to be working. Perhaps there was something wrong with the way I had installed python. I don't know, but I do know that I spent 3 hrs trying to get a program to run, after I reinstalled python, it only took one try to get it to run. Of course I did have to spend 15 minutes rewriting the file. Thanks for your input. Vernon Miller vvernon@earthlink.net _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ***************************************************************************= ** The information contained in this email and in any attachments=20 may be privileged and confidential. =20 The information is designated solely for the attention and use of=20 the intended recipient(s). =20 If you are not the intended recipient(s), please be aware that any=20 disclosure, copying, distribution or use of the contents of this=20 information is prohibited.=20 If you have received this email in error, please notify the sender=20 by telephone or email immediately. ***************************************************************************= ** From knguyen@seri.co.uk Wed Jul 23 07:50:01 2003 From: knguyen@seri.co.uk (Khai Nguyen) Date: Wed Jul 23 06:50:01 2003 Subject: [Tutor] read, write to file Message-ID: <341710540F08E34498A057DEE04DAAD7DFF1BB@ex1.seri.co.uk> Hi, Use writeline or writelines (please see doc) This script below works fine " f=3Dopen('C:/Python22/Tools/tmp/workfile.txt', 'w')=20 f.writeline('This is the first line of the file') F.close " Kind regards -----Original Message----- From: Vernon Miller [mailto:vvernon@earthlink.net]=20 Sent: Tuesday, July 22, 2003 12:15 AM To: Tutor@python.org Subject: [Tutor] read, write to file I spend all day trying to get this to work f=3Dopen('C:/Python22/Tools/tmp/workfile.txt', 'w') f.write('This is the first line of the file') after it finally seemed to work I tried to read the line with readline() What I got was several hundred lines of x's and o's, but nothing was written to the file last week I went through the same thing and after rebooting several times it finally decided to work, it seems to me that there is something fundamentally wrong with the read, write to file functions in this latest version of python. Vernon Miller vvernon@earthlink.net _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ***************************************************************************= ** The information contained in this email and in any attachments=20 may be privileged and confidential. =20 The information is designated solely for the attention and use of=20 the intended recipient(s). =20 If you are not the intended recipient(s), please be aware that any=20 disclosure, copying, distribution or use of the contents of this=20 information is prohibited.=20 If you have received this email in error, please notify the sender=20 by telephone or email immediately. ***************************************************************************= ** From jim_938@hotmail.com Wed Jul 23 10:26:02 2003 From: jim_938@hotmail.com (Jimmy verma) Date: Wed Jul 23 09:26:02 2003 Subject: [Tutor] problem with the file contents Message-ID: Hello, I am having a small problem in dealing with files. I am writing some stuff out of a font file. Like the name of the font family. When i see it on the command line it shows the proper output like this Luxi Serif But if i put the variable containing this into a file then it shows the contents in the file as: ^@L^@u^@x^@i^@ ^@S^@e^@r^@i^@f Please suggest sthing to solve the problem. Waiting for reply. With best regards. Jim _________________________________________________________________ Are you Unmarried? http://www.bharatmatrimony.com/cgi-bin/bmclicks1.cgi?4d Register in India's No 1 Matrimony. From john.moylan@rte.ie Wed Jul 23 11:42:01 2003 From: john.moylan@rte.ie (John Moylan) Date: Wed Jul 23 10:42:01 2003 Subject: [Tutor] re: excel In-Reply-To: <20030723132602.460.80333.Mailman@mail.python.org> References: <20030723132602.460.80333.Mailman@mail.python.org> Message-ID: <1058971264.5807.3.camel@localhost.localdomain> AFAIK OpenOffice has python bindings which might help you on Linux. You can find out more bv searching for OpenOffice + python + UNI ****************************************************************************** The information in this e-mail is confidential and may be legally privileged. It is intended solely for the addressee. Access to this e-mail by anyone else is unauthorised. If you are not the intended recipient, any disclosure, copying, distribution, or any action taken or omitted to be taken in reliance on it, is prohibited and may be unlawful. Please note that emails to, from and within RTÉ may be subject to the Freedom of Information Act 1997 and may be liable to disclosure. ****************************************************************************** From RASTM2@aol.com Wed Jul 23 13:19:01 2003 From: RASTM2@aol.com (RASTM2@aol.com) Date: Wed Jul 23 12:19:01 2003 Subject: [Tutor] pydoc cli in windoze Message-ID: <71.3329b7a1.2c500f4e@aol.com> Say fella's Is the pydoc command line interface accessible from the windows command line? I was reading the Lib\Ref 5.1 and ran across pydoc's example... ...same text documentation can also be viewed from outside the Python interpreter by running pydoc as a script at the operating system's command prompt. For example, running pydoc sys at a shell prompt will display documentation on the sys module, in a style similar to the manual pages shown by the Unix man command. Is this just for *NIX boxes or have I got a REAL problem, 'cuz' I get BAD COMMAND doing that, and typing C:\python pydoc sys or C:\python pydoc.py sys returns CAN'T OPEN FILE PYDOC.PY. Just wondering. I can always fire up an interpreter -- no big deal. Ray St. Marie rastm2@aol.com From DORSEY_EDMUND_K@LILLY.COM Wed Jul 23 15:45:03 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Wed Jul 23 14:45:03 2003 Subject: [Tutor] Anyway to do something like a #define in python? Message-ID: This is a multipart message in MIME format. --=_alternative 0066C94C05256D6C_= Content-Type: text/plain; charset="us-ascii" I think the subject is pretty self explanatory but how would you go about doing something like this in python? Is there a python equivalent to the C #define? Thanks! ~Ed --=_alternative 0066C94C05256D6C_= Content-Type: text/html; charset="us-ascii"
I think the subject is pretty self explanatory but how would you go about doing something like this in python?  Is there a python equivalent to the C #define?  Thanks! ~Ed   --=_alternative 0066C94C05256D6C_=-- From jeff@ccvcorp.com Wed Jul 23 15:47:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 23 14:47:03 2003 Subject: [Tutor] question regarding windows extensions and excel spreadhseets. References: <20030723203933.201aa781.thomi@thomi.imail.net.nz> Message-ID: <3F1ED83A.8010408@ccvcorp.com> Thomas CLive Richards wrote: >I have a program which generate some eight data every now and again. >What i need to do is to be able to append this to an excel spreadsheet, >while the spreadsheet is open on the users desktop. I have heard that >you can do this with Visual Basic, So I'm guessing you can do it with >the windows extensions too, right? > Yes, you can use win32com to control Excel, as well as (just about) any other COM-scriptable application -- more specifically, any application that supports COM Automation. (Generally, if an app is scriptable from Visual Basic, it's scriptable from Python through win32com as well.) >what's the difference between the win32 and win32com packages? which one >should i use for my application? Ideally i should be able to write a >smallish function which takes numerical input, and spits it at the excel >spreadsheet.. can this be done easily? what packages/modules/functions >should I be investigating? > The win32 package provides interfaces to the Windows OS itself. You'll want the win32com package, which allows you access to COM scripting. If you have any experience with Visual Basic scripting, the principles are very similar though the syntax is different. (Though, since you say that you don't typically use Windows, I'm guessing that you don't have much VB experience... ;) ) Someone else already mentioned "Python Programming on Win32"; it's unfortunate that you can't afford a copy, because it really will tell you everything you need to know. However, O'Reilly has a sample chapter available online, and you're in luck because this chapter is one of the most relevant one to your immediate problem: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Several of the code examples specifically use Excel, too. Hopefully, between that and the Visual Basic docs for Excel, you'll be able to work things out. (While the Excel docs do use VB instead of Python, and thus the syntax is a bit different, the underlying Excel object model is the same. Use those docs to get information about what Excel objects are available, and what they can do; comparing the VB code there with the information in the O'Reilly chapter should give you a good idea of how to translate VB syntax into Python syntax.) Once you've got a general idea from that, feel free to post here with specific problems. I've written Excel-automation scripts, but it's been a while.... >finally, although as a bit of an "aside", is there a module which >performs a similar task to the above, but under Linux? I'm guessing >it'd be application specific, so you'd have to do things differently >depending on whether you were using gnumeric, kspread or openoffice, >right? > Yes, any such thing on Linux would be application-specific. I understand that OpenOffice now has Python bindings available; I'm not sure about Gnumeric or Kspread. However, Linux doesn't have any overarching GUI-scripting interface that's comparable to COM. (Mozilla uses XPCOM, cross-platform COM, which works on Linux, but it's necessary for a wide range of products to use the same interface to get the same advantages that COM gives on Windows. XPCOM is not (yet) that widely accepted. There's also CORBA and a few other object protocols, none of which is widespread enough to truly compare to COM.) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Jul 23 15:54:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 23 14:54:01 2003 Subject: [Tutor] Anyway to do something like a #define in python? References: Message-ID: <3F1ED9E8.7030501@ccvcorp.com> DORSEY_EDMUND_K@LILLY.COM wrote: > > I think the subject is pretty self explanatory but how would you go > about doing something like this in python? Is there a python > equivalent to the C #define? Thanks! ~Ed No, there isn't, and on the whole that's a good thing. #define can be used in a variety of different ways, most of which have a more specific replacement in Python. For example, C macros are usually easily replaced by Python functions -- macros are useful because they're not type-specific, but Python is always non-type-specific. C constants can be replaced by normal variables -- they won't be read-only, so you'll have to trust programmers to understand that modifying something documented as a constant is a Bad Thing(tm), but this should rarely be a real difficulty. (Naming conventions, i.e. constants are named in all-caps, can help prevent accidental tampering.) Is there something specific that you're trying to translate? Jeff Shannon Technician/Programmer Credit International From jaredw1234567@hotmail.com Wed Jul 23 16:04:01 2003 From: jaredw1234567@hotmail.com (Jared W) Date: Wed Jul 23 15:04:01 2003 Subject: [Tutor] Help with a tutorial Message-ID: http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html I know this is should be really easy, but I couldn't figure it out and it aggrivates me when I can't do something. Could someone please tell me how to do the exercise on the link above? Thanks, Jared _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From hall@ouhep1.nhn.ou.edu Wed Jul 23 16:45:05 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Wed Jul 23 15:45:05 2003 Subject: [Tutor] Help with a tutorial In-Reply-To: Message-ID: Hi Jared, This looks like a homework problem.... There have been many arguments made on this list in regards to the ethics involved in answering homework problems on the list. I dont feel that they should be answered directly, but I have no problem with giving some helpful hints to point someone in the right direction. so, in that regard, looking at the excercise, and thinking of how I would tackle that problem, I would give you this hint: Think strings.... Ike On Wed, 23 Jul 2003, Jared W wrote: > http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html > > I know this is should be really easy, but I couldn't figure it out and it > aggrivates me when I can't do something. Could someone please tell me how > to do the exercise on the link above? > > Thanks, > Jared > > _________________________________________________________________ > The new MSN 8: smart spam protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From dyoo@hkn.eecs.berkeley.edu Wed Jul 23 17:07:28 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 23 16:07:28 2003 Subject: [Tutor] Help with a tutorial In-Reply-To: Message-ID: On Wed, 23 Jul 2003, Jared W wrote: > http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html > > I know this is should be really easy, but I couldn't figure it out Hi Jared, Hmmm..., now that I look at it, the question itself is weird! And I'm having difficulty parsing it in English... *grin* Here's the question Josh poses: """ Rewrite the high_low.py program from section 5.2 to use the last two digits of time at that moment to be the 'random' number. """ I think there's a phrasing mistake here --- the question is probably meant to be a two-parter: """ Rewrite the high_low.py program from section 5.2: 1. To use the last two digits of time at that moment. 2. To be the 'random' number. """ Can anyone confirm that this is what Josh meant? If so, we need to send this correction to him so that he can fix his tutorial. Anyway, Jared, does this clarify things? Try adjusting the high_low.py program: ### number = 78 guess = 0 while guess != number : guess = input ("Guess a number: ") if guess > number : print "Too high" elif guess < number : print "Too low" print "Just right" ### so that the 'number' isn't hardcoded to the number 78. Please feel free to ask more questions about this, and try explaining what part is getting you stuck. Good luck to you! From alex@caustic-creations.com Wed Jul 23 17:13:01 2003 From: alex@caustic-creations.com (Alex from Caustic Creations) Date: Wed Jul 23 16:13:01 2003 Subject: [Tutor] Stopping a loop with user input in curses Message-ID: <1058844990.857.12.camel@caustic.laptop> Thanks a lot for the replies everyone. Someone on the Python newsgroup suggested I use the select module to accomplish what I'm trying to do. Here is the code he modified to illustrate his solution: [Code] # Import curses module import curses, time stdscr = curses.initscr() from select import select def theClock(): # Define global colour scheme curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Get the screen size max_y, max_x = stdscr.getmaxyx() # Calculate the clock position relative to the screen size clock_x = max_x - 28 # Draw the clock clockWindow = curses.newwin(3, 26, 1, clock_x) clockWindow.bkgd(' ', curses.color_pair(1)) clockWindow.box() clockWindow.refresh() # If 'q' is pressed, exit finished = 0 while not finished: # finished = 0 until the 'q' key is pressed if select([0], [], [], 1)[0]: c = stdscr.getch() if c == ord('q'): curses.beep() finished = 1 break t = time.asctime() clockWindow.addstr(1, 1, t) clockWindow.refresh() def main(stdscr): # Bring up the clock function theClock() if __name__ == '__main__': curses.wrapper(main) [/Code] This seems like a very efficient way of accomplishing the task at hand. If anyone has any suggestions or comments, please do let me know. I'm trying to learn Python the right way. Alex From sean64@xtra.co.nz Wed Jul 23 17:13:13 2003 From: sean64@xtra.co.nz (Sean Richards) Date: Wed Jul 23 16:13:13 2003 Subject: [Tutor] how to call "~wxDialog()" in python? In-Reply-To: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> References: <20030722193304.2000ee2c.thomi@thomi.imail.net.nz> Message-ID: <20030722093514.GA1360@xtra.co.nz> Thomas CLive Richards wrote: > when trying to destroy a (WxWindows) window, I have to call a function > called "self.~wxDialog()" However, python complains about the '~' > character: > > thomi@Julie:~/work/python sources/wxPython$ ./wedderburn.py > File "./wedderburn.py", line 146 > EVT_BUTTON(self,ID_PREFS_CLOSEBUTTON,self.~wxDialog) > ^ > SyntaxError: invalid syntax > > > I tried escaping it with a '\' character, like you can do in some other > languages, but that didn't seem to work either. I also thought that > maybe the python wrapper to the wxWindows library had changed thename of > this function, but i couldn't see any mention of it in the latest > documentation. Not a wxPython guru but I can point you in the direction of the wxPython Wiki at http://wiki.wxpython.org for lots of examples and tips and wxPython comes with a directory full of demo programs that covers just about everything you need. As for destroying a wxPython dialog you would use self.Destroy() to destroy it. In the event handler you have written I think the normal procedure is to use that to call a function you have defined something like ... EVT_BUTTON(self, EXIT_ID,self.Exit) def Exit(self,event): """On exit Kill Everything. """ self.Destroy() Hope this helps a little. Get over to the wxPython wiki and have a look around it will make things a lot easier. Cheers, Sean -- +---------------------------------------------------------------+ | All spelling errors are intentional and are there to show new | | and improved ways of spelling old words. | +---------------------------------------------------------------+ -- +---------------------------------------------------------------+ | All spelling errors are intentional and are there to show new | | and improved ways of spelling old words. | +---------------------------------------------------------------+ From plusk@radford.edu Wed Jul 23 17:13:28 2003 From: plusk@radford.edu (Paul D. Lusk) Date: Wed Jul 23 16:13:28 2003 Subject: [Tutor] email with body AND attachments Message-ID: I'm trying to use the email package to create a message with both a body and one or more attachments. Using the code in the docs (email examples - node 12.2.10), I can create messages with all the attachments that I want, but nothing I've tried gives both attachments and a message body. Google is coming up blank on examples using the email package, though I did find examples using pre-email modules. Does anybody have an example handy using the email package? Paul From op73418@mail.telepac.pt Wed Jul 23 17:30:12 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Wed Jul 23 16:30:12 2003 Subject: [Tutor] email with body AND attachments In-Reply-To: Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Paul D. Lusk > Sent: quarta-feira, 23 de Julho de 2003 18:48 > To: tutor@python.org > Subject: [Tutor] email with body AND attachments > > > I'm trying to use the email package to create a message with > both a body and one or more attachments. Using the code in > the docs (email > examples - node 12.2.10), I can create messages with all > the attachments > that I want, but nothing I've tried gives both attachments > and a message > body. Google is coming up blank on examples using the email > package, though > I did find examples using pre-email modules. Does anybody > have an example > handy using the email package? > > Paul > This is a class I wrote a while ago to simplify things when it comes to writing MIME email mesages -- and never got to use it as a matter of fact. #Import standard modules. import smptlib import email import mimetypes #Exceptions. class SendError(Exception): """SendError exception class.""" pass class MessageError(Exception): """MessageError exception class.""" pass #Classes. class Message(object): """The Message class, a simplified MIME wrapper.""" types = {'text' : email.MIMEText.MIMEText} def __init__(self, message, subject, fromaddress, toaddresses): """The initializer.""" super(Message, self).__init__() #Generate message. MIMEText = email.MIMEText.MIMEText self.__message = MIMEText(message, _encoder = email.Encoders.encode_quopri) #Set fields. self.__message['Subject'] = subject self.__message['From'] = fromaddress self.__message['To'] = ';'.join(toaddresses) #Properties. def __get_sender(self): return self.__message['From'] sender = property(__get_sender) def __get_recipients(self): return self.__message['To'].split(';') recipents = property(__get_recipients) def __str__(self): return self.__message.as_string() def attach(self, filename): """Attach a file to Message.""" #Generate MIME message. filetype, encoding = mimetypes.guess_type(filename) maintype, subtype = filetype.split('/', 1) f = file(filename) try: data = f.read() finally: f.close() try: message = self.types[maintype](data, _subtype = subtype) except KeyError: raise MessageError("Unknown file type.", filename) #Attach message. self.__message.add_header('Content-Disposition', 'attachment', filename = filename) self.__message.attach(message) As you can see from the __init__ method a message with a body *is* a email.MIMEText.MIMEText instance. You then attach files in the usual manner. Hope it helps, with my best regards, G. Rodrigues P.S: I have no accompanying unit tests, so you must take this code as untested. Don't trust it. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From pauljhickey@eircom.net Wed Jul 23 17:41:02 2003 From: pauljhickey@eircom.net (Paul Hickey) Date: Wed Jul 23 16:41:02 2003 Subject: [Tutor] Help with a tutorial References: Message-ID: <003501c3515a$8a6cf9d0$fdc4fea9@pjhickey> Hi , i am also doing Josh's tutorial, ive just started that question and dont have the answer, sorry!!!!! However to clear things up as i read the thing, He wants you to rewrite the program to use the last two digits as the number, the word 'random' means that the number will be different each time you run the program, but not a truly 'random' number, its only gonna be 1 -60. A kinda random number!!! I say this because he does say earlier in the tutorial that you should be able to modify this program after the chapter on 'modules' to be a 'truly random' program, the chapter on modules is after the one Jared W is on now. Hope i did not make things more confused. Anyway its a great tutorial. Paul ----- Original Message ----- From: "Danny Yoo" To: "Jared W" Cc: Sent: Wednesday, July 23, 2003 9:05 PM Subject: Re: [Tutor] Help with a tutorial > > > On Wed, 23 Jul 2003, Jared W wrote: > > > http://www.honors.montana.edu/~jjc/easytut/easytut/node14.html > > > > I know this is should be really easy, but I couldn't figure it out > > > Hi Jared, > > > Hmmm..., now that I look at it, the question itself is weird! And I'm > having difficulty parsing it in English... *grin* > > > Here's the question Josh poses: > > > """ > Rewrite the high_low.py program from section 5.2 to use the last two > digits of time at that moment to be the 'random' number. > """ > > > > I think there's a phrasing mistake here --- the question is probably meant > to be a two-parter: > > > """ > Rewrite the high_low.py program from section 5.2: > > 1. To use the last two digits of time at that moment. > > 2. To be the 'random' number. > """ > > Can anyone confirm that this is what Josh meant? If so, we need to send > this correction to him so that he can fix his tutorial. > > > > Anyway, Jared, does this clarify things? Try adjusting the high_low.py > program: > > ### > number = 78 > guess = 0 > > while guess != number : > guess = input ("Guess a number: ") > > if guess > number : > print "Too high" > > elif guess < number : > print "Too low" > > print "Just right" > ### > > > so that the 'number' isn't hardcoded to the number 78. Please feel free > to ask more questions about this, and try explaining what part is getting > you stuck. > > > > Good luck to you! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From idiot1@netzero.net Wed Jul 23 21:31:03 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Wed Jul 23 20:31:03 2003 Subject: [Tutor] whacked up a wiki In-Reply-To: <1058994512.19834.137.camel@matt-richardsons-computer.local> References: <3F1E1780.30609@netzero.net> <1058994512.19834.137.camel@matt-richardsons-computer.local> Message-ID: <3F1F288B.6090303@netzero.net> working ok here. try again: http://www.tinylist.org/cgi-bin/piki.py Matt Richardson wrote: > On Tue, 2003-07-22 at 22:05, Kirk Bailey wrote: > >>actually, I installed piki, the all python wiki. >> >>WOW. This sort of thing has HUGE potential. Yers, I went over and looked at the wiki >>encyclopedia. FANTASTIC. >> >>The manual could have been better, and commenting in the script was pretty scarce >>indeed, but I skullcracked it, and it works. >> >>Viddie the thing at http://www.tinylist.org.cgi-bin/piki.py my good droogs! > > > I'm really interested in this, but I couldn't get your page to load. > Did you use piki-piki, the one Martin Pool wrote? > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From lonetwin@yahoo.com Thu Jul 24 04:37:01 2003 From: lonetwin@yahoo.com (lonetwin) Date: Thu Jul 24 03:37:01 2003 Subject: [Tutor] Anyway to do something like a #define in python? In-Reply-To: <3F1ED9E8.7030501@ccvcorp.com> References: <3F1ED9E8.7030501@ccvcorp.com> Message-ID: <200307241318.04114.lonetwin@yahoo.com> Hi there, On Thursday 24 Jul 2003 12:24 am, Jeff Shannon wrote: > DORSEY_EDMUND_K@LILLY.COM wrote: > > I think the subject is pretty self explanatory but how would you go > > about doing something like this in python? Is there a python > > equivalent to the C #define? Thanks! ~Ed That depends .... > No, there isn't, and on the whole that's a good thing. #define can be > used in a variety of different ways, most of which have a more specific > replacement in Python. That's true. There isn't any exact drop-in replacement for a #define, it=20 depends on what you need to do. Before we go into that, lets get one thing= =20 clear. What is a '#define' in C ?? It's a 'preprocessor' directive that replaces all occurrences of the=20 #defined name with whatever expression you provide. That means if you have #define ADD(x, y) x+y #define MAX 2000 =2E.then, *before* the actual compilation stage, all occurrences of ADD and= MAX=20 are simply rewritten with the expressions that you provided. ie: if somewhere you had written printf ('%d, %d', ADD(10, 20), MAX); that gets replaced by printf ('%d, %d', 10+20, 2000); *before* the compilation stage. The bad part about all this is, this = may=20 cause a lot of hard to trace bugs, because during the replacement=20 (preprocessing stage) no type checking or validation is done ...and you mig= ht=20 already know the pitfalls of automatic type conversion or incorrect type=20 specification in C. Anyways, back to python. Since python is any interpreted language, there= =20 isn't any preprocessing step. Nor is there a mechanism to replace occurrenc= es=20 of a name with an expression. On the other hand you _do_ have the ability t= o=20 assign expressions (even functions !!) to variables. So, although the=20 following statements might reflect similar behaviour to '#define', they are= =20 not the same thing. >>> ADD =3D lambda x, y: x+y >>> MAX =3D 2000 >>> def hello_world(): =2E.. print "Hello, world !" =2E.. >>> HELLO =3D hello_world >>> >>> ADD(10, 20) 30 >>> print MAX 2000 >>> HELLO() Hello, world ! >>> HTH Peace Steve =2D-=20 Never stand between a fire hydrant and a dog -- Murphy's Laws on Sex n=B049 From Janssen@rz.uni-frankfurt.de Thu Jul 24 08:51:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Thu Jul 24 07:51:01 2003 Subject: [Tutor] Help with a tutorial In-Reply-To: References: Message-ID: On Wed, 23 Jul 2003, Danny Yoo wrote: > Hmmm..., now that I look at it, the question itself is weird! And I'm > having difficulty parsing it in English... *grin* > Here's the question Josh poses: > """ > Rewrite the high_low.py program from section 5.2 to use the last two > digits of time at that moment to be the 'random' number. > """ > I think there's a phrasing mistake here --- the question is probably meant > to be a two-parter: > """ > Rewrite the high_low.py program from section 5.2: > > 1. To use the last two digits of time at that moment. > > 2. To be the 'random' number. > """ > > Can anyone confirm that this is what Josh meant? If so, we need to send > this correction to him so that he can fix his tutorial. > I don't understand your rephrasing either ;-) You can't rewrite high_low.py "to be the 'random' number" because high_low.py is not intended to provide such a number (but to use one). Also, the current section "Using Modules" has no need of a random number, so why rewrite high_low.py to "be" one? My guess is: """Rewrite the high_low.py program from section 5.2 to use the last two digits of time() [he has imported time.time into global namespace] as a 'random' number.""" "at that moment" is not important to mention, cause this is what time.time() does. "use something as something" seems to be clearer to me than "use something to be something". Michael From marc_barry@hotmail.com Thu Jul 24 12:19:03 2003 From: marc_barry@hotmail.com (Marc Barry) Date: Thu Jul 24 11:19:03 2003 Subject: [Tutor] Determining if an iterator has more elements. Message-ID: I have read numerous posts in the archive about the following question and I haven't been able to find an answer or rather an explanation for the following. I am using iterators in Python but am confused over determining when the iterator has no more elements. Here is a small code snippet to illustrate what I am talking about: a_list = [1,2,3,4,5] i = iter(a_list) try: while(1): print i.next() except StopIteration: pass Obviously, when you run the above it prints out the values 1, 2, 3... My problem is that the iterator contract in Python causes next() to raise a StopIteration exception when there are no further items in the iterator. The contract provides no such method to test whether the iterator has more elements (i.e. like Java's hasNext()). Therefore, I using the exception to detect when the iterator does not have anymore elements. I can't think of any other way to test for this. I don't think that exception handling is meant to be used to determine when to exit a loop. I realise that I could do the same thing with the following much simpler code: for i in iter(a_list): print i This though does not add to my understanding of how to handle iterator's when not iterating through them with a "for" statement. Any comments or suggestions on how to test if an iterator has more elements (without using the StopIteration exception to do so)? Marc _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From Nitin Gangahar" Hi!I also started python with Josh's tutorial.I'll try to find the ans. for the problem.I think U should use the time module for this. TY NITIN ___________________________________________________ Download the hottest & happening ringtones here! OR SMS: Top tone to 7333 Click here now: http://sms.rediff.com/cgi-bin/ringtone/ringhome.pl From wheelcrdan@hotmail.com Thu Jul 24 12:58:13 2003 From: wheelcrdan@hotmail.com (Dan Dud) Date: Thu Jul 24 11:58:13 2003 Subject: [Tutor] Danny Yoo and Magnus Lyckå I would like to say THANKS FOR ALL YOUR HELP Message-ID: Hi everyone I just wanted to take a minute and say thanks to Danny, and Magnus Lyckå that have been there since I started messing with programming. I would be lost if it wasn't for the both of you thanks for all your help with all my stupid questions.. I'm sure everyone around here is thankful too... Take care and I'm positive that I'll be back asking some more questions. Sincerely Danny D _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From phate@rockriver.net Thu Jul 24 13:13:02 2003 From: phate@rockriver.net (Michie DeBerry) Date: Thu Jul 24 12:13:02 2003 Subject: [Tutor] Random Numbers Message-ID: <200307241113.19208.phate@rockriver.net> Hello, Allow me to start by introducing myself. My name is Michie, and I am currently reading Sam's Teach Yourself Python in 24 Hours. I was wondering if there is anyway to create a random number in Python. I am currently writting a program to create a password for you. It will have more features later on, but for right now, that is all I need it to do. Any suggestions as how to go about creating a random number x number of times to get a-z or 0-9 from a list? Thx, Michie (pronounced Mickey) From jeff@ccvcorp.com Thu Jul 24 13:16:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 24 12:16:02 2003 Subject: [Tutor] Determining if an iterator has more elements. References: Message-ID: <3F200672.2020909@ccvcorp.com> Marc Barry wrote: > > try: > while(1): > print i.next() > except StopIteration: > pass > > Obviously, when you run the above it prints out the values 1, 2, 3... > My problem is that the iterator contract in Python causes next() to > raise a StopIteration exception when there are no further items in the > iterator. The contract provides no such method to test whether the > iterator has more elements (i.e. like Java's hasNext()). Therefore, I > using the exception to detect when the iterator does not have anymore > elements. I can't think of any other way to test for this. I don't > think that exception handling is meant to be used to determine when to > exit a loop. Actually, it is -- every for-loop in Python is effectively terminated through exception handling. A for loop has a hidden index variable that's incremented each trip through the loop; when that index variable is larger than the length of the sequence, an IndexError is raised. The for loop implicitly catches that exception and continues execution just after the body of the loop. In other words, if you were to explicitly write out the compiled code for a for loop, it'd have just about the same structure as your code snippet above. The thing to keep in mind, here, is that Python uses exceptions much more freely than Java or C++, for circumstances that are much less exceptional. Thus, it's considered perfectly good practice in Python that it's "easier to ask forgiveness than permission" -- i.e., try an operation and catch an exception if it fails, instead of attempting to check if the operation can succeed before performing the operation. Catching the StopIteration exception, as you do above, is indeed Pythonic and accepted. Jeff Shannon Technician/Programmer Credit International From zak@harlekin-maus.com Thu Jul 24 13:25:11 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Thu Jul 24 12:25:11 2003 Subject: [Tutor] Random Numbers In-Reply-To: <200307241113.19208.phate@rockriver.net> References: <200307241113.19208.phate@rockriver.net> Message-ID: <1259.192.206.201.217.1059063881.squirrel@mail.harlekin-maus.com> > Hello, > Any suggestions as how to go about creating a random number x number of > times to get a-z or 0-9 from a list? Thx, > Michie (pronounced Mickey) I don't want to give you the answer, so here's a hint: To repeat most things x number of times, you'll want to use a while or for loop. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From godoy@metalab.unc.edu Thu Jul 24 13:26:04 2003 From: godoy@metalab.unc.edu (Jorge Godoy) Date: Thu Jul 24 12:26:04 2003 Subject: [Tutor] Random Numbers In-Reply-To: <200307241113.19208.phate@rockriver.net> (Michie DeBerry's message of "Thu, 24 Jul 2003 11:13:19 -0500") References: <200307241113.19208.phate@rockriver.net> Message-ID: Michie DeBerry writes: > Hello, > Allow me to start by introducing myself. My name is Michie, and I am currently > reading Sam's Teach Yourself Python in 24 Hours. I was wondering if there is > anyway to create a random number in Python. I am currently writting a program > to create a password for you. It will have more features later on, but for > right now, that is all I need it to do. Any suggestions as how to go about > creating a random number x number of times to get a-z or 0-9 from a list? I did that when I created a graphical frontend to create crypt() and MD5 hashes of passwords. This is the relevant part: ---------------------------------------------------------------------- #!/usr/bin/env python import crypt import string import random from Crypto.Hash import MD5 (...) def ConvertPassword(self, event): characters = ''.join([string.ascii_letters, string.digits, './']) salt = ''.join([random.choice(characters), random.choice(characters)]) original_pwd = self.BxPasswd.GetValue() md5 = MD5.new(original_pwd).hexdigest() crypted = crypt.crypt(original_pwd, salt) self.TxtMD5.SetValue(md5) self.TxtCrypt.SetValue(crypted) ---------------------------------------------------------------------- See you, -- Godoy. From andi@buxach.de Thu Jul 24 13:33:01 2003 From: andi@buxach.de (Andreas Zwinkau) Date: Thu Jul 24 12:33:01 2003 Subject: [Tutor] pymad, pyao Message-ID: <20030724165415.042ff317.andi@buxach.de> Hi I made a jukebox daemon but it hangs sometimes for no reason. My suggestion is it hangs/loops during in- or output, which is pymad or pyao. I let pyao do the mixing of both streams, by just having run two players. I wondered i work with oss output. Could this be a source of problems? I have problems tracing the problem, because of the many threads which are running. How could i trace such problems? I let it spit out many message, when what happens, so far. But infinite loops are hard to find ... mfg Andreas Zwinkau | web: andi.dasstellenwirinsinternet.de | mail: andi@buxach.de | jabber: beza1e1@amessage.de From glingl@aon.at Thu Jul 24 13:55:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Thu Jul 24 12:55:02 2003 Subject: [Tutor] Random Numbers Message-ID: <3F200FDD.3020503@aon.at> Michie DeBerry schrieb: >Hello, >Allow me to start by introducing myself. My name is Michie, and I am currently >reading Sam's Teach Yourself Python in 24 Hours. I was wondering if there is >anyway to create a random number in Python. I am currently writting a program >to create a password for you. It will have more features later on, but for >right now, that is all I need it to do. Any suggestions as how to go about >creating a random number x number of times to get a-z or 0-9 from a list? > > Many things about "random" you find in the module random. Docs at: http://www.python.org/doc/current/lib/module-random.html random integers you may create with the function randint: >>> from random import randint >>> for i in range(25): print randint(1,7), 1 5 4 1 4 3 4 6 1 4 7 2 2 3 4 2 3 6 1 1 5 2 4 3 1 For your purpose the function choice, which selects random elements from a sequence, may be better suited: >>> from random import choice >>> for i in range(25): print choice("abcdefghijklmnopqrstuvwxyz"), u f l v y g f e e y s g j d i e v v q d b i l h q >>> HTH, Gregor >Thx, >Michie (pronounced Mickey) > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From mwagman@charter.net Thu Jul 24 14:20:01 2003 From: mwagman@charter.net (Mike Wagman) Date: Thu Jul 24 13:20:01 2003 Subject: [Tutor] Random Numbers In-Reply-To: <200307241113.19208.phate@rockriver.net> References: <200307241113.19208.phate@rockriver.net> Message-ID: <1059067232.2499.5.camel@Knoppix> One thing I chose as a starting to learn python exercise was random number generation. I wrote a command line dice roller, a Gui dice roller, and a module that handles some fairly complex rolling. I ran it through py2exe and found a free installer that works well but have not put the stand alone windows one on the page yet. http://www.geocities.com/mikewagman Can't say it's the cleanest code on the planet - but I was quite new then (still am fairly new). Found it a great learning experience. On Thu, 2003-07-24 at 11:13, Michie DeBerry wrote: > Hello, > Allow me to start by introducing myself. My name is Michie, and I am currently > reading Sam's Teach Yourself Python in 24 Hours. I was wondering if there is > anyway to create a random number in Python. I am currently writting a program > to create a password for you. It will have more features later on, but for > right now, that is all I need it to do. Any suggestions as how to go about > creating a random number x number of times to get a-z or 0-9 from a list? > Thx, > Michie (pronounced Mickey) > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Thu Jul 24 15:46:09 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 24 14:46:09 2003 Subject: [Tutor] Help with a tutorial In-Reply-To: Message-ID: > > """ > > Rewrite the high_low.py program from section 5.2 to use the last two > > digits of time at that moment to be the 'random' number. > > """ > > > I think there's a phrasing mistake here --- the question is probably meant > > to be a two-parter: > > > """ > > Rewrite the high_low.py program from section 5.2: > > > > 1. To use the last two digits of time at that moment. > > > > 2. To be the 'random' number. > > """ > I don't understand your rephrasing either ;-) [text cut] > My guess is: > > """Rewrite the high_low.py program from section 5.2 to use the last two > digits of time() [he has imported time.time into global namespace] as a > 'random' number.""" > > "at that moment" is not important to mention, cause this is what > time.time() does. "use something as something" seems to be clearer to me > than "use something to be something". Ah, better! Ok, your rephrasing makes a lot more sense. Jared, have you been able to make more progress on this problem? If not, try to tell us what part of the problem is getting you stuck. From idiot1@netzero.net Thu Jul 24 16:39:03 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 24 15:39:03 2003 Subject: [Tutor] piki, wiki, and such Message-ID: <3F203576.3000305@netzero.net> Having great fun, inhaling wikiwiki stuff at a dead run. Think I will take a stab at writing one. 1. modular is the way to go. 2. instead of hard coding the header and footer into the page viewing routine, I will use external files, so the user can edit the sourcefile. Anything in it that needs it can be parsed. 3. piki is big on objects and their methods; looks like I am going to pound the legenrary concrete skull into OOP at long last. The existing one is at http://www.tinylist.org/cgi-bin/piki.py -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From mlong@datalong.com Thu Jul 24 17:11:02 2003 From: mlong@datalong.com (Michael Long) Date: Thu Jul 24 16:11:02 2003 Subject: [Tutor] Send email w/ outlook Message-ID: Hi, This may be very simple but I have googled and read and googled some more without gaining any enlightenment. I have a python script that generates a file. I want to send that file as an attachement in an email. The machine that the script will run on uses outlook as the mail client to an exchange server. How do I go about this? BTW, I have downloaded and gone through the documentation in the win32all module. TIA, Mike From jeff@ccvcorp.com Thu Jul 24 17:42:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 24 16:42:02 2003 Subject: [Tutor] Send email w/ outlook References: Message-ID: <3F2044AA.9050208@ccvcorp.com> Michael Long wrote: >Hi, > >This may be very simple but I have googled and read and googled some >more without gaining any enlightenment. I have a python script that >generates a file. I want to send that file as an attachement in an >email. The machine that the script will run on uses outlook as the mail >client to an exchange server. How do I go about this? BTW, I have >downloaded and gone through the documentation in the win32all module. > > Instead of working out how to control Outlook, you're probably better off looking at the standard library's email and smtplib modules. You can generate your own email (with attachments) and send it directly to the server, rather than having to go through the intermediate step of controlling a mail client. Both of these modules should have pretty decent documentation. If you get stuck on anything, ask again here and we'll see what we can work out. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Jul 24 18:01:55 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 24 17:01:55 2003 Subject: [Tutor] Determining if an iterator has more elements. References: Message-ID: <3F20492B.3000006@ccvcorp.com> Marc Barry wrote: > Jeff: > > Thanks a million for your answer. The language is quite easy to learn > as I started reading about it on Monday and I already feel like I > have a good grasp on the language. Since you are knowledgeable on the > Python subject, I was wondering if you could offer some input on the > following questions: Sure, but I'm forwarding this back to the mailing list too, because others may have better input than mine. :) > 1. I need a sorted set data type and I noticed that there isn't one > in any of the python modules. I also need just a regular set data > type, but I think I solved that by using a dictionary with both the > key and the value as the same object. Do you know if there are any > Pyhton libraries that offer a sorted set implementation? Nothing standard. I believe that Sets will become a built-in type in Python 2.3 (due out any day now), but I don't know whether they'll be sortable. You could probably work out something that uses a dict to emulate a set, and keeps a sort()ed list of keys... I'm sure I've seen discussion about sorted dictionaries before, but can't recall whether it was here or on comp.lang.python; a bit of trawling through archives and google groups might turn something up. > 2. When I made my first Python class I put all of my class member > variables directly after the class declaration. After doing so, I > noticed that if I changed the variable in one instance of an object it > was changed in all instances (i.e. static variables). So I moved all > the variables inside the __init__ method and then everything seemed to > act like I expected (i.e. as instance variables). So is the previous > how you define static variables in Pyhton and the latter how you > define instance variables? Yes, pretty much, except that in Python they're typically called class variables rather than static variables. Also, you can get some potentially confusing effects depending on whether you're modifying an object or rebinding a name. Here's a short example: >>> class breakfast: ... spam = 0 ... food = ['eggs'] ... >>> s1 = breakfast() >>> s2 = breakfast() >>> s1.spam 0 >>> s1.spam = 3 >>> s1.spam 3 >>> s2.spam 0 >>> At first, both s1 and s2 share the class variable 'spam', which is 0. However, when I rebind the name by doing 's1.spam = 3', I'm creating a *new* instance variable named 'spam' on instance s1. s2, however, is still using the class variable. >>> s1.food ['eggs'] >>> s1.food.append('sausage') >>> s2.food ['eggs', 'sausage'] >>> s1.food ['eggs', 'sausage'] >>> Here, the change made to one showed up in both. What's the difference? Here, I've taken an existing object (the list pointed to by breakfast.food) and mutated it by adding another element. However, I haven't changed any of the names binding that list to my class (or either instance). Since I haven't created a new instance variable for s1, it's still pointing to the class variable, as is s2. The concept of name binding and object mutation is very important in Python, so if this is at all confusing to you, it might be good to search out some more thorough descriptions from the online tutorial and the list/newsgroup archives. > Also, I wasn't sure if I should reply to you via the mailing list. I > am not sure of the protocol and so please inform me if I shouldn't > contact you directly. I don't mind being contacted directly, but it's usually best to at least send a copy of things like this to the list. That way, if I should happen to be busy, someone else has the chance to answer your questions... and if I happen to give a wrong answer, someone else can correct me. :) Jeff Shannon Technician/Programmer Credit International From phate@rockriver.net Thu Jul 24 19:07:02 2003 From: phate@rockriver.net (Michie DeBerry) Date: Thu Jul 24 18:07:02 2003 Subject: [Tutor] Password Program Message-ID: <200307241707.01921.phate@rockriver.net> Hello peeps, I was wondering if it was possible to have a program in Python ask someone for a user name/password and then encrypt the password, save it to the harddrive, and later, when asked, decrypt the password and tell u what the un/pw is. From R. Alan Monroe" References: <200307241707.01921.phate@rockriver.net> Message-ID: <47732771259.20030724182441@columbus.rr.com> > I was wondering if it was possible to have a program in Python ask someone for > a user name/password and then encrypt the password, save it to the harddrive, > and later, when asked, decrypt the password and tell u what the un/pw is. I had never looked into this until recently, and I felt really stupid for it not having occurred to me. Most sytems enrypt the password in a way to where you purposely CAN'T decrypt it. Later, when the user logs in, they encrypt whatever the user typed for the password, and compare that to the stored encrypted password. I don't know if there's anything in the stock library that will do reversible encryption. Anyone know? Alan From justin@unixremedies.com Thu Jul 24 19:41:03 2003 From: justin@unixremedies.com (Justin Heath) Date: Thu Jul 24 18:41:03 2003 Subject: [Tutor] Password Program In-Reply-To: <200307241707.01921.phate@rockriver.net> References: <200307241707.01921.phate@rockriver.net> Message-ID: <3F205EE5.3070309@unixremedies.com> Michie DeBerry wrote: >Hello peeps, >I was wondering if it was possible to have a program in Python ask someone for >a user name/password and then encrypt the password, save it to the harddrive, >and later, when asked, decrypt the password and tell u what the un/pw is. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > Check out http://www.python.org/doc/2.2.3/lib/module-crypt.html. From dyoo@hkn.eecs.berkeley.edu Thu Jul 24 20:03:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 24 19:03:02 2003 Subject: [Tutor] Sorted dictionaries In-Reply-To: <3F20492B.3000006@ccvcorp.com> Message-ID: On Thu, 24 Jul 2003, Jeff Shannon wrote: > > 1. I need a sorted set data type and I noticed that there isn't one > > in any of the python modules. I also need just a regular set data > > type, but I think I solved that by using a dictionary with both the > > key and the value as the same object. Do you know if there are any > > Pyhton libraries that offer a sorted set implementation? > > Nothing standard. I believe that Sets will become a built-in type in > Python 2.3 (due out any day now), but I don't know whether they'll be > sortable. You could probably work out something that uses a dict to > emulate a set, and keeps a sort()ed list of keys... I'm sure I've seen > discussion about sorted dictionaries before, but can't recall whether it > was here or on comp.lang.python; a bit of trawling through archives and > google groups might turn something up. Here a link to that discussion: http://mail.python.org/pipermail/tutor/2002-November/018864.html We can implement a "sorted" map using a data structure called a "Red-Black Tree". Chris Gonnerman has written a nice rbtree module: http://newcenturycomputers.net/projects/rbtree.html Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Jul 24 20:13:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 24 19:13:03 2003 Subject: [Tutor] Password Program In-Reply-To: <47732771259.20030724182441@columbus.rr.com> Message-ID: On Thu, 24 Jul 2003, R. Alan Monroe wrote: > > I was wondering if it was possible to have a program in Python ask > > someone for a user name/password and then encrypt the password, save > > it to the harddrive, and later, when asked, decrypt the password and > > tell u what the un/pw is. > > I had never looked into this until recently, and I felt really stupid > for it not having occurred to me. Most sytems encrypt the password in a > way to where you purposely CAN'T decrypt it. Later, when the user logs > in, they encrypt whatever the user typed for the password, and compare > that to the stored encrypted password. > > I don't know if there's anything in the stock library that will do > reversible encryption. Anyone know? Hi Alan, There are some trivial ones. For example, ROT13 --- "rotating" a character by thirteen places --- is a standard 'encoding' in Python: ### >>> msg = "This is a test of the emergency broadcast system." >>> secret = msg.encode('rot13') >>> >>> secret 'Guvf vf n grfg bs gur rzretrapl oebnqpnfg flfgrz.' >>> >>> secret.encode('rot13') 'This is a test of the emergency broadcast system.' ### However, I think the Python implementors added it only because it's cute. Anyone who seriously uses ROT13 to secure secrets should be hung upside down for a few minutes to bring them to their senses. *grin* For doing real encryption, you may want to look at the Python Cryptography Toolkit: http://www.amk.ca/python/code/crypto.html Hope this helps! From alan.gauld@blueyonder.co.uk Fri Jul 25 04:16:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 25 03:16:02 2003 Subject: [Tutor] Anyway to do something like a #define in python? References: Message-ID: <008501c3527c$607c5850$6401a8c0@xp> > Is there a python equivalent to the C #define? Thankfully no, Python has removed the need for such a dangerous and ill behaved construct. As indeed has C++ where the use of #define (and most other pre-processor directives) is deprecated(*). Now what exactly were you thinking of doing with #define? Then we might be able to tell you how to do it safely in Python :-) Alan G (*)If you want to see why #define is evil read the relevant chapter in Bjarne Stroustrup's excellent book "The Design & Evolution of C++" From alan.gauld@blueyonder.co.uk Fri Jul 25 04:21:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 25 03:21:01 2003 Subject: [Tutor] Help with a tutorial References: Message-ID: <008e01c3527d$037eb110$6401a8c0@xp> > """ > Rewrite the high_low.py program from section 5.2 to use the last two > digits of time at that moment to be the 'random' number. > """ > """ > Rewrite the high_low.py program from section 5.2: > > 1. To use the last two digits of time at that moment. > > 2. To be the 'random' number. > """ > > Can anyone confirm that this is what Josh meant? I think its simpler than that. Josh is simply saying use the time() function to get a number. Take the last two digits and use them instead of 78 as the target. As Isaac said, the trick is to 'think strings' Alan G. From alan.gauld@blueyonder.co.uk Fri Jul 25 04:32:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 25 03:32:01 2003 Subject: [Tutor] [OT]Good read Message-ID: <00ca01c3527e$9ae80640$6401a8c0@xp> I've just finished the first paper referenced and thought I'd share it. It's a fascinating peek into the history of programming and computing in general, tracing events from the early 60's through to the early '80's and the appearance of the Apple Lisa. In particular it looks at the development of Smalltalk which has influenced, many languages including Pyhon (see, its not totally OT! :-) ----------------------------- > This isn't quite a book, but it is an excellent read for > anyone who wants to see how the computers we use today > evolved... Its a personal history of the development of > the Smalltalk programming language by its inventor Alan Kay. > (Published in 1993) > > The link is here, the article is only about 40 pages or so long > and only the first 10 pages are of general interest, after that > it gets a bit technical. > > http://www.metaobject.com/papers/Smallhistory.pdf. > > Kay was involved in many of the earliest attempts to produce > personal computers(and I'm talking 1960's here!) and carried > that experience thru' to his work with Xerox PARC in the '70's > It was after seeing Kay's team's results that Steve Jobs went > off to build a GUI for Apple... > > Its quite remarkable how advanced were the visions of the > workers back then. And how little we seem to have advanced > in the intervening 30 years. Although I guess PDAs are actually > one step further in some aspects than they were aiming for. > And tablet PCs are very close to the target. > > For a more generalist view of the same thing see Neal Stephenson's > excellent paper (which is also a real paper book), also linked... > > http://www.cryptonomicon.com/beginning.html > > You need to download the zipped PDF file ... > > Alan G. From guillermo.fernandez@epfl.ch Fri Jul 25 07:08:02 2003 From: guillermo.fernandez@epfl.ch (Guillermo Fernandez) Date: Fri Jul 25 06:08:02 2003 Subject: [Tutor] Password Program Message-ID: <3F21012E.6020107@epfl.ch> >Michie DeBerry wrote: >>>Hello peeps, >>>I was wondering if it was possible to have a program in Python ask >someone for >>>a user name/password and then encrypt the password, save it to the >harddrive, >>>and later, when asked, decrypt the password and tell u what the un/pw >is. >Justin Heath wrote: >Check out http://www.python.org/doc/2.2.3/lib/module-crypt.html. I'm afraid crypt is a one-way hash function, and thus impossible (well... or vey difficult :-) to decrypt. You'll probably find what you want here... at least you have the choice! ;-) http://www.amk.ca/python/code/crypto.html If you are a united-stater I guess you can still donwload the sources without problems (US relaxed the export controls for encryption software). Guille From mwagman@charter.net Fri Jul 25 10:33:18 2003 From: mwagman@charter.net (Mike Wagman) Date: Fri Jul 25 09:33:18 2003 Subject: [Tutor] Looking for some utilities Message-ID: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> I am having to move my development environment for a program I am working on from linux to windows, and I am looking for some utilities to run on windows. A text editor that supports tabs. While IDLE works great for an editor. I use a number of information files that I update while I code. Variable names, functions, to do list, change log, etc and would like to run them all in one program. FTP software. Nothing fancy but free with the ability to remember a log on. A 2 windows configurable file manager, similar to worker, or gentoo, or if you remember the old amiga DirWorks,Dir Opus, Disk master. I know this is a little off topic but I figured there were plently of people on this list that would know. From R. Alan Monroe" References: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: <147791760601.20030725104650@columbus.rr.com> > I am having to move my development environment for a program I am > working on from linux to windows, and I am looking for some utilities to > run on windows. > A text editor that supports tabs. Scite, from scintilla.org. From marc_barry@hotmail.com Fri Jul 25 11:43:12 2003 From: marc_barry@hotmail.com (Marc Barry) Date: Fri Jul 25 10:43:12 2003 Subject: [Tutor] Looking for some utilities Message-ID: Mike: I think that UltraEdit (http://www.ultraedit.com/) is the best windows text editor on the market. Although it isn't free. It allows for Python (and many other languages) syntax highlighting and has a number of tabs at the top of the screen that allow you quickly jump from one text file to another. It works perfect for exactly what you have described. It also has builtin FTP and so you can load and save your files directly to the FTP server. It really is agreat product, although I think it costs about $35.00 US. For a free FTP client Free FTP is okay (http://members.aol.com/brandyware/free.htm). It supports a lot of languages. Sorry, no comments for the file manager. Marc From: Mike Wagman To: Python List Subject: [Tutor] Looking for some utilities Date: 25 Jul 2003 08:31:36 -0500 I am having to move my development environment for a program I am working on from linux to windows, and I am looking for some utilities to run on windows. A text editor that supports tabs. While IDLE works great for an editor. I use a number of information files that I update while I code. Variable names, functions, to do list, change log, etc and would like to run them all in one program. FTP software. Nothing fancy but free with the ability to remember a log on. A 2 windows configurable file manager, similar to worker, or gentoo, or if you remember the old amiga DirWorks,Dir Opus, Disk master. I know this is a little off topic but I figured there were plently of people on this list that would know. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From w.richert@gmx.net Fri Jul 25 11:45:03 2003 From: w.richert@gmx.net (Willi Richert) Date: Fri Jul 25 10:45:03 2003 Subject: [Tutor] Sorted dictionaries In-Reply-To: References: Message-ID: <200307251643.42505.w.richert@gmx.net> > We can implement a "sorted" map using a data structure called a "Red-Black > Tree". Chris Gonnerman has written a nice rbtree module: > > http://newcenturycomputers.net/projects/rbtree.html BTW, which algorithms work behind dict() and sort() ? wr From tim@johnsons-web.com Fri Jul 25 13:50:07 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Fri Jul 25 12:50:07 2003 Subject: [Tutor] Looking for some utilities In-Reply-To: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> References: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: <20030725165404.GM3172@johnsons-web.com> I work primarily in Linux these days, but want to mention three that I have used for years and still do when in windows: Editor: Boxer - www.boxersoftware.com Not free, but cheap and hugely configurable, supports tabs I believe. File Manager: ZTreeWin: Functionally descended from XTree. http://www.ztree.com FTP Client: I still use WS_FTP when I use windows and recommend it to my clients. It remembers logons, and it has some nice features like local and remote file masks. ~tj~ * Mike Wagman [030725 05:46]: > I am having to move my development environment for a program I am > working on from linux to windows, and I am looking for some utilities to > run on windows. > > A text editor that supports tabs. While IDLE works great for an editor. > I use a number of information files that I update while I code. > Variable names, functions, to do list, change log, etc and would like to > run them all in one program. > > FTP software. Nothing fancy but free with the ability to remember a log > on. > > A 2 windows configurable file manager, similar to worker, or gentoo, or > if you remember the old amiga DirWorks,Dir Opus, Disk master. > > I know this is a little off topic but I figured there were plently of > people on this list that would know. > > > _______________________________________________ > 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 mlong@datalong.com Fri Jul 25 13:54:02 2003 From: mlong@datalong.com (Michael Long) Date: Fri Jul 25 12:54:02 2003 Subject: [Tutor] Send email w/ outlook Message-ID: Thanks for the information. The smtplib module makes this very simple to use and the documentation is very good. Cheers, Mike > Instead of working out how to control Outlook, you're probably better > off looking at the standard library's email and smtplib modules. You > can generate your own email (with attachments) and send it directly to > the server, rather than having to go through the intermediate step of > controlling a mail client. > > Both of these modules should have pretty decent documentation. If you > get stuck on anything, ask again here and we'll see what we can work out. > > Jeff Shannon > Technician/Programmer > Credit International > > > > From connally@fas.harvard.edu Fri Jul 25 13:55:03 2003 From: connally@fas.harvard.edu (Emily Lea Connally) Date: Fri Jul 25 12:55:03 2003 Subject: [Tutor] Looking for some utilities In-Reply-To: <20030725165404.GM3172@johnsons-web.com> Message-ID: Hey everyone, I'm very new to programming, in fact, Python is my first language. I've been teaching myself for the past week or so, and I ran into a problem with the program I'm currently trying to write. I need to read the file and search for an address that the user had entered earlier in the program and delete that address if found. Can I do this using a text file or should I set up a database or what? Sorry if this question is a little elementary, but I am honestly brand new to programming and really stuck here. The tutorials I've read online are helpful, but I still can't seem to get it right. thanks for any help you can offer M ************************************************************************* Forgiveness is the fragrance the violet sheds on the heel that has crushed it. - Mark Twain ************************************************************************* From mlong@datalong.com Fri Jul 25 14:15:03 2003 From: mlong@datalong.com (Michael Long) Date: Fri Jul 25 13:15:03 2003 Subject: [Tutor] Send email w/ outlook Message-ID: When I send an email to both my outlook account and my home account I find that the outlook account adds the subject line properly but my pop account does not recognize the subject line. The message is defined as follows: msg = '''\\ From: Me@my.org Subject: testin'... This is a test ''' What am I missing? Thanks, Mike > Thanks for the information. The smtplib module makes this very simple to > use and the documentation is very good. > > Cheers, > Mike > From phate@rockriver.net Fri Jul 25 15:25:03 2003 From: phate@rockriver.net (Michie DeBerry) Date: Fri Jul 25 14:25:03 2003 Subject: [Tutor] Proxy Clicker Message-ID: <200307251325.13573.phate@rockriver.net> Hello Gentleman, Sry to bother you guys again, and I appreciate all the help that you guys have been offering me lately. I have been searching the documentation, and can't really find anything on Proxy's and Sockets. I am in need of a program that will go to a URL through one IP address, and search the html till it finds a specific string, this being Click here to continue. After the program finds the string (it changes every 30 seconds) it will then go to the url that it finds, once through every proxy. Then it will search the second document (the http://www.outwar.com/...) untill it finds how many thugs/feet/fans whoever is using the program has. It is a wonderful idea, and I have a list of proxies that will work, just need the code for the program and I'm not really sure on what to do. Any help would be helpful. Thx, Michie. From Janssen@rz.uni-frankfurt.de Fri Jul 25 15:43:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Jul 25 14:43:02 2003 Subject: [Tutor] textfile or database - has appeared as: Looking for some utilities In-Reply-To: References: Message-ID: [the former subject was from another tread - a bit confusing] On Fri, 25 Jul 2003, Emily Lea Connally wrote: > Hey everyone, I'm very new to programming, in fact, Python is my first Hello Emily. > language. I've been teaching myself for the past week or so, and I ran > into a problem with the program I'm currently trying to write. > I need to read the file and search for an address that the user had > entered earlier in the program and delete that address if found. Can I do > this using a text file or should I set up a database or what? Both are reasonable choises. Databases are faster and has already commands to search, delete, update entries. Textfiles are simpler to use (you can e.g. watch and edit them with an editor). Using a textfile ist perhaps the best choice for a small project. One important aspect is the organization of the data. Let me explain: Suppose you have got no data organisation at all, say a file with random content and something between all kind of stuff is an address. A textfile is perfekt for this scenario, cause you just have to "search & replace" the address (replace by nothing to delete it). string.replace(address, '', file_as_string) would do it. Suppose you organise your data a bit more and put each single address on a line by itself (think of a list of email addresses), you can very well use a textfile, read it in line oriented manner (file_object.readline()), find the line containing the address and delete it. Next step. An address can consist of several informations (like phone number, snail mail address and so on). One way to handle this is to use identifiers on each line: """ phone_number:12345 country:de .... """ There is no point in reading such a file line by line any longer. You need to read it paragraph for paragraph - and you must write your own function/ programm logic for this job. Also deleting an address is now something slightly different. But anyway, a textfile can hold such informations and its not that hard to write a script to manipulate these informations. But when you want to do more and more tricky things like how often was an address actually used or if you want to combine one type of information (say addresses) with other types (say payments or bills) you might better off using a full blown database. Back to your post: it might well be that you can accomplish your task with a textfile but that's hard to tell, cause we don't know what your data is like. In case you havn't got a clue yet, you should post how your textfile would be organised and which code you have written that far to manipulate it. > Sorry if this question is a little elementary, Well, I find it the strength of tutor, to cope with elementary questions. I've seen mailing lists that try but were unable to explain simple things but python-tutor was often able to do so. Who knows? Perhaps some time somebody exposes a question to tutor, anybody *knows* the answere but - there's ain't nobody out there who can explain it ;-) With other words: tutor is the right place to ask simple questions. Michael > but I am honestly brand new > to programming and really stuck here. The tutorials I've read online are > helpful, but I still can't seem to get it right. > thanks for any help you can offer > M > > ************************************************************************* > Forgiveness is the fragrance the violet sheds on the heel that has > crushed it. > - Mark Twain > ************************************************************************* > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mhansen@cso.atmel.com Fri Jul 25 16:01:45 2003 From: mhansen@cso.atmel.com (Mike Hansen) Date: Fri Jul 25 15:01:45 2003 Subject: [Tutor] Re: Looking for some utilities In-Reply-To: <20030725160008.16802.29504.Mailman@mail.python.org> References: <20030725160008.16802.29504.Mailman@mail.python.org> Message-ID: <3F217E47.9010703@cso.atmel.com> I've been using Crimson Editor. http://www.crimsoneditor.com/ It has syntax highlighting, multiple tabs, ftp. A great Notepad replacement and all around good text editor is Textpad. Syntax highlighting, clip libraries, ... http://www.textpad.com If you can wrap your mind around it, many people seem to like emacs. Mike >From: Mike Wagman >To: Python List >Organization: >Date: 25 Jul 2003 08:31:36 -0500 >Subject: [Tutor] Looking for some utilities > >I am having to move my development environment for a program I am >working on from linux to windows, and I am looking for some utilities to >run on windows. > >A text editor that supports tabs. While IDLE works great for an editor. >I use a number of information files that I update while I code. >Variable names, functions, to do list, change log, etc and would like to >run them all in one program. > >FTP software. Nothing fancy but free with the ability to remember a log >on. > >A 2 windows configurable file manager, similar to worker, or gentoo, or >if you remember the old amiga DirWorks,Dir Opus, Disk master. > >I know this is a little off topic but I figured there were plently of >people on this list that would know. > > From alan.gauld@blueyonder.co.uk Fri Jul 25 16:08:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Fri Jul 25 15:08:02 2003 Subject: [Tutor] Looking for some utilities References: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: <000301c352df$cc026700$6401a8c0@xp> > I am having to move my development environment for a program I am > working on from linux to windows, and I am looking for some utilities to > run on windows. This may be stating the obvious but get a copy of cygwin installed. It gives you all the Linux tools you are used to(bash, vim, awk, sed, grep, etc) plus a version of python with GNU readline. > A text editor that supports tabs. I'm not sure I know what you mean here. Every editor I've ever used has supported tabs.... > While IDLE works great for an editor. > I use a number of information files that I update while I code. > Variable names, functions, to do list, change log, etc and > would like to run them all in one program. Well vim allows you to open multiple windows if thats what you mean? Or do you mean a ttabbed window inteface ala Netscape? - the penny drops... Can't help with that I hate tabbed editors, I prefer multi windows with buffer lists ala vim or emacs > FTP software. Nothing fancy but free with the ability > to remember a log on. WS-FTP is what I use, seems to work OK. > A 2 windows configurable file manager, similar to worker, or gentoo, > if you remember the old amiga DirWorks,Dir Opus, Disk master. What does that mean in comparison to Windows Explorer? Personally I tend to just use bash or explorer, between them they meet my neds. HTH, Alan G From mlong@datalong.com Fri Jul 25 16:48:01 2003 From: mlong@datalong.com (Michael Long) Date: Fri Jul 25 15:48:01 2003 Subject: [Tutor] win32file module documentation Message-ID: I would like to use win32file.GetDiskFreeSpace() but do not seem to be able find any documention on this module. I do not have win32file.py installed on my machine only win32file.pyd. Is the source available or at least some documentation explaining input and return values? Thanks, Mike From zak@harlekin-maus.com Fri Jul 25 17:15:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Jul 25 16:15:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge In-Reply-To: <20030718200309.0A4B9F699@xmxpita.excite.com> References: <20030718200309.0A4B9F699@xmxpita.excite.com> Message-ID: <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> Here's an interesting problem a coworker (former mentor) uses when hiring: * Write an algorithm to deal out a set of "cards" It's pretty straightforward in C, and here's a port of the C code in Python: ### import random def deck(size): d = range(size) for i in range(size): r = random.randrange(i, size) temp = d[i] d[i] = d[r] d[r] = d[i] return d ### You can replace the swap code, but weirdly it's slower to process. ### import random def deck2(size): d = range(size) for i in range(size): r = random.randrange(i, size) d[i], d[r] = d[r], d[i] return d ### Then my coworker turned around with this solution, which turns out to be the fastest of the three: ### import random def deck3(size): d = [(random.random(), i) for i in range(size)] d.sort() return [d[i][1] for i in range(size)] ### So my challenge, then: Can anyone come up with an even faster solution than option 3? As an aside, I tried this with deck(100000) through the profiler and go cumtimes as follows: deck = 5.126, deck2 = 5.693, deck3 = 3.327 --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From SWidney@ci.las-vegas.nv.us Fri Jul 25 17:43:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Jul 25 16:43:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86DF@sovereign.ci.las-vegas.nv.us> > Here's an interesting problem a coworker (former mentor) uses > when hiring: > * Write an algorithm to deal out a set of "cards" > > > So my challenge, then: Can anyone come up with an even faster solution > than option 3? > How about the batteries-included approach: >>> import random, profile >>> def deck3(size): ... d = [(random.random(), i) for i in range(size)] ... d.sort() ... return [d[i][1] for i in range(size)] ... >>> def deck4(size): ... d = [i for i in range(size)] ... random.shuffle(d) ... return d ... >>> profile.run('deck3(10000)') 10003 function calls in 0.520 CPU seconds >>> profile.run('deck4(10000)') 10003 function calls in 0.405 CPU seconds >>> profile.run('deck3(100000)') 100003 function calls in 5.633 CPU seconds >>> profile.run('deck4(100000)') 100003 function calls in 4.043 CPU seconds The performance of the Standard Library routines never fail to impress me. Especially those that deal with number-crunching. Are-you-listening-tim-one?-ly y'rs Scott From tpc@csua.berkeley.edu Fri Jul 25 17:51:02 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Jul 25 16:51:02 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 Message-ID: <20030725134113.V20475-100000@localhost.name> hello, I was wondering if anyone has tried to install MySQLdb on Redhat Linux 9. I just installed the module and it was fine: [root@nike download]# rpm -ivh MySQL-python-0.9.2-1.i386.rpm warning: MySQL-python-0.9.2-1.i386.rpm: V3 DSA signature: NOKEY, key ID 930b8ab6 Preparing... ########################################### [100%] 1:MySQL-python ########################################### [100%] though now when I try to run a python script that imports MySQLdb it says "ImportError: No module named MySQLdb". It is strange because rpm -qa | grep MySQL shows: [root@nike local]# rpm -qa | grep MySQL perl-DBD-MySQL-2.1021-3 MySQL-python-0.9.2-1 MySQL-shared-3.23.56-1.0.23 MySQL-client-4.0.14-0 MySQL-server-4.0.14-0 although when I try to find MySQLdb.py I cannot. From tim@johnsons-web.com Fri Jul 25 17:58:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Fri Jul 25 16:58:01 2003 Subject: [Tutor] Looking for some utilities In-Reply-To: <000301c352df$cc026700$6401a8c0@xp> References: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> <000301c352df$cc026700$6401a8c0@xp> Message-ID: <20030725210354.GA9120@johnsons-web.com> * Alan Gauld [030725 11:24]: > > > I am having to move my development environment for a program I am > > working on from linux to windows, and I am looking for some > utilities to > > run on windows. > > This may be stating the obvious but get a copy of cygwin installed. > It gives you all the Linux tools you are used to(bash, vim, awk, sed, > grep, etc) plus a version of python with GNU readline. > > > A text editor that supports tabs. > > I'm not sure I know what you mean here. Every editor I've > ever used has supported tabs.... > > > While IDLE works great for an editor. > > I use a number of information files that I update while I code. > > Variable names, functions, to do list, change log, etc and > > would like to run them all in one program. > > Well vim allows you to open multiple windows if thats what > you mean? Or do you mean a ttabbed window inteface ala > Netscape? - the penny drops... Can't help with that I hate > tabbed editors, I prefer multi windows with buffer lists > ala vim or emacs > > > FTP software. Nothing fancy but free with the ability > > to remember a log on. > > WS-FTP is what I use, seems to work OK. > > > A 2 windows configurable file manager, similar to worker, or gentoo, > > if you remember the old amiga DirWorks,Dir Opus, Disk master. > > What does that mean in comparison to Windows Explorer? > Personally I tend to just use bash or explorer, between them > they meet my neds. Probably veering even further off-topic here, but I'll go a step further than Alan and suggest that Win4Lin, available at www.netraverse.com allows windows desktop and virtual machine (unique I.P. address) to be run from Linux. Hahaha! and when Windows crashes, you just reboot it from the xterm command line in 10 seconds or less. You can then share the same filesystem - I can use Vim or emacs from linux and edit, deploy for windows without switching desktops or doing a dual-boot. and it costs less than a Night on the Town. tim -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From nas-pytut@python.ca Fri Jul 25 18:06:02 2003 From: nas-pytut@python.ca (Neil Schemenauer) Date: Fri Jul 25 17:06:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge In-Reply-To: <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> References: <20030718200309.0A4B9F699@xmxpita.excite.com> <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> Message-ID: <20030725211030.GA11331@glacier.arctrix.com> Zak Arntson wrote: > Here's an interesting problem a coworker (former mentor) uses when hiring: > * Write an algorithm to deal out a set of "cards" > > It's pretty straightforward in C, and here's a port of the C code in Python: Straightforward to do poorly. :-) I think all of the solutuions you posted are biased. See: http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCKEDFGNAA.tim_one%40email.msn.com Cheers, Neil From zak@harlekin-maus.com Fri Jul 25 18:10:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Jul 25 17:10:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC86DF@sovereign.ci.las-vegas.nv.us> References: <0E5508EBA1620743B409A2B8365DE16FDC86DF@sovereign.ci.las-vegas.nv.us> Message-ID: <2631.192.206.201.217.1059167378.squirrel@mail.harlekin-maus.com> Even better, see deck5 (following your advice on built-in functions! :) >>> def deck4(size): ... d = [i for i in range(size)] ... random.shuffle(d) ... return d ... >>> def deck5(size): ... d = range(size) ... random.shuffle(d) ... return d >>> profile.run('deck4(10000)') 10003 function calls in 0.272 CPU seconds >>> profile.run('deck5(10000)') 10003 function calls in 0.262 CPU seconds >>> profile.run('deck4(100000)') 100003 function calls in 2.852 CPU seconds >>> profile.run('deck5(100000)') 100003 function calls in 2.688 CPU seconds --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From zak@harlekin-maus.com Fri Jul 25 18:25:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Fri Jul 25 17:25:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge In-Reply-To: <20030725211030.GA11331@glacier.arctrix.com> References: <20030718200309.0A4B9F699@xmxpita.excite.com> <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> <20030725211030.GA11331@glacier.arctrix.com> Message-ID: <2696.192.206.201.217.1059168257.squirrel@mail.harlekin-maus.com> > Straightforward to do poorly. :-) I think all of the solutuions you > posted are biased. See: > > http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCKEDFGNAA.tim_one%40email.msn.com > > Cheers, > Neil Wow! Thanks for pointing that out. Well, all the solutions aside from the random.shuffle() one. :) --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From SWidney@ci.las-vegas.nv.us Fri Jul 25 18:39:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Jul 25 17:39:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86E1@sovereign.ci.las-vegas.nv.us> > Even better, see deck5 (following your advice on built-in > functions! :) > > >>> def deck4(size): > ... d = [i for i in range(size)] > ... random.shuffle(d) > ... return d > ... > >>> def deck5(size): > ... d = range(size) > ... random.shuffle(d) > ... return d > > >>> profile.run('deck4(10000)') > 10003 function calls in 0.272 CPU seconds > > >>> profile.run('deck5(10000)') > 10003 function calls in 0.262 CPU seconds > > >>> profile.run('deck4(100000)') > 100003 function calls in 2.852 CPU seconds > > >>> profile.run('deck5(100000)') > 100003 function calls in 2.688 CPU seconds Good call! I don't know why I left that list comprehension in there.... I also failed to warn that random.shuffle() mutates the list in-place, so you don't want to try something like: ... return random.shuffle(d) because you'll get None. Scott From roypython@hotmail.com Fri Jul 25 19:43:01 2003 From: roypython@hotmail.com (roy ollis) Date: Fri Jul 25 18:43:01 2003 Subject: [Tutor] (no subject) Message-ID:
while looking for python books i came across "the complete python training course" but there are two versions.  can anyone tell me the difference?  and which is better.  the strange thing is one version lists at $109 but is as cheap as $68 someplaces.  the other lists at $85 and is as cheap as $70.  and i believe both include a python book that sells for $85 alone.  i'm leaning for the 109 version but being discounted so much is it out of date?


STOP MORE SPAM with the new MSN 8 and get 2 months FREE* From dyoo@hkn.eecs.berkeley.edu Fri Jul 25 20:05:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 25 19:05:02 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 In-Reply-To: <20030725134113.V20475-100000@localhost.name> Message-ID: On Fri, 25 Jul 2003 tpc@csua.berkeley.edu wrote: > hello, I was wondering if anyone has tried to install MySQLdb on Redhat > Linux 9. I just installed the module and it was fine: > > [root@nike download]# rpm -ivh MySQL-python-0.9.2-1.i386.rpm > warning: MySQL-python-0.9.2-1.i386.rpm: V3 DSA signature: NOKEY, key ID > 930b8ab6 > Preparing... ########################################### > [100%] > 1:MySQL-python ########################################### > [100%] > > though now when I try to run a python script that imports MySQLdb it > says "ImportError: No module named MySQLdb". Hi tpc, Let's check something really quickly: are you using the standard Python that comes with Red Hat, or a locally-installed version? Check with: $ which python at your shell prompt and tell us what you get. In the same vein, try: $ /usr/bin/python and from there, see if you can do 'import MySQLdb' --- this should be successful. If you're using a locally installed Python, then you probably need to install the MySQLdb module from the source, since the RPM packages are designed to work only with the Python that comes in the Red Hat distribution. This might not be the cause of the problem, but it's highly likely. *grin* Good luck to you! From dyoo@hkn.eecs.berkeley.edu Fri Jul 25 20:30:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 25 19:30:01 2003 Subject: [Tutor] Sorted dictionaries In-Reply-To: <200307251643.42505.w.richert@gmx.net> Message-ID: On Fri, 25 Jul 2003, Willi Richert wrote: > > We can implement a "sorted" map using a data structure called a > > "Red-Black Tree". Chris Gonnerman has written a nice rbtree module: > > > > http://newcenturycomputers.net/projects/rbtree.html > > BTW, which algorithms work behind dict() and sort() ? Hi Willi, Python's Dictionary type is based on a classic data structure called a "hash table". If you'd like, we can give a small introduction on hash tables to get a feel for how they work. I think I wrote something about it a year or so ago on Python-Tutor, but I'm having a hard time finding it... Also, you can always look at Python's source code if you're interested in the primary literature. *grin* Seriously though, most of Python's source code is fairly readable, and it's sorta neat to see how it all the gears work. Here's a link to the 'dictobject.c' source: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/dictobject.c?rev=HEAD&content-type=text/vnd.viewcvs-markup as well as development notes: http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Objects/dictnotes.txt?rev=HEAD&content-type=text/vnd.viewcvs-markup The sort() method of lists had used an algorithm called 'samplesort' to minimize the number of comparisons it used. But around the middle of 2002, Tim Peters thought about sorting a bit: http://mail.python.org/pipermail/python-dev/2002-July/026837.html This thread is actually a lot of fun to read! The end result was that the sorting routine that Python uses was completely overhauled, and recent versions of Python now use "timsort": http://pythonowns.blogspot.com/2002_07_28_pythonowns_archive.html Good luck! From tpc@csua.berkeley.edu Fri Jul 25 20:41:46 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Fri Jul 25 19:41:46 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 In-Reply-To: Message-ID: <20030725161557.M21060-100000@localhost.name> hi Danny, I upgraded the standard RH9 Python 2.2 to 2.2.3. When I do a which and whereis python I get: [tpc@nike html]# which python /usr/bin/python [tpc@nike html]# whereis python python: /usr/bin/python2.2 /usr/bin/python /usr/lib/python2.2 /usr/lib/python1.5 /usr/include/python2.2 /usr/share/man/man1/python.1.gz and I do what you suggested: [tpc@nike html]# /usr/bin/python Python 2.2.3 (#1, Jun 16 2003, 13:21:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? ImportError: No module named MySQLdb but to no avail. I did try python setup.py build but it seems to have problems building '_mysql' extension and gives me: error: command 'gcc' failed with exit status 1 I guess I think about doing another clean reinstall of Redhat 9 and not upgrading anything. I was finally able to get idle installed and working by upgrading from the python 2.2.3 rpms from python.org. I have a sample of the error messages from python setup.py build: running build_ext building '_mysql' extension creating build/temp.linux-i686-2.2 gcc -DNDEBUG -O2 -g -pipe -march=i386 -mcpu=i686 -D_GNU_SOURCE -fPIC -fPIC -I/usr/include/mysql -I/usr/local/include/mysql -I/usr/local/mysql/include/mysql -I/usr/include/python2.2 -c _mysql.c -o build/temp.linux-i686-2.2/_mysql.o _mysql.c:41:19: mysql.h: No such file or directory _mysql.c:42:26: mysqld_error.h: No such file or directory _mysql.c:43:20: errmsg.h: No such file or directory _mysql.c:73: parse error before "MYSQL" _mysql.c:73: warning: no semicolon at end of struct or union _mysql.c:76: parse error before '}' token _mysql.c:76: warning: data definition has no type or storage class _mysql.c:87: parse error before "MYSQL_RES" _mysql.c:87: warning: no semicolon at end of struct or union _mysql.c:91: parse error before '}' token _mysql.c:91: warning: data definition has no type or storage class _mysql.c:103: parse error before '*' token On Fri, 25 Jul 2003, Danny Yoo wrote: > > > On Fri, 25 Jul 2003 tpc@csua.berkeley.edu wrote: > > > hello, I was wondering if anyone has tried to install MySQLdb on Redhat > > Linux 9. I just installed the module and it was fine: > > > > [root@nike download]# rpm -ivh MySQL-python-0.9.2-1.i386.rpm > > warning: MySQL-python-0.9.2-1.i386.rpm: V3 DSA signature: NOKEY, key ID > > 930b8ab6 > > Preparing... ########################################### > > [100%] > > 1:MySQL-python ########################################### > > [100%] > > > > though now when I try to run a python script that imports MySQLdb it > > says "ImportError: No module named MySQLdb". > > > Hi tpc, > > Let's check something really quickly: are you using the standard Python > that comes with Red Hat, or a locally-installed version? Check with: > > $ which python > > at your shell prompt and tell us what you get. > > > In the same vein, try: > > $ /usr/bin/python > > and from there, see if you can do 'import MySQLdb' --- this should be > successful. > > If you're using a locally installed Python, then you probably need to > install the MySQLdb module from the source, since the RPM packages are > designed to work only with the Python that comes in the Red Hat > distribution. > > > This might not be the cause of the problem, but it's highly likely. > *grin* Good luck to you! > > From dyoo@hkn.eecs.berkeley.edu Fri Jul 25 20:46:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 25 19:46:02 2003 Subject: [Tutor] Looking for some utilities In-Reply-To: Message-ID: On Fri, 25 Jul 2003, Emily Lea Connally wrote: > Hey everyone, I'm very new to programming, in fact, Python is my first > language. Hi Emily, welcome aboard! > I need to read the file and search for an address that the user had > entered earlier in the program and delete that address if found. Sounds good so far. > Can I do this using a text file or should I set up a database or what? > Sorry if this question is a little elementary, but I am honestly brand > new to programming and really stuck here. No problem. Your program sounds like a kind of "filtering" task, where we try to only keep things that fit a certain criteria. Here's an concrete example of filtering a list of numbers for "even" numbers: ### >>> numbers = range(20) >>> def is_even(x): ... return x % 2 == 0 ... >>> filtered_numbers = [] >>> for num in numbers: ... if is_even(num): ... filtered_numbers.append(num) ... >>> filtered_numbers [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] ### Here, our "criteria" is checking to see if a number "is_even()". The idea of filtering is general enough that it'll apply to any list of elements --- not just numbers. If you load your address file into a list, you can apply a similar filtering, and then write the filtered result back to disk. Doing manipulations (like deleting or inserting elements) is easy to do on lists, so if your entire address book can fit in memory, the list-manipulation approach should work well. It's not the most "efficient" way to do things, but it's simple. *grin* There are other approaches to your problem, and we can talk about them if you'd like. Please feel free to ask questions on Tutor; we'll be happy to help! From klappnase@freenet.de Fri Jul 25 20:50:02 2003 From: klappnase@freenet.de (klappnase@freenet.de) Date: Fri Jul 25 19:50:02 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 Message-ID: DQpIaSwNCiBJIG11c3QgYWRtaXQgdGhhdCBJIGRvbid0IGtub3cgbXVjaCBhYm91dCB0aGlzLCBi dXQgdGhpcyBvbmU6DQoNCj5fbXlzcWwuYzo0MToxOTogbXlzcWwuaDogTm8gc3VjaCBmaWxlIG9y IGRpcmVjdG9yeQ0KPl9teXNxbC5jOjQyOjI2OiBteXNxbGRfZXJyb3IuaDogTm8gc3VjaCBmaWxl IG9yIGRpcmVjdG9yeQ0KPl9teXNxbC5jOjQzOjIwOiBlcnJtc2cuaDogTm8gc3VjaCBmaWxlIG9y IGRpcmVjdG9yeQ0KDQpsb29rcyBsaWtlIHRoZXJlIG1pZ2h0IGJlIGEgTXlTUUwtZGV2ZWwgcGFj a2FnZSBtaXNzaW5nPw0KDQpHb29kIGx1Y2sNCg0KTWljaGFlbA0KCgoKLS0gCmVCYXkgLSBKZXR6 dCBiZXNzZXIgZWlua2F1ZmVuIQpVZWJlciAxLiBNaW8uIEFuZ2Vib3RlLiBTdGFydHByZWlzZSBh YiBFVVIgMSwtCmh0dHA6Ly93d3cuZnJlZW5ldC5kZS90aXBwL3Nob3BwaW5nL2ViYXk= From dyoo@hkn.eecs.berkeley.edu Fri Jul 25 20:56:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Jul 25 19:56:02 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 In-Reply-To: <20030725161557.M21060-100000@localhost.name> Message-ID: > I have a sample of the error messages from python setup.py build: > > > running build_ext > building '_mysql' extension > creating build/temp.linux-i686-2.2 > gcc -DNDEBUG -O2 -g -pipe -march=i386 -mcpu=i686 -D_GNU_SOURCE -fPIC -fPIC > -I/usr/include/mysql -I/usr/local/include/mysql > -I/usr/local/mysql/include/mysql -I/usr/include/python2.2 -c _mysql.c -o > build/temp.linux-i686-2.2/_mysql.o > _mysql.c:41:19: mysql.h: No such file or directory Ah. Ok, I see: the C compiler is having a hard time finding the "development" header files for MySQL. The line above: > -I/usr/include/mysql -I/usr/local/include/mysql > -I/usr/local/mysql/include/mysql -I/usr/include/python2.2 -c _mysql.c -o are saying "I'll look for these header files in /usr/include/mysql, /usr/local/include/mysql, and /usr/local/mysql/include/mysql." Three strikes, I guess. *grin* Do you have the mysql-devel RPM package installed? You'll need that before trying to compile MySQLdb locally. Also, once you have that development RPM installed, can you do a: $ rpm -ql mysql-devel and show us the output? That command tells us where the files of the package are going to, and I just need to make sure it's putting the development headers in the right place. This is not quite a Python-Tutor topic; we may want to move this off list until we get it resolved. Tpc, email me privately, and we'll give a summary of what we did on Python-Tutor once we fix the problem. Installation issues are always a pain... but let's see if we can get this one licked fast. Good luck! From idiot1@netzero.net Fri Jul 25 21:00:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Fri Jul 25 20:00:01 2003 Subject: [Tutor] wiki WORDS Message-ID: <3F21ADF9.9080302@netzero.net> OK, I thnk I want to code a wiki. The one I have uses one script for all functions, and is very much into classes and object oriented; which I do not yet grasp at all well. Also, it encodes headers and footers into the code. IMHO, this is not a Great Good Thing(tm) because it makes it hard as heck for one to customize the appearance of the pages, whereas reading in and spewing the header and footer of the page would lend itself to convient editing of the wiki's appearance. Also, this thing puts all functions in a single script; complex and confusing. However, If I do things in modules, this will simplify somewhat. One program is a reader. Reads in the header file, requested page, and footer file. Second part reads through the result, parsing imbedded markup and builting up a result string, then squirting that at stdout. Another is an editor. It sends a page with a simple textarea form containing the raw text of the body of the page. Form output goes to a script that saves that, and returns header, that new page, and footer as a result screen. Now this will take a little while to code up. If anyone wants to stick an ore in the water with me, you are hereby invited. Although we COULD discuss it here (and I for one would welcome the community's comments and suggestions if this is acceptable), I suggest that a better place would be on the wiki already working, or on a list hosted at the tinylist site. http://www.tinylist.org/ -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From idiot1@netzero.net Fri Jul 25 21:00:14 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Fri Jul 25 20:00:14 2003 Subject: [Tutor] Password Program In-Reply-To: <47732771259.20030724182441@columbus.rr.com> References: <200307241707.01921.phate@rockriver.net> <47732771259.20030724182441@columbus.rr.com> Message-ID: <3F21AAD8.5030403@netzero.net> R. Alan Monroe wrote: >>I was wondering if it was possible to have a program in Python ask someone for >>a user name/password and then encrypt the password, save it to the harddrive, >>and later, when asked, decrypt the password and tell u what the un/pw is. > > > I had never looked into this until recently, and I felt really stupid > for it not having occurred to me. Most sytems enrypt the password in a > way to where you purposely CAN'T decrypt it. Later, when the user logs > in, they encrypt whatever the user typed for the password, and compare > that to the stored encrypted password. > > I don't know if there's anything in the stock library that will do > reversible encryption. Anyone know? > > Alan Not a clue, but a brute force attack with a good guesser program will soon crack that, unless you do soething to hamper guessing. I used the time module in a password protected function of some importance to introduce a several second delay to purposely inconvience password guessing. Just thought I would toss in this idea as a small tool to hamper cracking passwords with guessing attacks. Also, many people generally use a word with a single number at the end. a simple way to make this much harder to crack means to slap another number on the other end, and not the same number, or even one in the middle as well. This will let you create a password that is easy to remember, but hard to guess. Also, I seem to recall that better logon routines limit the number of trys before the program aborts. Then you have to start the login procedure all over again, andother inconviencing of the guesser routine. Limiting connections does limit the number of guesser program connections that can simultaniously attack the server, but this also create a vulnerability to DOS attacks- if it only allows 5 connections, and mr cracker has 5 bots guessing passwords, you can't get into your own server, except from the console, a distressing situation. Hope some of the ruminations prove to be of some value. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From sigurd@12move.de Fri Jul 25 22:24:01 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Fri Jul 25 21:24:01 2003 Subject: [Tutor] wiki WORDS In-Reply-To: <3F21ADF9.9080302@netzero.net> (Kirk Bailey's message of "Fri, 25 Jul 2003 18:23:53 -0400") References: <3F21ADF9.9080302@netzero.net> Message-ID: On 26 Jul 2003, Kirk Bailey <- idiot1@netzero.net wrote: [...] > discuss it here (and I for one would welcome the community's comments > and suggestions if this is acceptable), I suggest that a better place > would be on the wiki already working, or on a list hosted at the > tinylist site. > http://www.tinylist.org/ If I read right you use at the moment PikiPiki as Wiki software. Are you aware of MoinMoin Wiki another descendant of PikiPiki? Or does your critique also apply to that code? Karl -- Please do *not* send copies of replies to me. I read the list From idiot1@netzero.net Fri Jul 25 23:31:45 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Fri Jul 25 22:31:45 2003 Subject: [Tutor] a screed from a top down mind about a bottom up language In-Reply-To: References: Message-ID: <3F21E7C5.7040103@netzero.net> ----preface to already written letter------------------------------------------------- SCREED- screaming creed. Ya know, after looking this letter over, I don't THINK it will step on any toes, and it was not intended to; but some people ARE VERY FOND of python, myself included, and MIGHT take this letter the wrong way, so let me make this very clear: I LOVE THIS LANGUAGE AND IT'S COMMUNITY. But right now I am looking at doing something rather different than I ever did before, and I am quite fustrated in certain mechanics of the language in how they oppose the creative process. on to the letter! -------------------------------------------------------------------------------------- ARG! (orcish 'oy') Well, it's a scripting language. It has to embrace certain limitations. I'm just grinding my teeth trying to unravel some ideas and pull this together, while thinking in 2 different directions- top down, and bottom up. It's a bit stressful. Python and a number of other languages have a common characteristic. They are bottom up. And after much consideration, I have concluded that this property truely sucks. IN ANY LANGUAGE. I do not think bottom up, but top down. The language I use should allow me to write this way. it does not. I cannot write a program in python without abandoning my greatest assett. This is not unique to python, BTW. Proceeding from most general to most specific, I would define terms and functions, and layer by layer refine the definition, going into more detail, until finally defining the lower levels with existing python words methods, ectera. As long as all terms are defined legally by the time I end my program, it should work. And each level outlines the shape of the next, speeding the design. Let's take a whack at managing an employee database: #SOURCECODE RENTASERF EMPLOYEE DATABASE MANAGER V:5.67 IN BOTSYAP2.1(C)2005 YODABOTS # #####MAIN DO LOOP#### DO: start crunch displayresults shutdown # FOLLOWING EXIT ONLY ENOUNTERED IF SOMETHING ABORTS DO TO ERROR! EXIT('FATALERROR IN MODULE'+$LASTFUNCTION) DONE; ######DEFINITIONS FOLLOW########### def start: readoptionsfile buildalistofallfiles readallfilesinlist clearscreen greetuser ; # def crunch: # a null input is just hitting the enter key. input='Y' while input: displayfiledata editfiledata savefiledata promptuserforinput ; # def displayresults: for file in listofallfiles: displayfiledata promptuserforakey ; # def shutdown: verifyflushallbuffers closeallfiles clearscreen restoreterminal #EXIT HERE IF NO ERROR. ERROR IN ANY FUNCTION ABORTS AND RETURNS TO DO LOOP EXIT('ok') ; ###END OF PSEUDOCODE### that goes from most abstract to incresingly specific. In time the thing would have gone on to SOON become a real no kidding application. And it would work. Because it's top down. Granted, to get it all right, the computer has to traverse the thing many times, creating intermediate links, tables, temp files, and finally cooking it all down to a nice straightforward file of code which will run. This is either stored in the computer's mass data storage device, or lives in memory, runs, then evaporates at the job's end, I don't much care which. (In the long run, this would be less expensive in computer power if it was compiled and saved as executable code; yuou only have to compile it once. Even if it's intermediate code which is interpeted, the huge majority of the work is DONE.) Lots of work for the computer to be sure, but memory is cheap, clockticks are cheap, and as long as the elecrons keep coming, IT DON'T CARE, it grinds away. And my devlopment time is RIPPED to a fraction of it's bottom up time. And that's GOOD, 'cause I am NOT cheap. People are expensive. In time, every word would be defined in other words, or in default primitives of the language. But python works from the other end, and this gets in it's own way. I don't know how to code a low level item as I do not know how it plugs into the middle layer item which I do not know how it plugs into a high level item, and at the same time I am trying to work out the scheme of overall operation anc convert it into high and medium and low code, all at once. I am ossilating back and forth from top to bottom to top and so on and on and on and my brain is going to !SCREAM! fairly soon now. This is not a language thing. This is a thinking thing. The language is simply blocking the strait path, providing it with a complex maze to thread. in the dark. no map. This is not unique to python; many languages are this way, even when they do not HAVE to be this way. In fact, there seems to be some sort of twisted concept that this is actually VIRTUEOUS somehow, to be bottom up. What virtue beyond hardship for hardship's sake is thus served escapes me. POLICY #1 Computers exist for the sake of people, not vice versa. Let this be a basic ethic of computing for all time. We should and ought to define them, not they us. POLICY #2 Computers are VERY FAST IDIOTS. *PEOPLE* are creative. Each should Stick to it's forte. Computers are very good at uncreatively crunching math, bit logic, shuffling data, storing data, SERVING data, and flipping control swiches on and off, FAST. They should do their thing and get out of the way, and let you and me get on with the sloppy and mysterious work of being fountainheads of creativity. They should assist that process, or AT THE LEAST avoid HINDERING it. POLICY#3 Chips are CHEAP. Iron is CHEAP. CLOCKCYCLES are CHEAP. MANHOURS are expensive. Therefore, we should invest a LOT of cash in providing ourselves with tools which conserve expensive resources, such as YOU and ME. Computers chould be organized with operating systems and user interfaces and languages which empower, not enslave. Bondage and Disipline languages should be SHUNNED in all commercial endeavors unless absolutely essencial to the venture. Languages, GUI's and OPSYS' which are broken, flakey, brittle, obstructionistic, mind numbing, or untrustworthy should be ERASED and REPLACED. (I think that may have just condemned a certain firm in Redmond, but who cares) Python is a wonderful language, in that it is high level, and has so very many great functions already worked up and sitting on the library shelf waiting to he stacked together in some wonderful new product, and in it's easy readibility and quick learning curve. Also, it has the finest community of users I have ever seen, except MAYBE for the Linux community, and I strongly suspect there is considerable overlap. Because it is interepeted, and executes things as it encounters them, on the fly, It HAS to define things before it can encounter a reference to them in another definition, or as a command to do something. This is bottom up. But bottom up inherently hobbles human creativity. Look how wonderful python already is at enhancing programmer output. IMAGINE HOW MUCH MORE IT COULD DO IF IT WAS IN HARMONY WITH NATURAL HUMAN CREATIVITY. Think about the possibilities for a while... end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From DRobertson@Covenant.com Sat Jul 26 01:22:02 2003 From: DRobertson@Covenant.com (Robertson, David S.) Date: Sat Jul 26 00:22:02 2003 Subject: [Tutor] Line Continuation Confusion Message-ID: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C3532D.50243610 Content-Type: text/plain Greetings and thanks to all. Although I have been programming for many years, I am new to Python; this list has already been a great help in climbing the learning curve! Now my question: I have read several books about line continuation in Python, and I am told consistently that "Python also joins adjacent physical lines into one logical line if an open parenthesis ((), bracket ([), or brace ({) has not yet been closed." ("Python in a Nutshell", Alex Martelli, O'Reilly) But when I try to run the following code, I get complaints from Python unless I use backslashes at the end of each line. Why doesn't the open parentheses after "execute" hold the statement open until the closing parentheses? oCursor.execute("SELECT count(*) FROM SchoolPlans WHERE SchoolsId = 1;") (BTW: I have, of course, tried making this statement all one line: it works great. It just ain't very readable!) Many thanks in advance. _david ------_=_NextPart_001_01C3532D.50243610 Content-Type: text/html Content-Transfer-Encoding: quoted-printable Line Continuation Confusion

Greetings and thanks to all.  Although I have = been programming for many years, I am new to Python; this list has = already been a great help in climbing the learning curve!  Now my = question:

I have read several books about line continuation in = Python, and I am told consistently that "Python also joins = adjacent physical lines into one logical line if an open parenthesis = ((), bracket ([), or brace ({) has not yet been closed."  = ("Python in a Nutshell", Alex Martelli, O'Reilly)  =

But when I try to run the following code, I get = complaints from Python unless I use backslashes at the end of each = line.  Why doesn't the open parentheses after "execute" = hold the statement open until the closing parentheses?

oCursor.execute("SELECT count(*)
        =         FROM = SchoolPlans 
        =         WHERE = SchoolsId =3D 1;")

(BTW: I have, of course, tried making this statement = all one line:  it works great.  It just ain't very = readable!)

Many thanks in advance.
_david






------_=_NextPart_001_01C3532D.50243610-- From Nitin Gangahar" Hello! I think Alan's absolutely right.I've got the code here it is: import time mytime=time.localtime( ) number=mytime[4] guess=-1 while guess != number: guess = input("Guess a number: ") if guess > number : print "Too high" elif guess < number : print "Too low" print "Just right" >""" >Rewrite the high_low.py program from section 5.2 to use the last >two >digits of time at that moment to be the 'random' number. >""" >""" >Rewrite the high_low.py program from section 5.2: > > 1. To use the last two digits of time at that moment. > > 2. To be the 'random' number. >""" > >Can anyone confirm that this is what Josh meant? >I think its simpler than that. Josh is simply saying use the >time() function to get a number. Take the last two digits >and use them instead of 78 as the target. As Isaac said, >the trick is to 'think strings' > >Alan G. ___________________________________________________ Download the hottest & happening ringtones here! OR SMS: Top tone to 7333 Click here now: http://sms.rediff.com/cgi-bin/ringtone/ringhome.pl From glingl@aon.at Sat Jul 26 03:35:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Jul 26 02:35:02 2003 Subject: [Tutor] Line Continuation Confusion References: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> Message-ID: <3F222186.1050204@aon.at> Robertson, David S. schrieb: > > Greetings and thanks to all. Although I have been programming for > many years, I am new to Python; this list has already been a great > help in climbing the learning curve! Now my question: > > I have read several books about line continuation in Python, and I am > told consistently that "Python also joins adjacent physical lines into > one logical line if an open parenthesis ((), bracket ([), or brace ({) > has not yet been closed." ("Python in a Nutshell", Alex Martelli, > O'Reilly) > > But when I try to run the following code, I get complaints from Python > unless I use backslashes at the end of each line. Why doesn't the > open parentheses after "execute" hold the statement open until the > closing parentheses? > > oCursor.execute("SELECT count(*) > FROM SchoolPlans > WHERE SchoolsId = 1;") > I think this is because the argument of execute is a string, opened with " Such strings have to be closed in the same line by another ". Python understands multi-line-strings, which have to be delimited by """ like this: print """a, be, bu""" a, be, bu >>> len( """a, be, bu""" ) 9 >>> I suppose , but I'm not sure, oCursor.execute will also digest multiline-strings. If not, an error will occur, but no Python-syntax-error. (I'm not that familiar with SQL) Try it. HTH, Gregor > (BTW: I have, of course, tried making this statement all one line: it > works great. It just ain't very readable!) > > Many thanks in advance. > _david > > > > > > From alex@gabuzomeu.net Sat Jul 26 06:06:01 2003 From: alex@gabuzomeu.net (Alexandre Ratti) Date: Sat Jul 26 05:06:01 2003 Subject: [Tutor] Sorted dictionaries In-Reply-To: References: Message-ID: <3F22444F.3060004@gabuzomeu.net> Hello, Danny Yoo wrote: >Python's Dictionary type is based on a classic data structure called a >"hash table". If you'd like, we can give a small introduction on hash >tables to get a feel for how they work. I think I wrote something about >it a year or so ago on Python-Tutor, but I'm having a hard time finding > > Here are two introductions that I saved in my notewiki: http://mail.python.org/pipermail/tutor/2002-January/011281.html http://mail.python.org/pipermail/tutor/2002-March/013211.html Cheers. Alexandre From alan.gauld@blueyonder.co.uk Sat Jul 26 06:16:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat Jul 26 05:16:02 2003 Subject: [Tutor] a screed from a top down mind about a bottom up language References: <3F21E7C5.7040103@netzero.net> Message-ID: <000301c35356$3be96430$6401a8c0@xp> HI Kirk, You are hitting on some very profound issues here. Ones that have challenged the most brilliant minds in computing for years. However, I do wonder about some of what you wrote. For example: > I do not think bottom up, but top down. The language I use > should allow me to write this way. it does not. Most folks think top down. Thats why most software design books teach top down design. So you start at the top, work your way to the bottom and then sstart coding your way back up to where you started. Thats the theory. Now Python, being "executable pseudo code" allows you to follow that process when *writing* the code but not when executing it. ie you can only run it once you've reached the bottom level - which is I think your point. But thats true of every computer language because computers being stupid can only add 1+1 or 1+0 or 0+0 and move data from A to B. Anything else we need to tell them - thats why programming is intrinsically hard. > Proceeding from most general to most specific, I would define > terms and functions, and layer by layer refine the definition, > going into more detail, until finally defining the lower levels > with existing python words methods, That is a description of how I write most of my bigger programs, whether in Python or any other language. (Actually its more correct to say thats how I write programs using procedural programming, if I use OOP then the technique changes because OOP doesn't work so well top down) > #####MAIN DO LOOP#### > DO: > start > crunch > displayresults > shutdown > # FOLLOWING EXIT ONLY ENOUNTERED IF SOMETHING ABORTS DO TO ERROR! > EXIT('FATALERROR IN MODULE'+$LASTFUNCTION) > DONE; def main(): try: while True: start() crunch() displayResults() shutdown() except: print Error("Fatal error in Function") > ######DEFINITIONS FOLLOW########### > def start: > readoptionsfile > buildalistofallfiles > readallfilesinlist > clearscreen > greetuser def start(): readoptionsfile() buildalistofallfiles() readallfilesinlist() clearscreen() greetuser() etc/... Looks like pretty standard Python so far. Its also exactly how I write procedural code. What do you do different? > And it would work. Because it's top down. The two don't necessarily go together unfortunaely! :-) > The computer has to traverse the thing many times, creating > intermediate links,tables, temp files, and finally cooking > it all down to a nice straightforward file of code which will run. Thats a pretty good description of what the Python comiler does. > This is either stored in the computer's mass data storage device, As a .pyc file > In time, every word would be defined in other words, Which brings me back to the real challenge. You can't run intermediate versions of your code until you define stubs for the lowest level you have reached. Now in python we can do that easily(with "pass") but it might be nice for the computer to just define dummy stibs for us. Unfortunately that has a big danger for producing reliabe code... > In fact, there seems to be some sort of twisted concept > that this is actually VIRTUEOUS somehow, to be bottom up. Nope, the top down approach is usually recommended as the best way, but as I said at the statrt computers are so stupid that until you define the bottom level they can't do anything. The compromise is to write ots of stubs at each level then iteratively fill in the stubs until that level is complete Your Policies are great BTW and what most good language designers try to apply within the limits of current technology. In fact the Allan Kay paper I posted the other day explains exactly how he tried to meet those policies(including building his own hardware!) when designing Smalltalk. > Because it is interepeted, and executes things as it > encounters them, on the fly, It HAS to define things before > it can encounter a reference to them in another definition, Not totally true. Provided you keep things inside functions you can refer to things that haven't yet been defined, otherwise recursion wouldn't work! So this works: def foo() bar() # refer to bar before its defined def bar() print 'boo!' So provided we put our top level code into a function - traditionally called main() and then call main as the last thing in our program - traditionally inside the if __name__ == "__main__": mantra - then your style of top down programming works in Python pretty well as you requested... > IMAGINE HOW MUCH MORE IT COULD DO IF IT WAS IN HARMONY > WITH NATURAL HUMAN CREATIVITY. Thats where OOP comes in, it tries to go beyond the top-down discipline and allow an even more creative approach that is still more closely aligned to the way the human brain works. This is based on evolving patterns of ideas, with bits(objects) being added as you think of them. It also focuses on experimenting with ideas as you go, trying things out even before the final solution works. Python is second only to Smalltalk in this regard IMHO. Alan G. From pythontutor@venix.com Sat Jul 26 11:43:01 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat Jul 26 10:43:01 2003 Subject: [Tutor] Line Continuation Confusion In-Reply-To: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> References: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> Message-ID: <3F229337.6040003@venix.com> (reply intermixed below) Robertson, David S. wrote: > .... > I have read several books about line continuation in Python, and I am > told consistently that "Python also joins adjacent physical lines into > one logical line if an open parenthesis ((), bracket ([), or brace ({) > has not yet been closed." ("Python in a Nutshell", Alex Martelli, > O'Reilly) BUT you must break at a "syntax whitespace" point in the line, typically after a comma. You can't simply break a string literal. Gregor's suggestion of using the triple quote for a multiline string WILL work. However, if you need to print the SQL command for debugging, it might be hard to read. operator.add(123,456) operator.add(123, 456) are OK operator.add(1 23,456) is not OK. Breaking your string literal is like breaking the numeric literal 123. I usually use the backslash to tie my SQL lines together. This works nicely because Python (like C) automatically concatenates successive string literals. "abcdefg" "hijklmn" become "abcdefghijklmn". "SELECT count(*) " \ "FROM SchoolPlans " \ "WHERE SchoolsId = 1;" becomes "SELECT count(*) FROM SchoolPlans WHERE SchoolsId = 1;" > .... > Many thanks in advance. > _david -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From pythontutor@venix.com Sat Jul 26 12:09:01 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat Jul 26 11:09:01 2003 Subject: [Tutor] Proxy Clicker In-Reply-To: <200307251325.13573.phate@rockriver.net> References: <200307251325.13573.phate@rockriver.net> Message-ID: <3F229938.10407@venix.com> The program wget may do what you need. If you do write your own python code, these modules urlparse urllib urllib2 should contain what you need. In particular, urllib2 includes a class proxyHandler. Michie DeBerry wrote: > Hello Gentleman, > Sry to bother you guys again, and I appreciate all the help that you guys have > been offering me lately. > I have been searching the documentation, and can't really find anything on > Proxy's and Sockets. I am in need of a program that will go to a URL through > one IP address, and search the html till it finds a specific string, this > being Click here to > continue. After the program finds the string (it changes every 30 > seconds) it will then go to the url that it finds, once through every proxy. > Then it will search the second document (the http://www.outwar.com/...) > untill it finds how many thugs/feet/fans whoever is using the program has. > It is a wonderful idea, and I have a list of proxies that will work, just need > the code for the program and I'm not really sure on what to do. Any help > would be helpful. > Thx, > Michie. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From olof.krantz@telia.com Sat Jul 26 13:44:12 2003 From: olof.krantz@telia.com (Olof Krantz) Date: Sat Jul 26 12:44:12 2003 Subject: [Tutor] ui for Python Message-ID: <1059237737.5587.4.camel@laptop.krantz.se> Hi! I've been using python for a while, and I've decided to start using guis now. I've already tried wxPython, and I like it. Which ui is best? And I have one more question. How do I add stuff to a wxGridSizer? I haven't found any documentation about it, and no code samples either. ./oZt From pythontutor@venix.com Sat Jul 26 15:36:44 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Sat Jul 26 14:36:44 2003 Subject: [Tutor] win32file module documentation In-Reply-To: References: Message-ID: <3F22C9E9.4010800@venix.com> .pyd files are DLL's for Python and probably written in C. On WinNT, I am using the ActiveState Python distribution. The Help (Help/Python Manuals/Contents/Python On Windows Extensions\ /PythonWin32Extensions Help/Modules/win32file) showed this: win32file.GetDiskFreeSpace (int, int, int, int) = GetDiskFreeSpace(rootPathName) Determines the free space on a device. Parameters rootPathName : PyUnicode address of root path Return Value The result is a tuple of integers representing (sectors per cluster, bytes per sector, number of free clusters, total number of clusters) Michael Long wrote: > I would like to use win32file.GetDiskFreeSpace() but do not seem to be > able find any documention on this module. I do not have win32file.py > installed on my machine only win32file.pyd. Is the source available or > at least some documentation explaining input and return values? > > Thanks, > Mike > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From idiot1@netzero.net Sat Jul 26 16:27:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Sat Jul 26 15:27:01 2003 Subject: [Tutor] oop tutorial Message-ID: <3F22D5D1.1020106@netzero.net> http://homepages.unl.ac.uk/~chalkp/proj/ootutor/ Looks good, working on inhaling it now. -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From mlong@datalong.com Sat Jul 26 16:59:01 2003 From: mlong@datalong.com (Michael Long) Date: Sat Jul 26 15:59:01 2003 Subject: [Tutor] win32file module documentation Message-ID: Thanks for the excellent explanation. This python thingy sure is making my job much easier... > .pyd files are DLL's for Python and probably written in C. > > On WinNT, I am using the ActiveState Python distribution. The Help > (Help/Python Manuals/Contents/Python On Windows Extensions\ > /PythonWin32Extensions Help/Modules/win32file) > showed this: From alan.gauld@blueyonder.co.uk Sat Jul 26 17:51:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sat Jul 26 16:51:01 2003 Subject: [Tutor] Line Continuation Confusion References: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> Message-ID: <002001c353b7$5c6ec630$6401a8c0@xp> > oCursor.execute("SELECT count(*) > FROM SchoolPlans > WHERE SchoolsId = 1;") Single quoted strings have to be on one line, if you had used a triple quoted string it would be fine. Some further examples: def f(s): pass def g(s,i): pass f(""" SELECT FOO FROM BAR WHERE X = 42""") g("SELECT COUNT FROM FOO", 42) g( "SELECT COUNT FROM FOO", 42) f("SELECT FOO FROM BAZ \ WHERE X=42") # can use the explicit separator '\' too HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From pauljhickey@eircom.net Sat Jul 26 18:26:01 2003 From: pauljhickey@eircom.net (Paul Hickey) Date: Sat Jul 26 17:26:01 2003 Subject: [Tutor] Help with Python on Red Hat 8 Message-ID: <007b01c353bc$374aec80$fdc4fea9@pjhickey> This is a multi-part message in MIME format. ------=_NextPart_000_0078_01C353C4.98E202F0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi , I've been using Python on windows for a short time. I Just loaded RH8 on to a laptop and went to use Python, its not listed = anywhere in the GUI, I found it by opening the Terminal. In terminal I typed Python, and now Python is running. However its at the >>>_ prompt, so my question is how do I open a file = to write a program, and save it as I did in Windows. Its a newbie question for sure! But I do want to get back to my = tutorial's and would prefer to stay on RH, rather than using another = box with windows. Thanks for your time. Paul. ------=_NextPart_000_0078_01C353C4.98E202F0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hi , I've been using Python on windows = for a short=20 time.
I Just loaded RH8 on to a laptop and = went to use=20 Python, its not listed anywhere in the GUI, I found it by opening the=20 Terminal.
In terminal I typed Python, and now = Python is=20 running.
However its at the >>>_ = prompt, so my=20 question is how do I open a file to write a program, and save it as I = did in=20 Windows.
Its a newbie question for sure! But I = do want to=20 get back to my tutorial's and would prefer to stay on RH, rather than=20  using another box with windows.
Thanks for your time.
Paul.
------=_NextPart_000_0078_01C353C4.98E202F0-- From tbstep@tampabay.rr.com Sat Jul 26 18:34:01 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Sat Jul 26 17:34:01 2003 Subject: [Tutor] Help with Python on Red Hat 8 In-Reply-To: <007b01c353bc$374aec80$fdc4fea9@pjhickey> References: <007b01c353bc$374aec80$fdc4fea9@pjhickey> Message-ID: <200307261731.24010@toddloki> On Saturday 26 July 2003 05:23 pm, Paul Hickey wrote: > Hi , I've been using Python on windows for a short time. > I Just loaded RH8 on to a laptop and went to use Python, its not listed > anywhere in the GUI, I found it by opening the Terminal. In terminal I > typed Python, and now Python is running. > However its at the >>>_ prompt, so my question is how do I open a file to > write a program, and save it as I did in Windows. Its a newbie question for > sure! But I do want to get back to my tutorial's and would prefer to stay > on RH, rather than using another box with windows. Thanks for your time. > Paul. That is your interactive prompt. If you want to write an actual program you'll need to just code it in a text editor and save it with a .py extension (not really necessary, but helps you in keeping track of what kind of file it is). When you want to run it, type 'python .py' at your command prompt. You can use the interactive prompt to run some tutorials, but not to write any lengthy program and save it. -- Todd Stephens From tutor@python.org Sat Jul 26 19:11:01 2003 From: tutor@python.org (Rob McGee) Date: Sat Jul 26 18:11:01 2003 Subject: [Tutor] Help with Python on Red Hat 8 In-Reply-To: <007b01c353bc$374aec80$fdc4fea9@pjhickey> References: <007b01c353bc$374aec80$fdc4fea9@pjhickey> Message-ID: <20030726221035.GC1963@obrien.1984.lan> On Sat, Jul 26, 2003 at 10:23:54PM +0100, Paul Hickey wrote: > I Just loaded RH8 on to a laptop and went to use Python, its not > listed anywhere in the GUI, I found it by opening the Terminal. python itself is not a GUI program; it is a character-based interpreter. > In terminal I typed Python, and now Python is running. That's "python", BTW: Unix-like OS's are case-sensitive. > However its at the >>>_ prompt, so my question is how do I open a file > to write a program, and save it as I did in Windows. This can be done in any editor. Many of them do syntax highlighting and colour for python and other languages. Put this: #!/usr/bin/env python as the first line of yourScript.py (the ".py" is optional), and make it executable: chmod +x yourScript.py You can then run that script from the command line by name (but you'll need a path, either relative or absolute, if it's not in your shell's search path -- $PATH in bash.) KDE can set up command shortcuts similar to what Windows does. You can also use KDE's interface to make a file executable. KDE can hide many details from the user, just as Windows does ... which can be either / both good and bad (depending on the user and his/her needs.) You might want an IDE. You probably have IDLE installed. You can do "locate idle.py" (after the locate database has been created, which is probably done automatically at night) to find it. It may be set up as an icon in your GUI -- I don't know. (Note that KDE, the most common GUI choice these days, is by no means the only one. There is far more choice and variation among X11 window managers and desktop environments than there is in Windows, and most of them are completely customisable. KDevelop also supports python. You say you have Red Hat 8.0, but the GUI's of the free software world move very quickly, so that's behind the times already. Perhaps you'll want to consider more recent releases. The older ones work just fine, of course, but the thing is, a few years ago most of these GUI projects were considerably behind Windows in terms of functionality and ease of use. I'm not sure that's still the case.[1] Welcome to GNU/Linux, HTH. Rob - /dev/rob0 [1] I never intend to find out, either. :) Having already made the switch long ago, there's no need to go back. KDE 3.1.2 beats any Windows I ever used (3.1, 95, NT4). Much of what I do is command- line work anyway, so I'm not interested in a sales pitch for XP. :) From R. Alan Monroe" References: <007b01c353bc$374aec80$fdc4fea9@pjhickey> <20030726221035.GC1963@obrien.1984.lan> Message-ID: <37919408509.20030726221418@columbus.rr.com> From: Sebastian Hans Subject: Re: Which language will use? From: grante@visi.com (Grant Edwards) Newsgroups: comp.os.linux.development.apps In article , Tom Felker wrote: > On Thu, 24 Jul 2003 19:42:51 +0800, Eric Chan wrote: > >> Dear ALL, >> >> I am a new baby of using Linux. I want to ask which programming language >> should use for writing Linux application. >> >> Thanks a lot. > > Well, what will your app do? Dude, you've got your priorities all wrong. Here's the proper order for things: 1) Pick development platform: Linux 2) Pick language: Python 3) Pick GUI library: GTK or wxWindows 4) Write program 5) Figure out what program does -- Moderators accept or reject articles based solely on the criteria posted in the Frequently Asked Questions. Article content is the responsibility of the submitter. Submit articles to ahbou-sub@duke.edu. To write to the moderators, send mail to ahbou-mod@duke.edu. From qsc@icon.co.za Sun Jul 27 04:33:02 2003 From: qsc@icon.co.za (Quentin) Date: Sun Jul 27 03:33:02 2003 Subject: [Tutor] ui for Python In-Reply-To: <1059237737.5587.4.camel@laptop.krantz.se> References: <1059237737.5587.4.camel@laptop.krantz.se> Message-ID: <3F237FFB.6040705@icon.co.za> Have a look at Boa Constructor: http://sourceforge.net/projects/boa-constructor/ It will help you with both your questions. (And help you build and understand GUI's.) Also, spend some time with the Demo that came with wxPython. Quentin From jaredw1234567@hotmail.com Sun Jul 27 04:53:02 2003 From: jaredw1234567@hotmail.com (Jared W) Date: Sun Jul 27 03:53:02 2003 Subject: [Tutor] Re:Help on Tutor Message-ID: Hello Nitin, The part I had trouble on was getting the last two digits from the time. Your program is exactly what I'm looking for, but could you explain how you did that? It works and it's right, but I don't understand how you did what you did. Thanks to everyone who helped. Jared >From: "Nitin Gangahar" >Reply-To: "Nitin Gangahar" >To: jaredw1234567@hotmail.com >CC: tutor@python.org >Subject: Re:Help on Tutor >Date: 26 Jul 2003 06:21:47 -0000 > >Hello! > I think Alan's absolutely right.I've got the code here it is: >import time >mytime=time.localtime( ) >number=mytime[4] >guess=-1 > >while guess != number: > guess = input("Guess a number: ") > > if guess > number : > print "Too high" > > elif guess < number : > print "Too low" > >print "Just right" > > > > > > >>""" >>Rewrite the high_low.py program from section 5.2 to use the last two >>digits of time at that moment to be the 'random' number. >>""" >>""" >>Rewrite the high_low.py program from section 5.2: >> >> 1. To use the last two digits of time at that moment. >> >> 2. To be the 'random' number. >>""" >> >>Can anyone confirm that this is what Josh meant? > >>I think its simpler than that. Josh is simply saying use the >>time() function to get a number. Take the last two digits >>and use them instead of 78 as the target. As Isaac said, >>the trick is to 'think strings' >> >>Alan G. >___________________________________________________ >Download the hottest & happening ringtones here! >OR SMS: Top tone to 7333 >Click here now: http://sms.rediff.com/cgi-bin/ringtone/ringhome.pl > > _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From missive@hotmail.com Sun Jul 27 11:59:01 2003 From: missive@hotmail.com (Lee Harr) Date: Sun Jul 27 10:59:01 2003 Subject: [Tutor] Re:Help on Tutor Message-ID: > Your program is exactly what I'm looking for, but could you explain how >you did that? >>import time >>mytime=time.localtime( ) >>number=mytime[4] >>guess=-1 >> >>while guess != number: >> guess = input("Guess a number: ") >> >> if guess > number : >> print "Too high" >> >> elif guess < number : >> print "Too low" >> >>print "Just right" >> One of the great things about python is that if you don't see what is happening by just reading the code, you can play with the code in the interactive interpreter: >>>import time >>>mytime = time.localtime() >>>mytime (2003, 7, 27, 10, 54, 38, 6, 208, 1) >>>help(time.localtime) Help on built-in function localtime: localtime(...) localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. When 'seconds' is not passed in, convert the current time instead. >>>number = mytime[4] >>>number 54 Plus, the online documentation is some of the best around: http://python.org/doc/current/lib/module-time.html _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From pauljhickey@eircom.net Sun Jul 27 13:09:02 2003 From: pauljhickey@eircom.net (Paul Hickey) Date: Sun Jul 27 12:09:02 2003 Subject: [Tutor] Not to bad,not to good!how to tell apart!! Message-ID: <000a01c35459$4e6cedd0$fdc4fea9@pjhickey> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C35461.B0198810 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable newbie help needed!! This is what i've got i could do with some help, thanks! s =3D raw_input ("How are you?") if s.find('fine')>=3D0: print "Im glad that your good!' elif s.find('OK')>=3D0: print "Happy to hear your OK!" elif s.find('bad')>=3D0: print "Hey look on the bright side, coud be worse!' elif s.find('not too bad')>=3D0: print " im glad to hear your good!" The last line don't work!!! Help. Also can i 'bunch' several words together like, elif s.find('fine' or 'good' or 'OK' )>=3D0: print "Glad that thinigs are going well!" This line dont work either!!! I've tried to play with this but ot no avail There's also the thing about upper and lower case is that a major thing = or will i forget about that for the time being. Or ?? Am i going about this the right way, if i can 'bunch' several key = words in the same statement the i could save a lot of typing, however is = there a better method that a newbie might have a hope of understanding. Help with ANY part of this would be great. Thanks for your time, hope im not asking for too much! Paul ------=_NextPart_000_0007_01C35461.B0198810 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
newbie help needed!!
 
This is what i've got i could do with = some help,=20 thanks!
 
s =3D raw_input ("How are = you?")
if s.find('fine')>=3D0:
    print "Im glad that = your=20 good!'
elif s.find('OK')>=3D0:
    print "Happy to hear = your=20 OK!"
elif = s.find('bad')>=3D0:
    print "Hey look on = the bright=20 side, coud be worse!'
elif s.find('not too = bad')>=3D0:
    print " im glad to = hear your=20 good!"
 
The last line don't work!!! = Help.
 
Also can i 'bunch' several words  = together=20 like,
 
elif s.find('fine' or 'good' or 'OK'=20 )>=3D0:
    print "Glad that = thinigs are=20 going well!"
 
This line dont work = either!!!
I've tried to play with this but ot no=20 avail
 
There's also the thing about upper and = lower case=20 is that a major thing or will i forget about that for the time=20 being.
 
Or ?? Am i going about this the right = way, if i can=20 'bunch' several key words in the same statement the i could save a lot = of=20 typing, however is there a better method that a newbie might have a hope = of=20 understanding.
Help with ANY part of this would = be=20 great.
Thanks for your time, hope im not = asking for too=20 much!
Paul
------=_NextPart_000_0007_01C35461.B0198810-- From RASTM2@aol.com Sun Jul 27 14:01:08 2003 From: RASTM2@aol.com (RASTM2@aol.com) Date: Sun Jul 27 13:01:08 2003 Subject: [Tutor] Boa ? Bugs Oh Acetominiphin ? Sorry I know it's great BUT>>>>> Message-ID: <1dc.ea83a9d.2c555f0f@aol.com> In a message dated 7/27/03 11:01:37 AM Central Daylight Time, tutor-request@python.org writes: > Have a look at Boa Constructor: > http://sourceforge.net/projects/boa-constructor/ > It will help you with both your questions. (And help you build and > understand GUI's.) > Also, spend some time with the Demo that came with wxPython. > I'm having trouble with a documented bug in the Boa readme file. --------8<--------- Sometimes (but rarely) [(I only wish it was rarely)ed.] Boa crashes at startup while opening files in the Editor. [ No. It crashes every time I load it. ] To get around it you may start Boa with the command-line switch -E which will start with an empty Editor. I don't think it's a Boa bug. Seams the Boa team does't know quite what is wrong. They recommend ensuring that the wxPython file version is compatable with the current Python installation. Really, I've been to the Doc's on this one and have found nothing else I can do. WHAAAAA I'm running wxPython ver(2.4.1.2u) -- Python 2.2.3c1 and also MarkH.'s Pythonwin32 extensions. And some time ago I fed a unicode patch to this WinBox from MS Upgradesite -- I wonder...... I've played around with anygui and Tcl\Tk and wxPython and Visual Python but I was really looking forward to trying Boa. If you know of someone that has struggled with this, and suceeded can ya point s/he my way? In the mean time I'll be searching the old Google file. Thanks, Ya'll do a real nice service for us, and I appreciate ya lettin me vent. Ray Rastm2@ (Ja)ol.comeandgetthespaminator <-- disassemble # 5 From glingl@aon.at Sun Jul 27 14:05:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Sun Jul 27 13:05:03 2003 Subject: [Tutor] Not to bad,not to good!how to tell apart!! References: <000a01c35459$4e6cedd0$fdc4fea9@pjhickey> Message-ID: <3F24069C.2010703@aon.at> Paul Hickey schrieb: > newbie help needed!! > > This is what i've got i could do with some help, thanks! > > s = raw_input ("How are you?") > if s.find('fine')>=0: > print "Im glad that your good!' > elif s.find('OK')>=0: > print "Happy to hear your OK!" > elif s.find('bad')>=0: > print "Hey look on the bright side, coud be worse!' > elif s.find('not too bad')>=0: > print " im glad to hear your good!" > > The last line don't work!!! Help. > Hi, Paul, in any if-elif-elif-... statement exactly one branch will be executed. In your case if s.find('not too bad')>=0 is True, then also s.find('bad')>=0 is true, so the corresponding branch will be executed and "Hey, look at ..." will be printed. If you exchanged this last two branches, the statement will work as desired. > Also can i 'bunch' several words together like, > elif s.find('fine' or 'good' or 'OK' )>=0: > print "Glad that thinigs are going well!" > This is possible, but for the Python interpreter: >>> 'fine' or 'good' or 'OK' 'fine' The reason for this is a bit sophisticated, but for now you should keep in mind that or-ing (and and-ing) expressions may have surprising results for you. (If you like to read about this, look at http://www.python.org/doc/current/lib/truth.html and http://www.python.org/doc/current/lib/boolean.html ) However this is not the case if the expressions are themselves boolen ones. So the following will work: elif s.find('fine'')>=0 or s.find('good')>=0 or s.find('OK')>=0: print "etc ...." > This line dont work either!!! > I've tried to play with this but ot no avail > > There's also the thing about upper and lower case is that a major > thing or will i forget about that for the time being. > To manage this you have to use the string-methods lower() and upper(): >>> s = "I'm ok" >>> s.find('OK') -1 >>> s.upper().find('OK') 4 >>> s.find('ok') 4 >>> t = "I'm OK" >>> t.find("ok") -1 >>> t.lower().find("ok") 4 >>> > Or ?? Am i going about this the right way, if i can 'bunch' several > key words in the same statement the i could save a lot of typing, > however is there a better method that a newbie might have a hope of > understanding. > Help with ANY part of this would be great. > Thanks for your time, hope im not asking for too much! Certainly not. Look on the bright side and feel free to ask more ... Gregor > Paul From RASTM2@aol.com Sun Jul 27 14:12:02 2003 From: RASTM2@aol.com (RASTM2@aol.com) Date: Sun Jul 27 13:12:02 2003 Subject: [Tutor] Re: My earlier rant on Bugs on Acetominiphin Message-ID: <17.3be71a96.2c5561a9@aol.com> I took another look at the output of the MSDos command line and .... [...] importing Explorers.DAVExplorer importing Explorers.SSHExplorer attaching wxPython doc strings showing main frames then the gui loads then the core dumps then the email gets sent then the answer comes... Please, let the answer come. again Ray rastm2@@OL>COM From wheelcrdan@hotmail.com Sun Jul 27 14:45:03 2003 From: wheelcrdan@hotmail.com (Dan Dud) Date: Sun Jul 27 13:45:03 2003 Subject: [Tutor] Re:Help on Tutor Message-ID: Hello and good mornig I was just curious why you imported "time" for this program and not somthing like "random". Just curious?????????? Have a good one Danny D >From: "Lee Harr" >To: tutor@python.org >Subject: [Tutor] Re:Help on Tutor >Date: Sun, 27 Jul 2003 14:57:47 +0000 > >> Your program is exactly what I'm looking for, but could you explain how >>you did that? > >>>import time >>>mytime=time.localtime( ) >>>number=mytime[4] >>>guess=-1 >>> >>>while guess != number: >>> guess = input("Guess a number: ") >>> >>> if guess > number : >>> print "Too high" >>> >>> elif guess < number : >>> print "Too low" >>> >>>print "Just right" >>> > > >One of the great things about python is that if you don't see what is >happening by just reading the code, you can play with the code in the >interactive interpreter: > > >>>>import time >>>>mytime = time.localtime() >>>>mytime >(2003, 7, 27, 10, 54, 38, 6, 208, 1) >>>>help(time.localtime) >Help on built-in function localtime: > >localtime(...) > localtime([seconds]) -> >(tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) > > Convert seconds since the Epoch to a time tuple expressing local time. > When 'seconds' is not passed in, convert the current time instead. > >>>>number = mytime[4] >>>>number >54 > > >Plus, the online documentation is some of the best around: >http://python.org/doc/current/lib/module-time.html > >_________________________________________________________________ >The new MSN 8: advanced junk mail protection and 2 months FREE* >http://join.msn.com/?page=features/junkmail > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From sigurd@12move.de Sun Jul 27 15:42:01 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Sun Jul 27 14:42:01 2003 Subject: [Tutor] Not to bad,not to good!how to tell apart!! In-Reply-To: <000a01c35459$4e6cedd0$fdc4fea9@pjhickey> (Paul Hickey's message of "Sun, 27 Jul 2003 17:08:23 +0100") References: <000a01c35459$4e6cedd0$fdc4fea9@pjhickey> Message-ID: On 27 Jul 2003, Paul Hickey <- pauljhickey@eircom.net wrote: > This is what i've got i could do with some help, thanks! > s = raw_input ("How are you?") > if s.find('fine')>=0: > print "Im glad that your good!' ^ > elif s.find('OK')>=0: > print "Happy to hear your OK!" > elif s.find('bad')>=0: > print "Hey look on the bright side, coud be worse!' ^ > elif s.find('not too bad')>=0: > print " im glad to hear your good!" > The last line don't work!!! Help. First to that line: (a) I marked the two lines where you used the wrong quotes. You started with `"' but ended with `''. That won't work. (b) The second elif is true if the word `bad' could be found; so the last elif will never be executed. To correct this you would have to change sequence of the `elif's (change three and two). > Also can i 'bunch' several words together like, > elif s.find('fine' or 'good' or 'OK' )>=0: > print "Glad that thinigs are going well!" Yes but the syntax is different. You have to write: elif s.find('fine') or s.find('good') > There's also the thing about upper and lower case is that a major thing or > will i forget about that for the time being. That's simple solved. Just convert s before comparision to lowercase or uppercase. Eg: s = s.lower() > Or ?? Am i going about this the right way, if i can 'bunch' several key words > in the same statement the i could save a lot of typing, however is there a > better method that a newbie might have a hope of understanding. Help with ANY You could solve it in another way without a lot elif clauses. You can't use a dictionary here because order matters. # First create a mapping of answers to phrases you would like to see as # answers. ans = ["Im glad that your good!", "Happy to hear your OK!", " im glad to hear your good!", "Hey look on the bright side, coud be worse!"] answer = [('fine', ans[0]), ('good', ans[0]), ('ok', ans[1]), ('not too bad',ans[2]), ('bad', ans[3])] # Now it is easy to add new keywords which should give the same answer. # Now the raw input (we lowercase it immediately) s = raw_input ("How are you?").lower() # And now the answer for (k, v) in answer: if s.find(k) != -1: print v break Karl -- Please do *not* send copies of replies to me. I read the list From alan.gauld@blueyonder.co.uk Sun Jul 27 16:44:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sun Jul 27 15:44:01 2003 Subject: [Tutor] Update to my tutorial Message-ID: <003a01c35477$3e7d3420$6401a8c0@xp> I just spent some time updating my Python tutorial This is not the big upgrade I discussed a while back, to cater for v2, but is preparatory to that. It does include: - a tweak to the style sheets to help complaints about difficulty reading the red code against the blue background. - many many typos etc fixed thanks to Petr Prikryl one of the Czech translators. Hopefully next week I'll get Petr's new improved Czech version up too. - Some code improvements and clarifications requested by other readers. In short if you have pointed out an error in the pasy 6 months it should now be fixed! Any new ones shouldbe notified to me directly please! Enjoy, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Plaxo Contact Update for Scott Kurland" This is a multi-part message in MIME format. --------------C0302C3E1ADE2168BC4F49CB Content-Type: multipart/alternative; boundary="----=_NextPart_001_0028_01C2C189.94CF9E70" ------=_NextPart_001_0028_01C2C189.94CF9E70 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Hi Tutor, I'm updating my address book. Please update my contact information for you. Click the following link to correct or confirm your information: https://www.plaxo.com/edit_contact_info?r=4295037101-7856928--1392975751&t=web Name: tutor Job Title: Company: Work E-mail: tutor@python.org Work Phone: Work Fax: Work Address Line 1: Work Address Line 2: Work City, State, Zip: Mobile Phone: Home E-mail: Home Phone: Home Fax: Home Address Line 1: Home Address Line 2: Home City, State, Zip: My current contact information: P.S. I've included my Plaxo card below so that you have my current information. I've also attached a copy as a vCard. +----------------- | Scott Kurland | skurland@juggler.net | Registered Massage Therapist | | 4204 Bradwood Road | Austin 78722 | mobile: 512-791-6821 +------------------------------------- ____________________________________________________________ This message was sent to you by skurland@juggler.net via Plaxo. To have Plaxo automatically handle these messages in the future, go to: http://www.plaxo.com/autoreply Plaxo's Privacy Policy: http://www.plaxo.com/support/privacy ------=_NextPart_001_0028_01C2C189.94CF9E70 Content-Type: text/html; charset="ISO-8859-1" Content-Transfer-Encoding: 8bit Your Contact Info

Hi Tutor,

I'm updating my address book. Please update my contact information for you.

Thanks,
Scott Kurland

 

tutor
no title
no company
no work address
tutor@python.org
no web page
IM: none
work: none
fax: none
mobile: none
pager: none
 
Personal Information
no home address
no email
no web page
IM: none
home: none
fax: none
mobile: none
birthday: none
     
 


P.S. I've attached my current information in a vcard. If you get Plaxo too, we can stay connected without the hassle of sending emails back and forth.

------=_NextPart_001_0028_01C2C189.94CF9E70-- --------------C0302C3E1ADE2168BC4F49CB Content-Type: text/x-vcard; charset=ISO-8859-1; name="Scott Kurland.vcf" Content-Transfer-Encoding: 8bit Content-Disposition: attachment; filename="Scott Kurland.vcf" BEGIN:VCARD VERSION:2.1 X-PLAXO-VERSION:1.0 N:Kurland;Scott;;; FN:Scott Kurland TITLE:Registered Massage Therapist ADR;WORK;ENCODING=QUOTED-PRINTABLE:;;4204 Bradwood Road=0D=0AAustin 78722=0D=0A;;;; TEL;CELL;VOICE:512-791-6821 EMAIL;PREF;INTERNET:skurland@juggler.net END:VCARD --------------C0302C3E1ADE2168BC4F49CB-- From alan.gauld@blueyonder.co.uk Sun Jul 27 18:04:02 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Sun Jul 27 17:04:02 2003 Subject: [Tutor] Re:Help on Tutor References: Message-ID: <005701c35482$3d46aef0$6401a8c0@xp> > I was just curious why you imported "time" for this program and not somthing > like "random". Just curious?????????? Coz the original question came from someone doing a tutorial which posed as an exercise how to use time as a way to get a pseudo random number. I agree the random module would seem a better long term solution. Alan G. From nyberg.kent@spray.se Sun Jul 27 19:02:05 2003 From: nyberg.kent@spray.se (Kent Nyberg) Date: Sun Jul 27 18:02:05 2003 Subject: [Tutor] Howto use gnome-projects written in glade with python? Message-ID: <1059343269.2231.56.camel@Snutten> Hello dear friends! I am playing around with python and ran into a little problem. I have made this gnome2 interface in Glade that i want to show with python. All the examples i have on my computer uses "import gtk.glade" to show glade-projects. As far as i know all those projects are gtk+ projects, so to import gtk.glade seems ok. What to do for gnome-projects? Import gnome.glade? Nope, there is no such module. If i load the gnome2 interface with gtk.glade then the program segfaults. The code works well with gtk+ glade-projects, so it cant be big errors in the code. I hope i just missed something to import. Sorry if im not that good on explaining the problem, i am pretty new to python. From RASTM2@aol.com Mon Jul 28 04:27:01 2003 From: RASTM2@aol.com (RASTM2@aol.com) Date: Mon Jul 28 03:27:01 2003 Subject: [Tutor] Boa Better Os Alert! Message-ID: <18.3352018c.2c5629fc@aol.com> Ray --In a message dated 7/27/03 3:55:38 PM Central Daylight Time, tutor-request@python.org writes: > I'm having trouble with a documented bug in the Boa readme file. This line is incorrect. The problem is the OS. As it turns out, JanC on the comp.lang.python said that my Win98 installation would not work the Boa if I used the Unicode version of wxPython. I swapped the installation over to the ASCII version of wxPython and BAM, I gotta Boa!. Couldn't be happier... Ray Rastm2@ (Ja)ol.comeandgetthespaminator <-- disassemble # 5 From justin@unixremedies.com Mon Jul 28 11:48:15 2003 From: justin@unixremedies.com (Justin Heath) Date: Mon Jul 28 10:48:15 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 In-Reply-To: <20030725134113.V20475-100000@localhost.name> References: <20030725134113.V20475-100000@localhost.name> Message-ID: <3F253513.5010500@unixremedies.com> tpc@csua.berkeley.edu wrote: >hello, I was wondering if anyone has tried to install MySQLdb on Redhat >Linux 9. I just installed the module and it was fine: > >[root@nike download]# rpm -ivh MySQL-python-0.9.2-1.i386.rpm >warning: MySQL-python-0.9.2-1.i386.rpm: V3 DSA signature: NOKEY, key ID >930b8ab6 >Preparing... ########################################### >[100%] > 1:MySQL-python ########################################### >[100%] > >though now when I try to run a python script that imports MySQLdb it says >"ImportError: No module named MySQLdb". > >It is strange because rpm -qa | grep MySQL shows: > >[root@nike local]# rpm -qa | grep MySQL >perl-DBD-MySQL-2.1021-3 >MySQL-python-0.9.2-1 >MySQL-shared-3.23.56-1.0.23 >MySQL-client-4.0.14-0 >MySQL-server-4.0.14-0 > >although when I try to find MySQLdb.py I cannot. > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > I am using RedHat 9 and installed this module and it works fine. I did have an error because my case did not match the module name (oops). Running the following worked for me: > up2date MySQL-python > python >>> import MySQLdb Also, just FYI the README and FAQ files are located in /usr/share/doc/MySQL-python-0.9.1. Hope that helps, Justin From vicki@thepenguin.org Mon Jul 28 12:05:02 2003 From: vicki@thepenguin.org (Vicki Stanfield) Date: Mon Jul 28 11:05:02 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 Message-ID: <31763.206.53.226.4.1059404696.squirrel@www.thepenguin.org> > Also, just FYI the README and FAQ files are located in > /usr/share/doc/MySQL-python-0.9.1. > > Hope that helps, > Justin Probably in /usr/share/doc/MySQL-python-0.9.2/ for him since he is using version MySQL-python-9.2.1. --vicki From goki75@vsnl.net Mon Jul 28 12:09:01 2003 From: goki75@vsnl.net (G Kiran) Date: Mon Jul 28 11:09:01 2003 Subject: [Tutor] hanging cgi Message-ID: <002601c35519$2c1b5d00$b84c41db@VULCAN> This is a multi-part message in MIME format. ------=_NextPart_000_0020_01C35547.439B0E20 Content-Type: multipart/alternative; boundary="----=_NextPart_001_0021_01C35547.439B0E20" ------=_NextPart_001_0021_01C35547.439B0E20 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I was writing an multi-threaded cgi script for scanning ports of my = servers to check status of the services. the program runs fine on xitami on win xp and as standalone program but on win 2000 with IIS returns CGI error when run on iis after = executing half way saying it returns some incomplete headers ------=_NextPart_001_0021_01C35547.439B0E20 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I was writing an  = multi-threaded cgi=20 script for scanning ports of my servers to check status of the=20 services.
 
the program runs fine on xitami on win = xp and as=20 standalone program
 
but on win 2000 with = IIS returns CGI error when run on iis after = executing half=20 way
saying it returns some incomplete=20 headers
 
------=_NextPart_001_0021_01C35547.439B0E20-- ------=_NextPart_000_0020_01C35547.439B0E20 Content-Type: application/x-pkcs7-signature; name="smime.p7s" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="smime.p7s" MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIII6TCCAngw ggHhoAMCAQICAwmDjzANBgkqhkiG9w0BAQQFADCBkjELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdl c3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMQ8wDQYDVQQKEwZUaGF3dGUxHTAbBgNVBAsT FENlcnRpZmljYXRlIFNlcnZpY2VzMSgwJgYDVQQDEx9QZXJzb25hbCBGcmVlbWFpbCBSU0EgMjAw MC44LjMwMB4XDTAzMDMxNTA4MzkyM1oXDTA0MDMxNDA4MzkyM1owQTEfMB0GA1UEAxMWVGhhd3Rl IEZyZWVtYWlsIE1lbWJlcjEeMBwGCSqGSIb3DQEJARYPZ29raTc1QHZzbmwubmV0MIGfMA0GCSqG SIb3DQEBAQUAA4GNADCBiQKBgQC8C230dhVsUcrPo+jdpzis1aI9bM9NFfm6bPg7smjfnZmNVWYy A9WBXQQxxuhzNZWt2Hcz/msvm6gb057z9HtJgV9PSFxp33vsQEBF+uYt10S+nuEHVBNiy38zisWZ V4i6SxgZU8MEfDUhwOy/pANQ0A6WzvyuevzHr8skRMvuVwIDAQABoywwKjAaBgNVHREEEzARgQ9n b2tpNzVAdnNubC5uZXQwDAYDVR0TAQH/BAIwADANBgkqhkiG9w0BAQQFAAOBgQBYVMDF2bf8Lcbz V87sE3Z4QE9vPtFK70U7Ok8R/3qGBv5BAO5Lp00GFq52BHGLlsjMHG5jzZionhS9xO5IdhdHbvQe 3iXYwHsuHndu134j6I0QL0d5OksiWylX6MWejO2FX+X9sk7Ms342jC7bpc2gJhj/fIzDY98l5FbW nMfMqjCCAy0wggKWoAMCAQICAQAwDQYJKoZIhvcNAQEEBQAwgdExCzAJBgNVBAYTAlpBMRUwEwYD VQQIEwxXZXN0ZXJuIENhcGUxEjAQBgNVBAcTCUNhcGUgVG93bjEaMBgGA1UEChMRVGhhd3RlIENv bnN1bHRpbmcxKDAmBgNVBAsTH0NlcnRpZmljYXRpb24gU2VydmljZXMgRGl2aXNpb24xJDAiBgNV BAMTG1RoYXd0ZSBQZXJzb25hbCBGcmVlbWFpbCBDQTErMCkGCSqGSIb3DQEJARYccGVyc29uYWwt ZnJlZW1haWxAdGhhd3RlLmNvbTAeFw05NjAxMDEwMDAwMDBaFw0yMDEyMzEyMzU5NTlaMIHRMQsw CQYDVQQGEwJaQTEVMBMGA1UECBMMV2VzdGVybiBDYXBlMRIwEAYDVQQHEwlDYXBlIFRvd24xGjAY BgNVBAoTEVRoYXd0ZSBDb25zdWx0aW5nMSgwJgYDVQQLEx9DZXJ0aWZpY2F0aW9uIFNlcnZpY2Vz IERpdmlzaW9uMSQwIgYDVQQDExtUaGF3dGUgUGVyc29uYWwgRnJlZW1haWwgQ0ExKzApBgkqhkiG 9w0BCQEWHHBlcnNvbmFsLWZyZWVtYWlsQHRoYXd0ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0A MIGJAoGBANRp19SwlGRbcelH2AxRtupykbCEXn0tDY97Et+FJXUodDpCLGMnn5V7S+9+GYcdhuqj 3bnOlmQawhRuRKx85o/oTQ9xH0A4pgCjh3j2+ZSGXq3qwF5269kUo11uenwMpUtVfwYZKX+emibV ars4JAhqmMex2qOYkf152+VaxBy5AgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN AQEEBQADgYEAx+ySfk749ZalZ2IqpPBNEWDQb41gWGGsJrtSNVwIzzD7qEqWih9iQiOMFw/0umSc F6xHKd+dmF7SbGBxXKKs3Hnj524ARx+1DSjoAp3kmv0T9KbZfLH43F8jJgmRgHPQFBveQ6mDJfLm nC8Vyv6mq4oHdYsM3VGEa+T40c53ooEwggM4MIICoaADAgECAhBmRXK3zHT1z2N2RYTQLpEBMA0G CSqGSIb3DQEBBAUAMIHRMQswCQYDVQQGEwJaQTEVMBMGA1UECBMMV2VzdGVybiBDYXBlMRIwEAYD VQQHEwlDYXBlIFRvd24xGjAYBgNVBAoTEVRoYXd0ZSBDb25zdWx0aW5nMSgwJgYDVQQLEx9DZXJ0 aWZpY2F0aW9uIFNlcnZpY2VzIERpdmlzaW9uMSQwIgYDVQQDExtUaGF3dGUgUGVyc29uYWwgRnJl ZW1haWwgQ0ExKzApBgkqhkiG9w0BCQEWHHBlcnNvbmFsLWZyZWVtYWlsQHRoYXd0ZS5jb20wHhcN MDAwODMwMDAwMDAwWhcNMDQwODI3MjM1OTU5WjCBkjELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdl c3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMQ8wDQYDVQQKEwZUaGF3dGUxHTAbBgNVBAsT FENlcnRpZmljYXRlIFNlcnZpY2VzMSgwJgYDVQQDEx9QZXJzb25hbCBGcmVlbWFpbCBSU0EgMjAw MC44LjMwMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDeMzKmY8cJJUU+0m54J2eBxdqIGYKX DuNEKYpjNSptcDz63K737nRvMLwzkH/5NHGgo22Y8cNPomXbDfpL8dbdYaX5hc1VmjUanZJ1qCeu 2HL5ugL217CR3hzpq+AYA6h8Q0JQUYeDPPA5tJtUihOH/7ObnUlmAC0JieyUa+mhaQIDAQABo04w TDApBgNVHREEIjAgpB4wHDEaMBgGA1UEAxMRUHJpdmF0ZUxhYmVsMS0yOTcwEgYDVR0TAQH/BAgw BgEB/wIBADALBgNVHQ8EBAMCAQYwDQYJKoZIhvcNAQEEBQADgYEAMbFLR135AXHl9VNsXXnWPZjA JhNigSKnEvgilegbSbcnewQ5uvzm8iTrkfq97A0qOPdQVahs9w2tTBu8A/S166JHn2yiDFiNMUIJ EWywGmnRKxKyQF1q+XnQ6i4l3Yrk/NsNH50C81rbyjz2ROomaYd/SJ7OpZ/nhNjJYmKtBcYxggH+ MIIB+gIBATCBmjCBkjELMAkGA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UE BxMJQ2FwZSBUb3duMQ8wDQYDVQQKEwZUaGF3dGUxHTAbBgNVBAsTFENlcnRpZmljYXRlIFNlcnZp Y2VzMSgwJgYDVQQDEx9QZXJzb25hbCBGcmVlbWFpbCBSU0EgMjAwMC44LjMwAgMJg48wCQYFKw4D AhoFAKCBujAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMzA3Mjgx NTAxNDZaMCMGCSqGSIb3DQEJBDEWBBRAsCyHbR6Oz0oWlTJq+JdAkWKBWDBbBgkqhkiG9w0BCQ8x TjBMMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggqhkiG9w0DAgIBQDAHBgUrDgMCBzAN BggqhkiG9w0DAgIBKDAHBgUrDgMCHTANBgkqhkiG9w0BAQEFAASBgLirOVIPmbrK0Sos4E7KpAtk 7/7iVREO0jtjxmXruJ8n/lxFqbLLcTldKp0e5hg+Ex4Jn878nRcBfCo73zwWQuN5SI+13iYafBvS QnTv6DlxUIOtTptGqqcWkZLAkohls097AkI8NDjrYCM8Usw4DRxkCY/bFv8I9eK7CWtFUC0ZAAAA AAAA ------=_NextPart_000_0020_01C35547.439B0E20-- From SWidney@ci.las-vegas.nv.us Mon Jul 28 12:31:01 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Mon Jul 28 11:31:01 2003 Subject: [Tutor] Re:Help on Tutor Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86E5@sovereign.ci.las-vegas.nv.us> > >>>import time > >>>mytime = time.localtime() > >>>mytime > (2003, 7, 27, 10, 54, 38, 6, 208, 1) > >>>help(time.localtime) > Help on built-in function localtime: > > localtime(...) > localtime([seconds]) -> > (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) > > Convert seconds since the Epoch to a time tuple > expressing local time. > When 'seconds' is not passed in, convert the current time instead. > > >>>number = mytime[4] > >>>number > 54 Two things: first, the fifth element in the list is the current minute, not the second! You'll approach "randomness" more closely if you use the current second. So if you're going to use time.localtime(), use index [5]. Second, other's here have pointed out that you'll only get integers in the range 0-59. Kinda cuts down on the usefulness of using seconds. However, using time.time() will give you better results and it's where I think the exercise was heading. Take a look: >>> import time >>> help(time.time) Help on built-in function time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. ## This looks promising. Does my clock provide fractions? >>> help(time.time()) Help on float: 1059404203.9859999 ## Yep. So I'll have to deal with that. ## The easiest way would be to just get rid of the fractional part >>> int(time.time()) 1059404248 ## And it would be much easier to get the last two digits ## if I was dealing with a string. >>> str(int(time.time())) '1059404275' ## Great! Now I just need the last two characters. >>> str(int(time.time()))[-2:] '89' ## There. Now I can compare that to the string that the user enters. ## Oh, and if I need that to be a number again... >>> int(str(int(time.time()))[-2:]) 39 ## I'll run it a few more times to be sure it works. >>> int(str(int(time.time()))[-2:]) 42 >>> int(str(int(time.time()))[-2:]) 46 >>> int(str(int(time.time()))[-2:]) 94 >>> int(str(int(time.time()))[-2:]) 1 >>> ## Yep. We get a number in the range 0-99. Much better fit for the exercise From goki75@vsnl.net Mon Jul 28 12:52:01 2003 From: goki75@vsnl.net (G Kiran) Date: Mon Jul 28 11:52:01 2003 Subject: [Tutor] Time out socket wait Message-ID: <004901c3551f$9621cad0$b84c41db@VULCAN> This is a multi-part message in MIME format. --Boundary_(ID_05zI1SMAebNqUYV+c8YDew) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT how do i timeout if its taking too long for a socket.connect to establish a connect? ] thankx in advance -gk --Boundary_(ID_05zI1SMAebNqUYV+c8YDew) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
how do i timeout if its taking too long for a socket.connect to establish a connect?
 
]
thankx in advance
 
-gk
--Boundary_(ID_05zI1SMAebNqUYV+c8YDew)-- From dyoo@hkn.eecs.berkeley.edu Mon Jul 28 14:16:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 13:16:02 2003 Subject: [Tutor] Time out socket wait In-Reply-To: <004901c3551f$9621cad0$b84c41db@VULCAN> Message-ID: > how do i timeout if its taking too long for a socket.connect to > establish a connect? Hi gk, You may need to use a third-party module called 'timeoutsocket' http://www.timo-tasi.org/python/timeoutsocket.py [Side note: In the upcoming version of Python (Python 2.3), sockets will have a 'settimeout()' method: http://python.org/dev/doc/devel/lib/socket-objects.html ] Good luck to you! From dyoo@hkn.eecs.berkeley.edu Mon Jul 28 14:22:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 13:22:01 2003 Subject: [Tutor] Re:Help on Tutor In-Reply-To: <0E5508EBA1620743B409A2B8365DE16FDC86E5@sovereign.ci.las-vegas.nv.us> Message-ID: On Mon, 28 Jul 2003, Scott Widney wrote: > ## Yep. So I'll have to deal with that. > ## The easiest way would be to just get rid of the fractional part > >>> int(time.time()) > 1059404248 > ## And it would be much easier to get the last two digits > ## if I was dealing with a string. > >>> str(int(time.time())) > '1059404275' > ## Great! Now I just need the last two characters. > >>> str(int(time.time()))[-2:] > '89' Hi Scott, An alternative way of doing this, without as much string manipulation, can be to use the "modulo" (remainder) operator. Anything divided by 100 will leave a remainder between 0 and 99. ### >>> int(time.time()) % 100 16 ### Hope this helps! From jpollack@socrates.Berkeley.EDU Mon Jul 28 14:32:25 2003 From: jpollack@socrates.Berkeley.EDU (jpollack@socrates.Berkeley.EDU) Date: Mon Jul 28 13:32:25 2003 Subject: [Tutor] database question Message-ID: Hi, For all of you pythonistas that use the language to handle large amounts of data, especially in a bioinformatic context: I'm pretty new to the language and up to this point, I've been able to make do with storing data in a text file. However, I'm building a tool that digs out data from the Genome Browser and then excises what I think to be putative promoter regions. My question is this: The entirety of the file I'm generating is about 223 megabytes. Trying to read in a text file of this size is just ridiculous. I think this probably begs for a database application, but I"ve never used any before. I really don't know any SQL either, aside from the basic concept. Does anyone have any thoughts about what kind of database is python friendly and would be easy to use for a beginner? Also, I assume there are python modules out there for populating and querying such things? The only fields I would have would be: Accession Number, Chromosome, Strand State, Hits (different database calls for the transcription start site... all integers), and the sequence (this is about 7000 bytes generally). Thanks so much, Joshua Pollack From magnus@thinkware.se Mon Jul 28 14:32:44 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jul 28 13:32:44 2003 Subject: [Tutor] =?ISO-8859-1?B?UmU6IFtUdXRvcl0gR2V0IG1lIG91dCBvZiB0aGUgYmx1ZSAoaGVscCB1cmdlbnRseSBuZWVkZWQhKQ==?= Message-ID: Obviously, this has nothing to do with Python, but if you set up an environment variable such as HOME during startup, and it's not in the control panel settings, it's probably either in an AUTOEXEC.BAT or in some kind of net logon script. -----Ursprungligt meddelande----- Fr=E5n: Gregor Lingl Skickat: 2003-07-22 08:42:18 Till: Danny Yoo Kopia: tutor@python.org =C4mne: Re: [Tutor] Get me out of the blue (help urgently needed!) > I tried this yesterday, and indeed at the DOS prompt HOME had the > value "C:\epacris....", although it didn't show up as an environment=20 > variable > in 'system' of the control panel any more. --=20 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 tpc@csua.berkeley.edu Mon Jul 28 14:44:13 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Jul 28 13:44:13 2003 Subject: [Tutor] database question In-Reply-To: Message-ID: <20030728103744.Q39152-100000@localhost.name> the easiest way to get going is to download and install MySQL and then Python-MySQL module. Once you have both setup a quick run of a testdb.py script will show you how easy it is to get Python talking with MySQL: #!/usr/bin/env python import MySQLdb DB = 'test' def create_BIOINFO_table(): conn = MySQLdb.Connection(db=DB) cursor = conn.cursor() sql = """CREATE TABLE BIOINFO ( ACCESSION_NUMBER INT AUTO_INCREMENT PRIMARY KEY NOT NULL, CHROMOSOME VARCHAR(15) NOT NULL ) TYPE = InnoDB;""" result = cursor.execute(sql) conn.close() create_BIOINFO_table() On Mon, 28 Jul 2003 jpollack@socrates.Berkeley.EDU wrote: > > Hi, > > For all of you pythonistas that use the language to handle large amounts > of data, especially in a bioinformatic context: > > I'm pretty new to the language and up to this point, I've been able to > make do with storing data in a text file. However, I'm building a tool > that digs out data from the Genome Browser and then excises what I think > to be putative promoter regions. My question is this: > > The entirety of the file I'm generating is about 223 megabytes. Trying to > read in a text file of this size is just ridiculous. I think this > probably begs for a database application, but I"ve never used any before. > I really don't know any SQL either, aside from the basic concept. > > Does anyone have any thoughts about what kind of database is python > friendly and would be easy to use for a beginner? Also, I assume there > are python modules out there for populating and querying such things? > > > The only fields I would have would be: Accession Number, Chromosome, > Strand State, Hits (different database calls for the transcription start > site... all integers), and the sequence (this is about 7000 bytes > generally). > > > Thanks so much, > > Joshua Pollack > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff@ccvcorp.com Mon Jul 28 14:47:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 28 13:47:02 2003 Subject: [Tutor] Line Continuation Confusion References: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> <3F229337.6040003@venix.com> Message-ID: <3F2561B6.8080502@ccvcorp.com> Lloyd Kvam wrote: > Robertson, David S. wrote: > >> I have read several books about line continuation in Python, and I am >> told consistently that "Python also joins adjacent physical lines >> into one logical line if an open parenthesis ((), bracket ([), or >> brace ({) has not yet been closed." ("Python in a Nutshell", Alex >> Martelli, O'Reilly) > > > BUT you must break at a "syntax whitespace" point in the line, > typically after > a comma. [...] > > I usually use the backslash to tie my SQL lines together. > > This works nicely because Python (like C) automatically concatenates > successive string literals. > "abcdefg" "hijklmn" become "abcdefghijklmn". > > "SELECT count(*) " \ > "FROM SchoolPlans " \ > "WHERE SchoolsId = 1;" > becomes > "SELECT count(*) FROM SchoolPlans WHERE SchoolsId = 1;" In fact, the backslashes are unnecessary in this case (though they don't hurt). If you're within an open set of parens, sequential strings are automatically concatenated. >>> def f(foo): ... print foo ... >>> >>> f("This is a " ... "long string that's " ... "split across several lines.") This is a long string that's split across several lines. >>> Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Mon Jul 28 14:55:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 28 13:55:05 2003 Subject: [Tutor] Boa Better Os Alert! References: <18.3352018c.2c5629fc@aol.com> Message-ID: <3F256381.5010102@ccvcorp.com> RASTM2@aol.com wrote: >Ray --In a message dated 7/27/03 3:55:38 PM Central Daylight Time, >tutor-request@python.org writes: > >>I'm having trouble with a documented bug in the Boa readme file. >> >> > >This line is incorrect. The problem is the OS. >As it turns out, JanC on the comp.lang.python said that my >Win98 installation would not work the Boa if I used the Unicode >version of wxPython. > I believe that the wxPython web page warns that the Unicode build may not work properly under Win9x, because those versions of Windows don't have full Unicode support -- from the wxPython website, "It will also mostly work on Windows 95/98/Me systems, but it is a bit of a hack-job." So it's not too surprising that something like Boa, which stretches wxPython to its fullest, has problems running the Unicode build on the Win9x series... >I swapped the installation over to the ASCII version of wxPython and BAM, >I gotta Boa!. > Glad that works for you. :) Btw, if you have further problems with wxPython or Boa, you'll probably get a more effective response from the wxPython-users mailing list (see http://wxpython.org/maillist.php) than here... Jeff Shannon Technician/Programmer Credit International From SWidney@ci.las-vegas.nv.us Mon Jul 28 14:58:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Mon Jul 28 13:58:02 2003 Subject: [Tutor] Re:Help on Tutor Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC86E8@sovereign.ci.las-vegas.nv.us> > An alternative way of doing this, without as much string > manipulation, can > be to use the "modulo" (remainder) operator. Anything > divided by 100 will > leave a remainder between 0 and 99. > > ### > >>> int(time.time()) % 100 > 16 > ### > Oops. Good catch! I tell you, I have a one-track mind. Someone mentioned string manipulation at the beginning of the thread and I couldn't see past it. Certainly shows the value of having many eyes looking at both the problem and the solution. Thanks! From choncho101@radio.fm Mon Jul 28 14:59:06 2003 From: choncho101@radio.fm (antonio salgado) Date: Mon Jul 28 13:59:06 2003 Subject: [Tutor] newbie!!! Message-ID: <20030728175649.79C5A3E17@sitemail.everyone.net> Hi there to all: I'm new to programming and would like to ask you for some guidance: is Python a good start for programming? what kind or type of projects can I do with it? are there some web pages that use Python? Sorry if these questions are dumb, but really need to know. Geertings to all of you from Mexico. (I know I'll learn from all of you and hope to help you when I can!!!) _____________________________________________________________ Why pay $35.00 for a Web Address? iDotz.Net offers Cool Domains @ Great Prices! Starting at: $8.75/Year. Go: http://www.idotz.net From jeff@ccvcorp.com Mon Jul 28 15:09:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 28 14:09:01 2003 Subject: [Tutor] ui for Python References: <1059237737.5587.4.camel@laptop.krantz.se> Message-ID: <3F2566CF.2080902@ccvcorp.com> Olof Krantz wrote: >Hi! > >I've been using python for a while, and I've decided to start using guis >now. I've already tried wxPython, and I like it. Which ui is best? > "Best" is a matter of opinion and taste. Tkinter is usually seen as being very easy to get a basic UI running, but difficult to do anything more advanced. wxPython has a steeper initial learning curve, but is much more powerful overall. Some people love PyQT, which is supposedly as powerful as wxPython but easier to learn, though there's some potential license issues on Win32 (QT is a proprietary product, and commercial use on Windows requires a pricey license). I'm a wxPython-user, myself. I'd say that if you've tried that and liked it, you'll probably do just fine to stick with it. >And I have one more question. How do I add stuff to a wxGridSizer? I >haven't found any documentation about it, and no code samples either. > > The docs for sizers are a bit weak. Try reading the wxPyWiki about sizers (http://wiki.wxpython.org/index.cgi/UsingSizers) -- there isn't specific info about wxGridSizers there, but much of the same information will apply. For code samples, look in the demo that comes with wxPython -- the demo's code is often *the* best documentation for wxPython, and I always keep the demo running when I'm writing wxPython code so that I can easily refer to it. If you have further questions about anything wxPython-related, you can always ask them on the wxPython-users mailing list (see http://wxpython.org/maillist.php), where you're likely to get faster and more effective answers than here. Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Mon Jul 28 15:35:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 14:35:02 2003 Subject: [Tutor] database question In-Reply-To: Message-ID: On Mon, 28 Jul 2003 jpollack@socrates.Berkeley.EDU wrote: > For all of you pythonistas that use the language to handle large amounts > of data, especially in a bioinformatic context: Hi Joshua, I'm somewhat familiar with it. *grin* > I'm pretty new to the language and up to this point, I've been able to > make do with storing data in a text file. However, I'm building a tool > that digs out data from the Genome Browser and then excises what I think ^^^^^^^^^^^^^^ Out of curiosity, do you mean GBrowse from the GMOD project? http://gmod.sourceforge.net/ > to be putative promoter regions. > > The entirety of the file I'm generating is about 223 megabytes. Trying > to read in a text file of this size is just ridiculous. It actually depends on what we are doing! If we can read it as a 'stream' --- that is, if we can read it line by line, and don't have to keep the whole file in memory --- then the size of the file isn't a limiting factor. That is, something like: ### for line in myfile: print line ### will work perfectly well regardless of file size, because we only keep a single line in memory at a time. It's when we're doing something like: ### lines = myfile.readlines() ### that file size matters, since now this code tries to keep all of the lines in memory at once. But you're right: searching for information in this file won't be too feasible if it's in flat text format, since you'll probably want to find specific records really fast. It does sound worthwhile, then, to learn how to use databases. > The only fields I would have would be: Accession Number, Chromosome, > Strand State, Hits (different database calls for the transcription start > site... all integers), and the sequence (this is about 7000 bytes > generally). Sounds good. Have you tried MySQL or PostgreSQL? I know a few of us are just starting to experiment with MySQL now, so you're in good company. *grin* At the moment, I'm more familiar with MySQL than PostgreSQL. There is a good tutorial on MySQL and Python programming here: http://www.devshed.com/Server_Side/Python/PythonMySQL/print_html You will probably need to install the third-party 'MySQLdb' module: http://sourceforge.net/projects/mysql-python Doing databases is actually not too bad; there are a few pitfalls, but we can help you avoid those. *grin* Please feel free to ask more questions; we'll be glad to help. Good luck! From jeff@ccvcorp.com Mon Jul 28 15:42:26 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Jul 28 14:42:26 2003 Subject: [Tutor] newbie!!! References: <20030728175649.79C5A3E17@sitemail.everyone.net> Message-ID: <3F256E67.90605@ccvcorp.com> antonio salgado wrote: >Hi there to all: >I'm new to programming and would like to ask you for some guidance: >is Python a good start for programming? > Yes. One of the design goals of Python has been that it should be relatively easy for non-programmers to use, and there's been a growing effort to get Python used as an instructional language for beginning programming students. Some would make the case that Python is the *best* place to start programming. ;) >what kind or type of projects can I do with it? > Just about anything. You might have difficulties writing core operating system libraries and device drivers, but other than that it's pretty much wide open. Word processing, image editing, database applications, web services, instant messaging clients... all of these and more have been done in Python. >are there some web pages that use Python? > There's a fair number of them, some of which are pretty big. Perhaps you've heard of Google? ;) They make heavy use of Python (among a couple of other languages) in their search engine. >Sorry if these questions are dumb, but really need to know. >Geertings to all of you from Mexico. >(I know I'll learn from all of you and hope to help you when I can!!!) > > Everyone starts somewhere. And these aren't dumb questions, they're valid concerns for someone who's new to programming. Obviously people on this mailing list will be somewhat biased in Python's favor, but I think you'll enjoy it. :) Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Mon Jul 28 16:03:13 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 15:03:13 2003 Subject: [Tutor] [OT] MySQLdb on Redhat 9 In-Reply-To: <20030725170423.D21313-100000@localhost.name> Message-ID: Hi tpc, On Fri, 25 Jul 2003 tpc@csua.berkeley.edu wrote: > hi Danny, here's a head scratcher... I do what you suggest after I > installed the mysql-devel via rpm in response to Michael's > (klappnase@freenet.de) email: [some content cut] > So I ran my script again and it gave me the ImportError again. > However, I got the idea to try python setup.py build and install from > source and it worked ! The lesson for next time is, if you want to > upgrade your default MySQL from 3.23 to 4 and you rpm the server and > client, be sure to also rpm the "Libraries and Header files" portion. Yes. The development libraries are pretty necessary for serious work; I've always been a bit miffed that Red Hat bundles the development headers separately from the main RPMs, though I understand that they have good reasons for doing the separation. > I am not sure why the rpm of MySQL-devel did not work, but it certainly > allowed the build and install from source to work, which I am grateful > for. It actually does make slightly perverse sense. Here's a summary of what I think was going on (cc'd to tutor@python.org as a followup): You had initially had Red Hat's Python installed. Some time ago, I think you installed an unofficial RPM of Python 2.3, which overwrote Red Hat's Python. (This was sorta bad: it would have been much better to install Python 2.3 in a separate "local" directory so that it doesn't conflict. Oh well.) Later, when you tried installed the MySQL-Python RPM, you ran into problems. That's because the MySQL-Python RPM is hardcoded to work with the Python that's was initially installed with your Red Hat distribution, not Python 2.3. Extension modules are version specific, and since you had installed Python 2.3, the RPM's won't work with it. So your only recourse is to do it with source. You tried compiling MySQL-Python from source, and again ran into problems, but this time, with compiling the extension module: > > running build_ext building '_mysql' extension creating > > build/temp.linux-i686-2.2 gcc -DNDEBUG -O2 -g -pipe -march=i386 > > -mcpu=i686 -D_GNU_SOURCE -fPIC -I/usr/include/mysql > > -I/usr/local/include/mysql -I/usr/local/mysql/include/mysql > > -I/usr/include/python2.2 -c _mysql.c -o > > build/temp.linux-i686-2.2/_mysql.o > > > _mysql.c:41:19: mysql.h: No such file or directory But this too is explainable: compiling anything that deals with MySQL requires MySQL's development headers, which are included in the 'MySQL-devel' RPM. As soon as you installed the development package, then doing: python setup.py install worked. (Just to clarify: The MySQL-devel RPM not only will allow you to install Python's MySQLdb module, but drivers for other languages (like Perl's DBI module) as well. MySQL-devel consists of a bunch of C header files, so it's not specifically designed for Python. You can think of them as the defined API "interface", and anything that uses that API needs to see that interface to compile properly.) Hope this helps elucidate things! *grin* From dyoo@hkn.eecs.berkeley.edu Mon Jul 28 16:31:47 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 15:31:47 2003 Subject: [Tutor] database question [files can be iterated on] In-Reply-To: Message-ID: On Mon, 28 Jul 2003 jpollack@socrates.Berkeley.EDU wrote: > > Out of curiosity, do you mean GBrowse from the GMOD project? > > > http://gmod.sourceforge.net/ > > No, the Genome Browser at UCSC. I'll have a look at the site above... is > it a collection of python tools for bioinformatics? Unfortunately not Python. GMOD is an umbrella project headed by many of the main biological databases. I'm working on the Publication Literature component ("Pubsearch"), which is mostly in Java (with some Jython and Perl sprinked in there...) I'm doing a CC to the rest of the Tutor group, since your next question is a very good one: > > ### > > for line in myfile: > > print line > > ### > > > > will work perfectly well regardless of file size, because we only keep a > > single line in memory at a time. > > Ok. Stupid Question time. in the above example, doesn't "myfile" have > to be read in as a file ahead of time? (e.g. > myfile=open('blahblah.txt').read() ?) No, it's actually perfectly fine to just open up a file: ### myfile = open('blahblah.txt') ### myfile is an open file, and we can think of it as a source of information. We can then progressively read its information from it in a loop. We can do it line by line like this: ### for line in myfile: .... ### It's important to see that this process is very different from: ### myfile = open('blahblah.txt').read() ### There might be a slight confusion here because we're using a variable named 'myfile', but it's not a file at all, but a string of the contents of that file. Hmmm... that sounds confusing. *grin* Ok, let's try this. It helps to see if it we split up the expression into two lines: ### myfile = open('blahblah.txt') contents = myfile.read() ### In this case, we're asking Python to read the whole contents of myfile. Does the distinction make sense? The same reasoning applies to: ### myfile = open('blahblah.txt') lines = myfile.readlines() ### and is something we should try to avoid, if we expect our files to be huge. 'lines' here will become a list of all the lines in myfile, and that's bad for memory reasons. The key idea is that we'd like to treat our file as an "iterator", where we only need to pay attention to the current line, or get the "next" line. This "iterator" approach saves memory, since an iterator-based approach only concentrates on a single line at a time. Python's files support iterators --- most things can be turned into iterators by using the iter() builtin function. Explicitly, this looks like: ### myfile = open('blahblah.txt') for line in iter(myfile): ... ### And the 'for' loop has been designed to "march" across any iterator, so things work out. In fact, as of Python 2.2, it implicitely does an iter() on the object it's marching against. Now we can shorten it to: ### myfile = open('blahblah.txt') for line in myfile: ... ### David Mertz has written a small introduction into the concept of an iterator: http://www-106.ibm.com/developerworks/library/l-pycon.html Please feel free to ask questions about this. > What are you working on at Berkeley? It's always good to know some > locals. :) I'm actually working at the Carnegie Institute of Washington: http://carnegiedpb.stanford.edu/ So I'm on the other side of the Bay at the moment. Sorry! But we're going to have a BayPiggies meeting sometime next month; drop by if you have time: http://www.baypiggies.net/ > Thanks for the reply, I shall try and get mySQL working along with the > python interface. Incidentally, do you know if mySQL has a Windows > version? You can check on: http://mysql.com/ I'm pretty sure that the MySQL 4 server can run on Windows. But how well it runs is another question. *grin* Best of wishes to you! From pythontutor@venix.com Mon Jul 28 16:34:02 2003 From: pythontutor@venix.com (Lloyd Kvam) Date: Mon Jul 28 15:34:02 2003 Subject: [Tutor] Line Continuation Confusion In-Reply-To: <3F2561B6.8080502@ccvcorp.com> References: <00BBF6F79C12644E9F83EA55929390E1023BBCEE@mars.covenant.com> <3F229337.6040003@venix.com> <3F2561B6.8080502@ccvcorp.com> Message-ID: <3F257A7C.7080707@venix.com> Even better. Thanks. Jeff Shannon wrote: > Lloyd Kvam wrote: > >> Robertson, David S. wrote: >> >>> I have read several books about line continuation in Python, and I am >>> told consistently that "Python also joins adjacent physical lines >>> into one logical line if an open parenthesis ((), bracket ([), or >>> brace ({) has not yet been closed." ("Python in a Nutshell", Alex >>> Martelli, O'Reilly) >> >> >> >> BUT you must break at a "syntax whitespace" point in the line, >> typically after >> a comma. [...] >> >> I usually use the backslash to tie my SQL lines together. >> >> This works nicely because Python (like C) automatically concatenates >> successive string literals. >> "abcdefg" "hijklmn" become "abcdefghijklmn". >> >> "SELECT count(*) " \ >> "FROM SchoolPlans " \ >> "WHERE SchoolsId = 1;" >> becomes >> "SELECT count(*) FROM SchoolPlans WHERE SchoolsId = 1;" > > > > In fact, the backslashes are unnecessary in this case (though they don't > hurt). If you're within an open set of parens, sequential strings are > automatically concatenated. > > >>> def f(foo): > ... print foo > ... >>> > >>> f("This is a " > ... "long string that's " > ... "split across several lines.") > This is a long string that's split across several lines. > >>> > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-443-6155 fax: 801-459-9582 From magnus@thinkware.se Mon Jul 28 16:38:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Jul 28 15:38:01 2003 Subject: [Tutor] =?ISO-8859-1?B?UmU6IFtUdXRvcl0gc29ydGluZyBhICdsYXJnZScgZGF0YWZpbGU=?= Message-ID: -----Ursprungligt meddelande----- Fr=E5n: Wilhelmsen Jan Skickat: 2003-07-22 15:59:59 Till: 'tutor@python.org' =C4mne: [Tutor] sorting a 'large' datafile > I tried to read in all the lines but everything crashes when I do. There is no reason that reading a file of that size should cause a crash. What kind of error do you get? Make sure that you run your program from a command prompt or from within an IDE (PythonWin or IDLE etc) so that you get to see tracebacks if you get a Python exception. If you just double-click on a .py-file and the program exits with an error, you won't see what happened... --=20 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 dyoo@hkn.eecs.berkeley.edu Mon Jul 28 19:33:35 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Jul 28 18:33:35 2003 Subject: [Tutor] newbie!!! [sample source code at Useless Python and Vaults of Parnassus] In-Reply-To: <3F256E67.90605@ccvcorp.com> Message-ID: On Mon, 28 Jul 2003, Jeff Shannon wrote: Hi Antonio, > >what kind or type of projects can I do with it? > > Just about anything. You might have difficulties writing core operating > system libraries and device drivers, but other than that it's pretty > much wide open. Word processing, image editing, database applications, > web services, instant messaging clients... all of these and more have > been done in Python. There's a great web site that has examples of code that people on the Tutor list have written. It's called "Useless Python": http://uselesspython.com There's a lot of examples there that show all kinds of programs there. If you browse around, you may get a better feel for what kind of things we can program in python. There is a more "serious" collection of Python programmers at the Vaults of Parnassus: http://www.vex.net/parnassus Good luck to you! From idiot1@netzero.net Mon Jul 28 20:39:09 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Mon Jul 28 19:39:09 2003 Subject: [Tutor] wiki WORDS In-Reply-To: References: <3F21ADF9.9080302@netzero.net> <3F21EA0B.20003@netzero.net> Message-ID: <3F25B3DF.2080603@netzero.net> Karl Pflästerer wrote: > On 26 Jul 2003, Kirk Bailey <- idiot1@netzero.net wrote: > > Hi Kirk, > > >>(Guten Morgen Mine Herr?) >>(about 20% of my command of German, and I think the spelling is way off...) > > > Well my english is only slightly better (sadly). Merrily the way you > wrote it is sounds in german like a mixture from german and dutch. And > as Python is from GvR and he is from the netherlands it's kind of funny. > There ARE no coincidences, and God(dess?) DOES SO have a sense of humor... And your English typing is delightful. I would never dare this conversation in German. Or Hawaiian. I'm startled I *HAVE THE NERVE* to do it in English, my mother tounge. > [...] > >>I am aware of it. Possibly I misunderstand you, or you me? I am not >>'critical' of ANYTHING, I just want to understand this, and write one >>myself, and install a few minor refinements, like the ability to >>easily customize the header and footer. > > > Perhaps I used the word critique in a sense it#s not used in english. I > used it the way it's used in academic speech where it doesn't imply per > se a negative meaning. I see critique as a good thing as it can help to > improve things. Ah, I see, good. My 'critique' of moinmoin is not a moral condemnation of it or anyone else, but rather a concern for the security of a server with 2 commercial websites, and several noncommercial ones. It has never been cracked; I like that record. > > >>I never wrote a wiki before. I want to write a basic one, that >>duplicates a simple wiki. MoinMoin is more advanced, and would be an >>even more difficult challenge to duplicate. > > > I understand now your motivation. It sounds interesting. If I find the > time I will subscríbe to that mailing list. > Hmm, now THERE's a thought. OK, I will go create a list over on the tinylist site. This will take >1< minute.... ok, done. the list now exists. Here is where to go to join it: http://www.tinylist.org/cgi-bin/TLwebform2.py?wiki-project Also, there is an EXISTING if minimal wiki, 'piki', on the site. Here's THAT url: http://www.tinylist.org/cgi-bin/piki.py >>The one on the site now is working. Took an hour to get everything >>right, and away it went! Spent most of the evening after that playing >>with it. Alas, it is very strong in the use of CLASSES and OBJECTS, >>and I am still hammering OOP and CLASSES into my brain through my >>concrete skull. > > > I have a split opinion towards OOP. I see a lot of cases where IMO a > eg. functional approach would be a lot easier to grok. > Sometimes it is, according to some notable correspondants. Note the wiki now sports a BASIC explanation of oop. I found a introductory tutorial that managed to drive a crack into the concrete! :-) > [...] > > In <3F22121B.7070806@netzero.net> Kirk Bailey wrote: > > [...] > > >>I can see it is going to be quite a spell wrapping my brains around >>this enough to be able to write one. > > >>Someday, someday... > > > I always say to myself if I see such a great piece of software that the > people who wrote it also started with a simple solution and it evolved > over time. Look eg. at TeX (well DEK is an exception; I would really > like to get to know him and to see how such an extremly intelligent man > is in `normal life'). > > [...] > > Karl -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From clay@shirky.com Mon Jul 28 23:45:02 2003 From: clay@shirky.com (Clay Shirky) Date: Mon Jul 28 22:45:02 2003 Subject: [Tutor] Newbie question: Google API on OS X In-Reply-To: <3F25B3DF.2080603@netzero.net> Message-ID: I'm trying to run a Google API query in Python, on an OSX machine, using python 2.2 Mark Pilgrim's google module fails with an error File "./SOAP.py", line 2790, in _parseSOAP parser = xml.sax.make_parser() File "/BinaryCache/python/python-3.root~193/ usr/lib/python2.2/xml/sax/__init__.py", line 93, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found Attempting to update SOAP.py to 0.10.2, via 'python setup.py install' fails with the error File "SOAPpy/wstools/XMLSchema.py", line 14, in ? from xml.dom.ext import SplitQName ImportError: No module named ext Is the Mac python 2.2 non-standard? Do I need an additional xml module? Or is there another way to run the Google API? Thanks, -clay From lonetwin@yahoo.com Tue Jul 29 04:42:01 2003 From: lonetwin@yahoo.com (lonetwin) Date: Tue Jul 29 03:42:01 2003 Subject: [Tutor] [Very OT] MySQLdb on Redhat 9 In-Reply-To: <3F253513.5010500@unixremedies.com> References: <20030725134113.V20475-100000@localhost.name> <3F253513.5010500@unixremedies.com> Message-ID: <200307291325.17355.lonetwin@yahoo.com> Hi there, Just a some rpm tips. To list all the files installed by a rpm do a rpm -ql To list all the files that a (not yet installed) rpm _would_ install do a rpm -qpl eg: rpm -qpl MySQL-python-0.9.2-1.i386.rpm To list the rpm that a particular file belongs to, do a rpm -qf /path/to/file HTH Peace Steve -- You or I must yield up his life to Ahrimanes. I would rather it were you. I should have no hesitation in sacrificing my own life to spare yours, but we take stock next week, and it would not be fair on the company. -- J. Wellington Wells From klappnase@freenet.de Tue Jul 29 07:29:02 2003 From: klappnase@freenet.de (klappnase) Date: Tue Jul 29 06:29:02 2003 Subject: [Tutor] Re: How to stop screensaver from starting up In-Reply-To: <20030728202229.GD14508@unpythonic.net> References: <9a410299.0307280614.444cc2b2@posting.google.com> <20030728202229.GD14508@unpythonic.net> Message-ID: <20030729122942.595bd056.klappnase@freenet.de> On Mon, 28 Jul 2003 15:22:29 -0500 Jeff Epler wrote: Hello Jeff, thanks for the feedback. > > For systems using xscreensaver, see xscreensaver-command(1). > > You could use > xscreensaver-command -throttle > to force screen blanking (not screensaver) when the system is idle > or > xscreensaver-command -exit > to force the screensaver process to exit. In the former case, you would > use > xscreensaver-command -unthrottle > to restart the screensaver, and in the latter case > xscreensaver -nosplash > in the latter. > > This is not robust if multiple processes all try to manipulate the > screensaver without some additional kind of locking. > I know this, but what I had in mind was, if there is a possibility to disable the screensaver directly from within python/tkinter just as long as a certain process in my application is running (it's the recording issue I had posted here some time ago, there seems to be a memory leak every time a screensaver starts up). The basic problem is that the xscreensaver-command will not work if someone uses kde-screensavers. I am sorry if this is a silly question, may be what I want is not really possible at all. I just thought this might be an easier way to solve this recording problem, if my application could "grab" the screen while recording is running, than trying a workaround for the snack recording function. Best regards and thanks again Michael From webmaster@dte.ua.pt Tue Jul 29 08:39:54 2003 From: webmaster@dte.ua.pt (=?ISO-8859-1?Q?M=E1rio_Gamito?=) Date: Tue Jul 29 07:39:54 2003 Subject: [Tutor] problems in a python script Message-ID: <3F265CDA.9090004@dte.ua.pt> Hi, I've downloaded the 30 days trial version of editize and followed the instructions in http://plone.org/Members/tlynch/HowToIntegrateEditize to install it. Everything runs smoothly until the creation of munge.py as explained in the above link. I get an error saying " Script line 4 inputvalue = inputvalue.replace("\r", "") ^ SyntaxError: invalid syntax" A curious thing is that when i save it, not only i get the above error, but also the lines begining with double cardinal (##) are gone!!! Also the text refers to "Note: you might need to edit the line calling munge in wysiwyg_support to reflect the name of your folder where all the Editize stuff is stored." Where is this is done ? Thank you in advance for your time and patience. Warm Regards, Mário Gamito munge.py ----------------------------------------------------- ## Script (Python) "munge" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=inputvalue ##title= # to guard against files that might contain only # returns or linefeeds, we will delete each separately # rather than trying: replace("\r\n", "") inputvalue = inputvalue.replace("\r", "") inputvalue = inputvalue.replace("\n", "") inputvalue = inputvalue.replace("'", "'") return inputvalue ------------------------------------------------------------ From glingl@aon.at Tue Jul 29 09:34:50 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Jul 29 08:34:50 2003 Subject: [Tutor] problems in a python script References: <3F265CDA.9090004@dte.ua.pt> Message-ID: <3F266A00.8010209@aon.at> Mário Gamito schrieb: > Hi, > > I've downloaded the 30 days trial version of editize and followed the > instructions in http://plone.org/Members/tlynch/HowToIntegrateEditize > to install it. > > Everything runs smoothly until the creation of munge.py as explained > in the above link. I get an error saying > > " Script line 4 > inputvalue = inputvalue.replace("\r", "") > ^ > SyntaxError: invalid syntax" This looks like if this line were indented some (three ?) blanks from the left margin. In Python blanks (or "white space" in general) has syntactic meaning. Therefore in a simple script a simple statement like this assignment MUST NOT be indented. Remove the indentation and things will work. HTH, Gregor > > A curious thing is that when i save it, not only i get the above > error, but also the lines begining with double cardinal (##) are gone!!! > > Also the text refers to "Note: you might need to edit the line calling > munge in wysiwyg_support to reflect the name of your folder where all > the Editize stuff is stored." > > Where is this is done ? > > Thank you in advance for your time and patience. > > Warm Regards, > Mário Gamito > > > > > munge.py > ----------------------------------------------------- > ## Script (Python) "munge" > ##bind container=container > ##bind context=context > ##bind namespace= > ##bind script=script > ##bind subpath=traverse_subpath > ##parameters=inputvalue > ##title= > > # to guard against files that might contain only > # returns or linefeeds, we will delete each separately > # rather than trying: replace("\r\n", "") > inputvalue = inputvalue.replace("\r", "") > inputvalue = inputvalue.replace("\n", "") > inputvalue = inputvalue.replace("'", "'") > > return inputvalue > ------------------------------------------------------------ > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From james2dope@yahoo.com Tue Jul 29 15:35:09 2003 From: james2dope@yahoo.com (james middendorff) Date: Tue Jul 29 14:35:09 2003 Subject: [Tutor] help with dates Message-ID: <20030729183446.99998.qmail@web13907.mail.yahoo.com> I am attempting to write a little program that will tell you on which day a certain holiday will fall. In whatever year you want. I am a beginner and was wondering how I should tackle this project, or is someone could point my in the right direction? Thanks for any help ===== "I would kill everyone in this room for a drop of sweet beer." ----Homer Simpson---- __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From sigurd@12move.de Tue Jul 29 16:53:01 2003 From: sigurd@12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Jul 29 15:53:01 2003 Subject: [Tutor] help with dates In-Reply-To: <20030729183446.99998.qmail@web13907.mail.yahoo.com> (james middendorff's message of "Tue, 29 Jul 2003 11:34:46 -0700 (PDT)") References: <20030729183446.99998.qmail@web13907.mail.yahoo.com> Message-ID: On 29 Jul 2003, james middendorff <- james2dope@yahoo.com wrote: > I am attempting to write a little program that will > tell you on which day a certain holiday will fall. In > whatever year you want. I am a beginner and was > wondering how I should tackle this project, or is > someone could point my in the right direction? Thanks You could define some fixed date as zero and make all computations with regard to that date. Depending on your needs your resolution could be days or seconds (eg. in Unix day zero is 01.01.1970). Then you need a formula to compute leap years; in C that could be (from RFC3339) ,---- | Here is a sample C subroutine to calculate if a year is a leap year: | | /* This returns non-zero if year is a leap year. Must use 4 digit | year. | */ | int leap_year(int year) | { | return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); | } `---- After the computation you transfer the days or seconds back to a date. Leap seconds can't be computed but must be looked up in a table. ,----[ rfc3339 ] | The following table is an excerpt from the table maintained by the | United States Naval Observatory. The source data is located at: | | | This table shows the date of the leap second, and the difference | between the time standard TAI (which isn't adjusted by leap seconds) | and UTC after that leap second. | | UTC Date TAI - UTC After Leap Second | -------- --------------------------- | 1972-06-30 11 | 1972-12-31 12 | 1973-12-31 13 | 1974-12-31 14 | 1975-12-31 15 | 1976-12-31 16 | 1977-12-31 17 | 1978-12-31 18 | 1979-12-31 19 | 1981-06-30 20 | 1982-06-30 21 | 1983-06-30 22 | 1985-06-30 23 | 1987-12-31 24 | 1989-12-31 25 | 1990-12-31 26 | 1992-06-30 27 | 1993-06-30 28 | 1994-06-30 29 | 1995-12-31 30 | 1997-06-30 31 | 1998-12-31 32 `---- Karl -- Please do *not* send copies of replies to me. I read the list From dyoo@hkn.eecs.berkeley.edu Tue Jul 29 17:38:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Jul 29 16:38:01 2003 Subject: [Tutor] help with dates In-Reply-To: <20030729183446.99998.qmail@web13907.mail.yahoo.com> Message-ID: On Tue, 29 Jul 2003, james middendorff wrote: > I am attempting to write a little program that will tell you on which > day a certain holiday will fall. In whatever year you want. I am a > beginner and was wondering how I should tackle this project, or is > someone could point my in the right direction? Thanks for any help Hey James, long time no chat. *grin* For holidays that are consistently held on a certain day, you may be able to use the 'calendar' module (or maybe not! Read below.): http://www.python.org/doc/lib/module-calendar.html It has a function called 'weekday()' that sounds almost right: ### >>> calendar.weekday(2003, 7, 29) 1 ### weekday() returns the day number (0 is monday, 1 is tuesday, etc...). The only problem with it is that it depends on a certain function that's limited to dates after 1970! The reason for it is this: calendar uses the time module, which itself depends on the computer system clock. And all computer clocks start, not at Year 0, but at the "Epoch" (January 1970). If we try going below that range, we'll hit an error: ### >>> calendar.weekday(1009,7,29) Traceback (most recent call last): File "", line 1, in ? File "/home/dyoo/local/Python-2.2.1/lib/python2.2/calendar.py", line 106, in weekday secs = mktime((year, month, day, 0, 0, 0, 0, 0, 0)) ValueError: year out of range ### So the straightforward approach, using the 'calendar' module, probably isn't robust enough for your problem. For more serious date-time stuff, you may want to look at the mx.DateTime module instead: http://www.lemburg.com/files/python/mxDateTime.html And here, it works: ### >>> import mx.DateTime >>> date = mx.DateTime.DateTime(1009, 7, 29) >>> date.day_of_week 5 ### Hope this helps! From wildthing777@hotmail.com Tue Jul 29 18:19:23 2003 From: wildthing777@hotmail.com (Asia Turner-Bridger) Date: Tue Jul 29 17:19:23 2003 Subject: [Tutor] help Message-ID: hi, i'm having problems running programs. with the basic stuff. such as when i write "width = input ("enter width:")" then press enter with the intention of continueing writing the program and running it later. it then as soon as i press enter orders me to "enter the width:" so i have to- therefore messing up my program. when i want it to run all together at once. and just continue to write "length = input ("enter length:")". how can i sort out my problem? what am i doing wrong? is it because i press enter? thanx _________________________________________________________________ Get Hotmail on your mobile phone http://www.msn.co.uk/msnmobile From uche.ogbuji@fourthought.com Tue Jul 29 18:19:43 2003 From: uche.ogbuji@fourthought.com (Uche Ogbuji) Date: Tue Jul 29 17:19:43 2003 Subject: [Tutor] Re: [XML-SIG] XML documentation In-Reply-To: Message from cybersamurai@mac.com of "Sun, 20 Jul 2003 23:22:43 -0300." <359178A8-BB22-11D7-B454-000393B10A78@mac.com> Message-ID: <20030726145716.1702B1340AC@borgia.local> > I need know here I can find documentation about XML and Python. I know > How read and write a new XML file but I don't know edit. I offer: http://www.xml.com/pub/q/pyxml http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/pyxml-akara -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com XML Data Bindings in Python, Part 2 - http://www.xml.com/pub/a/2003/07/02/py-xm l.html Introducing Examplotron - http://www-106.ibm.com/developerworks/xml/library/x-x mptron/ Charming Jython - http://www-106.ibm.com/developerworks/java/library/j-jython.h tml Python, Web services, and XSLT - http://www-106.ibm.com/developerworks/xml/libr ary/ws-pyth13/ A custom-fit career in app development - http://www.adtmag.com/article.asp?id=7 744 From thomi@thomi.imail.net.nz Tue Jul 29 18:24:01 2003 From: thomi@thomi.imail.net.nz (Thomas Clive Richards) Date: Tue Jul 29 17:24:01 2003 Subject: [Tutor] help In-Reply-To: References: Message-ID: <20030730092305.42d81c22.thomi@thomi.imail.net.nz> > how can i sort out my problem? what am i doing wrong? is it because i > press enter? Hi, python has a command line interpreter, which sounds like what you're using. If you want to run all the commands at once, create a text file and give it a .py extension. in this file, write your program. Note that under windows, it's a good idea to put "timport time" at the top , and "time.sleep(10)" at the bottom. This will cause the output window to remain open for 10 seconds after the program has finished running. HTH! -- Thomi Richards, thomi@thomi.imail.net.nz From jeff@ccvcorp.com Tue Jul 29 18:53:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Jul 29 17:53:01 2003 Subject: [Tutor] help References: <20030730092305.42d81c22.thomi@thomi.imail.net.nz> Message-ID: <3F26ECBA.1050600@ccvcorp.com> Thomas Clive Richards wrote: >>how can i sort out my problem? what am i doing wrong? is it because i >>press enter? >> >> > >Hi, > >python has a command line interpreter, which sounds like what you're >using. If you want to run all the commands at once, create a text file >and give it a .py extension. in this file, write your program. Note that >under windows, it's a good idea to put "timport time" at the top , and >"time.sleep(10)" at the bottom. This will cause the output window to >remain open for 10 seconds after the program has finished running. > > Another (probably preferable) way to accomplish that is to simply add this line to the end of the program: raw_input("Press Enter to end this program.") raw_input() will wait for something to be entered, i.e. for the return key to be pressed. We don't really care at this point what's typed, just so long as the program waits until *something* has been done to end it, so this works pretty well. The O.P.'s problem can also be solved within the interactive interpreter, though. The trick is to put the sequence of things that you want to do inside a function, using the def keyword -- >>> def show_area(): ... width = input("Enter width: ") ... length = input("Enter length: ") ... area = width * length ... print "The area is:", area ... >>> Now you can call show_area() as a shorthand for all of those commands at once, like so: >>> show_area() Enter width: 5 Enter length: 8 The area is: 40 >>> Even if you do put your code in a separate file (which you'd need to do if you want to save it and run it at a later date), it's a very good idea to put everything into functions like this. By separating your program into small pieces, it becomes a lot easier to understand what's going on in each part, which makes it easier to understand what's happening overall too. Jeff Shannon Technician/Programmer Credit International From nas-pytut@python.ca Tue Jul 29 19:35:02 2003 From: nas-pytut@python.ca (Neil Schemenauer) Date: Tue Jul 29 18:35:02 2003 Subject: [Tutor] Newbie question: Google API on OS X In-Reply-To: References: <3F25B3DF.2080603@netzero.net> Message-ID: <20030729224022.GA29410@glacier.arctrix.com> Clay Shirky wrote: > Is the Mac python 2.2 non-standard? Do I need an additional xml module? Or > is there another way to run the Google API? I can't help you directly since I'm not an XML person. You might have better luck posting to the XML SIG list: http://www.python.org/sigs/xml-sig/ You could also check out the XML topical documentation on python.org: http://pyxml.sourceforge.net/topics/docs.html HTH, Neil From Andy Dulson Tue Jul 29 19:42:05 2003 From: Andy Dulson (Andy Dulson) Date: Tue Jul 29 18:42:05 2003 Subject: Re[2]: [Tutor] help with dates In-Reply-To: References: <20030729183446.99998.qmail@web13907.mail.yahoo.com> Message-ID: <15430012370.20030729233906@discorice.org> Tuesday, July 29, 2003, Karl Pflästerer wrote: KP> Then you need a formula to compute leap years; I'm a complete newbie when it comes to Python, but thought this might be of interest. When you have your function to compute leap years, the following formula might be useful. It gives the day of the week on which a given date falls. Let d = the day of the month (ie 1st) m = month (starting with 1 for March, 2 for April,... and 12 for February) c = century (first two digits of the year) y = the year in the century (the last two digits of the year) L = 1 if the year is leap year, 0 otherwise w = the day of the week (Sunday = 0, Monday = 1, ... Saturday = 6) Then: w = d + [2.6m-0.2] + y + [y/4] -2c + [c/4] - (L+1)[m/11] (mod 7) [x] represents the greatest integer function, the largest n such that n <= x, ie math.floor(x) This is copied virtually verbatim from my number theory lecture notes. The proof was an optional exercise so I, um, don't have it to hand. They give a nice example to shows it works though. It works for dates from 1582 onwards, when the Gregorian calendar was adopted, apparently. Hope this is useful, or at the very least interesting. Andy From idiot1@netzero.net Tue Jul 29 21:42:01 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Tue Jul 29 20:42:01 2003 Subject: [Tutor] OHMYGOD... Message-ID: <3F2711FB.3070804@netzero.net> OOPS... We lost the site. ALL of it. EVERY last file. Completely erased. And I am embarrissed to admit I did it myself. I installed the moinmoin wiki. I decided it was iinsecure and went to delete the thing, and all it's subdirectories. I *THOUGHT* I was in the moin-1.0 dir when I issued "rm -R *". I was in the domain's webroot. The entire domain (the box holds several) went away. NOW, *YOU* LEARN FROM *MY* TRAGIC MISTAKE. DON'T DO THAT! Good thing the hosting firm does backups, even when it's my box. BAD news is the last one was 3 weeks ago. TinyList.1.7.3 is GONE, tarball ANd working installation. Several site page updates are GONE. Several doc file updates are GONE. The recently installed wiki is GONE. 3 weeks of my life down the John L Crapper just that easy. Wonderful and powerful is FreeBsD. Fortunately, the damage is moderate. I had 1.7.0 saved locally, and uploaded it. The wiki also was locally stored, but not it's pages. I have worked all afternoon to rebuild it as best I could. Oh- a wiki. Click this to see our wiki and have some fun with interactive web pages. It's written in python of course. http://www.tinylist.org/cgi-bin/piki.py Dont't do that... verify everything before doing anything serious. -- end Cheers! Kirk D Bailey + thunk + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + thunk + Sigh. From shalehperry@comcast.net Tue Jul 29 22:37:46 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Tue Jul 29 21:37:46 2003 Subject: [Tutor] OHMYGOD... In-Reply-To: <3F2711FB.3070804@netzero.net> References: <3F2711FB.3070804@netzero.net> Message-ID: <200307291834.42287.shalehperry@comcast.net> > > Good thing the hosting firm does backups, even when it's my box. BAD > news is the last one was 3 weeks ago. TinyList.1.7.3 is GONE, tarball > ANd working installation. Several site page updates are GONE. Several > doc file updates are GONE. The recently installed wiki is GONE. > what have we learned boys and girls? 1) use a revision control system This is very, very important. Even if it is just a small project now, get in the habit. This lets you recover from all kind of stupid mistakes (late night hacking, hacking while drunk, hacking while stupid, etc) Note, either do not store the main repository on the same machine or replicate it several places. This applies to code, config files, etc. I have a hacker friend who keeps ~/ in cvs, even his e-mail. 2) keep copies of things you are working on locally 3) learn from Linus. His famous quote is (basically) -- why should I worry about backups? I just put stuff on an ftp site and let the world mirror it for me. This is part of the rationale behind "release early, release often". From mwagman@charter.net Tue Jul 29 22:43:01 2003 From: mwagman@charter.net (Mike Wagman) Date: Tue Jul 29 21:43:01 2003 Subject: [Tutor] OHMYGOD...AMEN In-Reply-To: <200307291834.42287.shalehperry@comcast.net> References: <3F2711FB.3070804@netzero.net> <200307291834.42287.shalehperry@comcast.net> Message-ID: <1059529453.2452.1.camel@24-159-241-21.jvl.wi.charter.com> about 2 weeks ago had a hard drive fail, boot after I did my first off system backup in over a week. What can I say I got lucky. On Tue, 2003-07-29 at 20:34, Sean 'Shaleh' Perry wrote: > > > > Good thing the hosting firm does backups, even when it's my box. BAD > > news is the last one was 3 weeks ago. TinyList.1.7.3 is GONE, tarball > > ANd working installation. Several site page updates are GONE. Several > > doc file updates are GONE. The recently installed wiki is GONE. > > > > what have we learned boys and girls? > > 1) use a revision control system > This is very, very important. Even if it is just a small project now, get > in the habit. This lets you recover from all kind of stupid mistakes > (late night hacking, hacking while drunk, hacking while stupid, etc) > Note, either do not store the main repository on the same machine or > replicate it several places. > > This applies to code, config files, etc. I have a hacker friend who keeps > ~/ in cvs, even his e-mail. > > 2) keep copies of things you are working on locally > > 3) learn from Linus. His famous quote is (basically) -- why should I worry > about backups? > I just put stuff on an ftp site and let the world mirror it for me. This > is part of the rationale behind "release early, release often". > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From tbstep@tampabay.rr.com Tue Jul 29 23:13:00 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Tue Jul 29 22:13:00 2003 Subject: [Tutor] OHMYGOD... Message-ID: <200307292209.03791@toddloki> On Tuesday 29 July 2003 08:31 pm, Kirk Bailey wrote: > 3 weeks of my life down the John L Crapper just that easy. Wonderful and > powerful is FreeBsD. Wonderful and powerful is root in FreeBSD. -- Todd Stephens From tbstep@tampabay.rr.com Tue Jul 29 23:18:02 2003 From: tbstep@tampabay.rr.com (Todd Stephens) Date: Tue Jul 29 22:18:02 2003 Subject: [Tutor] Fwd: RELEASED Python 2.3 (final) Message-ID: <200307292214.05782@toddloki> ,--------------- Forwarded message (begin) Subject: RELEASED Python 2.3 (final) From: Barry A. Warsaw Date: Tue, 29 Jul 2003 20:02:26 -0400 Newsgroup: comp.lang.python.announce On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3 (final). Nineteen months in the making, Python 2.3 represents a commitment to stability and improved performance, with a minimum of new language features. Countless bugs and memory leaks have been fixed, many new and updated modules have been added, and the new type/class system introduced in Python 2.2 has been significantly improved. Python 2.3 can be up to 30% faster than Python 2.2. For more information on Python 2.3, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3 Highlights of this new release include: - A brand new version of IDLE, the Python IDE, from the IDLEfork project at SourceForge. - Many new and improved library modules including: sets, heapq, datetime, textwrap, optparse, logging, bsddb, bz2, tarfile, ossaudiodev, itertools, platform, csv, timeit, shelve, DocXMLRPCServer, imaplib, imp, trace, and a new random number generator based on the highly acclaimed Mersenne Twister algorithm (with a period of 2**19937-1). Some obsolete modules have been deprecated. - New and improved built-ins including: o enumerate(): an iterator yielding (index, item) pairs o sum(): a new function to sum a sequence of numbers o basestring: an abstract base string type for str and unicode o bool: a proper type with instances True and False o compile(), eval(), exec: fully support Unicode, and allow input not ending in a newline o range(): support for long arguments (magnitude > sys.maxint) o dict(): new constructor signatures o filter(): returns Unicode when the input is Unicode o int() can now return long o isinstance(), super(): Now support instances whose type() is not equal to their __class__. super() no longer ignores data descriptors, except for __class__. o raw_input(): can now return Unicode objects o slice(), buffer(): are now types rather than functions - Many new doctest extensions, allowing them to be run by unittest. - Extended slices, e.g. "hello"[::-1] returns "olleh". - Universal newlines mode for reading files (converts \r, \n and \r\n all into \n). - Source code encoding declarations. (PEP 263) - Import from zip files. (PEP 273 and PEP 302) - FutureWarning issued for "unsigned" operations on ints. (PEP 237) - Faster list.sort() is now stable. - Unicode filenames on Windows. (PEP 227) - Karatsuba long multiplication (running time O(N**1.58) instead of O(N**2)). - pickle, cPickle, and copy support a new pickling protocol for more efficient pickling of (especially) new-style class instances. - The socket module now supports optional timeouts on all operations. - ssl support has been incorporated into the Windows installer. - Many improvements to Tkinter. Python 2.3 contains many other improvements, including the adoption of many Python Enhancement Proposals (PEPs). For details see: http://www.python.org/2.3/highlights.html Enjoy. happy-50th-birthday-geddy-ly y'rs, -Barry Barry Warsaw barry@python.org Python 2.3 Release Manager (and the PythonLabs team: Tim, Fred, Jeremy, and Guido) `--------------- Forwarded message (end) -- Todd Stephens From norvell@houseofspearman.org Wed Jul 30 02:12:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jul 30 01:12:02 2003 Subject: [Tutor] Paranoid Question Message-ID: <20030730051115.GA2550@houseofspearman.org> Until Mandrake releases rpms of Python-2.3, I thought I'd try it out but don't want it conflicting with version 2.2.2---or rather, with any system-related scripts which depend on v2.2.2. After downloading and untarballing v2.3, I did the following: ./configure --prefix=/home/norvell/python make test make install So as long as I run idle from /home/norvell/python/bin/idle---and as long as I keep the #! line consistent with the prefix in any scripts---there should be no conflicts with the old version, right? Thanks for any answers. -- Norvell Spearman From alan.gauld@blueyonder.co.uk Wed Jul 30 05:29:01 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Wed Jul 30 04:29:01 2003 Subject: [Tutor] help References: Message-ID: <002501c35674$7ed96f80$6401a8c0@xp> > of continueing writing the program and running it later. it then as soon as > i press enter orders me to "enter the width:" You are trying to enter your program at the >>> prompt. You need to use the File->New menu to create a new blank window and type it in there. Then save it as a file ending in .py. You can run it from within the IDE(either IDLE or Pythonwin) or by double clicking the file in Exoplorer(assuming you are on Windows) For IDLE check out Danny's IDLE tutor which covers this with screenshots Its on the IDLE pages of the Python web site. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From RASTM2@aol.com Wed Jul 30 09:51:02 2003 From: RASTM2@aol.com (RASTM2@aol.com) Date: Wed Jul 30 08:51:02 2003 Subject: [Tutor] RE: james2dope's little prgm for holiday calendar Message-ID: <189.1ce42b17.2c591920@aol.com> In a message dated 7/29/03 9:19:34 PM Central Daylight Time james2dope@python.org writes: > I am attempting to write a little program that will > tell you on which day a certain holiday will fall. In > whatever year you want. I am a beginner and was > wondering how I should tackle this project, or is > someone could point my in the right direction? Thanks > for any help > Hi, james2dope If I were planning such a project I would go to http://rudy.ca/doomsday.html for help and inspiratioin and links to other such the same. It's called the Doomsday Algorithm, and it was originally created by Dr. John Conway, a very interesting mathemetician. Dr. Conway devised a way to determine what day of the week any date in history would fall on so that you could do the calculation in your head. I think that if you can do that calculation in your head, you won't have too much trouble converting it to Python. You will have to pay particular attention to Easter Sunday thou, as this date is very rarely the same on any two consecutive years. Also, a search for "Doomsday Algorithm", "calendars, Python" and combinations of such on google will prob'ly yield many free sources of completed scripts and info to get you going. Ray St. Marie Rastm2@aol.com From norvell@houseofspearman.org Wed Jul 30 10:39:09 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jul 30 09:39:09 2003 Subject: [Tutor] Paranoid Question In-Reply-To: <20030730122904.GA60057@elvis.mu.org> References: <20030730051115.GA2550@houseofspearman.org> <20030730122904.GA60057@elvis.mu.org> Message-ID: <20030730133541.GA12566@houseofspearman.org> On Wednesday, 2003.07.30, 05:29:04 -0700, Gus Mueller wrote: > I can say that yes, the #! pointing to /home/norvell/python/bin/python > should work fine- but one thing you might want to consider, is having > this: > #!/usr/bin/env python > at the top of you scripts, and adjusting your $PATH environment variable > so that /home/norvell/python/bin is ahead of /usr/local/bin and /usr/bin > - that way when some day you get rid of your custom python install, you > scripts will still work. Thanks much. That will greatly simplify things later on. -- Norvell Spearman From shalehperry@comcast.net Wed Jul 30 10:51:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Wed Jul 30 09:51:02 2003 Subject: [Tutor] OHMYGOD... In-Reply-To: <200307292209.03791@toddloki> References: <200307292209.03791@toddloki> Message-ID: <200307300649.22966.shalehperry@comcast.net> On Tuesday 29 July 2003 19:09, Todd Stephens wrote: > On Tuesday 29 July 2003 08:31 pm, Kirk Bailey wrote: > > 3 weeks of my life down the John L Crapper just that easy. Wonderful and > > powerful is FreeBsD. > > Wonderful and powerful is root in FreeBSD. > thanks, I forgot that as my last item: *) everytime you login as root, ask yourself if you could accomplish the task as a simple user with tools like su and sudo. Root is a loaded gun waiting to misfire. From marichar@csusb.edu Wed Jul 30 14:06:02 2003 From: marichar@csusb.edu (Matt Richardson) Date: Wed Jul 30 13:06:02 2003 Subject: [Tutor] function to ignore case Message-ID: <1059584730.7289.127.camel@matt-richardsons-computer.local> Can someone point me to a function that will ignore case when searching for a string? This is how my 17 month old must feel--knowing what you want but not how to say it :) Matt -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From zak@harlekin-maus.com Wed Jul 30 14:17:01 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Wed Jul 30 13:17:01 2003 Subject: [Tutor] function to ignore case In-Reply-To: <1059584730.7289.127.camel@matt-richardsons-computer.local> References: <1059584730.7289.127.camel@matt-richardsons-computer.local> Message-ID: <1920.192.207.104.212.1059585258.squirrel@mail.harlekin-maus.com> > Can someone point me to a function that will ignore case when searching > for a string? This is how my 17 month old must feel--knowing what you > want but not how to say it :) > > Matt The typical method is to convert the strings to all uppercase or lowercase. See the lower() and upper() methods of the string type. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From marichar@csusb.edu Wed Jul 30 14:20:03 2003 From: marichar@csusb.edu (Matt Richardson) Date: Wed Jul 30 13:20:03 2003 Subject: [Tutor] function to ignore case In-Reply-To: <1920.192.207.104.212.1059585258.squirrel@mail.harlekin-maus.com> References: <1059584730.7289.127.camel@matt-richardsons-computer.local> <1920.192.207.104.212.1059585258.squirrel@mail.harlekin-maus.com> Message-ID: <1059585566.7289.131.camel@matt-richardsons-computer.local> > The typical method is to convert the strings to all uppercase or > lowercase. See the lower() and upper() methods of the string type. > > --- > Zak Arntson OK, that's what I thought I would have to do. I thought it might be easier if there were a method that would search a file for string "Foo" and return all instances "Foo" or "foo", rather than convert the string and the file being searched to the same case. That's cool, I need the practice :) -- Matt Richardson Instructional Support Technician Department of Art CSU San Bernardino marichar@csusb.edu From reggie@merfinllc.com Wed Jul 30 14:21:54 2003 From: reggie@merfinllc.com (Reggie Dugard) Date: Wed Jul 30 13:21:54 2003 Subject: [Tutor] function to ignore case In-Reply-To: <1059584730.7289.127.camel@matt-richardsons-computer.local> References: <1059584730.7289.127.camel@matt-richardsons-computer.local> Message-ID: <1059585597.30707.19.camel@pika> Matt, You don't mention what version of python you're using, but assuming you're using a release that's not too old, there are a couple of ways to do what you want. You can use regular expression searching (re module) and specify the IGNORECASE flag: >>> import re >>> m = re.search('multi', 'A mUltiCased string', re.IGNORECASE) >>> bool(m) True >>> OR You can convert both strings to a common case using the upper() or lower() string methods, before you do the comparison: >>> s = 'A mUltiCased string'.lower() >>> s 'a multicased string' >>> s.find('multi') 2 >>> Hope this puts you on the right track On Wed, 2003-07-30 at 10:05, Matt Richardson wrote: > Can someone point me to a function that will ignore case when searching > for a string? This is how my 17 month old must feel--knowing what you > want but not how to say it :) > > Matt -- Reggie From bgailer@alum.rpi.edu Wed Jul 30 14:22:12 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Jul 30 13:22:12 2003 Subject: [Tutor] function to ignore case In-Reply-To: <1059584730.7289.127.camel@matt-richardsons-computer.local> Message-ID: <5.2.1.1.0.20030730111554.02b52610@66.28.54.253> --=======3CCC28C1======= Content-Type: text/plain; x-avg-checked=avg-ok-6B4038B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:05 AM 7/30/2003 -0700, Matt Richardson wrote: >Can someone point me to a function that will ignore case when searching >for a string? If you are using re, specify the re.IGNORECASE option If you are using find or one of its relatives, upcase the search-in string and the search-for string using the str upper method. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=======3CCC28C1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6B4038B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======3CCC28C1=======-- From zak@harlekin-maus.com Wed Jul 30 14:46:02 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Wed Jul 30 13:46:02 2003 Subject: [Tutor] Deal a Random Deck - Challenge In-Reply-To: <20030725211030.GA11331@glacier.arctrix.com> References: <20030718200309.0A4B9F699@xmxpita.excite.com> <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> <20030725211030.GA11331@glacier.arctrix.com> Message-ID: <2059.192.207.104.212.1059587121.squirrel@mail.harlekin-maus.com> > Zak Arntson wrote: >> Here's an interesting problem a coworker (former mentor) uses when >> hiring: >> * Write an algorithm to deal out a set of "cards" > > Straightforward to do poorly. :-) I think all of the solutuions you > posted are biased. See: > http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCKEDFGNAA.tim_one%40email.msn.com > > Cheers, > Neil Actually, that algorithm is subtly different. It looks like: ### import random def shuffle_biased(list): count = len(list) for i in range(count): j = random.randint(count) list[i], list[j] = list[j], list[i] ### Where the proper (i.e., non-biased) solution using element swapping looks like: ### import random def shuffle_unbiased(list): count = len(list) for i in range(count): j = random.randrange(i, count) list[i], list[j] = list[j], list[i] ### The difference is in choosing j. In the shuffle_biased the value at j can be swapped a ton of times. In the shuffle_unbiased, when the value at j is swapped, it cannot be swapped again. --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From R. Alan Monroe" References: <200307292209.03791@toddloki> <200307300649.22966.shalehperry@comcast.net> Message-ID: <1711235090546.20030730135540@columbus.rr.com> Can all Windows users on a LAN/WAN cleanly run a central installation of Python from a central server? Or is this not really practical? I think speed would be an issue but is it supported at all? Alan From jeff@ccvcorp.com Wed Jul 30 16:27:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 30 15:27:01 2003 Subject: [Tutor] Does Python support a centralized network install? References: <200307292209.03791@toddloki> <200307300649.22966.shalehperry@comcast.net> <1711235090546.20030730135540@columbus.rr.com> Message-ID: <3F281C05.6060307@ccvcorp.com> R. Alan Monroe wrote: >Can all Windows users on a LAN/WAN cleanly run a central installation of >Python from a central server? Or is this not really practical? I think >speed would be an issue but is it supported at all? > This could depend on what you mean by "supported" -- there's (AFAIK) no attempt to specifically support this, nor do I envision it to be likely. However, I imagine that it might be possible to coerce it into working, within several restrictions. 1) You'd need to use a Python installation that had no dependency on the registry. You could have a script on the central server that'd set up environment variables, though. 2) All users would need to be able to run the same (platform-dependent) .pyc files. I'm not sure how much of a limitation this will actually be -- it might be that all Windows users are okay, or it might be that all users must be running the exact same version of Windows on similar hardware. 3) You'd be subject to notable lag times and delays. Depending on the usage, the half-second delay in accessing a mapped network drive may cause significant problems. On the other hand, it would definitely be possible to install Python on every machine, and set the import path to look for modules/applications that are located on a central network share. Jeff Shannon Technician/Programmer Credit International From shalehperry@comcast.net Wed Jul 30 16:48:02 2003 From: shalehperry@comcast.net (Sean 'Shaleh' Perry) Date: Wed Jul 30 15:48:02 2003 Subject: [Tutor] Paranoid Question In-Reply-To: <20030730051115.GA2550@houseofspearman.org> References: <20030730051115.GA2550@houseofspearman.org> Message-ID: <200307301247.16640.shalehperry@comcast.net> On Tuesday 29 July 2003 22:11, Norvell Spearman wrote: > > So as long as I run idle from /home/norvell/python/bin/idle---and as > long as I keep the #! line consistent with the prefix in any > scripts---there should be no conflicts with the old version, right? > indeed, you are safe. Via Debian's package system I currently have ALL of the 2.x series and 1.52 installed. I can invoke any of them as pythonX.Y. /usr/bin/python is a symlink to the newest version. Each one was compiled with the version number in the destination path so there are no conflicts. Keep that in mind for your next install, you may want ~/norvell/python2.4. From DORSEY_EDMUND_K@LILLY.COM Wed Jul 30 17:20:02 2003 From: DORSEY_EDMUND_K@LILLY.COM (DORSEY_EDMUND_K@LILLY.COM) Date: Wed Jul 30 16:20:02 2003 Subject: [Tutor] Printing to Screen Message-ID: This is a multipart message in MIME format. --=_alternative 006F98F605256D73_= Content-Type: text/plain; charset="us-ascii" Is there a way to print but not have it do a new line For instance in java you have print and println in C you have to specify the end of line marker. Whenever I use print in python is puts a newline. Do I need to use a different method for printing to the screen? For example... for x in xrange(0, 5): print x would print 0 1 2 3 4 What if I want it to print 01234 Thanks! --=_alternative 006F98F605256D73_= Content-Type: text/html; charset="us-ascii"
Is there a way to print but not have it do a new line

For instance in java you have print and println in C you have to specify the end of line marker.

Whenever I use print in python is puts a newline.

Do I need to use a different method for printing to the screen?

For example...

for x in xrange(0, 5):
        print x

would print

0
1
2
3
4


What if I want it to print

01234

Thanks! --=_alternative 006F98F605256D73_=-- From op73418@mail.telepac.pt Wed Jul 30 17:40:04 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Wed Jul 30 16:40:04 2003 Subject: [Tutor] Printing to Screen In-Reply-To: Message-ID: -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of DORSEY_EDMUND_K@LILLY.COM Sent: quarta-feira, 30 de Julho de 2003 21:19 To: tutor@python.org Subject: [Tutor] Printing to Screen >Is there a way to print but not have it do a new line > >For instance in java you have print and println in C you have to specify the end of line marker. > >Whenever I use print in python is puts a newline. > >Do I need to use a different method for printing to the screen? > >For example... > >for x in xrange(0, 5): > print x > >would print > >0 >1 >2 >3 >4 > > >What if I want it to print > >01234 > Putting a comma next to what you want to print prevents Python from adding a newline, e.g. >>> for i in xrange(5): ... print i, ... 0 1 2 3 4 But it does add a space. The best may be to concatenate every string you want to print, e.g.: >>> to_print = [] >>> for i in xrange(5): ... to_print.append(i) ... >>> string_to_print = "".join([str(i) for i in to_print]) >>> print string_to_print 01234 It's left as an exercise figuring out the whys and the whats of the code. If you have any doubts just holler. With my best regards, G. Rodrigues From bgailer@alum.rpi.edu Wed Jul 30 17:45:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Jul 30 16:45:01 2003 Subject: [Tutor] Printing to Screen In-Reply-To: Message-ID: <5.2.1.1.0.20030730143426.02c45468@66.28.54.253> --=======690D411B======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6B4038B; boundary="=====================_19877051==.ALT" --=====================_19877051==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6B4038B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:18 PM 7/30/2003 -0500, DORSEY_EDMUND_K@LILLY.COM wrote: >Is there a way to print but not have it do a new line >For instance in java you have print and println in C you have to specify >the end of line marker. >Whenever I use print in python is puts a newline. >Do I need to use a different method for printing to the screen? >For example... > >for x in xrange(0, 5): > print x > >would print > >0 >1 >2 >3 >4 > >What if I want it to print > >01234 There is no direct answer. If you say print x, you will get 0 1 2 3 4 If you print a backspace before each number print '\x08%x' % i, you will get (the desired) 01234 unless you are in pythonwin which prints a graphic interpretation of control characters. The better approach is to collect the desired output in a string, then print the string result = '' for x in xrange(0, 5): result += str(x) print x Or create, then join, a list: print ''.join([str(x) for x in xrange(0,5)]) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_19877051==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6B4038B; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:18 PM 7/30/2003 -0500, DORSEY_EDMUND_K@LILLY.COM wrote:

Is there a way to print but not have it do a new line
For instance in java you have print and println in C you have to specify the end of line marker.
Whenever I use print in python is puts a newline.
Do I need to use a different method for printing to the screen?
For example...

for x in xrange(0, 5):
        print x

would print

0
1
2
3
4

What if I want it to print

01234

There is no direct answer. If you say
    print x,
you will get
0 1 2 3 4
If you print a backspace before each number
    print '\x08%x' % i,
you will get (the desired)
01234
unless you are in pythonwin which prints a graphic interpretation of control characters.

The better approach is to collect the desired output in a string, then print the string
result = ''
for x in xrange(0, 5):
    result += str(x)
print x

Or create, then join, a list:
print ''.join([str(x) for x in xrange(0,5)])

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_19877051==.ALT-- --=======690D411B======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6B4038B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======690D411B=======-- From jeff@ccvcorp.com Wed Jul 30 17:50:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Jul 30 16:50:03 2003 Subject: [Tutor] Printing to Screen References: Message-ID: <3F282F90.1070800@ccvcorp.com> DORSEY_EDMUND_K@LILLY.COM wrote: > > Is there a way to print but not have it do a new line > > For instance in java you have print and println in C you have to > specify the end of line marker. > > Whenever I use print in python is puts a newline. If you end your print statement with a comma, then you'll (probably) be given a space instead of a newline -- I say probably because if the line already ends in whitespace, print will not add more. This feature is called "softspace", and it's intended to help print be a quick & easy way to display simple things -- but print is not designed to give you complete control over your output. If you need finer control over the output than print gives you, then you can import sys and use sys.stdout.write() -- sys.stdout is a file-like object that represents your current standard output, and print internally writes to sys.stdout. You can use most file methods on sys.stdout (though not seek-related ones). Keep in mind that, because sys.stdout is a buffered I/O device, you may need to call sys.stdout.flush() to actually have written data appear on the screen. Jeff Shannon Technician/Programmer Credit International From bgailer@alum.rpi.edu Wed Jul 30 17:53:01 2003 From: bgailer@alum.rpi.edu (Bob Gailer) Date: Wed Jul 30 16:53:01 2003 Subject: [Tutor] Printing to Screen Message-ID: <5.2.1.1.0.20030730144509.02c3fbd0@66.28.54.253> --=======3E5A30B5======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-6B4038B; boundary="=====================_20337353==.ALT" --=====================_20337353==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-6B4038B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:18 PM 7/30/2003 -0500, DORSEY_EDMUND_K@LILLY.COM wrote: >Is there a way to print but not have it do a new line >For instance in java you have print and println in C you have to specify >the end of line marker. >Whenever I use print in python is puts a newline. >Do I need to use a different method for printing to the screen? >For example... > >for x in xrange(0, 5): > print x > >would print > >0 >1 >2 >3 >4 > >What if I want it to print > >01234 I spoke too soon. import sys for x in xrange(0, 5): sys.stdout.write(str(x)) sys.stdout.write('\n') # newline Bob Gailer bgailer@alum.rpi.edu 303 442 2625 --=====================_20337353==.ALT Content-Type: text/html; x-avg-checked=avg-ok-6B4038B; charset=us-ascii Content-Transfer-Encoding: 8bit At 03:18 PM 7/30/2003 -0500, DORSEY_EDMUND_K@LILLY.COM wrote:

Is there a way to print but not have it do a new line
For instance in java you have print and println in C you have to specify the end of line marker.
Whenever I use print in python is puts a newline.
Do I need to use a different method for printing to the screen?
For example...

for x in xrange(0, 5):
        print x

would print

0
1
2
3
4

What if I want it to print

01234

I spoke too soon.
import sys
for x in xrange(0, 5):
    sys.stdout.write(str(x))
sys.stdout.write('\n') # newline

Bob Gailer
bgailer@alum.rpi.edu
303 442 2625
--=====================_20337353==.ALT-- --=======3E5A30B5======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6B4038B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.500 / Virus Database: 298 - Release Date: 7/10/2003 --=======3E5A30B5=======-- From dyoo@hkn.eecs.berkeley.edu Wed Jul 30 18:44:43 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Jul 30 17:44:43 2003 Subject: [Tutor] Printing to Screen In-Reply-To: <3F282F90.1070800@ccvcorp.com> Message-ID: On Wed, 30 Jul 2003, Jeff Shannon wrote: > DORSEY_EDMUND_K@LILLY.COM wrote: > > > > > Is there a way to print but not have it do a new line > > > > For instance in java you have print and println in C you have to > > specify the end of line marker. > > If you need finer control over the output than print gives you, then you > can import sys and use sys.stdout.write() -- sys.stdout is a file-like > object that represents your current standard output, and print > internally writes to sys.stdout. Hi Dorsey, In fact, if you use sys.stdout.write(), it'll feel almost exactly like C's printf() function. For example, the following C code: /*** C code **/ int x = 20; printf("%d squared is equals to: %d\n", x, x*x); /*************/ has a direct translation in Python: ### Python code ### x = 20 sys.stdout.write("%d square is equal to: %d\n" % (x, x*x)) ### So if you need printf()-like functionality, use the write() method of the stdout file object. You can use the String Formatting operations to interpolate variable values into your string. If you find yourself doing a lot of sys.stdout.write()'s, you can simplify your typing by using a helper variable: ### >>> import sys >>> sys.stdout.write >>> write = sys.stdout.write >>> write >>> write("hello world\n\nThis is a test!\n") hello world This is a test! ### Python allows us to pull any object's method and make it look like a simple function, and the example above shows a good use of it. Good luck! From norvell@houseofspearman.org Wed Jul 30 18:56:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Wed Jul 30 17:56:02 2003 Subject: [Tutor] Paranoid Question In-Reply-To: <200307301247.16640.shalehperry@comcast.net> References: <20030730051115.GA2550@houseofspearman.org> <200307301247.16640.shalehperry@comcast.net> Message-ID: <20030730215518.GA12742@houseofspearman.org> On Wednesday, 2003.07.30, 12:47:16 -0700, Sean 'Shaleh' Perry wrote: > indeed, you are safe. Via Debian's package system I currently have ALL of the > 2.x series and 1.52 installed. I can invoke any of them as pythonX.Y. > /usr/bin/python is a symlink to the newest version. Each one was compiled > with the version number in the destination path so there are no conflicts. > Keep that in mind for your next install, you may want ~/norvell/python2.4. My system has two pythons in /usr/bin as well. Thanks for the tip. -- Norvell Spearman From logiplex@qwest.net Wed Jul 30 19:24:03 2003 From: logiplex@qwest.net (Cliff Wells) Date: Wed Jul 30 18:24:03 2003 Subject: [Tutor] Does Python support a centralized network install? In-Reply-To: <3F281C05.6060307@ccvcorp.com> References: <200307292209.03791@toddloki> <200307300649.22966.shalehperry@comcast.net> <1711235090546.20030730135540@columbus.rr.com> <3F281C05.6060307@ccvcorp.com> Message-ID: <1059603756.8920.4249.camel@software1.logiplex.internal> On Wed, 2003-07-30 at 12:27, Jeff Shannon wrote: > R. Alan Monroe wrote: > > >Can all Windows users on a LAN/WAN cleanly run a central installation of > >Python from a central server? Or is this not really practical? I think > >speed would be an issue but is it supported at all? > > > > This could depend on what you mean by "supported" -- there's (AFAIK) no > attempt to specifically support this, nor do I envision it to be likely. > However, I imagine that it might be possible to coerce it into working, > within several restrictions. > > 1) You'd need to use a Python installation that had no dependency on the > registry. You could have a script on the central server that'd set up > environment variables, though. Actually, it's possible to simply insert the proper registry entries using a script. Windows allows you to put registry entries in a .reg file and simply run it. We did this a couple of years ago at a job I had. I haven't used Windows since leaving that job so I'm afraid I don't recall the values. > 2) All users would need to be able to run the same (platform-dependent) > .pyc files. I'm not sure how much of a limitation this will actually be > -- it might be that all Windows users are okay, or it might be that all > users must be running the exact same version of Windows on similar hardware. We had Windows NT 4.0 on all PC's but I doubt it matters much. The biggest problem was generation of .pyc files. This has to be done by hand by someone with proper permissions on the server. There was some discussion about adding support for specifying where .pyc files go, but I don't know if it made it in for 2.3. > 3) You'd be subject to notable lag times and delays. Depending on the > usage, the half-second delay in accessing a mapped network drive may > cause significant problems. We didn't notice any slowdown. But we had fairly expensive network equipment and fast servers. > On the other hand, it would definitely be possible to install Python on > every machine, and set the import path to look for modules/applications > that are located on a central network share. The main problem with this is keeping the PC's up-to-date (if there are very many of them). Especially since things like migrating to a new version of Python require reinstalling third party modules. Regards, -- Cliff Wells, Software Engineer Logiplex Corporation (www.logiplex.net) (503) 978-6726 (800) 735-0555 From glingl@aon.at Wed Jul 30 19:50:09 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Jul 30 18:50:09 2003 Subject: [Tutor] Deal a Random Deck - Good news References: <20030718200309.0A4B9F699@xmxpita.excite.com> <2333.192.206.201.217.1059164050.squirrel@mail.harlekin-maus.com> <20030725211030.GA11331@glacier.arctrix.com> <2059.192.207.104.212.1059587121.squirrel@mail.harlekin-maus.com> Message-ID: <3F284C02.903@aon.at> Zak Arntson schrieb: >>Zak Arntson wrote: >> >> >>>Here's an interesting problem a coworker (former mentor) uses when >>>hiring: >>> * Write an algorithm to deal out a set of "cards" >>> >>> >>Straightforward to do poorly. :-) I think all of the solutuions you >>posted are biased. See: >> http://groups.google.com/groups?selm=LNBBLJKPBEHFEDALKOLCKEDFGNAA.tim_one%40email.msn.com >> >>Cheers, >> Neil >> >> > >Actually, that algorithm is subtly different. It looks like: >### >import random >def shuffle_biased(list): > count = len(list) > for i in range(count): > j = random.randint(count) > list[i], list[j] = list[j], list[i] >### > >Where the proper (i.e., non-biased) solution using element swapping looks >like: >### >import random >def shuffle_unbiased(list): > count = len(list) > for i in range(count): > j = random.randrange(i, count) > list[i], list[j] = list[j], list[i] >### > > Actually shuflle from module random is defined similarly, but using random.random(), i.e. generating random reals, as this is approximately twice as fast as creating random integers. (I think this is the reason, why deck3 is so much faster than deck1 or deck2, but slower than deck4 or deck5 - because they don't need to sort. Here the code for shuffle from module random: def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that "most" permutations of a long sequence can never be generated. """ if random is None: random = self.random for i in xrange(len(x)-1, 0, -1): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] Wow! The docstring explains, that there is another reason for shuffle to be biased, which is independent of shuffle's algorithm but depends solely on the random generator used. Up to Python 2.2 a Wichmann-Hill generator with period 6,953,607,871,644 was used. This is smaller than 16! = 20922789888000. This means, that Python2.2's shuffle cannot generate all permutations of sequences with more than 15 Elements.And already for 16 Elements only a third of all possible permutations is generated. This was changed with Python 2.3 using a Mersenne Twister generator with period 2**19937-1 (which is an integer with 6002 digits). Since 2080! < 2**19937-1 < 2081!, Python 2.3's shuffle should be fairly unbiased for sequences with length nearly up to 2080. And the other good news: Python 2.3's random generator is more than 20% faster than the old one. Regards, Gregor >The difference is in choosing j. In the shuffle_biased the value at j can >be swapped a ton of times. In the shuffle_unbiased, when the value at j is >swapped, it cannot be swapped again. > >--- >Zak Arntson >www.harlekin-maus.com - Games - Lots of 'em > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From klappnase@freenet.de Wed Jul 30 21:13:02 2003 From: klappnase@freenet.de (klappnase) Date: Wed Jul 30 20:13:02 2003 Subject: [Tutor] How to get messages from stderr Message-ID: <20030731021253.404a731a.klappnase@freenet.de> Hello everyone, I try to get progress messages from a shell command on the fly while the process is still running for use in a progress window. The problem is that most of these messages are printed to stderr. Now I tried something like: def runcmd(self): self.pp = popen2.Popen4(cmd) self.ppp = self.pp.fromchild self.frame.after(100, self.getprogress) def getprogress(self): self.progress = self.ppp.read() self.frame.after(100, self.getprogress) but I found that I only got any output after the child process had finished. It seems to work as long as I only get the output from stdout with Popen3, but I need the stderr messages. Does anyone know a way to get the output from stderr while the child process is still running? Any help would be very appreciated. Thanks Michael From Janssen@rz.uni-frankfurt.de Wed Jul 30 22:55:03 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Jul 30 21:55:03 2003 Subject: [Tutor] How to get messages from stderr In-Reply-To: <20030731021253.404a731a.klappnase@freenet.de> Message-ID: On Thu, 31 Jul 2003, klappnase wrote: > def runcmd(self): > self.pp = popen2.Popen4(cmd) > self.ppp = self.pp.fromchild > self.frame.after(100, self.getprogress) > > def getprogress(self): > self.progress = self.ppp.read() > self.frame.after(100, self.getprogress) > > but I found that I only got any output after the child process had > finished. It seems to work as long as I only get the output from > stdout with Popen3, but I need the stderr messages. Does anyone know a > way to get the output from stderr while the child process is still > running? Any help would be very appreciated. can't remember those popenX thing but perhaps you can redirect the output to stdout (depends on what OS you use and if you don't need to keep the streams seperate)? os.popen("[command] 2>&1") is Linux-bash Syntax to redirect stderr to stdout. regards Michael From klappnase@freenet.de Thu Jul 31 06:14:02 2003 From: klappnase@freenet.de (klappnase) Date: Thu Jul 31 05:14:02 2003 Subject: [Tutor] How to get messages from stderr In-Reply-To: References: <20030731021253.404a731a.klappnase@freenet.de> Message-ID: <20030731111411.2285a507.klappnase@freenet.de> On Thu, 31 Jul 2003 03:54:25 +0200 (CST) Michael Janssen wrote: > On Thu, 31 Jul 2003, klappnase wrote: > > > def runcmd(self): > > self.pp = popen2.Popen4(cmd) > > self.ppp = self.pp.fromchild > > self.frame.after(100, self.getprogress) > > > > def getprogress(self): > > self.progress = self.ppp.read() > > self.frame.after(100, self.getprogress) > > > > but I found that I only got any output after the child process had > > finished. It seems to work as long as I only get the output from > > stdout with Popen3, but I need the stderr messages. Does anyone know a > > way to get the output from stderr while the child process is still > > running? Any help would be very appreciated. > > can't remember those popenX thing but perhaps you can redirect the output > to stdout (depends on what OS you use and if you don't need to keep the > streams seperate)? > > os.popen("[command] 2>&1") is Linux-bash Syntax to redirect stderr to > stdout. > > regards > Michael > Thank you so much for the feedback. Sorry, I forgot to mention that it is a linux box. Unfortunately this does not seem to solve my problem, the messages only appear if "cmd" has finished. The problem seems to be that the file object containing the data from stderr should be closed first before I can read the data, but how is it possible then that further writing is done there? Does anyone know help? Thanks in advance Michael From qsc@icon.co.za Thu Jul 31 06:43:02 2003 From: qsc@icon.co.za (Quentin) Date: Thu Jul 31 05:43:02 2003 Subject: [Tutor] OT: Save all HTML pages Message-ID: <3F28E46E.8060103@icon.co.za> Hi Sorry for the OT, but it is a problem I found with the Python online docs. How can I download and/or save all the webpages that is linked from a main index page without having to open them all first? I would like to read them ofline. Using Mozilla 1.3b. Thanks Quentin From op73418@mail.telepac.pt Thu Jul 31 06:55:02 2003 From: op73418@mail.telepac.pt (Rodrigues) Date: Thu Jul 31 05:55:02 2003 Subject: [Tutor] OT: Save all HTML pages In-Reply-To: <3F28E46E.8060103@icon.co.za> Message-ID: > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Quentin > > Hi > Sorry for the OT, but it is a problem I found with the > Python online docs. > How can I download and/or save all the webpages that is > linked from a > main index page without having to open them all first? > I would like to read them ofline. > Using Mozilla 1.3b. Download the Python installer and install it in your computer. Docs are included. With my best regards, G. Rodrigues From qsc@icon.co.za Thu Jul 31 07:00:02 2003 From: qsc@icon.co.za (Quentin) Date: Thu Jul 31 06:00:02 2003 Subject: [Tutor] OT: Save all HTML pages In-Reply-To: References: Message-ID: <3F28E873.1040601@icon.co.za> >>> Sorry for the OT, but it is a problem I found with the >>> Python online docs. > Download the Python installer and install it in your computer. Docs > are included. Let me rephrase that: All the documents that is related with Python, such as online tutorials and Python add-ons. Thanks Quentin From carroll@tjc.com Thu Jul 31 12:03:27 2003 From: carroll@tjc.com (Terry Carroll) Date: Thu Jul 31 11:03:27 2003 Subject: [Tutor] XML documentation In-Reply-To: <359178A8-BB22-11D7-B454-000393B10A78@mac.com> Message-ID: On Sun, 20 Jul 2003 cybersamurai@mac.com wrote: > I need know here I can find documentation about XML and Python. I know > How read and write a new XML file but I don't know edit. I really liked the O'Reilly book: http://www.amazon.com/exec/obidos/tg/detail/-/0596001282 http://www.oreilly.com/catalog/pythonxml/ -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From carroll@tjc.com Thu Jul 31 12:08:14 2003 From: carroll@tjc.com (Terry Carroll) Date: Thu Jul 31 11:08:14 2003 Subject: [Tutor] Looking for some utilities In-Reply-To: <1059139896.2433.5.camel@24-159-241-21.jvl.wi.charter.com> Message-ID: On 25 Jul 2003, Mike Wagman wrote: > I am having to move my development environment for a program I am > working on from linux to windows, and I am looking for some utilities to > run on windows.... > > FTP software. Nothing fancy but free with the ability to remember a log > on. I really like NCFTP. It's mostly line oriented, but works very well. http://www.ncftpd.com > A 2 windows configurable file manager, similar to worker, or gentoo, or > if you remember the old amiga DirWorks,Dir Opus, Disk master. You know, I never realized how much I missed that from my Amiga days. I use two Explorer windows, but it's not the same. -- Terry Carroll | "I say to you that the VCR is to the American Santa Clara, CA | film producer and the American public as the carroll@tjc.com | Boston strangler is to the woman home alone." | Jack Valenti, MPAA President Modell delendus est | Testimony before Congress, 1982 From tpc@csua.berkeley.edu Thu Jul 31 12:18:03 2003 From: tpc@csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Thu Jul 31 11:18:03 2003 Subject: [Tutor] OT: Save all HTML pages In-Reply-To: <3F28E873.1040601@icon.co.za> Message-ID: <20030731080120.G58764-100000@localhost.name> are you on a Unix system ? if so you may want to use wget. I do not know what to use if you are on a Windows system, except maybe installing a Unix shell emulator such as CygWin (cygwin.com) On Thu, 31 Jul 2003, Quentin wrote: > > >>> Sorry for the OT, but it is a problem I found with the > >>> Python online docs. > > > Download the Python installer and install it in your computer. Docs > > are included. > Let me rephrase that: All the documents that is related with Python, > such as online tutorials and Python add-ons. > > Thanks > Quentin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff@ccvcorp.com Thu Jul 31 14:05:52 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 13:05:52 2003 Subject: [Tutor] How to get messages from stderr References: <20030731021253.404a731a.klappnase@freenet.de> <20030731111411.2285a507.klappnase@freenet.de> Message-ID: <3F294C59.5070803@ccvcorp.com> klappnase wrote: >>>def getprogress(self): >>> self.progress = self.ppp.read() >>> self.frame.after(100, self.getprogress) >>> >>>but I found that I only got any output after the child process had >>>finished. It seems to work as long as I only get the output from >>>stdout with Popen3, but I need the stderr messages. Does anyone know a >>>way to get the output from stderr while the child process is still >>>running? Any help would be very appreciated. >>> I believe that your problem may be with using read(), with no arguments. By default, read() will return everything up to end-of-file. For a pipe, EOF doesn't occur until the pipe is closed. Therefore, self.ppp.read() will block until the pipe is closed, i.e. the command stops running. Try calling read() with an argument multiple times, and assembling the results yourself. In one of my own programs, I needed to supply input to an external command, and determined that that command would output exactly 18 bytes of data before waiting for input, so I used this code: def _runcommand(self, command): print command i, o = os.popen4(command) print o.read(18) i.write(self.paramstring) i.write('\n') i.flush() result = o.readlines() return result I couldn't just use read() or readlines(), because those calls would hang waiting for EOF or EOL respectively, neither of which would happen at the point I was interested in. Jeff Shannon Technician/Programmer Credit International From norvell@houseofspearman.org Thu Jul 31 14:20:03 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu Jul 31 13:20:03 2003 Subject: [Tutor] else clauses on loops Message-ID: <20030731135426.GA11492@houseofspearman.org> I'm working through the Tutorial yet again (Release 2.3 this time) and this time got stuck on section 4.4, ``break and continue Statements, and else Clauses on Loops.'' Here's the code from that section: >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 With which for loop is the else associated? Because of the indentation level I'd think it belongs to the outer for loop, but the else gets executed when the loop is not terminated by a break or continue. In this case the break belongs to the inner for (right?) so how does else know that it's supposed to execute? -- Norvell Spearman From jeff@ccvcorp.com Thu Jul 31 14:44:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 13:44:01 2003 Subject: [Tutor] else clauses on loops References: <20030731135426.GA11492@houseofspearman.org> Message-ID: <3F29556B.8000702@ccvcorp.com> Norvell Spearman wrote: >I'm working through the Tutorial yet again (Release 2.3 this time) and >this time got stuck on section 4.4, ``break and continue Statements, and >else Clauses on Loops.'' Here's the code from that section: > > >>> for n in range(2, 10): > ... for x in range(2, n): > ... if n % x == 0: > ... print n, 'equals', x, '*', n/x > ... break > ... else: > ... # loop fell through without finding a factor > ... print n, 'is a prime number' > ... > >With which for loop is the else associated? Because of the indentation >level I'd think it belongs to the outer for loop, but the else gets >executed when the loop is not terminated by a break or continue. In >this case the break belongs to the inner for (right?) so how does else >know that it's supposed to execute? > It uses the same format as an if/else -- the else should be at the same indentation level as the condition statement that it applies to. With this: if test1(): if test2(): foo() else: bar() it's expected that the else applies to the test2() condition, because they are at the same indentation level. If the else were to apply to the test1() condition, it'd be indented like so: if test1(): if test2(): foo() else: bar() The same logic holds true when it's for statements instead of if statements -- any time you have statements that are a syntactic group, they should be at the same indentation level. Jeff Shannon Technician/Programmer Credit International From norvell@houseofspearman.org Thu Jul 31 14:49:01 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu Jul 31 13:49:01 2003 Subject: [Tutor] else clauses on loops In-Reply-To: <3F29556B.8000702@ccvcorp.com> References: <20030731135426.GA11492@houseofspearman.org> <3F29556B.8000702@ccvcorp.com> Message-ID: <20030731174805.GA13723@houseofspearman.org> On Thursday, 2003.07.31, 10:44:11 -0700, Jeff Shannon wrote: > It uses the same format as an if/else -- the else should be at the same > indentation level as the condition statement that it applies to. Thanks. As soon as you mentioned the if/else it clicked for me. -- Norvell Spearman From ebernert@crpud.net Thu Jul 31 15:41:53 2003 From: ebernert@crpud.net (Elizabeth Bernert) Date: Thu Jul 31 14:41:53 2003 Subject: [Tutor] Unsure why won't work Message-ID: <3F2962A4.8030306@crpud.net> This is a multi-part message in MIME format. --------------060002050206020906060601 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit I changed the top line to the line the works in my comp to get programs working, (i.e. #!c:/Python22/python.exe) but that did not work.. Does anyone have any ideas? --------------060002050206020906060601 Content-Type: text/plain; name="tail.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="tail.py" #!usr/bin/python # # Usage: python tail.py [file-name] # # Continuously look for new data in a file and write it to terminal. If # the file name is omitted, standard input is used # import sys, time # Position the file near the end, unless it's pretty small already def findEof(input): import os size = os.fstat(input.fileno())[6] if (size > 500): # seek to 400 bytes from end of file print 'seeking back' input.seek(-500, 2) # Infinitely loop looking for new data in file def tail(input): while 1: line = input.readline() if line == '': # empty - wait and try again time.sleep(2) else: # trailing comma to supress newlines (which line already has) print line, # actually begin the code - look for a file name if len(sys.argv) > 1: input = open(sys.argv[1]) else: input = sys.stdin findEof(input) tail(input) --------------060002050206020906060601-- From jeff@ccvcorp.com Thu Jul 31 15:52:26 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 14:52:26 2003 Subject: [Tutor] Unsure why won't work References: <3F2962A4.8030306@crpud.net> Message-ID: <3F296552.5080107@ccvcorp.com> Elizabeth Bernert wrote: > I changed the top line to the line the works in my comp to get > programs working, (i.e. #!c:/Python22/python.exe) but that did not > work.. Does anyone have any ideas? What *precisely* are you doing that's not working? If you're running Windows (as I presume you are from the above comment), then the shebang line doesn't matter -- that's a unix convention, and to Windows it looks like an ordinary comment line. Under Win9x, you must use the python command to run a script -- i.e., $ python tail.py somefile.txt Under Win2k/XP, it's possible to have Explorer recognize files with a .py extension as being executable and associated with the python interpreter. I believe that the installer (at least for the ActiveState distribution) does this automatically. In that case, you'd only need to type $ tail somefile.txt (provided, of course, that tail.py is located on your $PATH). Jeff Shannon Technician/Programmer Credit International From patterner@rocketmail.com Thu Jul 31 16:41:02 2003 From: patterner@rocketmail.com (Chris Readle) Date: Thu Jul 31 15:41:02 2003 Subject: [Tutor] Unsure why won't work In-Reply-To: <3F296552.5080107@ccvcorp.com> Message-ID: <20030731194021.14533.qmail@web40603.mail.yahoo.com> You also need to make sure that python.exe in in your path. For Win2k and XP you can do this by right-clicking My Computer and left-clicking Properties. Then look under the Advanced tab, and clich the Environment variables button. In the System Variables listing, look for Path, double click to edit. Add ; c:\python22; to the end of the listing. chris --- Jeff Shannon wrote: > Elizabeth Bernert wrote: > > > I changed the top line to the line the works in my comp to get > > programs working, (i.e. #!c:/Python22/python.exe) but that did not > > work.. Does anyone have any ideas? > > > What *precisely* are you doing that's not working? > > If you're running Windows (as I presume you are from the above comment), > > then the shebang line doesn't matter -- that's a unix convention, and to > > Windows it looks like an ordinary comment line. > > Under Win9x, you must use the python command to run a script -- i.e., $ > python tail.py somefile.txt > > Under Win2k/XP, it's possible to have Explorer recognize files with a > .py extension as being executable and associated with the python > interpreter. I believe that the installer (at least for the ActiveState > > distribution) does this automatically. In that case, you'd only need to > > type $ tail somefile.txt (provided, of course, that tail.py is located > on your $PATH). > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From patterner@rocketmail.com Thu Jul 31 16:42:09 2003 From: patterner@rocketmail.com (Chris Readle) Date: Thu Jul 31 15:42:09 2003 Subject: [Tutor] Unsure why won't work In-Reply-To: <3F296552.5080107@ccvcorp.com> Message-ID: <20030731194036.70130.qmail@web40613.mail.yahoo.com> You also need to make sure that python.exe in in your path. For Win2k and XP you can do this by right-clicking My Computer and left-clicking Properties. Then look under the Advanced tab, and clich the Environment variables button. In the System Variables listing, look for Path, double click to edit. Add ; c:\python22; to the end of the listing. chris --- Jeff Shannon wrote: > Elizabeth Bernert wrote: > > > I changed the top line to the line the works in my comp to get > > programs working, (i.e. #!c:/Python22/python.exe) but that did not > > work.. Does anyone have any ideas? > > > What *precisely* are you doing that's not working? > > If you're running Windows (as I presume you are from the above comment), > > then the shebang line doesn't matter -- that's a unix convention, and to > > Windows it looks like an ordinary comment line. > > Under Win9x, you must use the python command to run a script -- i.e., $ > python tail.py somefile.txt > > Under Win2k/XP, it's possible to have Explorer recognize files with a > .py extension as being executable and associated with the python > interpreter. I believe that the installer (at least for the ActiveState > > distribution) does this automatically. In that case, you'd only need to > > type $ tail somefile.txt (provided, of course, that tail.py is located > on your $PATH). > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free, easy-to-use web site design software http://sitebuilder.yahoo.com From jeff@ccvcorp.com Thu Jul 31 17:03:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 16:03:01 2003 Subject: [Tutor] Unsure why won't work References: <3F2962A4.8030306@crpud.net> <3F296552.5080107@ccvcorp.com> <3F2970CE.7090300@crpud.net> Message-ID: <3F2975ED.6040104@ccvcorp.com> Elizabeth Bernert wrote: > Sorry, I forgot to mention that I am attemping to run tail.py through > Apache on Win XP. Ah, a fairly significant little detail, there. ;) I really haven't played around with CGI or Apache, so I don't know how much I can help here. I'm forwarding this back to the list so that others who know more about this sort of thing may be able to offer suggestions. I do have a few thoughts, however... > The only way I know to get programtitle.py programs working is to > open IE (running IE 6.0.*) and type > http://localhost:8080/cgi-bin/programtitle.py in the address bar. > Attempting to run tail.py by the command line gives me a syntax error, > where trying in IE gives me a HTTP 500 and the error log said that the > file was UTL (unable to locate) when I used your example on my programs. Well, if you're getting a syntax error at the command line, then even if Apache *could* locate the file it wouldn't work. Post a complete traceback of the syntax error, and we can probably get that sorted out fairly quickly. At the same time, this program is not designed to work with CGI. You typically cannot just dump a normal program into cgi-bin and have it work -- if nothing else, the program needs to output the correct cgi headers in order to work with HTTP. Also, due to the limitations of HTTP, it's difficult to write a constantly-updating program -- the protocol works on a file-based basis. A web browser requests a file, and typically cannot (properly) display the file until the entire contents have arrived. Since this program is continually sending new output, you never send an entire "file" ... so even if a browser is able to show a response, you'll have a single page which is constantly growing, which is probably not the preferred way of doing this. You could perhaps have the program write a single-page snapshot of the file and include a meta-refresh tag, which would tell the browser to reload the file (thus grabbing a new snapshot) after a few seconds. > I know that the program works on a mac, as is, but I don't know the > difference and aside from path names which differ from comupter to > computer I have been unable to find differences, except sometimes > things work and sometimes they don't. If you're getting a syntax error, then I'm surprised that it works as-is on a Mac -- Python syntax is the same everywhere. One possibility is that line-endings didn't get converted -- different OSs use different ways to indicate the end of a line (*nix uses , Mac uses , and Windows uses ), and things can get confused if you have the wrong type of line ending. Jeff Shannon Technician/Programmer Credit International From justin@unixremedies.com Thu Jul 31 19:07:31 2003 From: justin@unixremedies.com (Justin Heath) Date: Thu Jul 31 18:07:31 2003 Subject: [Tutor] Recursion help Message-ID: <3F298E37.8070600@unixremedies.com> I am working thru some of the examples in the "Learning to Program" tutorial. I am going thru the recusrion section and have gotten stumped. Here is the code I have run below: def printList(L): # if its empty do nothing if not L: return # if its a list call printList on 1st element if type(L[0]) == type([]): printList(L[0]) else: #no list so just print print L[0] # now process the rest of L printList(L[1:]) myList=[1,2,3,4,5] printList(myList) The output is as follows: 1 2 3 4 5 It "appears" that the code is running thru the else block over and over until it reaches the end of the list. However, I do not see how the list is being enumerated or how it knows to go to the next item in the list. Can anyone shed some light on this? Thanks, Justin From zak@harlekin-maus.com Thu Jul 31 19:22:15 2003 From: zak@harlekin-maus.com (Zak Arntson) Date: Thu Jul 31 18:22:15 2003 Subject: [Tutor] Recursion help In-Reply-To: <3F298E37.8070600@unixremedies.com> References: <3F298E37.8070600@unixremedies.com> Message-ID: <2920.192.207.104.212.1059690117.squirrel@mail.harlekin-maus.com> > I am working thru some of the examples in the "Learning to Program" > tutorial. I am going thru the recusrion section and have gotten stumped. > Here is the code I have run below: > > def printList(L): > # if its empty do nothing > if not L: return Reexamine this if statement. What will the type of L[0] be? > # if its a list call printList on 1st element > if type(L[0]) == type([]): > printList(L[0]) > else: #no list so just print > print L[0] > # now process the rest of L > printList(L[1:]) > > It "appears" that the code is running thru the else block over and over > until it reaches the end of the list. However, I do not see how the list > is being enumerated or how it knows to go to the next item in the list. > Can anyone shed some light on this? You can look at it this way: printList((1,2,3)) prints (1,2,3)[0] which is 1 runs printList((1,2,3)[1:]) = printList((2,3)) now we're in printList((2,3)) prints (2,3)[0] which is 2 runs printList((2,3)[1:]) and so on ... > > Thanks, > Justin --- Zak Arntson www.harlekin-maus.com - Games - Lots of 'em From justin@unixremedies.com Thu Jul 31 19:31:56 2003 From: justin@unixremedies.com (Justin Heath) Date: Thu Jul 31 18:31:56 2003 Subject: [Tutor] Recursion help In-Reply-To: <2920.192.207.104.212.1059690117.squirrel@mail.harlekin-maus.com> References: <3F298E37.8070600@unixremedies.com> <2920.192.207.104.212.1059690117.squirrel@mail.harlekin-maus.com> Message-ID: <3F2993D4.5070303@unixremedies.com> Zak Arntson wrote: >>I am working thru some of the examples in the "Learning to Program" >>tutorial. I am going thru the recusrion section and have gotten stumped. >>Here is the code I have run below: >> >>def printList(L): >> # if its empty do nothing >> if not L: return >> >> > >Reexamine this if statement. What will the type of L[0] be? > > > >> # if its a list call printList on 1st element >> if type(L[0]) == type([]): >> printList(L[0]) >> else: #no list so just print >> print L[0] >> # now process the rest of L >> printList(L[1:]) >> >>It "appears" that the code is running thru the else block over and over >>until it reaches the end of the list. However, I do not see how the list >>is being enumerated or how it knows to go to the next item in the list. >>Can anyone shed some light on this? >> >> > >You can look at it this way: >printList((1,2,3)) > prints (1,2,3)[0] which is 1 > runs printList((1,2,3)[1:]) = printList((2,3)) > now we're in printList((2,3)) > prints (2,3)[0] which is 2 > runs printList((2,3)[1:]) and so on ... > > > >>Thanks, >>Justin >> >> > >--- >Zak Arntson >www.harlekin-maus.com - Games - Lots of 'em > > Thank you. I completely missed the fact that L was being re-assigned when printList() was run again. Thanks, Justin From amk@amk.ca Thu Jul 31 19:56:03 2003 From: amk@amk.ca (A.M. Kuchling) Date: Thu Jul 31 18:56:03 2003 Subject: [Tutor] Comments wanted on new Python introduction Message-ID: <20030731225824.GA30757@nyman.amk.ca> A new set of introductory pages for python.org is being developed. The current draft of a revised version is at http://www.python.org/topics/learn/ . If you're learning or have recently learned Python, I'd like to hear your opinions. Are the pages helpful? Are there useful resources that aren't linked to, or beginner questions that aren't answered? Thanks for your help! --amk (www.amk.ca) Had a hard day in the catacombs, have we? -- The Doctor, in "The Masque of Mandragora" From dyoo@hkn.eecs.berkeley.edu Thu Jul 31 21:00:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Jul 31 20:00:02 2003 Subject: [Tutor] Recursion help [experimenting with a recursive function] In-Reply-To: <3F298E37.8070600@unixremedies.com> Message-ID: On Thu, 31 Jul 2003, Justin Heath wrote: > I am working thru some of the examples in the "Learning to Program" > tutorial. I am going thru the recusrion section and have gotten stumped. > > Here is the code I have run below: > > def printList(L): > # if its empty do nothing > if not L: return > # if its a list call printList on 1st element > if type(L[0]) == type([]): > printList(L[0]) > else: #no list so just print > print L[0] > # now process the rest of L > printList(L[1:]) Hi Justin, A good way to test out a recursive function --- to see how it works --- is to start on small examples, and then work ourselves up to large ones. You tested it initially with: > myList=[1,2,3,4,5] > > printList(myList) > > The output is as follows: > 1 > 2 > 3 > 4 > 5 But that's too big of an example. *grin* Try smaller ones. Here's a simple one: ### printList([]) ### If we read the code, we'll see that trying to "printList()" the empty list will cleanly exit out of the function. Ok, so we've got that handled. Let's build on our knowledge. What happens if we try something like this? ### printList([42]) ### In this case, our "L" list will be [42]. If we look back at the code: > def printList(L): > # if its empty do nothing > if not L: return > # if its a list call printList on 1st element > if type(L[0]) == type([]): > printList(L[0]) > else: #no list so just print > print L[0] > # now process the rest of L > printList(L[1:]) it shouldn't be too hard to see that this will hit the third case: ### else: #no list so just print print L[0] ### and print out "42" on our screen. Finally, it'll try to print out the rest of this list by doing a: printList([]) at the end of the function. So now we have to do printList([])... but we already know what doing printList([]) does, since we just tried it a few minutes ago: it doesn't do anything! Let's summarize: printList([42]) just prints the number 42. We're stating the "obvious", but it's important to understand here that the function does stop if we do printList([42]). If you're hung up at this point, start asking more questions! *grin* > It "appears" that the code is running thru the else block over and over > until it reaches the end of the list. However, I do not see how the list > is being enumerated or how it knows to go to the next item in the list. > Can anyone shed some light on this? Ok, now we know what will happen if we do something like printList([]) and printList([42]). Let's make the example slightly larger. Now we can be a bit more ambitious. We can try: ### printList([17, 42]) ### You'll notice that it does: print 17 followed by: printList([42]) But we already know what printList([42]) does: we just did it a few minutes ago. So this ends up printing 17 and 42 in sequence. Try guessing what our next example will look like. *grin* So one effective way to understand a recursive process is to push really simple examples on it and see what it does. Then progressively make those examples larger and larger. By then, you should have a good idea of what that recursive function does. Hope this helps! From idiot1@netzero.net Thu Jul 31 21:10:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 31 20:10:02 2003 Subject: [Tutor] OHMYGOD... In-Reply-To: <200307300649.22966.shalehperry@comcast.net> References: <200307292209.03791@toddloki> <200307300649.22966.shalehperry@comcast.net> Message-ID: <3F29AFBF.6020501@netzero.net> Sean 'Shaleh' Perry wrote: > On Tuesday 29 July 2003 19:09, Todd Stephens wrote: > >>On Tuesday 29 July 2003 08:31 pm, Kirk Bailey wrote: >> >>>3 weeks of my life down the John L Crapper just that easy. Wonderful and >>>powerful is FreeBsD. >> >>Wonderful and powerful is root in FreeBSD. >> > > > thanks, I forgot that as my last item: > > *) everytime you login as root, ask yourself if you could accomplish the task > as a simple user with tools like su and sudo. Root is a loaded gun waiting > to misfire. > Even then, the real problem came due to me issuing a powerful and dangerous command while laboring under a misunderstanding- where I was, to be precise. Now, I could have kept this secret, or blaimed it on a HDD failure and (blablabla, excuss follow...), but I thought, as this IS the tutor list, that it would be an EXCELLENT bad example of how easy it is to make a simple mistake and really SCREW THE POOCH. I hope a LOT of beople learn from my excellent bad example. And as the server holds several domains, anything really important will soon be backed up on another server on the LAN on a nightly backup, as soon as I can hoodwink////////persuade the host into updating the backup script from monthly/weekly to monthly/daily. (systemwide/website). > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From ebernert@crpud.net Thu Jul 31 21:36:55 2003 From: ebernert@crpud.net (Elizabeth Bernert) Date: Thu Jul 31 20:36:55 2003 Subject: [Tutor] CGI Programming Message-ID: <3F29B5AB.2090504@crpud.net> This is a multi-part message in MIME format. --------------090807090907020605060706 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit I am programming in Pythono 2.2 through Apache. I have searched though google and have been unable to come up with anything. I can "hold" onto the inputs from the user for one submit, but no farther. Is there a way to hold onto the words for another submit. I am writing Mad Libs (C) for a class project and am at a loss. I have attached my project and placed comments at the problem. Thank-you in advance for all advice. Sincerely, Elizabeth Bernert --------------090807090907020605060706 Content-Type: text/plain; name="LIB_College.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="LIB_College.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/LIB_College.py # Program Files\Apache Group\Apache2\cgi-bin\LIB_College.py # Final Project - python CGI script import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" form = cgi.FieldStorage() ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) PLURAL_NOUN2 = str(form.getvalue('PLURAL_NOUN2')) PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) ADJECTIVE2 = str(form.getvalue('ADJECTIVE2')) ADJECTIVE3 = str(form.getvalue('ADJECTIVE3')) PLURAL_NOUN4 = str(form.getvalue('PLURAL_NOUN4')) NUMBER1 = str(form.getvalue('NUMBER1')) NOUN1 = str(form.getvalue('NOUN1')) PLURAL_NOUN5 = str(form.getvalue('PLURAL_NOUN5')) AN_OCCUPATION1 = str(form.getvalue('AN_OCCUPATION1')) AN_OCCUPATION2 = str(form.getvalue('AN_OCCUPATION2')) PLURAL_NOUN6 = str(form.getvalue('PLURAL_NOUN6')) ADJECTIVE4 = str(form.getvalue('ADJECTIVE4')) print '' print "Our American Universities offer students many" + " " + ADJECTIVE1 print "courses that will prepare them to become good" + " " + PLURAL_NOUN1 + ". You can get a degree as a Bachelor of" + " " + PLURAL_NOUN2 + ", or tske a regular liberal" + PLURAL_NOUN3 print "course. Or, if you want to become a/an" + " " + ADJECTIVE2 print "engineer, you can study" + " " + ADJECTIVE3 print "mathmatics and differential" + " " + PLURAL_NOUN4 + ". Then after" + " " + NUMBER1 print "years, if you want to continue your studis, you can write a/an" + " " + NOUN1 print "and become a Doctor of" + " " + PLURAL_NOUN5 + ". When you get out into the world, if you have a diploma from a university, you will be able to get a job as a/an" + " " + AN_OCCUPATION1 + ". If you don't have a diploma, you will have to take a job as a/an" + " " + AN_OCCUPATION2 + ". So it's important that you study hard in highschool so you will do well on your College Enterence" + " " + PLURAL_NOUN6 + ". Remember, 'A little learning is a/an" + " " + ADJECTIVE4 print "thing." print '' #HERE IS MY PROBLEM # # # # print """

""" # # #MY PROBLEM IS ABOVE # # print """
    If you want to input new words, then please fill out the entire form:



    Don't forget:
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives.
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'.
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns.
    A VERB is an action word. Run, pitch, jump, and swim are verbs.
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] or a room [Bathroom, Kitchen].
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words.
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , what is meant is a word that is one of those things.
    When a PLURAL is asked for be sure to pluralize the word.
ADJECTIVE::
PLURAL_NOUN:
PLURAL_NOUN:
PLURAL_NOUN:
ADJECTIVE:
ADJECTIVE:
PLURAL_NOUN:
NUMBER:
NOUN:
PLURAL_NOUN:
AN_OCCUPATION:
AN_OCCUPATION:
PLURAL_NOUN:
ADJECTIVE:
A_PERSON:
NOUN:
NOUN:
A_PERSON:
NUMBER:
NOUN:
FAMOUS_PERSON:
VERB:
NAME:
NAME:
NOUN:
NOUN:
""" form = cgi.FieldStorage() if len(form)>0: ADJECTIVE1 = form.getvalue('ADJECTIVE1') ADJECTIVE2 = form.getvalue('ADJECTIVE2') ADJECTIVE3 = form.getvalue('ADJECTIVE3') ADJECTIVE4 = form.getvalue('ADJECTIVE4') PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') NUMBER1 = form.getvalue('NUMBER1') NUMBER2 = form.getvalue('NUMBER2') NOUN1 = form.gervalue('NOUN1') NOUN2 = form.getvalue('NOUN2') NOUN3 = form.getvalue('NOUN3') NOUN4 = form.getvalue('NOUN4') NOUN5 = form.getvalue('NOUN5') NOUN6 = form.getvalue('NOUN6') AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') A_PERSON1 = form.getvalue('A_PERSON1') A_PERSON2 = form.getvalue('A_PERSON2') NAME1 = form.getvalue('NAME1') NAME2 = form.getvalue('NAME2') VERB1 = form.getvalue('VERB1') FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') else: ADJECTIVE1 = 'blond' ADJECTIVE2 = 'blond' ADJECTIVE3 = 'blond' ADJECTIVE4 = 'blond' PLURAL_NOUN1 = 'women' PLURAL_NOUN2 = 'men' PLURAL_NOUN3 = 'women' PLURAL_NOUN4 = 'men' PLURAL_NOUN5 = 'women' PLURAL_NOUN6 = 'men' NUMBER1 = '1' NUMBER2 = '2' NOUN1 = 'woman' NOUN2 = 'man' NOUN3 = 'woman' NOUN4 = 'man' NOUN5 = 'woman' NOUN6 = 'man' AN_OCCUPATION1 = 'teacher' AN_OCCUPATION2 = 'waitress' A_PERSON1 = ' fill in later ' A_PERSON2 = ' fill in later ' NAME1 = ' fill in later ' NAME2 = ' fill in later ' VERB1 = 'run' FAMOUS_PERSON1 = 'GOD' --------------090807090907020605060706 Content-Type: text/plain; name="final.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="final.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/final.py # Program Files\Apache Group\Apache2\cgi-bin\final.py # Final Lab - python CGI script # Elizabeth Bernert import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" print """
    Please fill out the entire form:
    Don't forget:
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives.
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'.
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns.
    A VERB is an action word. Run, pitch, jump, and swim are verbs.
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] or a room [Bathroom, Kitchen].
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words.
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , what is meant is a word that is one of those things.
    When a PLURAL is asked for be sure to pluralize the word.


ADJECTIVE::
PLURAL_NOUN:
PLURAL_NOUN:
PLURAL_NOUN:
ADJECTIVE:
ADJECTIVE:
PLURAL_NOUN:
NUMBER:
NOUN:
PLURAL_NOUN:
AN_OCCUPATION:
AN_OCCUPATION:
PLURAL_NOUN:
ADJECTIVE:
A_PERSON:
NOUN:
NOUN:
A_PERSON:
NUMBER:
NOUN:
FAMOUS_PERSON:
VERB:
NAME:
NAME:
NOUN:
NOUN:
""" form = cgi.FieldStorage() if len(form)>0: ADJECTIVE1 = form.getvalue('ADJECTIVE1') ADJECTIVE2 = form.getvalue('ADJECTIVE2') ADJECTIVE3 = form.getvalue('ADJECTIVE3') ADJECTIVE4 = form.getvalue('ADJECTIVE4') PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') NUMBER1 = form.getvalue('NUMBER1') NUMBER2 = form.getvalue('NUMBER2') NOUN1 = form.gervalue('NOUN1') NOUN2 = form.getvalue('NOUN2') NOUN3 = form.getvalue('NOUN3') NOUN4 = form.getvalue('NOUN4') NOUN5 = form.getvalue('NOUN5') NOUN6 = form.getvalue('NOUN6') AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') A_PERSON1 = form.getvalue('A_PERSON1') A_PERSON2 = form.getvalue('A_PERSON2') NAME1 = form.getvalue('NAME1') NAME2 = form.getvalue('NAME2') VERB1 = form.getvalue('VERB1') FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') else: ADJECTIVE1 = 'blond' ADJECTIVE2 = 'blond' ADJECTIVE3 = 'blond' ADJECTIVE4 = 'blond' PLURAL_NOUN1 = 'women' PLURAL_NOUN2 = 'men' PLURAL_NOUN3 = 'women' PLURAL_NOUN4 = 'men' PLURAL_NOUN5 = 'women' PLURAL_NOUN6 = 'men' NUMBER1 = '1' NUMBER2 = '2' NOUN1 = 'woman' NOUN2 = 'man' NOUN3 = 'woman' NOUN4 = 'man' NOUN5 = 'woman' NOUN6 = 'man' AN_OCCUPATION1 = 'teacher' AN_OCCUPATION2 = 'waitress' A_PERSON1 = ' fill in later ' A_PERSON2 = ' fill in later ' NAME1 = ' fill in later ' NAME2 = ' fill in later ' VERB1 = 'run' FAMOUS_PERSON1 = 'GOD' --------------090807090907020605060706 Content-Type: text/plain; name="LIB_finalexam.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="LIB_finalexam.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/mult.py # Program Files\Apache Group\Apache2\cgi-bin\mult.py # Final Project - python CGI script import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" form = cgi.FieldStorage() ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) A_PERSON1 = str(form.getvalue('A_PERSON1')) NOUN1 = str(form.getvalue('NOUN1')) PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) NOUN2 = str(form.getvalue('NOUN2')) NOUN3 = str(form.getvalue('NOUN3')) A_PERSON2 = str(form.getvalue('A_PERSON2')) NUMBER1 = str(form.getvalue('NUMBER1')) PLURAL_NOUN2 = str(form.getvalue('PLRAL_NOUN2')) NOUN4 = str(form.getvalue('NOUN4')) PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) print '' print "Well it's time for final exams again. Her are some sample questions with" + " " + ADJECTIVE1 print "answers that may give you an idea of what final exams are like:" print "

QUESTION: " print "
Who was the first president of the United States?" print "
ANSWER: " print "
" + A_PERSON1 print ", who was also called, 'The" + " " + NOUN1 print "of Our Country." print "

QUESTION: " print "
What is the shortest distance between two" + " " + PLURAL_NOUN1 + "?" print "
ANSWER: " print "
A straight" + " " + NOUN2 + "." print "

QUESTION: " print "Who said, 'I regret that I only have one" + " " + NOUN3 print "to give for my country.'?" print "
ANSWER: " print "
" + A_PERSON2 + "." print '' --------------090807090907020605060706-- From jeff@ccvcorp.com Thu Jul 31 22:10:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 21:10:02 2003 Subject: [Fwd: [Tutor] CGI Programming] Message-ID: <3F29BE15.2000906@ccvcorp.com> This is a multi-part message in MIME format. --------------040108010508010804040400 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit I'm forwarding this to the Tutor list. This really isn't an area I'm familiar with -- I have not yet done any CGI programming -- and I really don't have the free time to research this just now. Hopefully someone else on the list will be able to help... Jeff Shannon Technician/Programmer Credit International -------- Original Message -------- Subject: [Tutor] CGI Programming Date: Thu, 31 Jul 2003 17:34:51 -0700 From: Elizabeth Bernert Reply-To: ebernert@crpud.net To: tutor@python.org I am programming in Pythono 2.2 through Apache. I have searched though google and have been unable to come up with anything. I can "hold" onto the inputs from the user for one submit, but no farther. Is there a way to hold onto the words for another submit. I am writing Mad Libs (C) for a class project and am at a loss. I have attached my project and placed comments at the problem. Thank-you in advance for all advice. Sincerely, Elizabeth Bernert --------------040108010508010804040400 Content-Type: text/plain; name="LIB_College.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="LIB_College.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/LIB_College.py # Program Files\Apache Group\Apache2\cgi-bin\LIB_College.py # Final Project - python CGI script import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" form = cgi.FieldStorage() ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) PLURAL_NOUN2 = str(form.getvalue('PLURAL_NOUN2')) PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) ADJECTIVE2 = str(form.getvalue('ADJECTIVE2')) ADJECTIVE3 = str(form.getvalue('ADJECTIVE3')) PLURAL_NOUN4 = str(form.getvalue('PLURAL_NOUN4')) NUMBER1 = str(form.getvalue('NUMBER1')) NOUN1 = str(form.getvalue('NOUN1')) PLURAL_NOUN5 = str(form.getvalue('PLURAL_NOUN5')) AN_OCCUPATION1 = str(form.getvalue('AN_OCCUPATION1')) AN_OCCUPATION2 = str(form.getvalue('AN_OCCUPATION2')) PLURAL_NOUN6 = str(form.getvalue('PLURAL_NOUN6')) ADJECTIVE4 = str(form.getvalue('ADJECTIVE4')) print '' print "Our American Universities offer students many" + " " + ADJECTIVE1 print "courses that will prepare them to become good" + " " + PLURAL_NOUN1 + ". You can get a degree as a Bachelor of" + " " + PLURAL_NOUN2 + ", or tske a regular liberal" + PLURAL_NOUN3 print "course. Or, if you want to become a/an" + " " + ADJECTIVE2 print "engineer, you can study" + " " + ADJECTIVE3 print "mathmatics and differential" + " " + PLURAL_NOUN4 + ". Then after" + " " + NUMBER1 print "years, if you want to continue your studis, you can write a/an" + " " + NOUN1 print "and become a Doctor of" + " " + PLURAL_NOUN5 + ". When you get out into the world, if you have a diploma from a university, you will be able to get a job as a/an" + " " + AN_OCCUPATION1 + ". If you don't have a diploma, you will have to take a job as a/an" + " " + AN_OCCUPATION2 + ". So it's important that you study hard in highschool so you will do well on your College Enterence" + " " + PLURAL_NOUN6 + ". Remember, 'A little learning is a/an" + " " + ADJECTIVE4 print "thing." print '' #HERE IS MY PROBLEM # # # # print """
""" # # #MY PROBLEM IS ABOVE # # print """
    If you want to input new words, then please fill out the entire form:



    Don't forget:
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives.
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'.
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns.
    A VERB is an action word. Run, pitch, jump, and swim are verbs.
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] or a room [Bathroom, Kitchen].
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words.
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , what is meant is a word that is one of those things.
    When a PLURAL is asked for be sure to pluralize the word.
ADJECTIVE::
PLURAL_NOUN:
PLURAL_NOUN:
PLURAL_NOUN:
ADJECTIVE:
ADJECTIVE:
PLURAL_NOUN:
NUMBER:
NOUN:
PLURAL_NOUN:
AN_OCCUPATION:
AN_OCCUPATION:
PLURAL_NOUN:
ADJECTIVE:
A_PERSON:
NOUN:
NOUN:
A_PERSON:
NUMBER:
NOUN:
FAMOUS_PERSON:
VERB:
NAME:
NAME:
NOUN:
NOUN:
""" form = cgi.FieldStorage() if len(form)>0: ADJECTIVE1 = form.getvalue('ADJECTIVE1') ADJECTIVE2 = form.getvalue('ADJECTIVE2') ADJECTIVE3 = form.getvalue('ADJECTIVE3') ADJECTIVE4 = form.getvalue('ADJECTIVE4') PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') NUMBER1 = form.getvalue('NUMBER1') NUMBER2 = form.getvalue('NUMBER2') NOUN1 = form.gervalue('NOUN1') NOUN2 = form.getvalue('NOUN2') NOUN3 = form.getvalue('NOUN3') NOUN4 = form.getvalue('NOUN4') NOUN5 = form.getvalue('NOUN5') NOUN6 = form.getvalue('NOUN6') AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') A_PERSON1 = form.getvalue('A_PERSON1') A_PERSON2 = form.getvalue('A_PERSON2') NAME1 = form.getvalue('NAME1') NAME2 = form.getvalue('NAME2') VERB1 = form.getvalue('VERB1') FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') else: ADJECTIVE1 = 'blond' ADJECTIVE2 = 'blond' ADJECTIVE3 = 'blond' ADJECTIVE4 = 'blond' PLURAL_NOUN1 = 'women' PLURAL_NOUN2 = 'men' PLURAL_NOUN3 = 'women' PLURAL_NOUN4 = 'men' PLURAL_NOUN5 = 'women' PLURAL_NOUN6 = 'men' NUMBER1 = '1' NUMBER2 = '2' NOUN1 = 'woman' NOUN2 = 'man' NOUN3 = 'woman' NOUN4 = 'man' NOUN5 = 'woman' NOUN6 = 'man' AN_OCCUPATION1 = 'teacher' AN_OCCUPATION2 = 'waitress' A_PERSON1 = ' fill in later ' A_PERSON2 = ' fill in later ' NAME1 = ' fill in later ' NAME2 = ' fill in later ' VERB1 = 'run' FAMOUS_PERSON1 = 'GOD' --------------040108010508010804040400 Content-Type: text/plain; name="final.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="final.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/final.py # Program Files\Apache Group\Apache2\cgi-bin\final.py # Final Lab - python CGI script # Elizabeth Bernert import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" print """
    Please fill out the entire form:
    Don't forget:
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives.
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'.
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns.
    A VERB is an action word. Run, pitch, jump, and swim are verbs.
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] or a room [Bathroom, Kitchen].
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words.
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , what is meant is a word that is one of those things.
    When a PLURAL is asked for be sure to pluralize the word.


ADJECTIVE::
PLURAL_NOUN:
PLURAL_NOUN:
PLURAL_NOUN:
ADJECTIVE:
ADJECTIVE:
PLURAL_NOUN:
NUMBER:
NOUN:
PLURAL_NOUN:
AN_OCCUPATION:
AN_OCCUPATION:
PLURAL_NOUN:
ADJECTIVE:
A_PERSON:
NOUN:
NOUN:
A_PERSON:
NUMBER:
NOUN:
FAMOUS_PERSON:
VERB:
NAME:
NAME:
NOUN:
NOUN:
""" form = cgi.FieldStorage() if len(form)>0: ADJECTIVE1 = form.getvalue('ADJECTIVE1') ADJECTIVE2 = form.getvalue('ADJECTIVE2') ADJECTIVE3 = form.getvalue('ADJECTIVE3') ADJECTIVE4 = form.getvalue('ADJECTIVE4') PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') NUMBER1 = form.getvalue('NUMBER1') NUMBER2 = form.getvalue('NUMBER2') NOUN1 = form.gervalue('NOUN1') NOUN2 = form.getvalue('NOUN2') NOUN3 = form.getvalue('NOUN3') NOUN4 = form.getvalue('NOUN4') NOUN5 = form.getvalue('NOUN5') NOUN6 = form.getvalue('NOUN6') AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') A_PERSON1 = form.getvalue('A_PERSON1') A_PERSON2 = form.getvalue('A_PERSON2') NAME1 = form.getvalue('NAME1') NAME2 = form.getvalue('NAME2') VERB1 = form.getvalue('VERB1') FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') else: ADJECTIVE1 = 'blond' ADJECTIVE2 = 'blond' ADJECTIVE3 = 'blond' ADJECTIVE4 = 'blond' PLURAL_NOUN1 = 'women' PLURAL_NOUN2 = 'men' PLURAL_NOUN3 = 'women' PLURAL_NOUN4 = 'men' PLURAL_NOUN5 = 'women' PLURAL_NOUN6 = 'men' NUMBER1 = '1' NUMBER2 = '2' NOUN1 = 'woman' NOUN2 = 'man' NOUN3 = 'woman' NOUN4 = 'man' NOUN5 = 'woman' NOUN6 = 'man' AN_OCCUPATION1 = 'teacher' AN_OCCUPATION2 = 'waitress' A_PERSON1 = ' fill in later ' A_PERSON2 = ' fill in later ' NAME1 = ' fill in later ' NAME2 = ' fill in later ' VERB1 = 'run' FAMOUS_PERSON1 = 'GOD' --------------040108010508010804040400 Content-Type: text/plain; name="LIB_finalexam.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="LIB_finalexam.py" #!c:/Python22/python.exe # http://localhost:8080/cgi-bin/mult.py # Program Files\Apache Group\Apache2\cgi-bin\mult.py # Final Project - python CGI script import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" form = cgi.FieldStorage() ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) A_PERSON1 = str(form.getvalue('A_PERSON1')) NOUN1 = str(form.getvalue('NOUN1')) PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) NOUN2 = str(form.getvalue('NOUN2')) NOUN3 = str(form.getvalue('NOUN3')) A_PERSON2 = str(form.getvalue('A_PERSON2')) NUMBER1 = str(form.getvalue('NUMBER1')) PLURAL_NOUN2 = str(form.getvalue('PLRAL_NOUN2')) NOUN4 = str(form.getvalue('NOUN4')) PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) print '' print "Well it's time for final exams again. Her are some sample questions with" + " " + ADJECTIVE1 print "answers that may give you an idea of what final exams are like:" print "

QUESTION: " print "
Who was the first president of the United States?" print "
ANSWER: " print "
" + A_PERSON1 print ", who was also called, 'The" + " " + NOUN1 print "of Our Country." print "

QUESTION: " print "
What is the shortest distance between two" + " " + PLURAL_NOUN1 + "?" print "
ANSWER: " print "
A straight" + " " + NOUN2 + "." print "

QUESTION: " print "Who said, 'I regret that I only have one" + " " + NOUN3 print "to give for my country.'?" print "
ANSWER: " print "
" + A_PERSON2 + "." print '' --------------040108010508010804040400-- From jeff@ccvcorp.com Thu Jul 31 22:13:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 21:13:01 2003 Subject: [Tutor] Ack! Message-ID: <3F29BEAB.1000308@ccvcorp.com> Nevermind that last email from me. I wasn't in the mailbox I thought I was... It's been a long, frustrating day. Sorry to confuse anyone. :) Jeff Shannon Technician/Programmer Credit International From goki75@vsnl.net Thu Jul 31 22:37:19 2003 From: goki75@vsnl.net (G Kiran) Date: Thu Jul 31 21:37:19 2003 Subject: [Tutor] Re: Tutor digest, Vol 1 #2622 - 13 msgs References: <20030731160006.11018.13659.Mailman@mail.python.org> Message-ID: <000c01c357cd$28d07c50$bc4c41db@VULCAN> Hi, I am trying to limit no of threads i can spawn for a multi threaded socket server . presently i do this by the following fragment of code maxthreads=40 for ct in range(0,len(scanlist)-1): th.append(checkport(scanlist[ct]) th[ct].start() while threading.activeCount() > maxthreads : pass ##### this is how i am limiting the no of threads i am using the threading class fo my checkport function is there any other way of doing it...rather than the endless loop which i feel wastes the processor time -kiran From idiot1@netzero.net Thu Jul 31 22:48:02 2003 From: idiot1@netzero.net (Kirk Bailey) Date: Thu Jul 31 21:48:02 2003 Subject: [Tutor] global Message-ID: <3F29C6A3.4050100@netzero.net> Got a script that wants to bark. Early in the program I define some defaults for certain variables to define state (they are used as boolian flags, 1/0 stuff). Later, a function referrs o one- and barks. Says it does not know the variable- undefined. Hmmm, sure it is... Apparently this function is not aware the variable is already defined. How do I force a variable to be global so it will automatically be available to the insiode structure of a defined function without having to formally pass it as an arguement? -- -- end Cheers! Kirk D Bailey + think + http://www.howlermonkey.net +-----+ http://www.tinylist.org http://www.listville.net | BOX | http://www.sacredelectron.org Thou art free"-ERIS +-----+ 'Got a light?'-Promethieus + think + Fnord. From jeff@ccvcorp.com Thu Jul 31 22:59:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Jul 31 21:59:03 2003 Subject: [Tutor] global References: <3F29C6A3.4050100@netzero.net> Message-ID: <3F29C9A1.9050508@ccvcorp.com> Kirk Bailey wrote: > Got a script that wants to bark. Early in the program I define some > defaults for certain variables to define state (they are used as > boolian flags, 1/0 stuff). Later, a function referrs o one- and barks. > Says it does not know the variable- undefined. Hmmm, sure it is... > Apparently this function is not aware the variable is already defined. > How do I force a variable to be global so it will automatically be > available to the insiode structure of a defined function without > having to formally pass it as an arguement? Presuming that this is within the same module, nothing needs to be done. However, rebinding a name that [supposedly] points to a global object can result in a problem like what you mention -- >>> spam = 5 >>> def foo(value): ... print "Had %d spam," % spam ... spam = value ... print "Now have %d spam" % spam ... >>> foo(6) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo UnboundLocalError: local variable 'spam' referenced before assignment >>> spam 5 >>> Since there is an assignment to spam within the function foo(), spam becomes a local variable. Because of certain optimizations used for local variables, this means that if spam isn't found in the locals() [psuedo-]dict, it won't get looked up in the globals() dict. As a result, attempting to access spam before assigning to it causes an error -- Python knows that it should be a local, but can't find it there. This can be resolved by placing the statement 'global spam' at the top of foo(). That tells Python that this *isn't* a local variable, and that it should always be looked for in the globals() dict. If this isn't what's happening to you, then post the relevant code (the module-level definitions and the function that's using them) and the full traceback of the error. Jeff Shannon Technician/Programmer Credit International From tim@johnsons-web.com Thu Jul 31 23:09:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Thu Jul 31 22:09:01 2003 Subject: [Tutor] CGI Programming In-Reply-To: <3F29B5AB.2090504@crpud.net> References: <3F29B5AB.2090504@crpud.net> Message-ID: <20030801021509.GZ22826@johnsons-web.com> * Elizabeth Bernert [030731 16:48]: > I am programming in Pythono 2.2 through Apache. I have searched though > google and have been unable to come up with anything. I can "hold" onto > the inputs from the user for one submit, but no farther. Is there a way > to hold onto the words for another submit. I am writing Mad Libs (C) > for a class project and am at a loss. I have attached my project and > placed comments at the problem. Thank-you in advance for all advice. > Sincerely, Hello Elizabeth: One simple way to "persist" data would be to encode it in a query string that would carry data from page 1 posted to page 2 and then use the "get" method to transmit to page 3 (as an example) Another way, expanding on this example is that the data posted from page 1 (or passed via a query string as in http://www.somdomain.com/cgi-bin/cgi.py?var1=one&var2=two, for that matter) would be stored within a form on page 2 in fields of input/type "hidden". It would then be posted forward to page 3. The process I'm describing is language independent - there's also FastCgi, but learn CGI first :-) pythonesque example below.... > Elizabeth Bernert > #!c:/Python22/python.exe > # http://localhost:8080/cgi-bin/LIB_College.py > # Program Files\Apache Group\Apache2\cgi-bin\LIB_College.py > # Final Project - python CGI script > > import cgi > import cgitb; cgitb.enable() > > print "Content-type: text/html\n\n" > > form = cgi.FieldStorage() > > ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) > PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) > PLURAL_NOUN2 = str(form.getvalue('PLURAL_NOUN2')) > PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) > ADJECTIVE2 = str(form.getvalue('ADJECTIVE2')) > ADJECTIVE3 = str(form.getvalue('ADJECTIVE3')) > PLURAL_NOUN4 = str(form.getvalue('PLURAL_NOUN4')) > NUMBER1 = str(form.getvalue('NUMBER1')) > NOUN1 = str(form.getvalue('NOUN1')) > PLURAL_NOUN5 = str(form.getvalue('PLURAL_NOUN5')) > AN_OCCUPATION1 = str(form.getvalue('AN_OCCUPATION1')) > AN_OCCUPATION2 = str(form.getvalue('AN_OCCUPATION2')) > PLURAL_NOUN6 = str(form.getvalue('PLURAL_NOUN6')) > ADJECTIVE4 = str(form.getvalue('ADJECTIVE4')) So you could store something preposted as in '' %(str(form.getvalue('PLURAL_NOUN4'))) # untested code!! HTH tim > > print '' > > print "Our American Universities offer students many" + " " + ADJECTIVE1 > print "courses that will prepare them to become good" + " " + PLURAL_NOUN1 + ". You can get a degree as a Bachelor of" + " " + PLURAL_NOUN2 + ", or tske a regular liberal" + PLURAL_NOUN3 > print "course. Or, if you want to become a/an" + " " + ADJECTIVE2 > print "engineer, you can study" + " " + ADJECTIVE3 > print "mathmatics and differential" + " " + PLURAL_NOUN4 + ". Then after" + " " + NUMBER1 > print "years, if you want to continue your studis, you can write a/an" + " " + NOUN1 > print "and become a Doctor of" + " " + PLURAL_NOUN5 + ". When you get out into the world, if you have a diploma from a university, you will be able to get a job as a/an" + " " + AN_OCCUPATION1 + ". If you don't have a diploma, you will have to take a job as a/an" + " " + AN_OCCUPATION2 + ". So it's important that you study hard in highschool so you will do well on your College Enterence" + " " + PLURAL_NOUN6 + ". Remember, 'A little learning is a/an" + " " + ADJECTIVE4 > print "thing." > > print '' > > #HERE IS MY PROBLEM > # > # > # > # > print """ >
> >
> > >
>
> """ > # > # > #MY PROBLEM IS ABOVE > # > # > print """ >
>
    If you want to input new words, then please fill out the entire form:
>
>
>
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
>
    Don't forget: >
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives. >
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'. >
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns. >
    A VERB is an action word. Run, pitch, jump, and swim are verbs. >
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] > or a room [Bathroom, Kitchen]. >
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. > Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words. >
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , > what is meant is a word that is one of those things. >
    When a PLURAL is asked for be sure to pluralize the word. >
>
ADJECTIVE:: >
PLURAL_NOUN: >
PLURAL_NOUN: >
PLURAL_NOUN: >
ADJECTIVE: >
ADJECTIVE: >
PLURAL_NOUN: >
NUMBER: >
NOUN: >
PLURAL_NOUN: >
AN_OCCUPATION: >
AN_OCCUPATION: >
PLURAL_NOUN: >
ADJECTIVE: >
A_PERSON: >
NOUN: >
NOUN: >
A_PERSON: >
NUMBER: >
NOUN: >
FAMOUS_PERSON: >
VERB: >
NAME: >
NAME: >
NOUN: >
NOUN: >
> > > """ > > form = cgi.FieldStorage() > > if len(form)>0: > ADJECTIVE1 = form.getvalue('ADJECTIVE1') > ADJECTIVE2 = form.getvalue('ADJECTIVE2') > ADJECTIVE3 = form.getvalue('ADJECTIVE3') > ADJECTIVE4 = form.getvalue('ADJECTIVE4') > PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') > PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') > PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') > PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') > PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') > PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') > NUMBER1 = form.getvalue('NUMBER1') > NUMBER2 = form.getvalue('NUMBER2') > NOUN1 = form.gervalue('NOUN1') > NOUN2 = form.getvalue('NOUN2') > NOUN3 = form.getvalue('NOUN3') > NOUN4 = form.getvalue('NOUN4') > NOUN5 = form.getvalue('NOUN5') > NOUN6 = form.getvalue('NOUN6') > AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') > AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') > A_PERSON1 = form.getvalue('A_PERSON1') > A_PERSON2 = form.getvalue('A_PERSON2') > NAME1 = form.getvalue('NAME1') > NAME2 = form.getvalue('NAME2') > VERB1 = form.getvalue('VERB1') > FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') > else: > ADJECTIVE1 = 'blond' > ADJECTIVE2 = 'blond' > ADJECTIVE3 = 'blond' > ADJECTIVE4 = 'blond' > PLURAL_NOUN1 = 'women' > PLURAL_NOUN2 = 'men' > PLURAL_NOUN3 = 'women' > PLURAL_NOUN4 = 'men' > PLURAL_NOUN5 = 'women' > PLURAL_NOUN6 = 'men' > NUMBER1 = '1' > NUMBER2 = '2' > NOUN1 = 'woman' > NOUN2 = 'man' > NOUN3 = 'woman' > NOUN4 = 'man' > NOUN5 = 'woman' > NOUN6 = 'man' > AN_OCCUPATION1 = 'teacher' > AN_OCCUPATION2 = 'waitress' > A_PERSON1 = ' fill in later ' > A_PERSON2 = ' fill in later ' > NAME1 = ' fill in later ' > NAME2 = ' fill in later ' > VERB1 = 'run' > FAMOUS_PERSON1 = 'GOD' > > #!c:/Python22/python.exe > # http://localhost:8080/cgi-bin/final.py > # Program Files\Apache Group\Apache2\cgi-bin\final.py > # Final Lab - python CGI script > # Elizabeth Bernert > > import cgi > import cgitb; cgitb.enable() > > print "Content-type: text/html\n\n" > > print """ >
>
    Please fill out the entire form:
>
    Don't forget: >
    An ADJECTIVE describes something or somebody. Lumpy, soft, blond, ugly, messay, and short are adjectives. >
    An ADVERB tells how something is done. It modifies a verb and usually ends in 'ly'. >
    A NOUN is the name of a person, place, or thing. Woman, sidewalk, umbrella, horse-collar, bathtub, and nose are nouns. >
    A VERB is an action word. Run, pitch, jump, and swim are verbs. >
    When a GEOGRAPHICAL LOCATION is asked for, give any sort of place: a country or city [Spain, Cleaveland] > or a room [Bathroom, Kitchen]. >
    An EXCLAMATION or SILLY WORD is any sort of funny sound, gasp, grunt, or outcry. > Wow! Ouch! Whomp! Ick! Gadzooks! are exclamations and silly words. >
    When a specific word is asked for like NUMBER, A COLOR, AN ANIMAL, or A PART OF THE BODY , > what is meant is a word that is one of those things. >
    When a PLURAL is asked for be sure to pluralize the word. >
>
>
>
> > > > > > > > > > > > > > > > > > > > > > > > > > > > >
ADJECTIVE:: >
PLURAL_NOUN: >
PLURAL_NOUN: >
PLURAL_NOUN: >
ADJECTIVE: >
ADJECTIVE: >
PLURAL_NOUN: >
NUMBER: >
NOUN: >
PLURAL_NOUN: >
AN_OCCUPATION: >
AN_OCCUPATION: >
PLURAL_NOUN: >
ADJECTIVE: >
A_PERSON: >
NOUN: >
NOUN: >
A_PERSON: >
NUMBER: >
NOUN: >
FAMOUS_PERSON: >
VERB: >
NAME: >
NAME: >
NOUN: >
NOUN: >
> > > """ > > form = cgi.FieldStorage() > > if len(form)>0: > ADJECTIVE1 = form.getvalue('ADJECTIVE1') > ADJECTIVE2 = form.getvalue('ADJECTIVE2') > ADJECTIVE3 = form.getvalue('ADJECTIVE3') > ADJECTIVE4 = form.getvalue('ADJECTIVE4') > PLURAL_NOUN1 = form.getvalue('PLURAL_NOUN1') > PLURAL_NOUN2 = form.getvalue('PLURAL_NOUN2') > PLURAL_NOUN3 = form.getvalue('PLURAL_NOUN3') > PLURAL_NOUN4 = form.getvalue('PLURAL_NOUN4') > PLURAL_NOUN5 = form.getvalue('PLURAL_NOUN5') > PLURAL_NOUN6 = form.getvalue('PLURAL_NOUN6') > NUMBER1 = form.getvalue('NUMBER1') > NUMBER2 = form.getvalue('NUMBER2') > NOUN1 = form.gervalue('NOUN1') > NOUN2 = form.getvalue('NOUN2') > NOUN3 = form.getvalue('NOUN3') > NOUN4 = form.getvalue('NOUN4') > NOUN5 = form.getvalue('NOUN5') > NOUN6 = form.getvalue('NOUN6') > AN_OCCUPATION1 = form.getvalue('AN_OCCUPATION1') > AN_OCCUPATION2 = form.getvalue('AN_OCCUPATION2') > A_PERSON1 = form.getvalue('A_PERSON1') > A_PERSON2 = form.getvalue('A_PERSON2') > NAME1 = form.getvalue('NAME1') > NAME2 = form.getvalue('NAME2') > VERB1 = form.getvalue('VERB1') > FAMOUS_PERSON1 = form.getvalue('FAMOUS_PERSON1') > else: > ADJECTIVE1 = 'blond' > ADJECTIVE2 = 'blond' > ADJECTIVE3 = 'blond' > ADJECTIVE4 = 'blond' > PLURAL_NOUN1 = 'women' > PLURAL_NOUN2 = 'men' > PLURAL_NOUN3 = 'women' > PLURAL_NOUN4 = 'men' > PLURAL_NOUN5 = 'women' > PLURAL_NOUN6 = 'men' > NUMBER1 = '1' > NUMBER2 = '2' > NOUN1 = 'woman' > NOUN2 = 'man' > NOUN3 = 'woman' > NOUN4 = 'man' > NOUN5 = 'woman' > NOUN6 = 'man' > AN_OCCUPATION1 = 'teacher' > AN_OCCUPATION2 = 'waitress' > A_PERSON1 = ' fill in later ' > A_PERSON2 = ' fill in later ' > NAME1 = ' fill in later ' > NAME2 = ' fill in later ' > VERB1 = 'run' > FAMOUS_PERSON1 = 'GOD' > #!c:/Python22/python.exe > # http://localhost:8080/cgi-bin/mult.py > # Program Files\Apache Group\Apache2\cgi-bin\mult.py > # Final Project - python CGI script > > import cgi > > import cgitb; cgitb.enable() > > print "Content-type: text/html\n\n" > > form = cgi.FieldStorage() > > ADJECTIVE1 = str(form.getvalue('ADJECTIVE1')) > A_PERSON1 = str(form.getvalue('A_PERSON1')) > NOUN1 = str(form.getvalue('NOUN1')) > PLURAL_NOUN1 = str(form.getvalue('PLURAL_NOUN1')) > NOUN2 = str(form.getvalue('NOUN2')) > NOUN3 = str(form.getvalue('NOUN3')) > A_PERSON2 = str(form.getvalue('A_PERSON2')) > NUMBER1 = str(form.getvalue('NUMBER1')) > PLURAL_NOUN2 = str(form.getvalue('PLRAL_NOUN2')) > NOUN4 = str(form.getvalue('NOUN4')) > PLURAL_NOUN3 = str(form.getvalue('PLURAL_NOUN3')) > > print '' > > print "Well it's time for final exams again. Her are some sample questions with" + " " + ADJECTIVE1 > print "answers that may give you an idea of what final exams are like:" > print "

QUESTION: " > print "
Who was the first president of the United States?" > print "
ANSWER: " > print "
" + A_PERSON1 > print ", who was also called, 'The" + " " + NOUN1 > print "of Our Country." > print "

QUESTION: " > print "
What is the shortest distance between two" + " " + PLURAL_NOUN1 + "?" > print "
ANSWER: " > print "
A straight" + " " + NOUN2 + "." > print "

QUESTION: " > print "Who said, 'I regret that I only have one" + " " + NOUN3 > print "to give for my country.'?" > print "
ANSWER: " > print "
" + A_PERSON2 + "." > > print '' -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com