From danci_emanuel at yahoo.com Sat Jan 1 02:05:25 2011 From: danci_emanuel at yahoo.com (Danci Emanuel) Date: Fri, 31 Dec 2010 17:05:25 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 82, Issue 122 In-Reply-To: Message-ID: <500411.46727.qm@web110412.mail.gq1.yahoo.com> Thank you all for you prompt response! I solved the problem by installing Audiere.Happy New Year and I wish you blessings and successes to you and your loved ones. Regards, Emanuel DANCI --- On Fri, 12/31/10, tutor-request at python.org wrote: From: tutor-request at python.org Subject: Tutor Digest, Vol 82, Issue 122 To: tutor at python.org Date: Friday, December 31, 2010, 3:00 AM Send Tutor mailing list submissions to ??? tutor at 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 at python.org You can reach the person managing the list at ??? tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: ???1. Problem installing pyaudiere (Danci Emanuel) ???2. Re: Problem installing pyaudiere (Peter Otten) ???3. Re: Problem installing pyaudiere (Serdar Dalgic) ???4. Re: Python 2.7.1 interpreter (Frank Chang) _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From psmouty at live.com Sat Jan 1 18:02:51 2011 From: psmouty at live.com (pete) Date: Sat, 1 Jan 2011 17:02:51 +0000 Subject: [Tutor] syntax error that i cant spot! Message-ID: Hi, Please help just starting out and have come up with the following code to create a simple guessing game. on line 30 print good job etc i get a syntax error! sure it's simple but i've looked for ages and cant spot it! Regards Pete -------------- next part -------------- A non-text attachment was scrubbed... Name: guessing game.py Type: text/x-python Size: 832 bytes Desc: not available URL: From abhijeet.1989 at gmail.com Sat Jan 1 18:11:54 2011 From: abhijeet.1989 at gmail.com (Abhijeet Rastogi) Date: Sat, 1 Jan 2011 22:41:54 +0530 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: Message-ID: You missed a "+" after myName on line 30. On Sat, Jan 1, 2011 at 10:32 PM, pete wrote: > Hi, > Please help just starting out and have come up with the following code to > create a simple guessing game. > > on line 30 print good job etc i get a syntax error! sure it's simple but > i've looked for ages and cant spot it! > > Regards > Pete > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Abhijeet Rastogi (shadyabhi) http://www.google.com/profiles/abhijeet.1989 -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Jan 1 18:12:58 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 1 Jan 2011 12:12:58 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: Message-ID: On Sat, Jan 1, 2011 at 12:02 PM, pete wrote: > Hi, > Please help just starting out and have come up with the following code to > create a simple guessing game. > > on line 30 print good job etc i get a syntax error! sure it's simple but > i've looked for ages and cant spot it! > > Regards > Pete print 'Good job, ' + myName + "! You guessed the number in " + guessesTaken + ' guesses!' you forgot to place a plus in between myName and "! You guessed the number in ". > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From knacktus at googlemail.com Sat Jan 1 18:14:38 2011 From: knacktus at googlemail.com (Knacktus) Date: Sat, 01 Jan 2011 18:14:38 +0100 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: Message-ID: <4D1F60FE.2080406@googlemail.com> Am 01.01.2011 18:02, schrieb pete: > Hi, > Please help just starting out and have come up with the following code > to create a simple guessing game. > > on line 30 print good job etc i get a syntax error! sure it's simple but > i've looked for ages and cant spot it! There's a + missing after myName Also, I would use the same type of quotation marks. Not mixing '' and "". > > Regards > Pete > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From smokefloat at gmail.com Sat Jan 1 18:28:50 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 1 Jan 2011 12:28:50 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F60FE.2080406@googlemail.com> References: <4D1F60FE.2080406@googlemail.com> Message-ID: You also can place: else: print " this is not a number" And: if guess == number: break if guess == number: guessesTaken = str(guessesTaken) print 'Good job, ' + myName + "! You guessed the number in " + guessesTaken + ' guesses!' which could be combined. if guess == number: guessesTaken = str(guessesTaken) print 'Good job, ' + myName + "! You guessed the number in " + guessesTaken + ' guesses!' From beachkidken at gmail.com Sat Jan 1 20:28:45 2011 From: beachkidken at gmail.com (Ken Green) Date: Sat, 01 Jan 2011 14:28:45 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: Message-ID: <4D1F806D.6030400@gmail.com> I am caught off guard but what is the purpose of the plus sign? I don't recall seeing it used like that. Ken On 01/01/2011 12:11 PM, Abhijeet Rastogi wrote: > You missed a "+" after myName on line 30. > > On Sat, Jan 1, 2011 at 10:32 PM, pete > wrote: > > Hi, > Please help just starting out and have come up with the following > code to create a simple guessing game. > > on line 30 print good job etc i get a syntax error! sure it's > simple but i've looked for ages and cant spot it! > > Regards > Pete > > _ > > From kb1pkl at aim.com Sat Jan 1 20:34:45 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 01 Jan 2011 14:34:45 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F806D.6030400@gmail.com> References: <4D1F806D.6030400@gmail.com> Message-ID: <4D1F81D5.7000704@aim.com> On 01/01/2011 02:28 PM, Ken Green wrote: > I am caught off guard but what is the purpose of the plus sign? I don't > recall seeing it used like that. > > Ken > > On 01/01/2011 12:11 PM, Abhijeet Rastogi wrote: >> You missed a "+" after myName on line 30. >> >> On Sat, Jan 1, 2011 at 10:32 PM, pete > > wrote: >> >> Hi, >> Please help just starting out and have come up with the following >> code to create a simple guessing game. >> >> on line 30 print good job etc i get a syntax error! sure it's >> simple but i've looked for ages and cant spot it! >> >> Regards >> Pete >> >> _ >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor The + operator in this case concatenates, or joins, two strings. "Hello, " + "World" == "Hello, World" From bgailer at gmail.com Sat Jan 1 20:46:42 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 01 Jan 2011 14:46:42 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F806D.6030400@gmail.com> References: <4D1F806D.6030400@gmail.com> Message-ID: <4D1F84A2.3000805@gmail.com> On 1/1/2011 2:28 PM, Ken Green wrote: > I am caught off guard but what is the purpose of the plus sign? I > don't recall seeing it used like that. I just tried to look that up in the Python Manuals. No success! Where is it hiding? >>> a = 'a' >>> b = 'b' >>> c = a + b >>> print c ab Now you can recall seeing it. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sat Jan 1 20:50:47 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 01 Jan 2011 14:50:47 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F806D.6030400@gmail.com> References: <4D1F806D.6030400@gmail.com> Message-ID: <4D1F8597.2000507@gmail.com> On 1/1/2011 2:28 PM, Ken Green wrote: > I am caught off guard but what is the purpose of the plus sign? I > don't recall seeing it used like that. I just tried to look that up in the Python Manuals. No success! Where is it hiding? *** OOPS just found it in section 6.6 Sequence Types s + t the concatenation of s and t >>> a = 'a' >>> b = 'b' >>> c = a + b >>> print c ab Now you can recall seeing it. -- Bob Gailer 919-636-4239 Chapel Hill NC From enalicho at gmail.com Sat Jan 1 20:52:55 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 1 Jan 2011 19:52:55 +0000 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F806D.6030400@gmail.com> References: <4D1F806D.6030400@gmail.com> Message-ID: > > > I am caught off guard but what is the purpose of the plus sign? I don't > recall seeing it used like that. > The + sign there is used for concating two strings together, for example - output = 'foo' + 'bar' Will give the variable output the value of the characters 'foobar'. This also works with mixed values of variables holding strings and raw strings, for example - foo = 'foo' output = foo + 'bar' Which gives the same output as my previous example. To OP: I would not use the method you have used, but rather use string formatting, so I would use on line 10 - print 'Well, %s, I am thinking of a number between 1 & 20.' % (myName) And on line 30 (which won't need the str(guessesTaken) on line 29) - print 'Good job, %s! You guessed the number in %d guesses!' % (myName, guessesTaken) And then finally on line 34 - print 'Nope. The number I was thinking of was %d' % (number) By the way, for readability, tryToavoidCamelCase. I also recommend you look into functions, classes, and exceptions - this example is a good one with a lot of room to grow :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From beachkidken at gmail.com Sat Jan 1 20:58:25 2011 From: beachkidken at gmail.com (Ken Green) Date: Sat, 01 Jan 2011 14:58:25 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D1F84A2.3000805@gmail.com> References: <4D1F806D.6030400@gmail.com> <4D1F84A2.3000805@gmail.com> Message-ID: <4D1F8761.4080301@gmail.com> He had no space between the plus sign and the name value and that threw me. I am so used to using a space before or after the plus sign. Ken On 01/01/2011 02:46 PM, bob gailer wrote: > On 1/1/2011 2:28 PM, Ken Green wrote: >> I am caught off guard but what is the purpose of the plus sign? I >> don't recall seeing it used like that. > > I just tried to look that up in the Python Manuals. No success! Where > is it hiding? > > >>> a = 'a' > >>> b = 'b' > >>> c = a + b > >>> print c > ab > > Now you can recall seeing it. > From alan.gauld at btinternet.com Sun Jan 2 03:10:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2011 02:10:42 -0000 Subject: [Tutor] syntax error that i cant spot! References: <4D1F806D.6030400@gmail.com> Message-ID: "Noah Hall" wrote > By the way, for readability, tryToavoidCamelCase. Why avoidCamelCase? I actually prefer it to using_non_camel_case But it's been the standard in OOP languages since at least Smalltalk 80 (ie 1980) so I guess I'm just used to it... Alan G. From enalicho at gmail.com Sun Jan 2 04:27:10 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 2 Jan 2011 03:27:10 +0000 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: It's part of the Python naming conventions laid out by PEP 8. Have a read here - http://www.python.org/dev/peps/pep-0008/. Hope this helps. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 2 10:34:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2011 09:34:15 -0000 Subject: [Tutor] syntax error that i cant spot! References: <4D1F806D.6030400@gmail.com> Message-ID: "Noah Hall" wrote > It's part of the Python naming conventions laid out by PEP 8. Have a > read > here - http://www.python.org/dev/peps/pep-0008/. I'm quite familiar with PEP8 - although I disagree with quite a lot of it too! But PEP 8 is about consistency of style not "readability" which was what was claimed about CamelCase. I'm not aware of any studies which show CamelCase as being significantly less readable than underline_seperators. And even PEP8 encourages the use of CamelCase for classes or where it is already being used. Where it refers to readability in the use of underscores its referring to using the underscores to add readability ie bank_account rather than bankaccount, not in contrast to BankAccount. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From enalicho at gmail.com Sun Jan 2 14:52:32 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 2 Jan 2011 13:52:32 +0000 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: He has no classes in there. Therefore, there is no place it should be in this code. Please remember this is Python, and not Java nor anything else. To quote directly from PEP 8, in regards to functions and variables, "should be lowercase, with words separated by underscoresas necessary to improve readability.". Notice the word "readability" there ;). It's not a big issue when you're working by yourself, but when working with multiple people, or asking for help (like the OP here), you should stick to the conventions of that language. it saves you time when you're trying to read other people's code, it saves others' time when they try to read your code and it saves time when they try and fix your code. It just makes life easier. -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Sun Jan 2 15:40:57 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Sun, 2 Jan 2011 09:40:57 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld wrote: > Why avoidCamelCase? I actually prefer it to using_non_camel_case The readability is an often argued topic - I myself find the space of names_in_underscores to be more readable (words are distinct), but I try to follow the common conventions of the languages I'm using, and Python appears to use camelCase more than not. -- Brett Ritter / SwiftOne swiftone at swiftone.org From hugo.yoshi at gmail.com Sun Jan 2 15:59:29 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 2 Jan 2011 15:59:29 +0100 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: On Sun, Jan 2, 2011 at 3:40 PM, Brett Ritter wrote: > On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld wrote: >> Why avoidCamelCase? I actually prefer it to using_non_camel_case > > The readability is an often argued topic - I myself find the space of > names_in_underscores to be more readable (words are distinct), but I > try to follow the common conventions of the languages I'm using, and > Python appears to use camelCase more than not. > according to PEP 8, python doesn't use camelCase (mixedCase, as they call it) at all. Or shouldn't, in any case. No pun intended. For classnames you should use CapWords. The only difference with camelCase is the initial character. variable and function names should use lower_case_with_underscores. Hugo From kb1pkl at aim.com Sun Jan 2 16:00:59 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 02 Jan 2011 10:00:59 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: <4D20932B.4060305@aim.com> On 01/02/2011 09:40 AM, Brett Ritter wrote: > On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld wrote: >> Why avoidCamelCase? I actually prefer it to using_non_camel_case > > The readability is an often argued topic - I myself find the space of > names_in_underscores to be more readable (words are distinct), but I > try to follow the common conventions of the languages I'm using, and > Python appears to use camelCase more than not. > I tend to disagree with that. In the stdlib, as well as the builtins, many, many methods are alllowercase, for example str.isdigit() or socket.gethostname(). From alan.gauld at btinternet.com Sun Jan 2 16:52:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2011 15:52:07 -0000 Subject: [Tutor] syntax error that i cant spot! References: <4D1F806D.6030400@gmail.com> <4D20932B.4060305@aim.com> Message-ID: "Corey Richardson" wrote >> On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld >> wrote: >>> Why avoidCamelCase? I actually prefer it to using_non_camel_case >> >> Python appears to use camelCase more than not. >> > > I tend to disagree with that. In the stdlib, as well as the > builtins, > many, many methods are alllowercase, for example str.isdigit() or > socket.gethostname(). Which should, according to PEP8, be get_hostname()(*) and is_digit()... The stdlib is a mess of inconsistency. I assume that's why PEP8 seems to get more attention these days - it's been around for ages. Some modules use CamelCase, some use underscores and some just use long lowercase names (the worst option! - well apart from all uppercase like COBOL...!) (*)hostname could be host_name I guess but Unix tradition spells it as one word so I've followed that convention... Alan G From beachkidken at gmail.com Sun Jan 2 17:02:39 2011 From: beachkidken at gmail.com (Ken Green) Date: Sun, 02 Jan 2011 11:02:39 -0500 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: <4D20A19F.5040508@gmail.com> I generally prefer Camel Case as easily to use as it would be more difficult for me as a touch typist to hunt and peck for the underscore. Ken On 01/02/2011 09:40 AM, Brett Ritter wrote: > On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld wrote: >> Why avoidCamelCase? I actually prefer it to using_non_camel_case > The readability is an often argued topic - I myself find the space of > names_in_underscores to be more readable (words are distinct), but I > try to follow the common conventions of the languages I'm using, and > Python appears to use camelCase more than not. > From waynejwerner at gmail.com Mon Jan 3 02:58:04 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 2 Jan 2011 19:58:04 -0600 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> <4D20932B.4060305@aim.com> Message-ID: On Sun, Jan 2, 2011 at 9:52 AM, Alan Gauld wrote: > "Corey Richardson" wrote > > On Sat, Jan 1, 2011 at 9:10 PM, Alan Gauld >>> wrote: >>> >>>> Why avoidCamelCase? I actually prefer it to using_non_camel_case >>>> >>> >>> Python appears to use camelCase more than not. >>> >>> >> I tend to disagree with that. In the stdlib, as well as the builtins, >> many, many methods are alllowercase, for example str.isdigit() or >> socket.gethostname(). >> > > Which should, according to PEP8, be get_hostname()(*) and > is_digit()... > > The stdlib is a mess of inconsistency. I assume that's why PEP8 > seems to get more attention these days - it's been around for ages. > Some modules use CamelCase, some use underscores and > some just use long lowercase names (the worst option! - well > apart from all uppercase like COBOL...!) > Well, PEP8 does suggest that the preference is 1) lowercase names unless readability suffers, such as in goallist or something that can be improved, then 2) goal_list is preferred over goalList, unless 3) existing code uses theOtherWay. Personally I feel lowercase_with_underscores to be more readable than lowercaseWithoutUnderscores, although since I took that (required) Java class my junior year, I'm used to typingIncrediblyLongNamesThatAreRidiculouslyVerboseTellingYouEverythingThatTheClassOrFunctionMayOrMayNotDo, in that style of case. I am firmly convinced that Java is the reason IDEs with really good auto complete were developed ;) I try to code according to PEP8, and write all my functions/variables using onlylowercase except when_i_cant_tell_what_that_word_is. And of course I try to make my variables as short as possible, but no shorter :) -lowercasefully, wayne_werner > > (*)hostname could be host_name I guess but Unix tradition > spells it as one word so I've followed that convention... > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Mon Jan 3 13:03:32 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Mon, 3 Jan 2011 13:03:32 +0100 Subject: [Tutor] more scraping and saving Message-ID: <005301cbab3e$43fda710$cbf8f530$@kaasogmulvad.dk> Hi - I was helped the other day in an attempt to scrape and save a simple web page. I'm using what I learned and trying another. It should be very simple, but I only get the first row of names saved. Can anybody help with an explanation? (It's a public list of names of doctors with knows connections to the farmaceutical industry). This time I try to start at the right table (the third on the page) by using the class attribute. Does that make sense? Thanks in advance - here is the code: import urllib2 from BeautifulSoup import BeautifulSoup import codecs f = codecs.open("laeger.txt", "w", encoding="Latin-1") soup = BeautifulSoup(urllib2.urlopen('http://www.laegemiddelstyrelsen.dk/include/88 06/tilladelse_laeger.asp').read()) for row in soup('table', {'class' : 'tableLeftRight3030'}): tds = row('td') output = ";".join(tds[i].string for i in (0, 1, 2, 3, 4)) f.write(output + '\n') f.close() Tommy Kaas Kaas & Mulvad Lykkesholms Alle 2A, 3. 1902 Frederiksberg C Mobil: 27268818 Mail: tommy.kaas at kaasogmulvad.dk Web: www.kaasogmulvad.dk -------------- next part -------------- An HTML attachment was scrubbed... URL: From neo_vector at yahoo.com Mon Jan 3 15:52:26 2011 From: neo_vector at yahoo.com (Neo Vector) Date: Mon, 3 Jan 2011 22:52:26 +0800 (SGT) Subject: [Tutor] How does it work? Message-ID: <873771.11545.qm@web77114.mail.sg1.yahoo.com> Hi All, Could you explain me how does it work, pls? ============================== >>>r = '' >>>for c in 'abcd': r = c + r ... ... >>>r 'dcba' ============================== Best Regards, Neo Vector -------------- next part -------------- An HTML attachment was scrubbed... URL: From shrvtsnvs at gmail.com Mon Jan 3 16:02:18 2011 From: shrvtsnvs at gmail.com (Shrivats) Date: Mon, 3 Jan 2011 20:32:18 +0530 Subject: [Tutor] How does it work? In-Reply-To: <873771.11545.qm@web77114.mail.sg1.yahoo.com> References: <873771.11545.qm@web77114.mail.sg1.yahoo.com> Message-ID: <20110103150218.GA3185@zorander> On Mon, Jan 03, 2011 at 10:52:26PM +0800, Neo Vector wrote: > Hi All, Hello, > Could you explain me how does it work, pls? Sure, I'm not telling you how that works. However, I'll alter your code snippet a little bit and see if you can understand after that. > ============================== > >>>r = '1' > >>>for c in 'abcd': print r > r = c + r > ... > ... 1 a1 ba1 cba1 > >>>r > 'dcba1' > ============================== Let me know if you still face problems. HTH, Shrivats From shrvtsnvs at gmail.com Mon Jan 3 16:26:22 2011 From: shrvtsnvs at gmail.com (Shrivats) Date: Mon, 3 Jan 2011 20:56:22 +0530 Subject: [Tutor] How does it work? In-Reply-To: <20110103150218.GA3185@zorander> References: <873771.11545.qm@web77114.mail.sg1.yahoo.com> <20110103150218.GA3185@zorander> Message-ID: <20110103152622.GA3291@zorander> On Mon, Jan 03, 2011 at 08:32:18PM +0530, Shrivats wrote: > On Mon, Jan 03, 2011 at 10:52:26PM +0800, Neo Vector wrote: > > Hi All, > Hello, > > Could you explain me how does it work, pls? > > Sure, I'm not telling you how that works. However, I'll alter your code snippet > a little bit and see if you can understand after that. > > ============================== > > >>>r = '1' > > >>>for c in 'abcd': > print r > > r = c + r > > ... > > ... > 1 > a1 > ba1 > cba1 > > >>>r > > 'dcba1' > > ============================== > > Let me know if you still face problems. Oh, and for more information - http://docs.python.org/tutorial/introduction.html#strings http://docs.python.org/tutorial/controlflow.html#for-statements Specifically, the idea behind this is, Strings are basically a list of characters. So they can be treated as iterable collections. :) > > HTH, > > Shrivats From alan.gauld at btinternet.com Mon Jan 3 17:09:48 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Jan 2011 16:09:48 -0000 Subject: [Tutor] How does it work? References: <873771.11545.qm@web77114.mail.sg1.yahoo.com> Message-ID: "Neo Vector" wrote > Could you explain me how does it work, pls? > ============================== >>>>r = '' r is an empty string >>>>for c in 'abcd': c takes the value of each letter in turn > r = c + r strings can be added such that the result is the concatenation of the two strings. So in this case: r becomes the sum of its old value and the current value of c repeat for the next value of c. If that doesn't help then tell us which bit(s) of it you don't understand. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From patty at cruzio.com Mon Jan 3 18:06:22 2011 From: patty at cruzio.com (Patty) Date: Mon, 3 Jan 2011 09:06:22 -0800 Subject: [Tutor] How does it work? Message-ID: ----- Original Message ----- From: "Patty" To: "Alan Gauld" Sent: Monday, January 03, 2011 9:05 AM Subject: Re: [Tutor] How does it work? > Hi Folks - I read this code and tried to parse it as a pop quiz for myself > ;) and have a question, maybe 2 clarifications, below: > > ----- Original Message ----- > From: "Alan Gauld" > To: > Sent: Monday, January 03, 2011 8:09 AM > Subject: Re: [Tutor] How does it work? > > >> "Neo Vector" wrote >>> Could you explain me how does it work, pls? >>> ============================== >>>>>>r = '' >> >> r is an empty string >> >>>>>>for c in 'abcd': >> >> c takes the value of each letter in turn >> >>> r = c + r > > When I first looked at this - I thought that the variable 'c' would have > had to be initialized > first earlier in the program. And I thought that the programmer would > input a single char or a single space. I wasn't thinking counting > variable for some reason. So is 'for c in', one or more of key words that > Python understands that a loop is here and to actually trigger counting in > a loop? Does it start with a 1 or 0 internally to do this? > > I also realized a mistake I may have made - maybe I confused 'for c in' > with 'while c in'. > > r='' > c="d" > while c in 'abcd': > r=c+r > > Or > > r='' > c="d" > while c in ['a', 'b', 'c', 'd']: > r=c+r > > Also for myself I think I would have used different descriptive names for > variables so that would have been less likely to throw myself off. And > also doing this fast to see if I have learned. > > I really feel comfortable with Python now after six months and my small > application is completed and looks really good. I don't know how I would > have been able to make the simplest, smallest GUI part of my application - > using Tkinter and PIL- fast without the references and explanations of > Wayne Werner and Alan - Thanks to those on the list who are so helpful! > > Patty > > >> >> strings can be added such that the result is the concatenation of the two >> strings. So in this case: >> r becomes the sum of its old value and the current value of c >> >> repeat for the next value of c. >> >> If that doesn't help then tell us which bit(s) of it you don't >> understand. >> >> HTH, >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > From davea at ieee.org Mon Jan 3 18:52:50 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Jan 2011 12:52:50 -0500 Subject: [Tutor] How does it work? In-Reply-To: References: Message-ID: <4D220CF2.4040206@ieee.org> On 01/-10/-28163 02:59 PM, Patty wrote: > >>>>>>> for c in 'abcd': >>> >>> ...... >> When I first looked at this - I thought that the variable 'c' would >> have had to be initialized >> first earlier in the program. And I thought that the programmer would >> input a single char or a single space. I wasn't thinking counting >> variable for some reason. So is 'for c in', one or more of key words >> that Python understands that a loop is here and to actually trigger >> counting in a loop? Does it start with a 1 or 0 internally to do this? >> There's not necessarily any integer indexing going on. for xxx in yyy is a specific syntax that specifies a loop based on a sequence. In this case the string 'abcd' is a sequence of chars, so you get c to have a value of 'a', 'b', 'c', and 'd'. But other sequences might not have any index meaning at all, so it doesn't make sense to ask if it's 0 or 1 based. For example, you can iterate over the keys of a map, where the order is irrelevant. All you really know is you'll get them all if you finish the loop. >> I also realized a mistake I may have made - maybe I confused 'for c >> in' with 'while c in'. >> >> r='' >> c="d" >> while c in 'abcd': >> r=c+r >> You messed up the indentation. But if the r=c+r line is indented, then this is an infinite loop. It'll quit when memory is exhausted. Why? Because nothing in the loop changes c. So since it's in the sequence at the beginning, it will always be. >> Or >> >> r='' >> c="d" >> while c in ['a', 'b', 'c', 'd']: >> r=c+r >> Similarly here. >> Also for myself I think I would have used different descriptive names >> for variables so that would have been less likely to throw myself off. Good idea. >> And also doing this fast to see if I have learned. >> >> I really feel comfortable with Python now after six months and my >> small application is completed and looks really good. I don't know how >> I would have been able to make the simplest, smallest GUI part of my >> application - using Tkinter and PIL- fast without the references and >> explanations of Wayne Werner and Alan - Thanks to those on the list >> who are so helpful! >> >> Patty >> HTH DaveA From alan.gauld at btinternet.com Mon Jan 3 19:29:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Jan 2011 18:29:39 -0000 Subject: [Tutor] How does it work? References: Message-ID: "Patty" wrote >>>>>>>for c in 'abcd': >>> c takes the value of each letter in turn >> When I first looked at this - I thought that the variable 'c' would >> have had to be initialized first earlier in the program. It is initialized earluier - in the for statement, each time through the loop it gets reinitialized to a new value. >> ... I wasn't thinking counting variable for some reason. So is >> 'for c in', one or more of key words that Python understands that a >> loop is here and to actually trigger counting in a loop? Does it >> start with a 1 or 0 internally to do this? In the case of a for loop it doesn't count as such. It takes each value from a sequience and applies it to the loop variable. Personally I think it wouyld have read better if they called it "foreach" so your loop would look like foreach char in 'abcd': or foreach item in [1,2,3,4]: etc... But they didn't so we are stuck with for. >> I also realized a mistake I may have made - maybe I confused 'for c >> in' >> while c in 'abcd': This is completely different. In this case we can clarify it by adding some parentheses: while (c in 'abcd'): the test is all of the bit in parens. And the test is a test of whether c is in the string or not. Python does not modify the variable 'c' in this case, that only happens with a for loop. You can read more about the various python loop structures in the loops topic of my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From patty at cruzio.com Mon Jan 3 20:24:44 2011 From: patty at cruzio.com (Patty) Date: Mon, 3 Jan 2011 11:24:44 -0800 Subject: [Tutor] How does it work? References: <4D220CF2.4040206@ieee.org> Message-ID: <710003EE097B4CACA1F6D1FCC0841FCC@mycomputer> Yes, I knew there was something I wasn't getting. This is the explanation I was looking for - and I'm sorry about the incorrect indentation. And I agree with Alan that 'foreach' would have been a good name for this type of loop. I need to sort out 'loop structures' in my notes and read up on these for sure. Thanks, Patty ----- Original Message ----- From: "Dave Angel" To: "Patty" Cc: Sent: Monday, January 03, 2011 9:52 AM Subject: Re: [Tutor] How does it work? > On 01/-10/-28163 02:59 PM, Patty wrote: >> >>>>>>>> for c in 'abcd': >>>> >>>> ...... >>> When I first looked at this - I thought that the variable 'c' would >>> have had to be initialized >>> first earlier in the program. And I thought that the programmer would >>> input a single char or a single space. I wasn't thinking counting >>> variable for some reason. So is 'for c in', one or more of key words >>> that Python understands that a loop is here and to actually trigger >>> counting in a loop? Does it start with a 1 or 0 internally to do this? >>> > > There's not necessarily any integer indexing going on. for xxx in yyy > is a specific syntax that specifies a loop based on a sequence. In this > case the string 'abcd' is a sequence of chars, so you get c to have a > value of 'a', 'b', 'c', and 'd'. But other sequences might not have any > index meaning at all, so it doesn't make sense to ask if it's 0 or 1 > based. For example, you can iterate over the keys of a map, where the > order is irrelevant. All you really know is you'll get them all if you > finish the loop. > >>> I also realized a mistake I may have made - maybe I confused 'for c >>> in' with 'while c in'. >>> >>> r='' >>> c="d" >>> while c in 'abcd': >>> r=c+r >>> > > You messed up the indentation. But if the r=c+r line is indented, then > this is an infinite loop. It'll quit when memory is exhausted. Why? > Because nothing in the loop changes c. So since it's in the sequence at > the beginning, it will always be. > >>> Or >>> >>> r='' >>> c="d" >>> while c in ['a', 'b', 'c', 'd']: >>> r=c+r >>> > > Similarly here. > >>> Also for myself I think I would have used different descriptive names >>> for variables so that would have been less likely to throw myself off. > > Good idea. > >>> And also doing this fast to see if I have learned. >>> >>> I really feel comfortable with Python now after six months and my >>> small application is completed and looks really good. I don't know how >>> I would have been able to make the simplest, smallest GUI part of my >>> application - using Tkinter and PIL- fast without the references and >>> explanations of Wayne Werner and Alan - Thanks to those on the list >>> who are so helpful! >>> >>> Patty >>> > > HTH > > DaveA > > From scarolan at gmail.com Mon Jan 3 21:59:15 2011 From: scarolan at gmail.com (Sean Carolan) Date: Mon, 3 Jan 2011 14:59:15 -0600 Subject: [Tutor] matplotlib.pylab.plotfile formatting help Message-ID: I've got a csv file that contains two data fields, the short name of a month and an integer. I'm experimenting with pylab and ipython to get a feel for how pylab works. I'm able to generate a bar graph from my data, but there are two problems with it: 1. I don't want "2011" appended to the month names. This data is from 2010, and I only want the short month name under each bar. 2. The bars are very narrow and I'm not sure how to widen them. Here's my CSV data, stored in a file called csvdata.csv: month,systems Jan,17 Feb,49 Mar,77 Apr,59 May,42 Jun,137 Jul,102 Aug,115 Sep,57 Oct,134 Nov,131 Dec,197 And here's the "ipython -pylab" command that I'm using to generate the graph: plotfile('csvdata.csv', ('month', 'systems'), plotfuncs={'systems': 'bar'},) I've read through some of the documentation for matplotlib, but having never used matlab or pylab before today it's a bit confusing. Does anyone know how to solve #1 and #2 above? From tim at johnsons-web.com Mon Jan 3 23:46:47 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Jan 2011 13:46:47 -0900 Subject: [Tutor] Initialize values from a text input file Message-ID: <20110103224647.GA2497@johnsons-web.com> I'm just have a little fun here, but I bet that comments will help further elighten me on the subtleties of python. consider the following console session: >>> L = ['foo','bar'] >>> locals()[L[0]] = L[1] >>> foo 'bar' >>> 'foobar' in locals() False >>> 'foo' in locals() True >>> locals() {'__builtins__': , 'L': ['foo', 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar', '__doc__': None} Given that I have a text file as input with names and values with a seperator (TAB, for instance) I could initialize variables in a local scope, or I could build a dictionary. Actually the dictionary is preferable for the targeted application. However, for the sake of edification, I would welcome comments on the session above, and let's pretend that `L' is the result of a line read from a file and split on '\t'. TIA tim -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From alan.gauld at btinternet.com Tue Jan 4 00:26:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Jan 2011 23:26:43 -0000 Subject: [Tutor] Initialize values from a text input file References: <20110103224647.GA2497@johnsons-web.com> Message-ID: "Tim Johnson" wrote > consider the following console session: >>>> L = ['foo','bar'] >>>> locals()[L[0]] = L[1] >>>> foo > 'bar' >>>> locals() > {'__builtins__': , 'L': ['foo', > 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar', > '__doc__': None} > > I could initialize variables in a local scope, or I could build a > dictionary. Actually the dictionary is preferable for the targeted > application. Except in extreme cases I'd say a dictionary was better in almost any situation. Messing with locals() is a dodgy business at best, and can lead to debugging insanity at worst, its better to keep externally initialized data explicit in almost every case. > However, for the sake of edification, I would welcome comments on > the session above, and let's pretend that `L' is the result of a > line read from a file and split on '\t'. My only comment: Don't go there... creating random variables in your namespace that don't actually appear in your code makes using global variables seem positively benign. Once you create them what are you going to do? Litter your code with try: doSomething(withNameThatMightExist) except NameError: doSomethingElse() It is a minefield just waiting to suck you in. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Jan 4 00:46:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 04 Jan 2011 10:46:58 +1100 Subject: [Tutor] Initialize values from a text input file In-Reply-To: <20110103224647.GA2497@johnsons-web.com> References: <20110103224647.GA2497@johnsons-web.com> Message-ID: <4D225FF2.9070500@pearwood.info> Tim Johnson wrote: > I'm just have a little fun here, but I bet that comments will help > further elighten me on the subtleties of python. > > consider the following console session: >>>> L = ['foo','bar'] >>>> locals()[L[0]] = L[1] This will not do what you think it does. In general, local variables are not writable except the normal way by `name = value` assignment. Try this function: def spam(): x = 1 print(x) locals()['x'] = 2 print(x) The fact that assignment to locals() works in the top-level global scope is an accident of implementation. >>>> foo > 'bar' >>>> 'foobar' in locals() > False >>>> 'foo' in locals() > True >>>> locals() > {'__builtins__': , 'L': ['foo', > 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar', > '__doc__': None} > > Given that I have a text file as input with names and values > with a seperator (TAB, for instance) > I could initialize variables in a local scope, or I could build a > dictionary. Actually the dictionary is preferable for the targeted > application. Have you considered using the ConfigParser module? > However, for the sake of edification, I would welcome comments on > the session above, and let's pretend that `L' is the result of a > line read from a file and split on '\t'. (1) This won't work except in the global scope. (2) Even if it did work, do you trust the source of the text? Taking external data provided by arbitrary untrusted users and turning it into variables is a good way to have your computer owned by bad guys. This technique would make your software vulnerable to code injection attacks. You *might* be safe, if you never eval() or exec() the strings coming out of the file. But I wouldn't bet the security of my application on that -- especially if it were running in a web browser or on a server. Actually, no, that's wrong -- even if you never use eval() or exec(), you're still vulnerable to Denial Of Service attacks if the attacker can put junk you don't expect into the file. Something as trivial as: number = abc in the input file could crash your application, if you aren't performing sufficient data validation when you use "number". Or they can shadow builtins and stop your code from working: len = 123 # later... len(some_list) # this will fail This isn't a theoretical threat, something like 3 or 4 out of 5 security vulnerabilities these days are code injection attacks, and there are a LOT of security vulnerabilities. (The majority of these are SQL injections.) At the very least, you should pass the items through a white list of allowed variable names, and validate the values. Do not use a black list of forbidden variables! The problem with the black list idea is that it assumes that you can think of every possible vulnerability ahead of time. You can't. -- Steven From tim at johnsons-web.com Tue Jan 4 01:13:36 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Jan 2011 15:13:36 -0900 Subject: [Tutor] Initialize values from a text input file In-Reply-To: <4D225FF2.9070500@pearwood.info> References: <20110103224647.GA2497@johnsons-web.com> <4D225FF2.9070500@pearwood.info> Message-ID: <20110104001336.GB2497@johnsons-web.com> * Steven D'Aprano [110103 15:03]: > Tim Johnson wrote: >> I'm just have a little fun here, but I bet that comments will help >> further elighten me on the subtleties of python. >> >> consider the following console session: >>>>> L = ['foo','bar'] >>>>> locals()[L[0]] = L[1] > > This will not do what you think it does. In general, local variables are > not writable except the normal way by `name = value` assignment. Try > this function: > > def spam(): > x = 1 > print(x) > locals()['x'] = 2 > print(x) > > > The fact that assignment to locals() works in the top-level global scope > is an accident of implementation. :) thanks for doing my homework for me. > > Have you considered using the ConfigParser module? Good tip. I will look at it > (1) This won't work except in the global scope. > > (2) Even if it did work, do you trust the source of the text? Taking > external data provided by arbitrary untrusted users and turning it into > variables is a good way to have your computer owned by bad guys. Say what? I'm not talking about anything accessible by "arbitrary users". Sorry if I gave that impression! Thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From tim at johnsons-web.com Tue Jan 4 01:16:03 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Jan 2011 15:16:03 -0900 Subject: [Tutor] Initialize values from a text input file In-Reply-To: References: <20110103224647.GA2497@johnsons-web.com> Message-ID: <20110104001603.GC2497@johnsons-web.com> * Alan Gauld [110103 14:47]: > > "Tim Johnson" wrote > >> consider the following console session: >>>>> L = ['foo','bar'] >>>>> locals()[L[0]] = L[1] >>>>> foo >> 'bar' >>>>> locals() >> {'__builtins__': , 'L': ['foo', >> 'bar'], '__package__': None, '__name__': '__main__', 'foo': 'bar', >> '__doc__': None} >> >> I could initialize variables in a local scope, or I could build a >> dictionary. Actually the dictionary is preferable for the targeted >> application. Actually, the dictionary is the target medium > Except in extreme cases I'd say a dictionary was better in almost any > situation. Messing with locals() is a dodgy business at best, and can > lead to debugging insanity at worst, its better to keep externally > initialized data explicit in almost every case. I agree, that's why I said I "was having a little fun". Now, Alan, do you know anything about PHP? If you do, can you comment on the PHP extract() function? thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From mehgcap at gmail.com Tue Jan 4 01:47:56 2011 From: mehgcap at gmail.com (Alex Hall) Date: Mon, 3 Jan 2011 19:47:56 -0500 Subject: [Tutor] subclass not inheriting attributes? Message-ID: Hi all, I have a solitaire game in which I use a "Pile" class. This class is meant to hold a bunch of cards, so I subclass it for the deck, the ace stacks, and the seven main stacks, defining rules and methods for each but also relying on the parent Pile class's methods and attributes. However, I keep getting an error that an attribute in the parent does not exist in the child. Below is a simplified example, but it gives me the exact same error: child object has no attribute l. class parent(object): def __init__(self, l=None): if l is None: l=[] class child(parent): def __init__(self, *args, **kwords): super(parent, self).__init__(*args, **kwords) self.l.append(5) c=child() print c.l Again, I get an error saying that 'child' object has no attribute 'l'. Python 2.7 on win7x64. Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Tue Jan 4 02:06:04 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Jan 2011 01:06:04 -0000 Subject: [Tutor] Initialize values from a text input file References: <20110103224647.GA2497@johnsons-web.com> <20110104001603.GC2497@johnsons-web.com> Message-ID: "Tim Johnson" wrote > Now, Alan, do you know anything about PHP? If you do, can you > comment on the PHP extract() function? I know enough basic PHP to read a page with code in it and get the general drift. I've never written a line of it and have learned enough about it that I don't want to! :-) Now as for extract() - it doesn't appear in my Teach Yourself PHP book, so nope, I've no idea what it does, I'd need to look it up. And I'm way too lazy, and it's way too late to do that! :-) Alan G. From alan.gauld at btinternet.com Tue Jan 4 02:07:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Jan 2011 01:07:37 -0000 Subject: [Tutor] subclass not inheriting attributes? References: Message-ID: "Alex Hall" wrote > class parent(object): > def __init__(self, l=None): > if l is None: l=[] l is a local variable inside init(). You wanted self.l... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Tue Jan 4 02:12:20 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Jan 2011 01:12:20 +0000 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On 4 January 2011 00:47, Alex Hall wrote: > class parent(object): > def __init__(self, l=None): > if l is None: l=[] > Missing "self". Perhaps you meant: class parent(object): def __init__(self, l=None): if l is None: self.l=[] else: self.l=l Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Jan 4 02:13:50 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 3 Jan 2011 19:13:50 -0600 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On Mon, Jan 3, 2011 at 6:47 PM, Alex Hall wrote: > Hi all, > I have a solitaire game in which I use a "Pile" class. This class is > meant to hold a bunch of cards, so I subclass it for the deck, the ace > stacks, and the seven main stacks, defining rules and methods for each > but also relying on the parent Pile class's methods and attributes. > However, I keep getting an error that an attribute in the parent does > not exist in the child. Below is a simplified example, but it gives me > the exact same error: child object has no attribute l. > > class parent(object): > def __init__(self, l=None): > if l is None: l=[] > > class child(parent): > def __init__(self, *args, **kwords): > super(parent, self).__init__(*args, **kwords) > self.l.append(5) > > c=child() > print c.l > > Again, I get an error saying that 'child' object has no attribute 'l'. > Python 2.7 on win7x64. Thanks. Try p = parent() p.l Does that do what you expected? HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at gmail.com Tue Jan 4 02:16:45 2011 From: vceder at gmail.com (Vern Ceder) Date: Mon, 3 Jan 2011 20:16:45 -0500 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On Mon, Jan 3, 2011 at 7:47 PM, Alex Hall wrote: > Hi all, > I have a solitaire game in which I use a "Pile" class. This class is > meant to hold a bunch of cards, so I subclass it for the deck, the ace > stacks, and the seven main stacks, defining rules and methods for each > but also relying on the parent Pile class's methods and attributes. > However, I keep getting an error that an attribute in the parent does > not exist in the child. Below is a simplified example, but it gives me > the exact same error: child object has no attribute l. > > class parent(object): > def __init__(self, l=None): > if l is None: l=[] > > class child(parent): > def __init__(self, *args, **kwords): > super(parent, self).__init__(*args, **kwords) > I believe you need to pass the object both to super() and to the method itself, as in: super(parent, self).__init__(self, *args, **kwords) See the example at http://docs.python.org/library/functions.html?highlight=super#super HTH, Vern > self.l.append(5) > > c=child() > print c.l > > Again, I get an error saying that 'child' object has no attribute 'l'. > Python 2.7 on win7x64. Thanks. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Vern Ceder vceder at gmail.com, vceder at dogsinmotion.com The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Tue Jan 4 02:19:05 2011 From: mehgcap at gmail.com (Alex Hall) Date: Mon, 3 Jan 2011 20:19:05 -0500 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On 1/3/11, Wayne Werner wrote: > On Mon, Jan 3, 2011 at 6:47 PM, Alex Hall wrote: > >> Hi all, >> I have a solitaire game in which I use a "Pile" class. This class is >> meant to hold a bunch of cards, so I subclass it for the deck, the ace >> stacks, and the seven main stacks, defining rules and methods for each >> but also relying on the parent Pile class's methods and attributes. >> However, I keep getting an error that an attribute in the parent does >> not exist in the child. Below is a simplified example, but it gives me >> the exact same error: child object has no attribute l. >> >> class parent(object): >> def __init__(self, l=None): >> if l is None: l=[] Walter was right, and I changed it to if l is None: self.l=[] else: self.l=l It did not get rid of the error, though. >> >> class child(parent): >> def __init__(self, *args, **kwords): >> super(parent, self).__init__(*args, **kwords) >> self.l.append(5) >> >> c=child() >> print c.l >> >> Again, I get an error saying that 'child' object has no attribute 'l'. >> Python 2.7 on win7x64. Thanks. > > > Try > > p = parent() > p.l > > Does that do what you expected? Yes, I get [], just as I should. So the question is: if the parent class is working, why would a class that inherits it not have the l attribute? > > HTH, > Wayne > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From wprins at gmail.com Tue Jan 4 02:20:17 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Jan 2011 01:20:17 +0000 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: Sorry, my last post was too hasty. You also had a problem calling super. It should be like this: class parent(object): def __init__(self, l=None): if l is None: self.l=[] else: self.l=l class child(parent): def __init__(self, *args, **kwords): super(child, self).__init__(*args, **kwords) self.l.append(5) c=child() print c.l Basically: In Python 2.x "super()" doesn't know what the current class is. You have to tell it, as the first parameter. If you tell it a lie, strange things will happen. That's basically what you did. You called super(parent,...) instead of super(child,...) Have a good 2011... ;) Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Tue Jan 4 02:27:04 2011 From: mehgcap at gmail.com (Alex Hall) Date: Mon, 3 Jan 2011 20:27:04 -0500 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On 1/3/11, Walter Prins wrote: > Sorry, my last post was too hasty. You also had a problem calling super. > It should be like this: > > class parent(object): > def __init__(self, l=None): > if l is None: self.l=[] > else: self.l=l > > class child(parent): > def __init__(self, *args, **kwords): > super(child, self).__init__(*args, **kwords) > self.l.append(5) > > c=child() > print c.l > > Basically: In Python 2.x "super()" doesn't know what the current class is. > You have to tell it, as the first parameter. If you tell it a lie, strange > things will happen. That's basically what you did. You called > super(parent,...) instead of super(child,...) I see, and this does indeed now work! Thanks! > > Have a good 2011... ;) > > Walter > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From hugo.yoshi at gmail.com Tue Jan 4 02:37:11 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 4 Jan 2011 02:37:11 +0100 Subject: [Tutor] Initialize values from a text input file In-Reply-To: References: <20110103224647.GA2497@johnsons-web.com> <20110104001603.GC2497@johnsons-web.com> Message-ID: On Tue, Jan 4, 2011 at 2:06 AM, Alan Gauld wrote: > > "Tim Johnson" wrote > >> ?Now, Alan, do you know anything about PHP? If you do, can you >> ?comment on the PHP extract() function? > > I know enough basic PHP to read a page with code in it and get the general > drift. I've never written a line of it and have learned enough about it that > I don't want to! :-) > > Now as for extract() - it doesn't appear in my Teach Yourself PHP book, so > nope, I've no idea what it does, I'd need to look it up. > And I'm way too lazy, and it's way too late to do that! :-) > extract takes an array and merges it with the local symbol table. Essentially the same thing locals() would do if it was actually writable everywhere (as Steven points out it isn't). If you ask me, this is an insanely bad idea and I have not a clue as to why you'd actually want to do this, rather than just work with the array. Hugo From wprins at gmail.com Tue Jan 4 02:47:36 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 4 Jan 2011 01:47:36 +0000 Subject: [Tutor] subclass not inheriting attributes? In-Reply-To: References: Message-ID: On 4 January 2011 01:16, Vern Ceder wrote: > I believe you need to pass the object both to super() and to the method > itself, as in: > > super(parent, self).__init__(self, *args, **kwords) > > See the example at > http://docs.python.org/library/functions.html?highlight=super#super > > HTH, > > Vern > > I've already pointed out that you're supposed to tell super() the *current* class and Alex has already indicated that it now works for him? Is there a problem with everyone on the mailing list receving posts timeously? Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Tue Jan 4 03:16:42 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 3 Jan 2011 17:16:42 -0900 Subject: [Tutor] Initialize values from a text input file In-Reply-To: References: <20110103224647.GA2497@johnsons-web.com> <20110104001603.GC2497@johnsons-web.com> Message-ID: <20110104021642.GD2497@johnsons-web.com> * Hugo Arts [110103 17:12]: > On Tue, Jan 4, 2011 at 2:06 AM, Alan Gauld wrote: > > > > "Tim Johnson" wrote > > > >> ?Now, Alan, do you know anything about PHP? If you do, can you > >> ?comment on the PHP extract() function? > > > > I know enough basic PHP to read a page with code in it and get the general > > drift. I've never written a line of it and have learned enough about it that > > I don't want to! :-) > > > > Now as for extract() - it doesn't appear in my Teach Yourself PHP book, so > > nope, I've no idea what it does, I'd need to look it up. > > And I'm way too lazy, and it's way too late to do that! :-) > > > > extract takes an array and merges it with the local symbol table. > Essentially the same thing locals() would do if it was actually > writable everywhere (as Steven points out it isn't). > > If you ask me, this is an insanely bad idea and I have not a clue as > to why you'd actually want to do this, rather than just work with the > array. I've decided that members of my company (and I punished myself by appointing myself) had to learn a little PHP. At least enough to persuade a potential client why python would be a better choice. I would consider extract() one of those potent arguments as to why to use python.... thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From steve at pearwood.info Tue Jan 4 14:27:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 05 Jan 2011 00:27:33 +1100 Subject: [Tutor] Initialize values from a text input file In-Reply-To: <20110104001336.GB2497@johnsons-web.com> References: <20110103224647.GA2497@johnsons-web.com> <4D225FF2.9070500@pearwood.info> <20110104001336.GB2497@johnsons-web.com> Message-ID: <4D232045.80604@pearwood.info> Tim Johnson wrote: >>> consider the following console session: >>>>>> L = ['foo','bar'] >>>>>> locals()[L[0]] = L[1] [...] >> (2) Even if it did work, do you trust the source of the text? Taking >> external data provided by arbitrary untrusted users and turning it into >> variables is a good way to have your computer owned by bad guys. > Say what? I'm not talking about anything accessible by "arbitrary > users". Sorry if I gave that impression! No need to apologise, but you were talking about injecting variables straight into your code from a file, which has to come from *somewhere*. It's not a big leap to ask whether you trust the source of that file. If it comes from *you*, then presumably you trust yourself. (If you can't trust yourself, you have more problems than just code injection attacks...) You asked for comments, and I gave them :) But be careful -- code has a way of ending up used in different circumstances than it originally was created for. What starts off reading a config file you write yourself ends up accepting data uploaded to your web server by anonymous users in Bulgaria :) -- Steven From rdmoores at gmail.com Tue Jan 4 16:37:01 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 07:37:01 -0800 Subject: [Tutor] regex question Message-ID: I use regex = ".*" + search + ".*" p = re.compile(regex, re.I) in finding lines in a text file that contain search, a string entered at a prompt. What regex do I use to find lines in a text file that contain search, where search is a word entered at a prompt? Thanks, Dick Moores From waynejwerner at gmail.com Tue Jan 4 16:55:37 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 4 Jan 2011 09:55:37 -0600 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 9:37 AM, Richard D. Moores wrote: > I use > > regex = ".*" + search + ".*" > p = re.compile(regex, re.I) > > in finding lines in a text file that contain search, a string entered > at a prompt. > > What regex do I use to find lines in a text file that contain search, > where search is a word entered at a prompt? > > Thanks, > > Dick Moores You could use (2.6+ I think): word = raw_input('Enter word to search for: ') with open('somefile.txt') as f: for line in f: if word in line: print line You could always try a speed test, but I'm guessing that other than extremely large files (10k+ lines) you probably won't see much speed difference. Then again, you might! HTH, Wayne p.s. I tend to only use a regex when I absolutely need to, because usually when you try to solve one problem with a regex it becomes two problems. -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Tue Jan 4 17:02:01 2011 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 4 Jan 2011 17:02:01 +0100 Subject: [Tutor] matplotlib.pylab.plotfile formatting help In-Reply-To: References: Message-ID: <1F493031-CA23-4331-8B42-2384C49BE4C9@gmail.com> Hi Sean, > I've got a csv file that contains two data fields, the short name of a > month and an integer. I'm experimenting with pylab and ipython to get > a feel for how pylab works. I'm able to generate a bar graph from my > data, but there are two problems with it: > > 1. I don't want "2011" appended to the month names. This data is > from 2010, and I only want the short month name under each bar. > 2. The bars are very narrow and I'm not sure how to widen them. > > Here's my CSV data, stored in a file called csvdata.csv: > > month,systems > Jan,17 > > Dec,197 > > And here's the "ipython -pylab" command that I'm using to generate the graph: > > plotfile('csvdata.csv', ('month', 'systems'), plotfuncs={'systems': 'bar'},) > > I've read through some of the documentation for matplotlib, but having > never used matlab or pylab before today it's a bit confusing. Does > anyone know how to solve #1 and #2 above? I've never used plotfile before, but it seems like a simple quick'n'dirty function, good for having a quick glance at how the data look like. Which is also what the documentation for plotfile says. So in this case, your points 1 and 2 can be solved using the more generic approach, reading the file separately (possibly using a csv module) and using pylab.bar to plot your data. pylab.bar has a 'width' option, which would easily solve problem #2. I can also advice you to try the matplotlib mailing list: people will there will be much more knowledgeable wrt to matplotlib and pylab than on this mailing list: http://sourceforge.net/mailarchive/forum.php?forum_name=matplotlib-users Good luck, Evert From rdmoores at gmail.com Tue Jan 4 17:07:53 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 08:07:53 -0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 07:55, Wayne Werner wrote: > On Tue, Jan 4, 2011 at 9:37 AM, Richard D. Moores > You could use (2.6+ I think): > word = raw_input('Enter word to search for: ') > with open('somefile.txt') as f: > ?? for line in f: > ?? ? ? if word in line: > ?? ? ? ? ? ?print line I think I do need a regex for cases such as this: A file has these 2 lines: alksdhjf ksjhdf kjshf dex akjdhf jkdshf jsdhf alkdshf jkashd flkjdsf index alkdjshf alkdjshf And I want the only line that contains the word "dex" Dick From mehgcap at gmail.com Tue Jan 4 17:26:16 2011 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 4 Jan 2011 11:26:16 -0500 Subject: [Tutor] print stack traces not caused by errors Message-ID: Hi all, I am coming along quite nicely with Solitaire (sans graphics). However, I am getting some odd behavior, and I would like to see what is calling what so I can see where things are going wrong. It is not causing an error to print a traceback, but it is not doing what I expected at all. I tried the pdb module, but I am running a wx program so it is not helping. I tried: python -m pdb c:\prog\solitaire\game.py It gave me a prompt after my imports, so I typed "continue", and then I saw nothing except the errors I knew I would get when I intentionally hit some wrong keys. However, the behavior I was hoping to track triggers nothing, and pdb said nothing else until I closed the wx window. Is there a way to constantly track the stack of calls, preferably with arguments? TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From hugo.yoshi at gmail.com Tue Jan 4 18:06:38 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 4 Jan 2011 18:06:38 +0100 Subject: [Tutor] print stack traces not caused by errors In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 5:26 PM, Alex Hall wrote: > Hi all, > I am coming along quite nicely with Solitaire (sans graphics). > However, I am getting some odd behavior, and I would like to see what > is calling what so I can see where things are going wrong. It is not > causing an error to print a traceback, but it is not doing what I > expected at all. I tried the pdb module, but I am running a wx program > so it is not helping. I tried: > python -m pdb c:\prog\solitaire\game.py > > It gave me a prompt after my imports, so I typed "continue", and then > I saw nothing except the errors I knew I would get when I > intentionally hit some wrong keys. typing continue in pdb is just the command to keep going until it runs into program end (or uncaught exception). There are a lot more commands available though, and they're very powerful. You can use 'next' or 'step' to slowly go through your program, 'where' to print a stack trace, and 'print' to display the value of any expression in the current context. You can also set a "breakpoint" at a specific line with the break command. When you type continue, execution will proceed until it hits a breakpoint. You can even specify a list of commands to be executed when the breakpoint is hit. Commonly, you set breakpoints at places where you expect the bug to manifest, type continue, and when one hits you slowly step through code, carefully examine values of variables, get a sense of what's really going on. > However, the behavior I was hoping > to track triggers nothing, and pdb said nothing else until I closed > the wx window. Is there a way to constantly track the stack of calls, > preferably with arguments? TIA. > There's also the backtrace module, but pdb should be all you need. I suggest you check the documentation for both of them, a quick google should do. Hugo From swiftone at swiftone.org Tue Jan 4 18:31:07 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 4 Jan 2011 12:31:07 -0500 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 10:37 AM, Richard D. Moores wrote: > regex = ".*" + search + ".*" > p = re.compile(regex, re.I) > > in finding lines in a text file that contain search, a string entered > at a prompt. That's an inefficient regex (though the compiler may be smart enough to prune the unneeded ".*"). Just having "search" as your regex is fine (it will search for the pattern _in_ the string, no need to specify the other parts of the string), but if you're not using any special regex characters you're probably better off not using a regex and just using a string operation. Regexes are great for trying to do powerful and complicated things - and as such may be too complicated if you're trying to do a simple thing. -- Brett Ritter / SwiftOne swiftone at swiftone.org From rdmoores at gmail.com Tue Jan 4 18:44:53 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 09:44:53 -0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 09:31, Brett Ritter wrote: > On Tue, Jan 4, 2011 at 10:37 AM, Richard D. Moores wrote: >> regex = ".*" + search + ".*" >> p = re.compile(regex, re.I) > > Just having "search" as your regex is fine (it will search for the > pattern _in_ the string, no need to specify the other parts of the > string), I see. Thanks. > but if you're not using any special regex characters you're > probably better off not using a regex and just using a string > operation. Please see my reply to Wayne Werner. Dick From swiftone at swiftone.org Tue Jan 4 18:58:43 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 4 Jan 2011 12:58:43 -0500 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 11:07 AM, Richard D. Moores wrote: > A file has these 2 lines: > > alksdhjf ksjhdf kjshf dex akjdhf jkdshf jsdhf > alkdshf jkashd flkjdsf index alkdjshf alkdjshf > > And I want the only line that contains the word "dex" Ah! Then you want a slightly different Regex pattern. .*dex.* would match both lines. You'll need to be more specific when you say "the word dex" to determine your regex. \sdex\s will match dex surrounded by whitespace, which might be what you want. \bdex\b will match dex surrounded by word boundaries, which is probably the best pick. -- Brett Ritter / SwiftOne US2003011110 swiftone at swiftone.org From rdmoores at gmail.com Tue Jan 4 19:41:30 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 10:41:30 -0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: Please see http://tutoree7.pastebin.com/z9YeSYRw . I'm actually searching RTF files, not TXT files. I want to modify this script to handle searching on a word. So what, for example, should line 71 be? Dick From rdmoores at gmail.com Tue Jan 4 20:57:24 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 11:57:24 -0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 10:41, Richard D. Moores wrote: > Please see http://tutoree7.pastebin.com/z9YeSYRw . I'm actually > searching RTF files, not TXT files. > > I want to modify this script to handle searching on a word. So what, > for example, should line 71 be? OK, I think I've got it. in place of lines 66-75 I now have search = input("first search string: ") search = "\\b" + search + "\\b" if not search: print("Bye") sys.exit() elif search[0] != ' ': p = re.compile(search, re.I) else: p = re.compile(search) Dick From rdmoores at gmail.com Tue Jan 4 21:02:07 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 12:02:07 -0800 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: On Tue, Jan 4, 2011 at 11:57, Richard D. Moores wrote: > On Tue, Jan 4, 2011 at 10:41, Richard D. Moores wrote: >> Please see http://tutoree7.pastebin.com/z9YeSYRw . I'm actually >> searching RTF files, not TXT files. >> >> I want to modify this script to handle searching on a word. So what, >> for example, should line 71 be? > > OK, I think I've got it. > > in place of lines 66-75 I now have > > search = input("first search string: ") > ? ?search = "\\b" + search + "\\b" > ? ?if not search: > ? ? ? ?print("Bye") > ? ? ? ?sys.exit() > ? ?elif search[0] != ' ': > ? ? ? ?p = re.compile(search, re.I) > ? ?else: > ? ? ? ?p = re.compile(search) Oops. That should be search = input("first search string: ") if not search: print("Bye") sys.exit() elif search[0] != ' ': search = "\\b" + search + "\\b" p = re.compile(search, re.I) else: search = "\\b" + search + "\\b" p = re.compile(search) Dick From patty at cruzio.com Tue Jan 4 22:50:57 2011 From: patty at cruzio.com (Patty) Date: Tue, 4 Jan 2011 13:50:57 -0800 Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) References: Message-ID: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> Hi David - I was looking for the book you recomended below - "Python 3 Object Oriented Programming" by Dusty Phillips - and found it on Amazon for $43 new on up and $70 for used but maybe that was hardback? Do you happen to know of some other way to obtain it for less than $45? Thanks Patty ----- Original Message ----- From: "David" To: "John Russell" Cc: Sent: Saturday, December 11, 2010 3:47 PM Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) > On 12 December 2010 03:25, John Russell wrote: >> Last night I started working through a book (Beginning Python: Using >> Python >> 2.6 and Python 3.1) I bought to learn Python, and there is an example in >> it >> that doesn't make sense to me. > > I have that book too, and several others thankfully. I'm just writing > to share my experience, in case another perspective from another > relatively new python user is helpful to anyone. > > I found that book is written towards a friendly beginner level, but it > omits many details and is not a comprehensive reference. It does > include plenty of examples on many topics. I have read the opposite > criticism of other books, so it is probably impossible for one book to > fit all needs. > > Personally I became weary of the food/fridge/kitchen theme of the > early examples as it did not engage my interest at all, and there is > so much of it. However I have found that book valuable for its Part > III where it covers useful applications. Although I have come to > expect that its examples will often need typos corrected or other > small modifications to get them to run properly on Python 2.6. > > So while working through Parts I and II, if your experience is > anything like mine where I moved away from it fairly quickly, you will > definitely need other resources. Fortunately they are abundantly > available. In case you are unaware, a Tutorial and Reference are > integrated with Python. On my Linux box the tutorial is > file:///usr/share/doc/python-docs-x.x.x/html/tutorial/index.html and > the Alphabetic Index to the Reference is > file:///usr/share/doc/python-docs-x.x.x/html/genindex.html > > I find the Tutorial easily readable, whereas the Reference can be > challenging, but it is comprehensive and likely contains the answer to > most questions, somewhere. > > As an exercise I thought I'd try to find the answer to your question > using these built-in docs. The keyword is "slice" which we know from > the book. I couldn't find any coverage in the 2.6 tutorial so I looked > up "slice" in the Alphabetic Index, and the first link took me to a > section which includes the answer: "The slicing now selects all items > with index k such that i <= k < j where i and j are the specified > lower and upper bounds". > > In case you are not aware, the web has a vast amount of great material > for learning Python, see for example: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > As Python is an evolving language, one needs be mindful of the > differences between Python 2.x and Python 3.x when using this > material. > > My favourite Python book of my small beginners collection is "Python 3 > Object Oriented Programming" by Dusty Phillips. It claims: > "If you're new to object-oriented programming techniques, or if you > have basic Python skills, and wish to learn in depth how and when to > correctly apply object-oriented programming in Python, this is the > book for you". > I endorse that completely. Having learned the syntax basics elsewhere, > for me this is a book like no other. I find its topic coverage and all > its short examples consistently useful, powerful, and illuminating. I > find it easy to read, well matched to my level and interest, and it > has made a real difference to the code I write. I use classes with > confidence now. For example, it gave me the background and confidence > to design a custom sortable abstract class I needed, my first personal > experience of the power of OOP. > > Tthe python and tutorial mailing lists are a wonderul resource as you > are obviously aware. Thanks to all the contributors from whom I > continue to learn. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From davea at ieee.org Tue Jan 4 23:38:16 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Jan 2011 17:38:16 -0500 Subject: [Tutor] regex question In-Reply-To: References: Message-ID: <4D23A158.90108@ieee.org> On 01/-10/-28163 02:59 PM, Richard D. Moores wrote: > On Tue, Jan 4, 2011 at 11:57, Richard D. Moores wrote: >> On Tue, Jan 4, 2011 at 10:41, Richard D. Moores wrote: >>> Please see http://tutoree7.pastebin.com/z9YeSYRw . I'm actually >>> searching RTF files, not TXT files. >>> >>> I want to modify this script to handle searching on a word. So what, >>> for example, should line 71 be? >> >> OK, I think I've got it. >> >> in place of lines 66-75 I now have >> >> search =nput("first search string: ") >> search =\\b" + search + "\\b" >> if not search: >> print("Bye") >> sys.exit() >> elif search[0] != ': >> p =e.compile(search, re.I) >> else: >> p =e.compile(search) > > Oops. That should be > > search =nput("first search string: ") > if not search: > print("Bye") > sys.exit() > elif search[0] != ': > search =\\b" + search + "\\b" > p =e.compile(search, re.I) > else: > search =\\b" + search + "\\b" > p =e.compile(search) > > Dick > One hazard is if the string the user inputs has any regex special characters in it. If it's anything but letters and digits you probably want to escape it before combining it with your \\b strings. DaveA From steve at pearwood.info Tue Jan 4 23:58:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 05 Jan 2011 09:58:41 +1100 Subject: [Tutor] regex question In-Reply-To: <4D23A158.90108@ieee.org> References: <4D23A158.90108@ieee.org> Message-ID: <4D23A621.1040406@pearwood.info> Dave Angel wrote: > One hazard is if the string the user inputs has any regex special > characters in it. If it's anything but letters and digits you probably > want to escape it before combining it with your \\b strings. It is best to escape any user-input before passing it to regex regardless. The re.escape function will do the right thing whether the string is all letters and digits or not. >>> re.escape("dev") 'dev' >>> re.escape("dev+") 'dev\\+' -- Steven From alan.gauld at btinternet.com Wed Jan 5 00:59:24 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Jan 2011 23:59:24 -0000 Subject: [Tutor] print stack traces not caused by errors References: Message-ID: "Alex Hall" wrote > expected at all. I tried the pdb module, but I am running a wx > program > so it is not helping. I tried: > python -m pdb c:\prog\solitaire\game.py The key to using any debugger in a GUI environment is to set break points on the event handlers of interest. Then when the event fires the debugger will stop your code at the start of the event handler and you can examine the stack, variables etc and step through the code. Single line stepping is tiresome so usually you are better off setting another break point within the function (just before or within a loop maybe? Or after reading a line from a file...). A watch point is even better but sadly I don't think pdb supports those. But the debugger in Eclipse and winPDB(?) do I think. And of course print statements work too within the console window. HTH, Alan G. From mehgcap at gmail.com Wed Jan 5 01:06:09 2011 From: mehgcap at gmail.com (Alex Hall) Date: Tue, 4 Jan 2011 19:06:09 -0500 Subject: [Tutor] print stack traces not caused by errors In-Reply-To: References: Message-ID: Thanks to both of you. While I am not getting as much information from pdb as I get from an error traceback, I suspect that it is my fault and I will figure out how to get more. I will definitely look at setting breakpoints in the event handlers (every event is fired by a keystroke controled in an accelerator table). It is one of those problems that is hard to track down since it seems to happen randomly, though there is, of course, some set of circumstances causing the problem that I cannot figure out. I will get it eventually... hopefully! On 1/4/11, Alan Gauld wrote: > > "Alex Hall" wrote > >> expected at all. I tried the pdb module, but I am running a wx >> program >> so it is not helping. I tried: >> python -m pdb c:\prog\solitaire\game.py > > The key to using any debugger in a GUI environment is to set break > points on the event handlers of interest. Then when the event fires > the debugger will stop your code at the start of the event handler > and you can examine the stack, variables etc and step through > the code. > > Single line stepping is tiresome so usually you are better off > setting another break point within the function (just before or within > a loop maybe? Or after reading a line from a file...). A watch point > is even better but sadly I don't think pdb supports those. But > the debugger in Eclipse and winPDB(?) do I think. > > And of course print statements work too within the console > window. > > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From kb1pkl at aim.com Wed Jan 5 01:06:44 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 04 Jan 2011 19:06:44 -0500 Subject: [Tutor] print stack traces not caused by errors In-Reply-To: References: Message-ID: <4D23B614.8060603@aim.com> On 01/04/2011 06:59 PM, Alan Gauld wrote: > > "Alex Hall" wrote > >> expected at all. I tried the pdb module, but I am running a wx >> program >> so it is not helping. I tried: >> python -m pdb c:\prog\solitaire\game.py > > The key to using any debugger in a GUI environment is to set break > points on the event handlers of interest. Then when the event fires > the debugger will stop your code at the start of the event handler > and you can examine the stack, variables etc and step through > the code. > > Single line stepping is tiresome so usually you are better off > setting another break point within the function (just before or within > a loop maybe? Or after reading a line from a file...). A watch point > is even better but sadly I don't think pdb supports those. But > the debugger in Eclipse and winPDB(?) do I think. > > And of course print statements work too within the console > window. > > HTH, > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I've done almost all my debugging via print statements at crucial points. It's a good way to go, IMO. ~Corey Richardson From alan.gauld at btinternet.com Wed Jan 5 02:42:55 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 5 Jan 2011 01:42:55 +0000 (GMT) Subject: [Tutor] print stack traces not caused by errors In-Reply-To: References: Message-ID: <643533.29023.qm@web86703.mail.ird.yahoo.com> > and I will figure out how to get more. I will definitely look at > setting breakpoints in the event handlers (every event is fired by a > keystroke controled in an accelerator table). It doesn't matter about the events, only the handler. Provided you know the handler function that gets called you can set the break point on the function. (pdb) b foo will stop at the entry to foo() If you can happen to find a paper copy of my book there is a chapter in there about debugging whjich includes examples of using pdb and the IDLE debugger. (This is one of the few chapters that is not available on the web site). > problems that is hard to track down since it seems to happen randomly, If you use Pythons debugger you can set a group of variables to display every time you stop (you can do it in pdb too but its much more work!). That can help you quickly compare values of key variables and see which is causing the problem. but a simple print/raw_input in the code will do much the same... Alan G. From rdmoores at gmail.com Wed Jan 5 05:44:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 4 Jan 2011 20:44:11 -0800 Subject: [Tutor] regex question In-Reply-To: <4D23A621.1040406@pearwood.info> References: <4D23A158.90108@ieee.org> <4D23A621.1040406@pearwood.info> Message-ID: On Tue, Jan 4, 2011 at 14:58, Steven D'Aprano wrote: > Dave Angel wrote: > >> One hazard is if the string the user inputs has any regex special >> characters in it. ?If it's anything but letters and digits you probably want >> to escape it before combining it with your \\b strings. > > It is best to escape any user-input before passing it to regex regardless. > The re.escape function will do the right thing whether the string is all > letters and digits or not. > >>>> re.escape("dev") > 'dev' >>>> re.escape("dev+") > 'dev\\+' I didn't know about re.escape. from the 3.1.3 docs: re.escape(string) Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. I'm writing the script for my own use, and don't expect to be searching on non-alphanumerics. Even so, I'd like to incorporate re.escape. However, I'm using ' ' to set case sensitive searches, and '=' to set word searches. Would you take a look at my revised script at , lines 72-97? I tried using line 80, but I can't because '=' is a regular expression metacharacter. I could use some other character instead of '=', but I would want it to be one that can be typed easily without using the shift key. '=' is the best, I think. I did try to use 'qq' instead of '=', but that got messy. Or is there another, completely different way to do what I do in lines 72-97 with ' ' and '=' that wouldn't involve increasing the number of prompts? Right now, the user has to respond to 4 prompts, even though some responses are quickly made: either by entering nothing, or by entering anything. Dick From mindarson at live.com Wed Jan 5 06:24:18 2011 From: mindarson at live.com (Joel Knoll) Date: Wed, 5 Jan 2011 00:24:18 -0500 Subject: [Tutor] range function and floats? Message-ID: I'm new to Python and to programming in general. I'm trying to write a simple program to give the sine of each of a range of numbers, including multiples of pi. I keep getting a syntax error, highlighting my use of 2pi as an argument in the range, saying something like "expected integers, got float instead". Can I not use a float like pi in the range function? Or what might I be doing wrong? Also, I understand I may not be doing this in the most efficient way, but this is more about learning how the range function and floats work than about writing a super-efficient program. Thanks for your time, Joel C Knoll -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 5 10:21:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Jan 2011 09:21:06 -0000 Subject: [Tutor] print stack traces not caused by errors References: <4D23B614.8060603@aim.com> Message-ID: "Corey Richardson" wrote >> And of course print statements work too within the console >> window. > > I've done almost all my debugging via print statements at crucial > points. It's a good way to go, IMO. It's a good way to go for short simple programs. The big disadvantage is that the larger the program the more prints you need to insert. Then you have to take them all out again before shipping the final version. That's a lot of potentially error prone work. Plus a lot of print statements can slow code down which can be important where interaction with external systems/networks is important. A debugger usually has a much less invasive impact performance wise. Using a proper debugger allows you to dynamically "print" anything at any point in your program without leaving a footprint in your code when you are finished. Both print and debug have their place, my personal preference is a few print statements but if it gets to more than 3 or 4 then I move to the debugger. And a decent GUI debugger is *much* easier to use than pdg/gdb etc And of course a critical visual review of the code is the first step of all! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 5 10:26:53 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Jan 2011 09:26:53 -0000 Subject: [Tutor] range function and floats? References: Message-ID: "Joel Knoll" wrote > I'm trying to write a simple program to give the > sine of each of a range of numbers, including multiples of pi. > > I keep getting a syntax error, highlighting my use of 2pi > as an argument in the range, range requires integers. You need to scale your floats appropriately and convert to integers. Or in your case use the multipliers of pi as the arguments to range() and then multiply by pi when getting the sine. > ...this is more about learning how the range function and > floats work than about writing a super-efficient program. Unfortunately they don't work together. range(0.1,0.5,0.1) -> [0.1,0.2,0.3,0.4] doesn't work you need to do: for n in range(1,5): use( n/10 ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jan 5 12:14:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 05 Jan 2011 22:14:46 +1100 Subject: [Tutor] range function and floats? In-Reply-To: References: Message-ID: <4D2452A6.9050709@pearwood.info> Alan Gauld wrote: >> ...this is more about learning how the range function and floats work >> than about writing a super-efficient program. > > Unfortunately they don't work together. > > range(0.1,0.5,0.1) -> [0.1,0.2,0.3,0.4] doesn't work > you need to do: > > for n in range(1,5): use( n/10 ) There are pitfalls in writing a range() equivalent for floats. Here's one way that doesn't work: def new_range(start, end, step): # DON'T USE THIS!!! x = start while x < end: yield x x += step Here it seems to work: >>> list(new_range(5, 10, 0.25)) [5, 5.25, 5.5, 5.75, 6.0, 6.25, 6.5, 6.75, 7.0, 7.25, 7.5, 7.75, 8.0, 8.25, 8.5, 8.75, 9.0, 9.25, 9.5, 9.75] (Remember that the end argument is excluded!) But here it fails: >>> L = list(new_range(5, 10, 0.1)) >>> L[-1] == 9.9 # expect the last value to be 9.9 False >>> L[-1] == 10.0 # maybe it's 10 then False In fact, the last value is a totally unexpected 9.9999999999999822. Such is the perils of floating point rounding errors. I've written a recipe for a float range which I hope avoids as many of these problems as possible. It isn't possible to avoid *all* rounding error when doing floating point calculation, but this should minimize them: http://code.activestate.com/recipes/577068-floating-point-range/ As a bonus, it allows you to choose whether the start and end points are included or excluded. -- Steven From steve at pearwood.info Wed Jan 5 12:18:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 05 Jan 2011 22:18:32 +1100 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> Message-ID: <4D245388.9070409@pearwood.info> Noah Hall wrote: > He has no classes in there. Therefore, there is no place it should be in > this code. Please remember this is Python, and not Java nor anything else. [...] > It just makes life easier. Oh the irony... talking about making life easier, who are you talking to? What about? Please quote enough of the previous message to establish context -- when you are replying to the message, it is fresh in your mind. When others read your reply (possibly days later like I'm doing now), the context is anything but clear and your message comes across as merely mysterious and obscure. Thank you. -- Steven From enalicho at gmail.com Wed Jan 5 13:01:57 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 5 Jan 2011 12:01:57 +0000 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D245388.9070409@pearwood.info> References: <4D1F806D.6030400@gmail.com> <4D245388.9070409@pearwood.info> Message-ID: > > Please quote enough of the previous message to establish context -- when > you are replying to the message, it is fresh in your mind. When others read > your reply (possibly days later like I'm doing now), the context is anything > but clear and your message comes across as merely mysterious and obscure. Certainly. In fact, it was an error in that message - I had deleted accidentally that which I had quoted. Please be aware, however, rudeness does nothing for you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 5 14:17:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Jan 2011 00:17:46 +1100 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: References: <4D1F806D.6030400@gmail.com> <4D245388.9070409@pearwood.info> Message-ID: <4D246F7A.6040807@pearwood.info> Noah Hall wrote: >> Please quote enough of the previous message to establish context -- when >> you are replying to the message, it is fresh in your mind. When others read >> your reply (possibly days later like I'm doing now), the context is anything >> but clear and your message comes across as merely mysterious and obscure. > > > Certainly. In fact, it was an error in that message - I had deleted > accidentally that which I had quoted. Please be aware, however, rudeness > does nothing for you. "Please" and "Thank you" are rude? Oh my, have you lived a sheltered life :) -- Steven From enalicho at gmail.com Wed Jan 5 15:08:13 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 5 Jan 2011 14:08:13 +0000 Subject: [Tutor] syntax error that i cant spot! In-Reply-To: <4D246F7A.6040807@pearwood.info> References: <4D1F806D.6030400@gmail.com> <4D245388.9070409@pearwood.info> <4D246F7A.6040807@pearwood.info> Message-ID: > > "Please" and "Thank you" are rude? Oh my, have you lived a sheltered life > :) > Nej, it was your condescension that I found rude. Also, you did it again, perhaps on purpose though.. ;) -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Wed Jan 5 16:02:00 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 5 Jan 2011 09:02:00 -0600 Subject: [Tutor] range function and floats? In-Reply-To: <4D2452A6.9050709@pearwood.info> References: <4D2452A6.9050709@pearwood.info> Message-ID: On Wed, Jan 5, 2011 at 5:14 AM, Steven D'Aprano wrote: > Alan Gauld wrote: > > ...this is more about learning how the range function and floats work than >>> about writing a super-efficient program. >>> >> >> Unfortunately they don't work together. >> >> range(0.1,0.5,0.1) -> [0.1,0.2,0.3,0.4] doesn't work >> you need to do: >> >> for n in range(1,5): use( n/10 ) >> > > > There are pitfalls in writing a range() equivalent for floats. Here's one > way that doesn't work: > > > def new_range(start, end, step): > # DON'T USE THIS!!! > x = start > while x < end: > yield x > x += step > > Here it seems to work: > > >>> list(new_range(5, 10, 0.25)) > [5, 5.25, 5.5, 5.75, 6.0, 6.25, 6.5, 6.75, 7.0, 7.25, 7.5, > 7.75, 8.0, 8.25, 8.5, 8.75, 9.0, 9.25, 9.5, 9.75] > > (Remember that the end argument is excluded!) > > But here it fails: > > > >>> L = list(new_range(5, 10, 0.1)) > >>> L[-1] == 9.9 # expect the last value to be 9.9 > False > >>> L[-1] == 10.0 # maybe it's 10 then > False > > In fact, the last value is a totally unexpected 9.9999999999999822. Such is > the perils of floating point rounding errors. > > I've written a recipe for a float range which I hope avoids as many of > these problems as possible. It isn't possible to avoid *all* rounding error > when doing floating point calculation, but this should minimize them: > > http://code.activestate.com/recipes/577068-floating-point-range/ > > As a bonus, it allows you to choose whether the start and end points are > included or excluded. As an alternative to floating point, you can use the Decimal module: import decimal def new_range(start, stop, step): x = decimal.Decimal(str(start)) step = decimal.Decimal(str(step)) while x < stop: yield x x += step x = list(new_range(5, 10, 0.1)) x[-1] == decimal.Decimal(str(9.9)) #True float(x[-1]) == 9.9 #True The decimal module allows you to get rid of those pesky floating point errors. See http://docs.python.org/library/decimal.html for more info. On a related note, if you're interested in working with rational numbers (1/23, 3/4, etc.) there is also a fraction module http://docs.python.org/library/fractions.html. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 5 17:43:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Jan 2011 03:43:56 +1100 Subject: [Tutor] range function and floats? In-Reply-To: References: <4D2452A6.9050709@pearwood.info> Message-ID: <4D249FCC.9030708@pearwood.info> Wayne Werner wrote: > The decimal module allows you to get rid of those pesky floating point > errors. See http://docs.python.org/library/decimal.html for more info. That's a myth. Decimal suffers from the same floating point issues as binary floats. It's quite easy to demonstrate the same sort of rounding errors with Decimal as for float: >>> from decimal import Decimal as D >>> x = D(1)/D(3) >>> 3*x == 1 False Between 1 and 1000 inclusive, there are 354 such numbers: >>> nums = [] >>> for i in range(1, 1001): ... x = D(1)/D(i) ... if x*i != 1: nums.append(i) ... >>> len(nums) 354 The problem isn't just division and multiplication, nor does it just affect fractional numbers: >>> x = D(10)**30 >>> x + 100 == x True Here's another nice little demonstration of the problem: >>> def f(a): ... b = 9*a - 9 ... c = a - 1/D(9)*b ... return c # c should always equal 1 exactly ... >>> f(D("51.1")) == 1 False Decimal and float share more things in common than differences. Both are floating point numbers. Both have a fixed precision (although you can configure what that precision is for Decimal, but not float). Both use a finite number of bits, and therefore have a finite resolution. The only differences are: * as mentioned, you can configure Decimal to use more bits and higher precision, at the cost of speed and memory; * floats use base 2 and Decimal uses base 10; * floats are done in hardware and so are much faster than Decimal; So it simply isn't correct to suggest that Decimal doesn't suffer from rounding error. -- Steven From peterjsmith88+ctlinks at gmail.com Wed Jan 5 15:33:11 2011 From: peterjsmith88+ctlinks at gmail.com (F1r3f1y) Date: Wed, 5 Jan 2011 06:33:11 -0800 (PST) Subject: [Tutor] cx_Oracle help In-Reply-To: References: Message-ID: <30596546.post@talk.nabble.com> This guide helped me a lot with cx_Oracle http://codingtutorials.co.uk/blog/?p=31 Greg Lindstrom-3 wrote: > > Hello, > > I'm trying to help out a friend and am stumped. Can you help me out? > Thanks, > --greg > > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > I will briefly explain the problem I am facing. > I am using Oracle 9.2, Python 2.5 and I installed cx_Oracle- > 4.3.1-win32-9i-py25 in Python. > > From python I tried following : > >>> import cx_Oracle > >>> myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') > >>> CONN = cx_Oracle.connect(myusr, mypwd, myDsn) > Traceback (most recent call last): > File "", line 1, in > conn = cx_Oracle.Connection('scott','tiger',myDsn) > RuntimeError: Unable to acquire Oracle environment > handle > > I have set the below environment variables too > NLS_LANG: .WE8MSWIN1252 > ORACLE_HOME: D:\Tools\oracle\ora92 > ORACLE_SID: AUBDBS01 > PYTHON_HOME: d:\Utility\Python25 > PYTHONPATH: > %PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin > LD_LIBRARY_PATH: %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib > > Not getting any idea where I am wrong? > > Regards, > > Kishore > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://old.nabble.com/cx_Oracle-help-tp15293236p30596546.html Sent from the Python - tutor mailing list archive at Nabble.com. From waynejwerner at gmail.com Wed Jan 5 20:30:59 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 5 Jan 2011 13:30:59 -0600 Subject: [Tutor] range function and floats? In-Reply-To: <4D249FCC.9030708@pearwood.info> References: <4D2452A6.9050709@pearwood.info> <4D249FCC.9030708@pearwood.info> Message-ID: On Wed, Jan 5, 2011 at 10:43 AM, Steven D'Aprano wrote: > Wayne Werner wrote: > > The decimal module allows you to get rid of those pesky floating point >> errors. See http://docs.python.org/library/decimal.html for more info. >> > > That's a myth. Decimal suffers from the same floating point issues as > binary floats. It's quite easy to demonstrate the same sort of rounding > errors with Decimal as for float: > > >>> from decimal import Decimal as D > >>> x = D(1)/D(3) > >>> 3*x == 1 > False > I should have clarified - when I say pesky floating point errors I mean errors in precision that you naturally would not expect. 1/3 == .333 (repeating forever(?)). But on a computer, you're limited to a specific precision point (sort of), and the moment you truncate .333(repeating) to *any* finite points of precision you no longer have the result of the mathematical operation 1/3. Yes, 1/3*3 == 1, but the error in the Decimal module is *only* in division. It might be useful to define a "repeating" flag in the Decimal module for the results of such operations as 1/3, which would get rid of the error in truncation. But this is a fundamentally different error from the standard floating point errors. In [106]: 0.9 Out[106]: 0.90000000000000002 These are two different numbers, mathematically. If I say x = 0.9, I naturally assume that 0.9 is the value in x, not 0.90000000000000002. Of course it's all in the implementation of floating points, and the fact that Python evaluates 0.9 in a floating point context which results in the stored value, but that ignores the fact that *naturally* one does not expect this. And anyone who's been through 2nd or 3rd grade or whenever they teach about equality would expect that this would evaluate to False. In [112]: 0.90000000000000002 == 0.9 Out[112]: True You don't get such silliness with the Decimal module: In [125]: D('0.90000000000000002') == D('0.9') Out[125]: False > Between 1 and 1000 inclusive, there are 354 such numbers: > > >>> nums = [] > >>> for i in range(1, 1001): > ... x = D(1)/D(i) > ... if x*i != 1: nums.append(i) > ... > >>> len(nums) > 354 > > > > The problem isn't just division and multiplication, nor does it just affect > fractional numbers: > > >>> x = D(10)**30 > >>> x + 100 == x > True > > Decimal DOES get rid of floating point errors, except in the case of repeating (or prohibitively large precision values) In [127]: x = D(10)**30 In [128]: x Out[128]: Decimal('1.000000000000000000000000000E+30') In [129]: x + 100 Out[129]: Decimal('1.000000000000000000000000000E+30') If you reset the precision to an incredibly large number: decimal.getcontext().prec = 1000 In [131]: x = D(10)**30 In [132]: x Out[132]: Decimal('1000000000000000000000000000000') In [133]: x + 100 == x Out[133]: False Voila, the error has vanished! > > So it simply isn't correct to suggest that Decimal doesn't suffer from > rounding error. I never said rounding errors - I said "pesky floating point errors". When performing the operation 1/3, I naturally expect that my computer won't hold each of the 3's after the decimal point, and I don't categorize that as pesky - that's just good sense if you know a little about computers. I also expect that .333 * 3 would give me the number .999, and only .999, not .9990000000011 or some other wonky value. Of course it's interesting to note that Python handles the precision properly when dealing with strings, but not with the floating points themselves (at least on this particular trial): In [141]: .333 * 3 Out[141]: 0.99900000000000011 In [142]: str(.333*3) Out[142]: '0.999' In [143]: .333 * 3 == .999 Out[143]: False In [144]: str(.333*3) == str(.999) Out[144]: True Decimal and float share more things in common than differences. Both are > floating point numbers. Both have a fixed precision (although you can > configure what that precision is for Decimal, but not float). Both use a > finite number of bits, and therefore have a finite resolution. The only > differences are: > > * as mentioned, you can configure Decimal to use more bits and higher > precision, at the cost of speed and memory; > * floats use base 2 and Decimal uses base 10; > * floats are done in hardware and so are much faster than Decimal; > Precisely. It's not a magic bullet (1/3 != .33333333 mathematically, after all!), *but* it eliminates the errors that you wouldn't normally expect when working with "standard" points of precision, such as the expectation that 0.333 * 3 resulting in .999, not .99900000000011. Hopefully a little more precise, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From jasons at adventureaquarium.com Wed Jan 5 20:57:03 2011 From: jasons at adventureaquarium.com (Jason Staudenmayer) Date: Wed, 5 Jan 2011 14:57:03 -0500 Subject: [Tutor] user input help Message-ID: Hi all, I'm pretty new to programming in general and figured I'd try out python. I'm working on a small program to add users to a sqlite db. The problem I'm having it dealing with the user input, I'd like to be able to repeat the function to get the input if the user doesn't accept it. here's the code I have now: def promptInput(): """ Get employee data from user running this program""" lname = raw_input("Please enter employees last name\n") fname = raw_input("Please enter employees first name\n") email = raw_input("Please enter employee email address (or press enter to \ leave blank)\n") result = (lname, fname, email) return result def getEmplyInfo(): # get the data from input result = promptInput() # print the data so the user can check and verify spelling print "Is the following info correct [y/n]\n%s, %s %s" % (result[1], \ result[0], result[2]) check = raw_input() #see if the user needs to make corrections to the data he entered if check == "y": print "this check is done so we can add user" print "%s, %s %s" % (result[1], result[0], result[2]) else: check = "" promptInput() The if else loop is were I'm loosing it. If I select n it will ask for the input again but only once. If on the second time around I enter n to re-do it just exits. Thanks Jason ..?><((((?> From mehgcap at gmail.com Wed Jan 5 21:22:49 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 5 Jan 2011 15:22:49 -0500 Subject: [Tutor] user input help In-Reply-To: References: Message-ID: On 1/5/11, Jason Staudenmayer wrote: > Hi all, I'm pretty new to programming in general and figured I'd try out > python. > I'm working on a small program to add users to a sqlite db. The problem I'm > having it dealing with the user input, I'd like to be able to repeat the > function to get the input if the user doesn't accept it. > > here's the code I have now: > > def promptInput(): > """ Get employee data from user running this program""" > > lname = raw_input("Please enter employees last name\n") > fname = raw_input("Please enter employees first name\n") > email = raw_input("Please enter employee email address (or press enter > to \ > leave blank)\n") > result = (lname, fname, email) > return result > > def getEmplyInfo(): > # get the data from input > result = promptInput() > # print the data so the user can check and verify spelling > print "Is the following info correct [y/n]\n%s, %s %s" % (result[1], \ > result[0], result[2]) > check = raw_input() > #see if the user needs to make corrections to the data he entered > if check == "y": > print "this check is done so we can add user" > print "%s, %s %s" % (result[1], result[0], result[2]) > else: > check = "" > promptInput() > > The if else loop is were I'm loosing it. If I select n it will ask for the > input > again but only once. If on the second time around I enter n to re-do it just > exits. This is because the function is done once it detects the y or n, so after you enter the n, one of those if/else statements has fired, and the function has nothing else to do. You will want a while loop, something like: repeat=True while repeat: answer=raw_input("Is the data okay?") if answer=="y": repeat=False else: promptInput() repeat=True Anyway, something along those lines. Look in the manual for while loops. Basically, they are a way to repeat an action until a condition is met. You will also run across for loops, which are mostly used for repeating an event a set number of times. You can use them interchangeably, but they each have situations where one works better than the other, and you want a while loop here. > > > > Thanks > > Jason > > > > ..?><((((?> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From jasons at adventureaquarium.com Wed Jan 5 21:28:38 2011 From: jasons at adventureaquarium.com (Jason Staudenmayer) Date: Wed, 5 Jan 2011 15:28:38 -0500 Subject: [Tutor] user input help In-Reply-To: Message-ID: > -----Original Message----- > From: Alex Hall [mailto:mehgcap at gmail.com] > Sent: Wednesday, January 05, 2011 3:23 PM > To: Jason Staudenmayer > Cc: tutor at python.org > Subject: Re: [Tutor] user input help > > > On 1/5/11, Jason Staudenmayer wrote: > > Hi all, I'm pretty new to programming in general and > figured I'd try out > > python. > > I'm working on a small program to add users to a sqlite db. > The problem I'm > > having it dealing with the user input, I'd like to be able > to repeat the > > function to get the input if the user doesn't accept it. > > > > here's the code I have now: > > > > def promptInput(): > > """ Get employee data from user running this program""" > > > > lname = raw_input("Please enter employees last name\n") > > fname = raw_input("Please enter employees first name\n") > > email = raw_input("Please enter employee email address > (or press enter > > to \ > > leave blank)\n") > > result = (lname, fname, email) > > return result > > > > def getEmplyInfo(): > > # get the data from input > > result = promptInput() > > # print the data so the user can check and verify spelling > > print "Is the following info correct [y/n]\n%s, %s %s" > % (result[1], \ > > result[0], result[2]) > > check = raw_input() > > #see if the user needs to make corrections to the data > he entered > > if check == "y": > > print "this check is done so we can add user" > > print "%s, %s %s" % (result[1], result[0], result[2]) > > else: > > check = "" > > promptInput() > > > > The if else loop is were I'm loosing it. If I select n it > will ask for the > > input > > again but only once. If on the second time around I enter n > to re-do it just > > exits. > This is because the function is done once it detects the y or n, so > after you enter the n, one of those if/else statements has fired, and > the function has nothing else to do. You will want a while loop, > something like: > > repeat=True > while repeat: > answer=raw_input("Is the data okay?") > if answer=="y": repeat=False > else: > promptInput() > repeat=True > > Anyway, something along those lines. Look in the manual for while > loops. Basically, they are a way to repeat an action until a condition > is met. You will also run across for loops, which are mostly used for > repeating an event a set number of times. You can use them > interchangeably, but they each have situations where one works better > than the other, and you want a while loop here. > > > > > > > > Thanks > > > > Jason > > > > > > > > ..?><((((?> > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > That works great!! I forgot about while loops. It's been a while since I've used then. Thanks much Jason From mehgcap at gmail.com Wed Jan 5 22:41:17 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 5 Jan 2011 16:41:17 -0500 Subject: [Tutor] wx accelerator table: one keystroke seems skipped Message-ID: Hello all, First, this is about a wx accelerator table, so if it is too off-topic for this list, let me know. I have a table with 23 entries, all of which work. I added another entry last night, and it does not work. The odd thing, though, is that I do not get an error of any kind anywhere in the program, the keystroke simply does not call the function to which it should be bound. I even changed the function name to something that should have thrown an exception, but nothing at all happens. The keystroke in question is ctrl+m and is tied to ctrlM_id and the cancelMove() function. Below I have pasted my entire setHotkeys() function. Again, everything works except ctrl+m, but even that keystroke does not cause problems, it is like it is not even there. def setHotkeys(): upArrow_id=wx.NewId() downArrow_id=wx.NewId() leftArrow_id=wx.NewId() rightArrow_id=wx.NewId() space_id=wx.NewId() a_id=wx.NewId() f_id=wx.NewId() m_id=wx.NewId() r_id=wx.NewId() ctrlM_id=wx.NewId() ctrlN_id=wx.NewId() one_id=wx.NewId() two_id=wx.NewId() three_id=wx.NewId() four_id=wx.NewId() five_id=wx.NewId() six_id=wx.NewId() seven_id=wx.NewId() f1_id=wx.NewId() f2_id=wx.NewId() f3_id=wx.NewId() f4_id=wx.NewId() hotkeyList=[ (wx.ACCEL_NORMAL, wx.WXK_UP, upArrow_id), #up one face-up card in the current stack (wx.ACCEL_NORMAL, wx.WXK_DOWN, downArrow_id), #down one face-up card (wx.ACCEL_NORMAL, wx.WXK_LEFT, leftArrow_id), #left a stack (wx.ACCEL_NORMAL, wx.WXK_RIGHT, rightArrow_id), #right a stack (wx.ACCEL_NORMAL, ord('a'), a_id), #try to move last card to Ace stack (wx.ACCEL_NORMAL, ord('1'), one_id), #jump to stack 1 (wx.ACCEL_NORMAL, ord('2'), two_id), #jump to stack 2 (wx.ACCEL_NORMAL, ord('3'), three_id), #jump to stack 3 (wx.ACCEL_NORMAL, ord('4'), four_id), #jump to stack 4 (wx.ACCEL_NORMAL, ord('5'), five_id), #jump to stack 5 (wx.ACCEL_NORMAL, ord('6'), six_id), #jump to stack 6 (wx.ACCEL_NORMAL, ord('7'), seven_id), #jump to stack 7 (wx.ACCEL_NORMAL, ord('f'), f_id), #flip up a new card (wx.ACCEL_NORMAL, ord('r'), r_id), #read the current deck card in play (wx.ACCEL_CTRL, ord('m'), ctrlM_id), #cancel Move mode (wx.ACCEL_CTRL, ord('n'), ctrlN_id), #start a new hand (wx.ACCEL_NORMAL, ord('m'), m_id), #mark stack to be moved (wx.ACCEL_NORMAL, wx.WXK_SPACE, space_id), #move deck's facing card to activeStack #now f1-f4, for reviewing the four Ace stacks (wx.ACCEL_NORMAL, wx.WXK_F1, f1_id), (wx.ACCEL_NORMAL, wx.WXK_F2, f2_id), (wx.ACCEL_NORMAL, wx.WXK_F3, f3_id), (wx.ACCEL_NORMAL, wx.WXK_F4, f4_id)] #now bind the keys to their functions, using lambda to pass args f.Bind(wx.EVT_MENU, lambda evt, dir=1: exploreStack(evt, dir), id=upArrow_id) f.Bind(wx.EVT_MENU, lambda evt, dir=-1: exploreStack(evt, dir), id=downArrow_id) f.Bind(wx.EVT_MENU, lambda evt, dir=-1: move(evt, dir), id=leftArrow_id) f.Bind(wx.EVT_MENU, lambda evt, dir=1: move(evt, dir), id=rightArrow_id) f.Bind(wx.EVT_MENU, lambda evt: useDeckCard(evt), id=space_id) f.Bind(wx.EVT_MENU, lambda evt: toAcePile(evt), id=a_id) f.Bind(wx.EVT_MENU, lambda evt: deal(evt), id=f_id) f.Bind(wx.EVT_MENU, lambda evt: readDeckCard(evt), id=r_id) f.Bind(wx.EVT_MENU, lambda evt, target=1, jump=True: move(evt, target, jump), id=one_id) f.Bind(wx.EVT_MENU, lambda evt, target=2, jump=True: move(evt, target, jump), id=two_id) f.Bind(wx.EVT_MENU, lambda evt, target=3, jump=True: move(evt, target, jump), id=three_id) f.Bind(wx.EVT_MENU, lambda evt, target=4, jump=True: move(evt, target, jump), id=four_id) f.Bind(wx.EVT_MENU, lambda evt, target=5, jump=True: move(evt, target, jump), id=five_id) f.Bind(wx.EVT_MENU, lambda evt, target=6, jump=True: move(evt, target, jump), id=six_id) f.Bind(wx.EVT_MENU, lambda evt, target=7, jump=True: move(evt, target, jump), id=seven_id) f.Bind(wx.EVT_MENU, lambda evt, sel=activeStack: selectStack(evt, sel), id=m_id) f.Bind(wx.EVT_MENU, lambda evt: cancelMove(evt), id=ctrlM_id) f.Bind(wx.EVT_MENU, lambda evt: promptForNewGame(evt), id=ctrlN_id) f.Bind(wx.EVT_MENU, lambda evt, target=0: reviewAceStack(evt, target), id=f1_id) f.Bind(wx.EVT_MENU, lambda evt, target=1: reviewAceStack(evt, target), id=f2_id) f.Bind(wx.EVT_MENU, lambda evt, target=2: reviewAceStack(evt, target), id=f3_id) f.Bind(wx.EVT_MENU, lambda evt, target=3: reviewAceStack(evt, target), id=f4_id) hotkeys=wx.AcceleratorTable(hotkeyList) f.SetAcceleratorTable(hotkeys) -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From davea at ieee.org Wed Jan 5 23:08:21 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 05 Jan 2011 17:08:21 -0500 Subject: [Tutor] range function and floats? In-Reply-To: References: <4D2452A6.9050709@pearwood.info> <4D249FCC.9030708@pearwood.info> Message-ID: <4D24EBD5.9070801@ieee.org> On 01/-10/-28163 02:59 PM, Wayne Werner wrote: > On Wed, Jan 5, 2011 at 10:43 AM, Steven D'Apranowrote: > >> Wayne Werner wrote: >> >> The decimal module allows you to get rid of those pesky floating point >>> errors. See http://docs.python.org/library/decimal.html for more info. >>> >> >> That's a myth. Decimal suffers from the same floating point issues as >> binary floats. It's quite easy to demonstrate the same sort of rounding >> errors with Decimal as for float: >> >>>>> from decimal import Decimal as D >>>>> x = D(1)/D(3) >>>>> 3*x == 1 >> False >> > > I should have clarified - when I say pesky floating point errors I mean > errors in precision that you naturally would not expect. > I'd expect them. Apparently you would not. > 1/3 == .333 (repeating forever(?)). But on a computer, you're limited to a > specific precision point (sort of), and the moment you truncate > .333(repeating) to *any* finite points of precision you no longer have the > result of the mathematical operation 1/3. Yes, 1/3*3 == 1, but the error in > the Decimal module is *only* in division. It might be useful to define a > "repeating" flag in the Decimal module for the results of such operations as > 1/3, which would get rid of the error in truncation. Interesting flag. So how would it indicate that the decimal version of the number 762/477 repeats every 476 digits? But this is a > fundamentally different error from the standard floating point errors. > > In [106]: 0.9 > Out[106]: 0.90000000000000002 > These "errors" are in the conversion between string and floating point, and back again. The number 0.9 has a repeating bit pattern in binary floating point, so it cannot be represented exactly. That's not an error, it's a direct consequence of the decision to use binary floating point. And that decision was made decades ago, and is independent of Python. When I learned Fortran in the 60's, one of the things the book (McCracken) emphasized was not to compare real numbers with equality, but to use the form abs(x-y) These are two different numbers, mathematically. If I say x = 0.9, I > naturally assume that 0.9 is the value in x, not 0.90000000000000002. Of > course it's all in the implementation of floating points, and the fact that > Python evaluates 0.9 in a floating point context which results in the stored > value, but that ignores the fact that *naturally* one does not expect this. > And anyone who's been through 2nd or 3rd grade or whenever they teach about > equality would expect that this would evaluate to False. > Lots of stuff they teach in 3rd grade is oversimplified for the real world. > In [112]: 0.90000000000000002 == 0.9 > Out[112]: True > > You don't get such silliness with the Decimal module: > > In [125]: D('0.90000000000000002') == D('0.9') > Out[125]: False > > The conversion between string and float is logically a divide, where the denominator is a power of 10. So decimal floating point doesn't have any quantization errors for that conversion. Even if you use the decimal package, you need to understand these things, or you'll make the kind of error made a few days ago, where binary floating point values were passed into a decimal constructor. That won't "fix" problems that were already there. It just may mask them for certain cases. >> Between 1 and 1000 inclusive, there are 354 such numbers: >> >>>>> nums = [] >>>>> for i in range(1, 1001): >> ... x = D(1)/D(i) >> ... if x*i != 1: nums.append(i) >> ... >>>>> len(nums) >> 354 >> >> >> >> The problem isn't just division and multiplication, nor does it just affect >> fractional numbers: >> >>>>> x = D(10)**30 >>>>> x + 100 == x >> True >> >> > Decimal DOES get rid of floating point errors, except in the case of > repeating (or prohibitively large precision values) > > In [127]: x = D(10)**30 > > In [128]: x > Out[128]: Decimal('1.000000000000000000000000000E+30') > > In [129]: x + 100 > Out[129]: Decimal('1.000000000000000000000000000E+30') > > If you reset the precision to an incredibly large number: > decimal.getcontext().prec = 1000 > > In [131]: x = D(10)**30 > > In [132]: x > Out[132]: Decimal('1000000000000000000000000000000') > > In [133]: x + 100 == x > Out[133]: False > > Voila, the error has vanished! > > >> >> So it simply isn't correct to suggest that Decimal doesn't suffer from >> rounding error. > > > I never said rounding errors - I said "pesky floating point errors". When > performing the operation 1/3, I naturally expect that my computer won't hold > each of the 3's after the decimal point, and I don't categorize that as > pesky - that's just good sense if you know a little about computers. I also > expect that .333 * 3 would give me the number .999, and only .999, not > .9990000000011 or some other wonky value. Of course it's interesting to note > that Python handles the precision properly when dealing with strings, but > not with the floating points themselves (at least on this particular trial): > > In [141]: .333 * 3 > Out[141]: 0.99900000000000011 > > In [142]: str(.333*3) > Out[142]: '0.999' > > In [143]: .333 * 3 == .999 > Out[143]: False > > In [144]: str(.333*3) == str(.999) > Out[144]: True > > > Decimal and float share more things in common than differences. Both are >> floating point numbers. Both have a fixed precision (although you can >> configure what that precision is for Decimal, but not float). Both use a >> finite number of bits, and therefore have a finite resolution. The only >> differences are: >> >> * as mentioned, you can configure Decimal to use more bits and higher >> precision, at the cost of speed and memory; >> * floats use base 2 and Decimal uses base 10; >> * floats are done in hardware and so are much faster than Decimal; >> > > Precisely. It's not a magic bullet (1/3 != .33333333 mathematically, after > all!), *but* it eliminates the errors that you wouldn't normally expect when > working with "standard" points of precision, such as the expectation that > 0.333 * 3 resulting in .999, not .99900000000011. > > Hopefully a little more precise, > Wayne > From steve at pearwood.info Wed Jan 5 23:59:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 06 Jan 2011 09:59:14 +1100 Subject: [Tutor] range function and floats? In-Reply-To: References: <4D2452A6.9050709@pearwood.info> <4D249FCC.9030708@pearwood.info> Message-ID: <4D24F7C2.40709@pearwood.info> Wayne Werner wrote: > On Wed, Jan 5, 2011 at 10:43 AM, Steven D'Aprano wrote: > >> Wayne Werner wrote: >> >> The decimal module allows you to get rid of those pesky floating point >>> errors. See http://docs.python.org/library/decimal.html for more info. >>> >> That's a myth. Decimal suffers from the same floating point issues as >> binary floats. It's quite easy to demonstrate the same sort of rounding >> errors with Decimal as for float: >> >>>>> from decimal import Decimal as D >>>>> x = D(1)/D(3) >>>>> 3*x == 1 >> False >> > > I should have clarified - when I say pesky floating point errors I mean > errors in precision that you naturally would not expect. Say what? But that's the whole point -- you *must* expect them, because Decimal floating point numbers suffer the *exact* same issues with rounding and finite precision as binary floats. It may affect different specific numbers, but the issues are exactly the same. Just because Decimal uses base 10 doesn't make it immune to the same issues of rounding and precision as base 2 floats. > 1/3 == .333 (repeating forever(?)). But on a computer, you're limited to a > specific precision point (sort of), and the moment you truncate > .333(repeating) to *any* finite points of precision you no longer have the > result of the mathematical operation 1/3. Yes, 1/3*3 == 1, but the error in > the Decimal module is *only* in division. It might be useful to define a I'm surprised you can make such an obviously wrong claim -- you even discuss errors in addition further down. How can you do that and still say that errors only occur with division??? Decimal includes a significant amount of code to detect when the result of some operation is inexact, and to signal the user when it occurs. This does *not* only happen in division: >>> import decimal >>> decimal.getcontext().traps[decimal.Inexact] = 1 >>> a = decimal.Decimal('1e-30') >>> b = decimal.Decimal('11.1') >>> a+b Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.1/decimal.py", line 1178, in __add__ ans = ans._fix(context) File "/usr/local/lib/python3.1/decimal.py", line 1653, in _fix context._raise_error(Inexact) File "/usr/local/lib/python3.1/decimal.py", line 3812, in _raise_error raise error(explanation) decimal.Inexact: None > "repeating" flag in the Decimal module for the results of such operations as > 1/3, which would get rid of the error in truncation. But this is a You haven't thought that through very well. How do you deal with square roots and other fractional powers without truncation errors? What happens when you operate on two numbers with this repeating flag -- is the Decimal module supposed to include a full-blown algebra system to generate exact answers to such things as this? x = 1/Decimal(3) # 0.333 repeating y = 1/Decimal(27) # 0.037037 repeating x - y/10**9 # 0.333333333296296296 repeating How do you deal with numbers like pi or e without truncation? No, a repeating flag would just add unnecessary complexity for no real benefit. If you want to track fractions exactly, use the fractions module. > fundamentally different error from the standard floating point errors. But they aren't fundamentally different! That's the point! They are the same errors. They effect different numbers, because float is base 2 and Decimal is base 10, but they have the same fundamental cause. > In [106]: 0.9 > Out[106]: 0.90000000000000002 > > These are two different numbers, mathematically. If I say x = 0.9, I > naturally assume that 0.9 is the value in x, not 0.90000000000000002. Of Yes, and the exact same issue can occur in Decimal. It just affects different numbers. 0.9 is exact in base 10, but can't be represented exactly in base 2. Fortunately, the opposite is not the case: any finite number of binary bits is equivalent to a finite number of decimal digits, so unless you overflow the number of digits, you won't get an equivalent error for binary->decimal conversion. But there are numbers which can't be represented exactly in base 10 at any finite precision. 1/3 is one of them, so is 5/17 and an infinite number of other examples. You can even find examples of numbers which are exact in base 2 but inexact in Decimal at whatever finite precision you choose. >>> 2**120 1329227995784915872903807060280344576 >>> int( 1/( 1/Decimal(2**120) ) ) 1329227995784915872903807060000000000 Choose more digits for Decimal, and 2**120 can be stored exactly, but other, larger, numbers can't. > course it's all in the implementation of floating points, and the fact that > Python evaluates 0.9 in a floating point context which results in the stored > value, but that ignores the fact that *naturally* one does not expect this. > And anyone who's been through 2nd or 3rd grade or whenever they teach about > equality would expect that this would evaluate to False. Floating point numbers are not the same as the real numbers you learn about in school. It doesn't matter whether you use binary floats or decimal floats or base-19 floats. > In [112]: 0.90000000000000002 == 0.9 > Out[112]: True > > You don't get such silliness with the Decimal module: > > In [125]: D('0.90000000000000002') == D('0.9') > Out[125]: False Naturally Decimal is good at representing numbers which can be written exactly in decimal. That's what it was designed for :) > Decimal DOES get rid of floating point errors, except in the case of > repeating (or prohibitively large precision values) In other words, decimal gets rid of floating point errors, except for floating point errors. That's exactly what floating point errors are: numbers which can't be represented exactly in the given number of bits or digits. Regardless of base, you must expect floating point calculations to overflow, underflow, or just generally experience rounding errors. [...] > If you reset the precision to an incredibly large number: > decimal.getcontext().prec = 1000 Yes, one advantage of Decimal is that it gives you control of how many digits the numbers can store. This is a good, but expensive, feature. Nevertheless, it doesn't change the existence of rounding errors. No matter what precision you choose, I can ALWAYS give you numbers that will overflow or underflow that precision. > > In [131]: x = D(10)**30 > > In [132]: x > Out[132]: Decimal('1000000000000000000000000000000') > > In [133]: x + 100 == x > Out[133]: False > > Voila, the error has vanished! But only for that specific value. This is no different from the binary world, going from single precision floats to double to quad precision. At each stage you can represent more numbers exactly, because you have more bits to store them in, but there are always numbers that require more. Decimal is no different. >> So it simply isn't correct to suggest that Decimal doesn't suffer from >> rounding error. > > > I never said rounding errors - I said "pesky floating point errors". When Which ARE rounding errors. They're *all* rounding errors, caused by the same fundamental issue -- the impossibility of representing some specific exact number in the finite number of bits, or digits, available. Only the specific numbers change, not the existence of the errors. -- Steven From alan.gauld at btinternet.com Thu Jan 6 01:52:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Jan 2011 00:52:15 -0000 Subject: [Tutor] user input help References: Message-ID: "Jason Staudenmayer" wrote > I'm working on a small program to add users to a sqlite db. Try the database topic in my tutorial where I do a very similar thing... > code follows ------------- def promptInput(): ... result = (lname, fname, email) return result def getEmplyInfo(): # get the data from input result = promptInput() # print the data so the user can check and verify spelling print "Is the following info correct [y/n]\n%s, %s %s" % (result[1], \ result[0], result[2]) check = raw_input() #see if the user needs to make corrections to the data he entered if check == "y": print "this check is done so we can add user" print "%s, %s %s" % (result[1], result[0], result[2]) else: check = "" promptInput() > --------------------------- > The if else loop is were I'm loosing it. if else is not a loop it is a branch. See the What is Profgramming topic in my tutorial for a description of the different structures. Then see the loops and branching topics for loop and branch structures. You need a loop. The topics give examples. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kb1pkl at aim.com Thu Jan 6 04:01:38 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 05 Jan 2011 22:01:38 -0500 Subject: [Tutor] wx accelerator table: one keystroke seems skipped In-Reply-To: References: Message-ID: <4D253092.5050404@aim.com> On 01/05/2011 04:41 PM, Alex Hall wrote: > Hello all, > First, this is about a wx accelerator table, so if it is too off-topic > for this list, let me know. > > [snip] I would go ask the wxPython mailing list or similar, just my 2 cents. ~Corey Richardson From orasnita at gmail.com Thu Jan 6 07:41:46 2011 From: orasnita at gmail.com (Octavian Rasnita) Date: Thu, 6 Jan 2011 08:41:46 +0200 Subject: [Tutor] wx accelerator table: one keystroke seems skipped References: Message-ID: From: "Alex Hall" > Hello all, > First, this is about a wx accelerator table, so if it is too off-topic > for this list, let me know. > > I have a table with 23 entries, all of which work. I added another > entry last night, and it does not work. The odd thing, though, is that > I do not get an error of any kind anywhere in the program, the > keystroke simply does not call the function to which it should be > bound. I even changed the function name to something that should have > thrown an exception, but nothing at all happens. The keystroke in > question is ctrl+m and is tied to ctrlM_id and the cancelMove() Control+M is equivalent with a key so this might be the problem. Octavian From cwitts at compuscan.co.za Thu Jan 6 07:57:58 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 06 Jan 2011 08:57:58 +0200 Subject: [Tutor] cx_Oracle help In-Reply-To: <30596546.post@talk.nabble.com> References: <30596546.post@talk.nabble.com> Message-ID: <4D2567F6.8070500@compuscan.co.za> On 05/01/2011 16:33, F1r3f1y wrote: > This guide helped me a lot with cx_Oracle > http://codingtutorials.co.uk/blog/?p=31 > > > Greg Lindstrom-3 wrote: > >> Hello, >> >> I'm trying to help out a friend and am stumped. Can you help me out? >> Thanks, >> --greg >> >> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >> I will briefly explain the problem I am facing. >> I am using Oracle 9.2, Python 2.5 and I installed cx_Oracle- >> 4.3.1-win32-9i-py25 in Python. >> >> From python I tried following : >> >>> import cx_Oracle >> >>> myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') >> >>> CONN = cx_Oracle.connect(myusr, mypwd, myDsn) >> Traceback (most recent call last): >> File "", line 1, in >> conn = cx_Oracle.Connection('scott','tiger',myDsn) >> RuntimeError: Unable to acquire Oracle environment >> handle >> >> I have set the below environment variables too >> NLS_LANG:.WE8MSWIN1252 >> ORACLE_HOME: D:\Tools\oracle\ora92 >> ORACLE_SID: AUBDBS01 >> PYTHON_HOME: d:\Utility\Python25 >> PYTHONPATH: >> %PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin >> LD_LIBRARY_PATH: %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib >> >> Not getting any idea where I am wrong? >> >> Regards, >> >> Kishore >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > You need to install the Runtime, 3rd product option in the Oracle Universal Installer. -- Kind Regards, Christian Witts From brightstaar385 at yahoo.com Thu Jan 6 12:02:45 2011 From: brightstaar385 at yahoo.com (shaheryar ali) Date: Thu, 6 Jan 2011 03:02:45 -0800 (PST) Subject: [Tutor] I cant find add/remove in linux In-Reply-To: <4D2567F6.8070500@compuscan.co.za> References: <30596546.post@talk.nabble.com> <4D2567F6.8070500@compuscan.co.za> Message-ID: <102664.29688.qm@web110107.mail.gq1.yahoo.com> Hi everone out there, I cant find add/remove in my linux, I am using a virtual box and actually want to install apache, what should?I do:) thanks ________________________________ From: Christian Witts To: tutor at python.org Sent: Thu, January 6, 2011 8:57:58 AM Subject: Re: [Tutor] cx_Oracle help On 05/01/2011 16:33, F1r3f1y wrote: > This guide helped me a lot with cx_Oracle > http://codingtutorials.co.uk/blog/?p=31 > > > Greg Lindstrom-3 wrote: >? ? >> Hello, >> >> I'm trying to help out a friend and am stumped.? Can you help me out? >> Thanks, >> --greg >> >> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - >>? ? ? I will briefly explain the problem I am facing. >>? ? ? I am using Oracle 9.2, Python 2.5 and I installed cx_Oracle- >> 4.3.1-win32-9i-py25 in Python. >> >>? ? ? From python I tried following : >>? ? ? >>>? import cx_Oracle >>? ? ? >>>? myDsn = cx_Oracle.makedsn('ISCN47',1521,'AUBDBS01') >>? ? ? >>>? CONN = cx_Oracle.connect(myusr, mypwd, myDsn) >>? ? ? ? ? ? ? ? ? ? ? Traceback (most recent call last): >>? ? ? ? ? ? ? ? ? ? ? File "", line 1, in >>? ? ? ? ? ? ? ? ? ? conn = cx_Oracle.Connection('scott','tiger',myDsn) >>? ? ? ? ? ? ? ? ? ? RuntimeError: Unable to acquire Oracle environment >> handle >> >>? ? ? I have set the below environment variables too >>? ? ? ? ? ? NLS_LANG:.WE8MSWIN1252 >>? ? ? ? ? ? ORACLE_HOME:? ? ? ? D:\Tools\oracle\ora92 >>? ? ? ? ? ? ORACLE_SID:? ? ? ? ? AUBDBS01 >>? ? ? ? ? ? PYTHON_HOME:? ? ? ? d:\Utility\Python25 >>? ? ? ? ? ? PYTHONPATH: >>%PYTHON_HOME%\lib;%PYTHON_HOME%\DLLs;%PYTHON_HOME%\Lib\site-packages;%ORACLE_HOME%\bin >>n >>? ? ? ? ? ? LD_LIBRARY_PATH:? %LD_LIBRARY_PATH%;D:\Tools\oracle\ora92\lib >> >>? ? ? Not getting any idea where I am wrong? >> >> Regards, >> >> Kishore >> >> _______________________________________________ >> Tutor maillist? -? Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >>? ? ? >? ? You need to install the Runtime, 3rd product option in the Oracle Universal Installer. -- Kind Regards, Christian Witts _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Jan 6 14:02:59 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 6 Jan 2011 07:02:59 -0600 Subject: [Tutor] range function and floats? In-Reply-To: <4D24F7C2.40709@pearwood.info> References: <4D2452A6.9050709@pearwood.info> <4D249FCC.9030708@pearwood.info> <4D24F7C2.40709@pearwood.info> Message-ID: On Wed, Jan 5, 2011 at 4:59 PM, Steven D'Aprano wrote: > Wayne Werner wrote: > >> > > I never said rounding errors - I said "pesky floating point errors". When >> > > Which ARE rounding errors. They're *all* rounding errors, caused by the > same fundamental issue -- the impossibility of representing some specific > exact number in the finite number of bits, or digits, available. > > Only the specific numbers change, not the existence of the errors. So truncation == rounding. I can agree with that, though they've always seemed distinct entities before, because you can round up or round down, but truncation simply removes what you don't want, which is equivalent to rounding down at whatever precision you want. Round down the tens place (or truncate anything lower than 1e2): 10000010 => 10000000 Round down the thousandth place (or truncate everything "past" 1e-2): 1/3 = .3333(repeating) => .330 Having re-read and thought about it for a while, I think my argument simply distills down to this: using Decimal both allows you control over your significant figures, and (at least for me) *requires* you to think about what sort of truncation/rounding you will experience, and let's be honest - usually the source of errors is we, the programmers, not thinking enough about precision - and the result of this thought process is usually the elimination, not of truncation/rounding, but of not accounting for these errors. Which, to me, equates to "eliminating those pesky floating point errors". Although to be more accurate I should have said "eliminates those pesky programmer errors when dealing with floating point arithmetic." apoligetically, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Jan 6 16:35:37 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 6 Jan 2011 10:35:37 -0500 Subject: [Tutor] wx accelerator table: one keystroke seems skipped In-Reply-To: References: Message-ID: On 1/6/11, Octavian Rasnita wrote: > From: "Alex Hall" >> Hello all, >> First, this is about a wx accelerator table, so if it is too off-topic >> for this list, let me know. >> >> I have a table with 23 entries, all of which work. I added another >> entry last night, and it does not work. The odd thing, though, is that >> I do not get an error of any kind anywhere in the program, the >> keystroke simply does not call the function to which it should be >> bound. I even changed the function name to something that should have >> thrown an exception, but nothing at all happens. The keystroke in >> question is ctrl+m and is tied to ctrlM_id and the cancelMove() > > Control+M is equivalent with a key so this might be the problem. Very interesting! When I changed it to shift+m, it worked perfectly, yet ctrl+m is completely ignored. I will have to Google this. Thanks for the hint; I never thought it was the actual keystroke that was causing the problem. > > Octavian > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From ziad.harb at bsci.com Thu Jan 6 17:21:33 2011 From: ziad.harb at bsci.com (Harb, Ziad (STP)) Date: Thu, 6 Jan 2011 10:21:33 -0600 Subject: [Tutor] 4suite for python 2.7.1 Message-ID: I'm using python 2.7.1 at work and we need to install 4suite-xml library but I see that the last installer is for python 2.5. Can you direct me to where I can download this installer from. I don't want the zip file, I want an installer. If it does not exist, Can you help me to make one? Thanks Ziad Harb Software Engineer ?? Boston Scientific Corporation LATITUDE Patient Management 4211 Lexington Ave N Arden Hills, MN 55126 Tel 651.582.6159 ziad.harb at bsci.com www.bsci.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From orasnita at gmail.com Thu Jan 6 18:46:03 2011 From: orasnita at gmail.com (Octavian Rasnita) Date: Thu, 6 Jan 2011 19:46:03 +0200 Subject: [Tutor] wx accelerator table: one keystroke seems skipped References: Message-ID: <11F7D2802D1E400FB0C7D878056BA15B@teddy> From: "Alex Hall" > On 1/6/11, Octavian Rasnita wrote: >> From: "Alex Hall" >>> Hello all, >>> First, this is about a wx accelerator table, so if it is too off-topic >>> for this list, let me know. >>> >>> I have a table with 23 entries, all of which work. I added another >>> entry last night, and it does not work. The odd thing, though, is that >>> I do not get an error of any kind anywhere in the program, the >>> keystroke simply does not call the function to which it should be >>> bound. I even changed the function name to something that should have >>> thrown an exception, but nothing at all happens. The keystroke in >>> question is ctrl+m and is tied to ctrlM_id and the cancelMove() >> >> Control+M is equivalent with a key so this might be the problem. > Very interesting! When I changed it to shift+m, it worked perfectly, > yet ctrl+m is completely ignored. I will have to Google this. Thanks > for the hint; I never thought it was the actual keystroke that was > causing the problem. I think that not the keystroke is the problem, but the library that creates the GUI that handles it might have a bug. I gave you the idea that Control+M might not work because for example if you press that hotkey in Notepad, it is like you'd press . Or if you write "dir" in a command prompt and then press Control+M, it will execute that command just like after pressing But I think that a good key handler should be able to distinguish between and Control+M... Octavian From alan.gauld at btinternet.com Thu Jan 6 19:37:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Jan 2011 18:37:36 -0000 Subject: [Tutor] I cant find add/remove in linux References: <30596546.post@talk.nabble.com> <4D2567F6.8070500@compuscan.co.za> <102664.29688.qm@web110107.mail.gq1.yahoo.com> Message-ID: "shaheryar ali" wrote > I cant find add/remove in my linux, I am using a virtual box and > actually want to install apache, This has little if anything to do with Python so you should probably try another discussion group. However, if you do, they will need to know more information. Like what variant of Linux you are using... There are many different package managers (which is what you are looking for, I think). You might try looking for Synaptic, that seems quite common on distributions using apt-get (mainly Debian based). But others use different tools. > what should I do:) Post on a Linux forum? :-) HTH, Alan G. Python tutor list moderator. From alan.gauld at btinternet.com Thu Jan 6 19:43:37 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Jan 2011 18:43:37 -0000 Subject: [Tutor] 4suite for python 2.7.1 References: Message-ID: "Harb, Ziad (STP)" wrote > I'm using python 2.7.1 at work and we need to install 4suite-xml > library but I see that the last installer is for python 2.5. > Can you direct me to where I can download this installer from. > I don't want the zip file, I want an installer. If it does not > exist, > Can you help me to make one? You should get the best response by posting on the 4suite site. This list is really for answering beginner type questions about Python. You might strike it lucky and find someone here has had the same issue but you are much more likely to get an answer from a 4suite users forum. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Thu Jan 6 19:50:05 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 6 Jan 2011 12:50:05 -0600 Subject: [Tutor] wx accelerator table: one keystroke seems skipped In-Reply-To: <11F7D2802D1E400FB0C7D878056BA15B@teddy> References: <11F7D2802D1E400FB0C7D878056BA15B@teddy> Message-ID: On Thu, Jan 6, 2011 at 11:46 AM, Octavian Rasnita wrote: > > I think that not the keystroke is the problem, but the library that creates > the GUI that handles it might have a bug. > > I gave you the idea that Control+M might not work because for example if > you press that hotkey in Notepad, it is like you'd press . > > Or if you write "dir" in a command prompt and then press Control+M, it will > execute that command just like after pressing > > But I think that a good key handler should be able to distinguish between > and Control+M... Unless the operating system reports Ctrl-M as a carriage return before the GUI can capture it. I'd venture to say it warrants some experiments. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mark at martialfit.net Thu Jan 6 19:55:24 2011 From: mark at martialfit.net (Mark Weil) Date: Thu, 6 Jan 2011 10:55:24 -0800 Subject: [Tutor] wx accelerator table: one keystroke seems skipped In-Reply-To: <11F7D2802D1E400FB0C7D878056BA15B@teddy> References: <11F7D2802D1E400FB0C7D878056BA15B@teddy> Message-ID: Ctrl+M isn't bound to anything in particular in wxPython (the 'enter' key or otherwise). Drop down menus will auto-bind menu items if you include the shortcut keys on the menu's line item; Ctrl+N for New, for example. The OS could also be catching the event and doing something unwanted. Ctrl+M works as expected on mine python 2.7 wxPython 2.8.11 WinXP Your best chance at getting this resolved would be to post a sample app demonstrating the problem. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Fri Jan 7 13:47:31 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Fri, 7 Jan 2011 13:47:31 +0100 Subject: [Tutor] variabel from raw input into re.search? Message-ID: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> I try to write a program, where the user can write a word or a name and I will tell how many times the subject was mentioned in a text, I'm hosting. I guess it's possible but not this way it seems? The re is only searching for the word "name" and not the variable name I'm using Python 2.6.6. TIA Tommy import re name = raw_input('Who would you like to check'? ') mytxt = open("text.txt", "r") antal = [] for line in mytxt: if re.search("(.*)name(.*)", line): antal.append(line) print name + ' was mentioned ' + str(len(antal)) + ' times in the text, -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Fri Jan 7 14:02:39 2011 From: evert.rol at gmail.com (Evert Rol) Date: Fri, 7 Jan 2011 14:02:39 +0100 Subject: [Tutor] variabel from raw input into re.search? In-Reply-To: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> References: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> Message-ID: <44F9FAE4-0558-44AA-ADC2-BBD781867A40@gmail.com> Hi Tommy, > I try to write a program, where the user can write a word or a name and I will tell how many times the subject was mentioned in a text, I?m hosting. > I guess it?s possible but not this way it seems? > The re is only searching for the word ?name? and not the variable name > I?m using Python 2.6.6. > TIA > Tommy This looks very much like a problem that was asked just a few days ago. Have a look at the thread at http://mail.python.org/pipermail/tutor/2011-January/081034.html , and see if the solutions offered there can help you. Cheers, Evert > import re > name = raw_input(?Who would you like to check?? ') > > mytxt = open("text.txt", "r") > antal = [] > for line in mytxt: > if re.search("(.*)name(.*)", line): > antal.append(line) > print name + ' was mentioned ' + str(len(antal)) + ' times in the text, > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Fri Jan 7 14:07:55 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 7 Jan 2011 07:07:55 -0600 Subject: [Tutor] variabel from raw input into re.search? In-Reply-To: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> References: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> Message-ID: On Fri, Jan 7, 2011 at 6:47 AM, Tommy Kaas wrote: > I try to write a program, where the user can write a word or a name and I > will tell how many times the subject was mentioned in a text, I?m hosting. > > I guess it?s possible but not this way it seems? > > The re is only searching for the word ?name? and not the variable name > > I?m using Python 2.6.6. > > TIA > > Tommy > > > > import re > > name = raw_input(?Who would you like to check?? ') > > > > mytxt = open("text.txt", "r") > > antal = [] > > for line in mytxt: > > if re.search("(.*)name(.*)", line): > > antal.append(line) > > print name + ' was mentioned ' + str(len(antal)) + ' times in the text, > In Python, there is no such thing as variable interpolation, such as you'd find in PHP or Perl. So when you type "(.*)name(.*)" (which I'm fairly sure is the equivalent of r".*name.*", and also the equivalent search of "name"), you literally have "name" in your string. You have 3 options, string concatenation, and two styles of formatting: >>> name = 'Sir Arthur' >>> '.*' + name + '.*' '.*Sir Arthur.*' >>> '.*%s.*' % (name, ) '.*Sir Arthur.*' >>> '.*{0}.*'.format(name) '.*Sir Arthur.*' >>> '.*{name}.*'.format(name=name) '.*Sir Arthur.*' The last two examples are different ways to accomplish the same thing. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From subscriptions at cagttraining.com Fri Jan 7 14:08:39 2011 From: subscriptions at cagttraining.com (Bill Felton) Date: Fri, 7 Jan 2011 08:08:39 -0500 Subject: [Tutor] variabel from raw input into re.search? In-Reply-To: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> References: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> Message-ID: On Jan 7, 2011, at 7:47 AM, Tommy Kaas wrote: > I try to write a program, where the user can write a word or a name and I will tell how many times the subject was mentioned in a text, I?m hosting. > I guess it?s possible but not this way it seems? > The re is only searching for the word ?name? and not the variable name > I?m using Python 2.6.6. > TIA > Tommy > > import re > name = raw_input(?Who would you like to check?? ') > > mytxt = open("text.txt", "r") > antal = [] > for line in mytxt: > if re.search("(.*)name(.*)", line): > antal.append(line) > print name + ' was mentioned ' + str(len(antal)) + ' times in the text, > > WARNING: Just a beginner here, but... The problem looks to me to be this: "(.*)name(.*)" is a literal string, so Python never "sees" the variable to get the value. You can test this by copying your argument string into the shell and evaluating it. Since you want the value of the variable, not the name, try this: "(.*)"+name+"(.*)" There may be other issues, but that should get you the string you want. (Again, you test this expression before use to verify that it does what you want, just assign a string variable to 'name' before testing.) regards, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Fri Jan 7 14:18:13 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Fri, 7 Jan 2011 14:18:13 +0100 Subject: [Tutor] variabel from raw input into re.search? In-Reply-To: References: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> Message-ID: <00ba01cbae6d$56c1c980$04455c80$@kaasogmulvad.dk> You have 3 options, string concatenation, and two styles of formatting: >>> name = 'Sir Arthur' >>> '.*' + name + '.*' '.*Sir Arthur.*' >>> '.*%s.*' % (name, ) '.*Sir Arthur.*' >>> '.*{0}.*'.format(name) '.*Sir Arthur.*' >>> '.*{name}.*'.format(name=name) '.*Sir Arthur.*' The last two examples are different ways to accomplish the same thing. HTH, Wayne Thanks for the suggestion. Very useful. Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 7 17:50:32 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Jan 2011 16:50:32 -0000 Subject: [Tutor] variabel from raw input into re.search? References: <00a601cbae69$0c82aa00$2587fe00$@kaasogmulvad.dk> Message-ID: "Tommy Kaas" wrote >I try to write a program, where the user can write a word or a name >and I > will tell how many times the subject was mentioned in a text, I'm > hosting. > > I guess it's possible but not this way it seems? > > The re is only searching for the word "name" and not the variable > name You don't need a regex here. name = raw_input('Who would you like to check'? ') with open("text.txt", "r") as mytxt: antal = [line for line in mytxt if name in line] print name,' was mentioned ', len(antal),' times in the text' Should suffice. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From scarolan at gmail.com Fri Jan 7 18:16:12 2011 From: scarolan at gmail.com (Sean Carolan) Date: Fri, 7 Jan 2011 11:16:12 -0600 Subject: [Tutor] matplotlib.pylab.plotfile formatting help In-Reply-To: <1F493031-CA23-4331-8B42-2384C49BE4C9@gmail.com> References: <1F493031-CA23-4331-8B42-2384C49BE4C9@gmail.com> Message-ID: > I can also advice you to try the matplotlib mailing list: people will there will be much more knowledgeable wrt to matplotlib and pylab than on this mailing list: http://sourceforge.net/mailarchive/forum.php?forum_name=matplotlib-users Thanks for all the info; I managed to create a graph from my data by using a tutorial I found on the Internet. From scarolan at gmail.com Fri Jan 7 20:22:23 2011 From: scarolan at gmail.com (Sean Carolan) Date: Fri, 7 Jan 2011 13:22:23 -0600 Subject: [Tutor] shlex.split if there is an apostrophe in the string? Message-ID: I'm practicing manipulating data with a text file. I'm trying to use shlex.split to break up each line, which works great until it gets to the first apostrophe: fin = open('huckfinn.txt') startstring = 'START OF THIS PROJECT' for line in fin: print line words = shlex.split(line) This is the line is where it's choking, complaining that there is no closing quote: YOU don't know about me without you have read a book by the name of The How can I get shlex.split to ignore single apostrophes such as the one above? From jasons at adventureaquarium.com Fri Jan 7 20:34:02 2011 From: jasons at adventureaquarium.com (Jason Staudenmayer) Date: Fri, 7 Jan 2011 14:34:02 -0500 Subject: [Tutor] shlex.split if there is an apostrophe in the string? In-Reply-To: Message-ID: > -----Original Message----- > From: tutor-bounces+jasons=adventureaquarium.com at python.org > [mailto:tutor-bounces+jasons=adventureaquarium.com at python.org] > On Behalf Of Sean Carolan > Sent: Friday, January 07, 2011 2:22 PM > To: Tutor at python.org > Subject: [Tutor] shlex.split if there is an apostrophe in the string? > > > I'm practicing manipulating data with a text file. I'm trying to use > shlex.split to break up each line, which works great until it gets to > the first apostrophe: > > fin = open('huckfinn.txt') > startstring = 'START OF THIS PROJECT' > > for line in fin: > print line > words = shlex.split(line) > > This is the line is where it's choking, complaining that there is no > closing quote: > > YOU don't know about me without you have read a book by the > name of The > > How can I get shlex.split to ignore single apostrophes such > as the one above? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > WARNING Total newbie here. Looks like you need to filter you data to excape the quote marks. I'm just learning so I'm not sure how to do that yet. Jason ..?><((((?> From emile at fenx.com Fri Jan 7 21:13:53 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 07 Jan 2011 12:13:53 -0800 Subject: [Tutor] shlex.split if there is an apostrophe in the string? In-Reply-To: References: Message-ID: On 1/7/2011 11:22 AM Sean Carolan said... > I'm practicing manipulating data with a text file. I'm trying to use > shlex.split to break up each line, Is there a reason not to use split directly? for line in fin: words = line.split() Emile which works great until it gets to > the first apostrophe: > > fin = open('huckfinn.txt') > startstring = 'START OF THIS PROJECT' > > for line in fin: > print line > words = shlex.split(line) > > This is the line is where it's choking, complaining that there is no > closing quote: > > YOU don't know about me without you have read a book by the name of The > > How can I get shlex.split to ignore single apostrophes such as the one above? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From paulmg2010 at gmail.com Fri Jan 7 22:04:13 2011 From: paulmg2010 at gmail.com (Paul Griffiths) Date: Fri, 7 Jan 2011 21:04:13 +0000 Subject: [Tutor] vim as a python editor In-Reply-To: References: Message-ID: On 5 January 2011 11:54, Sean Carolan wrote: > > How have those of you who use vim configured it? I have looked > > on the web but got a bit confused by the advice and options. > > My setup includes: > > autoindent turned on at 4 spaces > ftplugin for "folding" functions like eclipse (this is my favorite! > you just push f to expand a function) > minibufexplorer for opening multiple files > taglist for jumping around your code to different functions (needs > exuberant ctags) > > Here are some instructions for setting most of these up: > > http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/ > Thank you Sean for the above link, and to everyone else who replied. There is obviously a lot that can be done with vim, but I will take your advice and build up these skills gradually and try to concentrate on learning python! I've learned that: - gvim may suit me better than vim - a tabbed console is not as good as having a separate window for vim, the python interpreter and the shell. (thank you Alan) - re-configuring the Caps Lock to be an extra Esc saves time - I must learn how to 'fold' functions -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben.ganzfried at gmail.com Fri Jan 7 18:38:52 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Fri, 7 Jan 2011 12:38:52 -0500 Subject: [Tutor] Odd result from function call Message-ID: When I call one of my functions from the shell (ie compare(10, 5)) it produces the correct output. However, when I run the program after calling the method later in the script, the result is bizarre. I'm curious why the wrong result is printed. Here is an example: def compare(x,y): if x < y: print (x, " is less than ", y) print("x is ", x, "y is ", y) elif x > y: print(x, " is greater than ", y) else: print(x, " and ", y, " are equal.") x = input("First x is: ") y = input("First y is: ") print("x is ", x) print("y is ", y) compare(x,y) a = input("Second x is: ") b = input("Second y is: ") print("x is ", a) print("y is ", b) compare(a,b) c = input("Third x is: ") d = input("Third y is: ") print("x is ", c) print("y is ", d) compare(c,d) Sample (and incorrect) output w/ 10, 5: First x is: 10 First y is: 5 x is 10 y is 5 10 is less than 5 x is 10 y is 5 Second x is: When I do simply compare(10, 5) from the shell, I get the correct output (ie 10 is greater than 5). I had thought I had narrowed the problem down to the fact that when I run the script only the first digit is counted-- however, it seems as if only the first digit is counted (ie anything starting w/ a 9 will be greater than anything starting with a 1 (even if the numbers are 9 and 1324234)), and THEN, the second digit is counted (such that 89 is correctly identified at 81). Anyway I'm wondering: 1) Why does the script run correctly when I simply call the function from the shell but not when I try to call the function from within the script? 2) What is actually going on such that only the first digit is being evaluated? That is, the interpreter knows that x is 10 and y is 5-- and yet, for some reason the 5 is being tested against the 1 and since 5 is bigger than 1, it concludes that 5 is greater than 10. thanks! Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From vince at vinces.ca Fri Jan 7 22:15:13 2011 From: vince at vinces.ca (Vince Spicer) Date: Fri, 7 Jan 2011 15:15:13 -0600 Subject: [Tutor] Odd result from function call In-Reply-To: References: Message-ID: On Fri, Jan 7, 2011 at 11:38 AM, Ben Ganzfried wrote: > When I call one of my functions from the shell (ie compare(10, 5)) it > produces the correct output. However, when I run the program after calling > the method later in the script, the result is bizarre. I'm curious why the > wrong result is printed. Here is an example: > > def compare(x,y): > if x < y: > print (x, " is less than ", y) > print("x is ", x, "y is ", y) > elif x > y: > print(x, " is greater than ", y) > else: > print(x, " and ", y, " are equal.") > > > x = input("First x is: ") > y = input("First y is: ") > print("x is ", x) > print("y is ", y) > compare(x,y) > a = input("Second x is: ") > b = input("Second y is: ") > print("x is ", a) > print("y is ", b) > compare(a,b) > c = input("Third x is: ") > d = input("Third y is: ") > print("x is ", c) > print("y is ", d) > compare(c,d) > > Sample (and incorrect) output w/ 10, 5: > > First x is: 10 > First y is: 5 > x is 10 > y is 5 > 10 is less than 5 > x is 10 y is 5 > Second x is: > > When I do simply compare(10, 5) from the shell, I get the correct output > (ie 10 is greater than 5). I had thought I had narrowed the problem down to > the fact that when I run the script only the first digit is counted-- > however, it seems as if only the first digit is counted (ie anything > starting w/ a 9 will be greater than anything starting with a 1 (even if the > numbers are 9 and 1324234)), and THEN, the second digit is counted (such > that 89 is correctly identified at 81). > > Anyway I'm wondering: > 1) Why does the script run correctly when I simply call the function from > the shell but not when I try to call the function from within the script? > 2) What is actually going on such that only the first digit is being > evaluated? That is, the interpreter knows that x is 10 and y is 5-- and > yet, for some reason the 5 is being tested against the 1 and since 5 is > bigger than 1, it concludes that 5 is greater than 10. > > thanks! > > Ben > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Ben It would appear that you are comparing string in your script and not integers a= int(input(.......)) -- Vince Spicer Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jan 7 22:16:15 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 7 Jan 2011 16:16:15 -0500 Subject: [Tutor] Odd result from function call In-Reply-To: References: Message-ID: Cast to an int: x=int(x) See if that helps. On 1/7/11, Ben Ganzfried wrote: > When I call one of my functions from the shell (ie compare(10, 5)) it > produces the correct output. However, when I run the program after calling > the method later in the script, the result is bizarre. I'm curious why the > wrong result is printed. Here is an example: > > def compare(x,y): > if x < y: > print (x, " is less than ", y) > print("x is ", x, "y is ", y) > elif x > y: > print(x, " is greater than ", y) > else: > print(x, " and ", y, " are equal.") > > > x = input("First x is: ") > y = input("First y is: ") > print("x is ", x) > print("y is ", y) > compare(x,y) > a = input("Second x is: ") > b = input("Second y is: ") > print("x is ", a) > print("y is ", b) > compare(a,b) > c = input("Third x is: ") > d = input("Third y is: ") > print("x is ", c) > print("y is ", d) > compare(c,d) > > Sample (and incorrect) output w/ 10, 5: > > First x is: 10 > First y is: 5 > x is 10 > y is 5 > 10 is less than 5 > x is 10 y is 5 > Second x is: > > When I do simply compare(10, 5) from the shell, I get the correct output (ie > 10 is greater than 5). I had thought I had narrowed the problem down to the > fact that when I run the script only the first digit is counted-- however, > it seems as if only the first digit is counted (ie anything starting w/ a 9 > will be greater than anything starting with a 1 (even if the numbers are 9 > and 1324234)), and THEN, the second digit is counted (such that 89 is > correctly identified at 81). > > Anyway I'm wondering: > 1) Why does the script run correctly when I simply call the function from > the shell but not when I try to call the function from within the script? > 2) What is actually going on such that only the first digit is being > evaluated? That is, the interpreter knows that x is 10 and y is 5-- and > yet, for some reason the 5 is being tested against the 1 and since 5 is > bigger than 1, it concludes that 5 is greater than 10. > > thanks! > > Ben > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From alan.gauld at btinternet.com Fri Jan 7 22:21:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Jan 2011 21:21:11 -0000 Subject: [Tutor] Odd result from function call References: Message-ID: "Ben Ganzfried" wrote > x = input("First x is: ") > y = input("First y is: ") input() reads strings > compare(x,y) the character '1' is less than the character '5' so far as Python is concerned > When I do simply compare(10, 5) from the shell, You are using integers. What happens if you use strings? >>> compare('10','5') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jan 7 22:25:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Jan 2011 21:25:08 -0000 Subject: [Tutor] vim as a python editor References: Message-ID: "Paul Griffiths" wrote > I've learned that: > ... > - re-configuring the Caps Lock to be an extra Esc saves time Huh? How do you use that? Its a new one on me. Why would two escape keys be useful? > - I must learn how to 'fold' functions Read the vim help. Also read about ctags - they work with python code too. Combining ctags with vim gives you some very powerful navigation tools - ie put the cursor on a function name and hit the tags key to go directly to the function definition. Even if it's in another file... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ashish.makani at gmail.com Fri Jan 7 22:48:51 2011 From: ashish.makani at gmail.com (ashish makani) Date: Fri, 7 Jan 2011 13:48:51 -0800 Subject: [Tutor] vim as a python editor In-Reply-To: References: Message-ID: @Alan, maybe hitting the actual "Esc" key requires too much "reach" Mapping CapsLock to escape maybe lets u type faster, perhaps I am just guessing though..maybe Paul can explain On vim, just saw this on hnews today morning...might be of interest http://news.ycombinator.com/item?id=2080342 http://vim.runpaint.org/ Happy Friday cheers ashish On Fri, Jan 7, 2011 at 1:25 PM, Alan Gauld wrote: > "Paul Griffiths" wrote > >> I've learned that: >> ... >> >> - re-configuring the Caps Lock to be an extra Esc saves time >> > > Huh? How do you use that? Its a new one on me. Why would two escape keys be > useful? > > > - I must learn how to 'fold' functions >> > > Read the vim help. > > Also read about ctags - they work with python code too. > Combining ctags with vim gives you some very powerful navigation tools - ie > put the cursor on a function name and hit the tags key to go directly to the > function definition. Even if it's in another file... > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.griffiths0 at googlemail.com Fri Jan 7 22:56:37 2011 From: paul.griffiths0 at googlemail.com (Paul Griffiths) Date: Fri, 7 Jan 2011 21:56:37 +0000 Subject: [Tutor] Tutor Digest, Vol 83, Issue 22 In-Reply-To: References: Message-ID: Date: Fri, 7 Jan 2011 21:25:08 -0000 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] vim as a python editor > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > "Paul Griffiths" wrote > > > I've learned that: > > ... > > - re-configuring the Caps Lock to be an extra Esc saves time > > Huh? How do you use that? Its a new one on me. Why would > two escape keys be useful? > I can touch type, and find the 'proper' Esc key is too far away for my little finger to reach comfortably. The Caps Lock key is easier to reach. > > > - I must learn how to 'fold' functions > > Read the vim help. > > Also read about ctags - they work with python code too. > Combining ctags with vim gives you some very powerful > navigation tools - ie put the cursor on a function name and > hit the tags key to go directly to the function definition. > Even if it's in another file... > > HTH, > > yes, thanks for that > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 83, Issue 22 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pyprog05 at gmail.com Fri Jan 7 23:16:14 2011 From: pyprog05 at gmail.com (PyProg PyProg) Date: Fri, 7 Jan 2011 23:16:14 +0100 Subject: [Tutor] Parse MPL files Message-ID: Hi all, I'm looking for a way to parse MPL files (.MPL or .mpl extension). These files are contained in the tree of some cameras that support the AVCHD ... and some cameras filming with a stream mpeg-ts. I know a person who seeks to recover the data contained in these files. MPL (or .mpl). The data in this kind of file are the date and location (by GPS info), I would help him recover the data. Is there a Python module who make that ?, or how to proceed ? Thank you in advance. a+ -- http://ekd.tuxfamily.org http://ekdm.wordpress.com http://lcs.dunois.clg14.ac-caen.fr/~alama/blog http://lprod.org/wiki/doku.php/video:encodage:avchd_converter From alan.gauld at btinternet.com Fri Jan 7 23:57:16 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 7 Jan 2011 22:57:16 +0000 (GMT) Subject: [Tutor] vim as a python editor In-Reply-To: References: Message-ID: <277787.69837.qm@web86703.mail.ird.yahoo.com> > > useful? > > I believe this is so you don't have to reach as far to hit ESC; caps > lock is located right next to the A key. Ah, that might make sense. I used to have a utility on my old Sun workstation to remap Caps lock to Ctrl because Ctrl was originally (on the first Sun's) where Ca[ps lock is and it made typing Ctrl sequences in emacs much easier. But as a non touch typist the fraction of a second it would save me is not really very helpful :-) Alan G. From kb1pkl at aim.com Sat Jan 8 00:30:39 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 07 Jan 2011 18:30:39 -0500 Subject: [Tutor] Parse MPL files Message-ID: <4D27A21F.5070001@aim.com> On 01/07/2011 05:16 PM, PyProg PyProg wrote: > Hi all, > > I'm looking for a way to parse MPL files (.MPL or .mpl extension). > These files are contained in the tree of some cameras that support the > AVCHD ... and some cameras filming with a stream mpeg-ts. > > I know a person who seeks to recover the data contained in these > files. MPL (or .mpl). The data in this kind of file are the date and > location (by GPS info), I would help him recover the data. > > Is there a Python module who make that ?, or how to proceed ? > > Thank you in advance. > > a+ > A google search yields no results for one. If you know the structure of the MPL file, you can write your own parser. Look through the file with a hex editor like Bless first, if you need to. Most likely the information you want is right at the start of the file. ~Corey Richardson From kb1pkl at aim.com Sat Jan 8 00:33:42 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 07 Jan 2011 18:33:42 -0500 Subject: [Tutor] Parse MPL files In-Reply-To: References: <4D27932D.8070106@aim.com> Message-ID: <4D27A2D6.3050503@aim.com> On 01/07/2011 06:29 PM, PyProg PyProg wrote: > 2011/1/7 Corey Richardson : > > Hi, > > Thanks for your response. > >> A google search yields no results for one. If you know the structure of >> the MPL file, you can write your own parser. Look through the file with >> a hex editor like Bless first, if you need to. Most likely the >> information you want is right at the start of the file. > > Parts of the data is inaccessible (very large parts in fact).The > structure is like that: > > Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) > [GCC 4.4.1] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> o = open("/home/toto/ae/00001.MPL", "r") >>>> oo = o.readlines() >>>> for listage, ligne in enumerate(oo): > ... print "Ligne n?", listage, ":", ligne > ... > Ligne n? 0 : MPLS0100:? > > Ligne n? 1 : ?@?`00005M2TS?X1?P> ?1und > ?und`00002M2TSp??> ?1und ?und`00003M2TSqu??> > ?1und ?und`00004M2T??> ?1und > ?und:?X??p??qu????J??6PLEXDR??? ? > > Ligne n? 2 : 2011. 1. 1 > > GH???? DD? : ?T%d > > Ligne n? 4 : 2011. 1. 1T%dGH???? X&? > > Ligne n? 5 : 2011. 1. 1T%dGH?????? > > Ligne n? 6 : 2011. 1. 1T%dGH???? > ??? > > ????(????~?????????????B???????~???"?????'???? > ?u???A???>???O??$mCy?C?N????g?????>?3??????@F?^?,dW&#?Y?}n?????A?$??`??N0 > ?d1A2 > > Ligne n? 7 : > > Ligne n? 8 : WGS-84 1GPSFRANCE > > ,dW&e n? 9 : FINIST?RELOCMARIA-PLOUZAN?---??N0 > ?d1A2 > > Ligne n? 10 : > > Ligne n? 11 : WGS-84 1GPSFRANCE > > 5"A2e n? 12 : FINIST?RELOCMARIA-PLOUZAN?---??N0qdW*?d > > Ligne n? 13 : > > Ligne n? 14 : WGS-84 GPSFRANCE > > Ligne n? 15 : FINIST?RE > 5"A2 PLOUGONVELINCENTRE AQUATIQUE TR?ZIROISE??N0qdW*?d > > Ligne n? 16 : > > Ligne n? 17 : WGS-84 GPSFRANCE > > Ligne n? 18 : FINIST?RE > PLOUGONVELINCENTRE AQUATIQUE TR?ZIROISE? ? > > ??DMC-TZ10?DMC-TZ10?DMC-TZ10?DMC-TZ10 > > > How to set up a hex editor ? > >> ~Corey Richardson > > a+ > Open the file not with 'r' but with 'rb'. That opens the file as binary, not text. To use Bless, run sudo apt-get install bless on Ubuntu and variants, for Windows try HxD, http://mh-nexus.de/en/hxd/. From steve at pearwood.info Sat Jan 8 01:22:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Jan 2011 11:22:53 +1100 Subject: [Tutor] vim as a python editor In-Reply-To: References: Message-ID: <4D27AE5D.3040806@pearwood.info> Alan Gauld wrote: > "Paul Griffiths" wrote >> I've learned that: >> ... >> - re-configuring the Caps Lock to be an extra Esc saves time > > Huh? How do you use that? Its a new one on me. Why would two escape keys > be useful? What if you want to escape the escape, so that (say) esc-C is the same as just C? Not-very-helpfully y'rs, -- Steven From steve at pearwood.info Sat Jan 8 01:31:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Jan 2011 11:31:34 +1100 Subject: [Tutor] shlex.split if there is an apostrophe in the string? In-Reply-To: References: Message-ID: <4D27B066.4020702@pearwood.info> Emile van Sebille wrote: > On 1/7/2011 11:22 AM Sean Carolan said... >> I'm practicing manipulating data with a text file. I'm trying to use >> shlex.split to break up each line, > > Is there a reason not to use split directly? > > for line in fin: > words = line.split() shlex.split was specifically written to overcome a limitation of str.split, namely that str.split doesn't understand quoting: >>> text = "This includes some 'quoted text', as they call it." >>> text.split() ['This', 'includes', 'some', "'quoted", "text',", 'as', 'they', 'call', 'it.'] >>> shlex.split(text) ['This', 'includes', 'some', 'quoted text,', 'as', 'they', 'call', 'it.'] Although the functions have the same name, they do different things. -- Steven From steve at pearwood.info Sat Jan 8 01:38:44 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Jan 2011 11:38:44 +1100 Subject: [Tutor] shlex.split if there is an apostrophe in the string? In-Reply-To: References: Message-ID: <4D27B214.6090006@pearwood.info> Sean Carolan wrote: [...] > YOU don't know about me without you have read a book by the name of The > > How can I get shlex.split to ignore single apostrophes such as the one above? >>> shlex.split("The Doctor's bow ties are cool, and Amy's uniform is hot.") ['The', 'Doctors bow ties are cool, and Amys', 'uniform', 'is', 'hot.'] >>> >>> shlex.split("The Doctor's bow ties are cool, and Amy's uniform is hot.", posix=False) ['The', "Doctor's", 'bow', 'ties', 'are', 'cool,', 'and', "Amy's", 'uniform', 'is', 'hot.'] Fans of Doctor Who will know exactly what I'm talking about... -- Steven From steve at pearwood.info Sat Jan 8 06:35:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 08 Jan 2011 16:35:51 +1100 Subject: [Tutor] range function and floats? In-Reply-To: References: <4D2452A6.9050709@pearwood.info> <4D249FCC.9030708@pearwood.info> <4D24F7C2.40709@pearwood.info> Message-ID: <4D27F7B7.9010808@pearwood.info> Wayne Werner wrote: > On Wed, Jan 5, 2011 at 4:59 PM, Steven D'Aprano wrote: > >> Wayne Werner wrote: >> >>> >> I never said rounding errors - I said "pesky floating point errors". When >> Which ARE rounding errors. They're *all* rounding errors, caused by the >> same fundamental issue -- the impossibility of representing some specific >> exact number in the finite number of bits, or digits, available. >> >> Only the specific numbers change, not the existence of the errors. > > > So truncation == rounding. I can agree with that, though they've always > seemed distinct entities before, because you can round up or round down, but > truncation simply removes what you don't want, which is equivalent to > rounding down at whatever precision you want. Well, technically truncation is a special case of rounding: round towards zero. When you round, you are throwing away information: the number you have might have (say) 20 digits of precision, and you only need, or want, or can take (say) 18 digits. (Or bits, for binary numbers, or whatever base you are using. There were some early Russian computers that used base three, many early Western machines used base 12, etc.) So you have to throw away two digits. How you throw them away is up to you. There are five basic types of rounding: 1 round towards positive infinity (take the ceiling); 2 round towards negative infinity (take the floor); 3 round towards zero (truncate); 4 round away from zero (like ceil for +ve numbers and floor for -ve); 5 round towards the nearest integer Number five is interesting, because numbers of the form N.5 are exactly half-way between two integers, and so you have to choose a strategy for breaking ties: 5a always round up (what you probably learned in school); 5b always round down; 5c round towards zero; 5d round away from zero; 5e round up if the result will be even, otherwise down; 5f round up if the result will be odd, otherwise down; 5g round up or down at random; 5h alternate between rounding up and rounding down; 5a introduce a small bias in the result: assuming the numbers you round are randomly distributed, you will tend to increase them more often than decrease them. 5b is the same, only reversed. 5c and 5d are overall symmetrical, but they introduce a bias in positive numbers, and an equal bur reversed bias in negative numbers. 5e and 5f are symmetrical, as is 5g provided the random number generator is fair. Likewise for 5h. Provided the numbers you deal with are unbiased, they won't introduce any bias. 5e is also interesting. It is sometimes called "statistician's rounding", but more often "banker's rounding" even though there is no evidence that it was ever used by bankers until the advent of modern computers. The bias involved from a poor choice of rounding can be significant. In 1982, the Vancouver Stock Exchange started a new index in 1982, with an initial value of 1000.000. After 22 months it had fallen to approximately 520 points, during a period that most stock prices were increasing. It turned out that the index was calculated by always rounding down to three decimal places, thousands of times each day. The correct value of the index should have been just under 1100. The accumulated rounding error from over half a million calculations in 22 months was enough to introduce rounding error of nearly 580 points -- a relative error of just over 50%. > Having re-read and thought about it for a while, I think my argument simply > distills down to this: using Decimal both allows you control over your > significant figures, From Python, Decimal gives you more control over precision and rounding than binary floats. If you're programming in a low-level language that gives you better access to the floating point routines, binary floats give you almost as much control. The only difference I'm aware of is that the Decimal module lets you choose any arbitrary number of significant digits, while low-level floats only have a choice of certain fixed number of bits. The IEEE 754 standard mandates half precision (16 bits), single (32 bits), double (64 bits, or what Python uses for floats) and quadruple (128 bits). Not all of those bits are available for precision, one bit is used for sign and some are used for the exponent. E.g. doubles have 53 bits of precision (except for denormalised numbers, which have fewer). > and (at least for me) *requires* you to think about > what sort of truncation/rounding you will experience, and let's be honest - > usually the source of errors is we, the programmers, not thinking enough > about precision - and the result of this thought process is usually the > elimination, not of truncation/rounding, but of not accounting for these > errors. Which, to me, equates to "eliminating those pesky floating point > errors". You can't eliminate rounding errors unless you have effectively infinite precision, which even at the cheap prices of RAM these days, would be quite costly :) But what you can do is *control* how much rounding error you get. This is not as easy as it might seem though... one problem is the so-called "Table-maker's Dilemma" (table as in a table of numbers): in general, there is no way of knowing how many extra digits you need to calculate in order to correctly round a mathematical function. -- Steven From smokefloat at gmail.com Sat Jan 8 13:11:18 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 8 Jan 2011 07:11:18 -0500 Subject: [Tutor] Command line scripts Message-ID: This is somewhat of a cross post,but I think it applies here as well. If I use as command line script, is there any disruption in the execution of the code using wxpython. In other words, is a command line app different from bindings in a compiled app? @ trace def play(self, event = None, text = None): if event == None: self.textlist = [] for item in text.split(' '): self.textlist.append(item) print self.textlist for word in self.textlist: self.espeak = subprocess.Popen(['espeak', word], stdout = subprocess.PIPE).communicate()[0] if event != None: self.textlist = [] for item in self.text2speech.GetValue().split(' '): self.textlist.append(item) print self.textlist for word in self.textlist: self.espeak = subprocess.Popen(['espeak', word], stdout = subprocess.PIPE).communicate()[0] -- Sometimes...my mama...says I get over excited about technology. From alan.gauld at btinternet.com Sat Jan 8 15:10:43 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Jan 2011 14:10:43 -0000 Subject: [Tutor] Command line scripts References: Message-ID: "David Hutto" wrote > If I use as command line script, is there any disruption in the > execution of the code using wxpython. I don't understand the question. wxPython is a GUI toolkit so how would you have a command line script using wxPython? Or do you mean running a wxPython GUI program from the command line? - that should work just fine. > In other words, is a command line app different from > bindings in a compiled app? What kind of bindings? And what do you mean by a compiled app? Python is interpreted (or actually compiled to byte code and the byte code is interpreted - but its the same principle). So-called exe generators simply bundle the interpreter witrh the code and auto run it. And wxPython is irrelevant to that debate since it is just a set of modules regardless of how you run it. > @ trace > def play(self, event = None, text = None): > if event == None: > self.textlist = [] > for item in text.split(' '): > self.textlist.append(item) > print self.textlist > for word in self.textlist: > self.espeak = > subprocess.Popen(['espeak', > word], stdout = > > subprocess.PIPE).communicate()[0] > if event != None: > self.textlist = [] > for item in > self.text2speech.GetValue().split(' '): > self.textlist.append(item) > print self.textlist > for word in self.textlist: > self.espeak = > subprocess.Popen(['espeak', > word], stdout = > > subprocess.PIPE).communicate()[0] Sorry, I'm missing the significance of this function? Confused,. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 8 15:17:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Jan 2011 14:17:05 -0000 Subject: [Tutor] Parse MPL files References: <4D27932D.8070106@aim.com> <4D27A2D6.3050503@aim.com> Message-ID: >> Parts of the data is inaccessible (very large parts in fact).The >> structure is like that: It is binary data so you need to open the file with a b flag (rb or wb) and you will probably need to use the struct module to convert the binary data into normal Pyython data types. Search the internet for a description of the file format, it will be easier than trying to figure it out by hand. >> How to set up a hex editor ? You don;t need an editor just a display. The standard Linux tool is od(octal dump) which takes various flags to display hex/strings etc. (Try man od) If on Windows use debug from the command line and use the d command within debug... If you use emacs it has a hex mode that can edit binary filess too. And I think vim can do it but have never tried... > not text. To use Bless, run sudo apt-get install bless on Ubuntu and > variants, for Windows try HxD, http://mh-nexus.de/en/hxd/. You only need bless and its cousins if you want to modify the data which you probably don't! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Sat Jan 8 15:44:14 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 8 Jan 2011 14:44:14 +0000 Subject: [Tutor] Parse MPL files In-Reply-To: References: Message-ID: On 7 January 2011 22:16, PyProg PyProg wrote: > Hi all, > > I'm looking for a way to parse MPL files (.MPL or .mpl extension). > These files are contained in the tree of some cameras that support the > AVCHD ... and some cameras filming with a stream mpeg-ts. > I've only been able to locate this: http://forum.videohelp.com/threads/296805-Reading-AVCHD-Playlist-files-BDMV-Playlist-*-mpl which links here: http://eiman.tv/misc/flashdump.txt ... which *might* be relevant and somewhat helpful. Hope that's of some use.... Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 9 00:40:19 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Jan 2011 23:40:19 -0000 Subject: [Tutor] Parse MPL files References: Message-ID: "Walter Prins" wrote >> I'm looking for a way to parse MPL files (.MPL or .mpl extension). >> These files are contained in the tree of some cameras that support >> the >> AVCHD ... and some cameras filming with a stream mpeg-ts. >> Try this for a starter for 10.... http://eiman.tv/misc/flashdump.txt Its a python script that the author claims to read mpl files. The discussion where I found it also has some rough specs: http://forum.videohelp.com/threads/296805-Reading-AVCHD-Playlist-files-BDMV-Playlist-*-mpl HTH, Alan G. From tim at johnsons-web.com Sun Jan 9 02:24:37 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 8 Jan 2011 16:24:37 -0900 Subject: [Tutor] Named-value formatting fails Message-ID: <20110109012437.GA10663@johnsons-web.com> I'm using 2.6.5 on ubuntu 10.04. I'm evaluating a very large string using a named-value formatting scheme. The process fails with the following error message: """not enough arguments for format string""" In the first place, I wouldn't expect to even see this error message, because as the python documentation says: """ Python calls the get-item method of the right-hand-side mapping (__getitem__), when the righthand side is an instance object. """ As for the right-hand mapping - I'm using the following: class Evalx: def __init__(self, localvals = None, globalvals = None): if localvals is None: self.locals = sys._getframe(1).f_locals else : self.locals = locals if globalvals is None: self.globals = sys._getframe(1).f_globals else : self.globals = globals def __getitem__(self,key): return eval(key,self.globals,self.locals) the implementation looks like this: self.content = content % Evalx() I would really appreciate some insights on this issue. I don't really know how to debug this, except for to look for some "%s" in the `content' string. TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From steve at pearwood.info Sun Jan 9 05:18:25 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jan 2011 15:18:25 +1100 Subject: [Tutor] Named-value formatting fails In-Reply-To: <20110109012437.GA10663@johnsons-web.com> References: <20110109012437.GA10663@johnsons-web.com> Message-ID: <4D293711.5070503@pearwood.info> There's a shorter answer and a longer answer to this question. The shorter answer is here. The longer answer will follow. Tim Johnson wrote: > I'm using 2.6.5 on ubuntu 10.04. > I'm evaluating a very large string using a named-value formatting > scheme. The process fails with the following error message: > """not enough arguments for format string""" ... > self.content = content % Evalx() ... > I don't really know how to debug this, except for to look for some > "%s" in the `content' string. Er, that would be a good start. Without knowing what string is on the left side of the % operator, how do you know how many items need to be on the right side? -- Steven From steve at pearwood.info Sun Jan 9 05:37:23 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jan 2011 15:37:23 +1100 Subject: [Tutor] Named-value formatting fails In-Reply-To: <20110109012437.GA10663@johnsons-web.com> References: <20110109012437.GA10663@johnsons-web.com> Message-ID: <4D293B83.5020509@pearwood.info> A more detailed response. Tim Johnson wrote: > I'm using 2.6.5 on ubuntu 10.04. > I'm evaluating a very large string using a named-value formatting > scheme. The process fails with the following error message: > """not enough arguments for format string""" I'd take that as a fairly straightforward error message. You have N fields on the right hand side, and at least N+1 on the left hand side, for some value of N. I'm not sure why you're perplexed -- there's nothing in your post that explains why this is more difficult than a mismatch in targets vs fields provided. > In the first place, I wouldn't expect to even see this error > message, because as the python documentation says: > """ > Python calls the get-item method of the right-hand-side mapping > (__getitem__), when the righthand side is an instance object. > """ Context and URL please. Just because you've just looked it up and have it fresh in your brain doesn't me the rest of us have too :) > As for the right-hand mapping - I'm using the following: > class Evalx: > def __init__(self, localvals = None, globalvals = None): Dear me... messing with globals and locals. That's always a bad sign. But let's assume this is that one time in 100 that it is actually justified... > if localvals is None: > self.locals = sys._getframe(1).f_locals Are you aware that this is non-portable and subject to change without notice? > else : > self.locals = locals > if globalvals is None: > self.globals = sys._getframe(1).f_globals > else : > self.globals = globals > def __getitem__(self,key): > return eval(key,self.globals,self.locals) Using eval is nearly always a bad thing. Your class is now potentially vulnerable to code injection attacks. I hope you can trust the source of the target string *and* the globals and locals functions. (And of course just because you can trust it *today*, doesn't mean you can tomorrow. Code has a way of being reused. > the implementation looks like this: > self.content = content % Evalx() What's self? What's content? What global and local variables do you have? (This is just one of the many reasons why messing with globals and locals is bad... you often can't see what a piece of code does unless you know exactly what *all* the locals and globals are, not just the ones in the piece of code you're looking at.) > I would really appreciate some insights on this issue. > I don't really know how to debug this, except for to look for some > "%s" in the `content' string. Quite. >>> x = 42 >>> "%(x)s" % Evalx() '42' >>> "%(x)s %s" % Evalx() Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string It's not just %s, of course, any % target that isn't named. This includes %s %d %i %f %g %G %r %x %X plus others. Oh, and if the security vulnerability isn't obvious already: >>> "%(x)s %(os.system('echo \"If I can fool you into running this, I will own your PC.\"'))s" % Evalx() If I can fool you into running this, I will own your PC. '42 0' This is just one of *many* ways to inject code into your string formatting operation. -- Steven From tcl76 at hotmail.com Sun Jan 9 07:25:53 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 06:25:53 +0000 Subject: [Tutor] Open a text file, read and print pattern matching Message-ID: hi, i have a sampledata as below. Pls refer to output, if found -1, how to list out all the Lane number? And if there is no -1, print PASS. My code is as below section. thanks tcl76 ####sampledata############ Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 0 1 2 -1 0 1 3 10 0 1 4 -1 0 1 5 12 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s ############################ ####output################### case1: Found -1 Lane 2 FAIL Lane 4 FAIL case2: No -1 All Lanes PASS ########################## ####Code#################### fname = "sampledata.txt" pattern = "-1" for search in open(fname): if pattern in search: print "FAIL" else: print "PASS" -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jan 9 07:39:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jan 2011 17:39:28 +1100 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: Message-ID: <4D295820.2010008@pearwood.info> tee chwee liong wrote: > hi, > > i have a sampledata as below. Pls refer to output, if found -1, how to list out all the Lane number? And if there is no -1, print PASS. My code is as below section. > > thanks > tcl76 > > ####sampledata############ > Platform: PC > Tempt : 25 > TAP0 :0 > TAP1 :1 > > +++++++++++++++++++++++++++++++++++++++++++++ > Port Chnl Lane EyVt > +++++++++++++++++++++++++++++++++++++++++++++ > 0 1 1 75 > 0 1 2 -1 > 0 1 3 10 > 0 1 4 -1 > 0 1 5 12 > +++++++++++++++++++++++++++++++++++++++++++++ > Time: 20s > ############################ > > ####output################### > case1: Found -1 > Lane 2 FAIL > Lane 4 FAIL > > case2: No -1 > All Lanes PASS > ########################## > > ####Code#################### > fname = "sampledata.txt" > pattern = "-1" > for search in open(fname): > if pattern in search: > print "FAIL" > else: > print "PASS" > fname = "sampledata.txt" > pattern = "-1" > for search in open(fname): > if pattern in search: > print "FAIL" > else: > print "PASS" > > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kb1pkl at aim.com Sun Jan 9 07:41:43 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 09 Jan 2011 01:41:43 -0500 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: Message-ID: <4D2958A7.1030205@aim.com> On 01/09/2011 01:25 AM, tee chwee liong wrote: > hi, > > i have a sampledata as below. Pls refer to output, if found -1, how to > list out all the Lane number? And if there is no -1, print PASS. My code > is as below section. > > thanks > tcl76 > > ####sampledata############ > Platform: PC > Tempt : 25 > TAP0 :0 > TAP1 :1 > > +++++++++++++++++++++++++++++++++++++++++++++ > Port Chnl Lane EyVt > +++++++++++++++++++++++++++++++++++++++++++++ > 0 1 1 75 > 0 1 2 -1 > 0 1 3 10 > 0 1 4 -1 > 0 1 5 12 > +++++++++++++++++++++++++++++++++++++++++++++ > Time: 20s > ############################ > > ####output################### > case1: Found -1 > Lane 2 FAIL > Lane 4 FAIL > > case2: No -1 > All Lanes PASS > ########################## You couldn't possibly have gotten that output from the code you provided, so why did you list it under output? > > ####Code#################### > fname = "sampledata.txt" > pattern = "-1" > for search in open(fname): > if pattern in search: > print "FAIL" > else: > print "PASS" > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor I'm not quite sure how your data file is supposed to be laid out. I suggest you have it setup so that every line that isn't actually data is commented out somehow, and you only search the actual data. So, your new data file could look like: -------paste---------------------------------- #Platform: PC #Tempt : 25 #TAP0 :0 #TAP1 :1 #+++++++++++++++++++++++++++++++++++++++++++++ #Port Chnl Lane EyVt #+++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 0 1 2 -1 0 1 3 10 0 1 4 -1 0 1 5 12 #+++++++++++++++++++++++++++++++++++++++++++++ #Time: 20s ---------end-paste---------------------------- Your script could look something like: data = [for line in open(filename) if not line.startswith("#") for line in data: line = line.split() if line[3] == pattern: print "Lane " + line[2] + " PASS" else: print "Lane " + line[2] + " FAIL" ~Corey Richardson From steve at pearwood.info Sun Jan 9 07:44:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 09 Jan 2011 17:44:58 +1100 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: Message-ID: <4D29596A.7070509@pearwood.info> Please excuse the double post, I had a problem with my email program. tee chwee liong wrote: > hi, > > i have a sampledata as below. Pls refer to output, if found -1, how to list out all the Lane number? And if there is no -1, print PASS. My code is as below section. > ####Code#################### > fname = "sampledata.txt" > pattern = "-1" > for search in open(fname): > if pattern in search: > print "FAIL" > else: > print "PASS" fname = "sampledata.txt" pattern = "-1" failed = False for line in open(fname): port, channel, lane, eyvt = line.split() if int(eyvt) == -1: failed = True print "Lane %s failed." % lane if not failed: print "All lanes pass." -- Steven From smokefloat at gmail.com Sun Jan 9 10:44:29 2011 From: smokefloat at gmail.com (David Hutto) Date: Sun, 9 Jan 2011 04:44:29 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: Message-ID: On Sat, Jan 8, 2011 at 9:10 AM, Alan Gauld wrote: > "David Hutto" wrote > >> If I use as command line script, is there any disruption in the >> execution of the code using wxpython. > > I don't understand the question. > wxPython is a GUI toolkit so how would you have a command > line script using wxPython? Or do you mean running a wxPython > GUI program from the command line? - that should work just fine. No. The function below is called on an event within a wxpython app. The following line is what I mean by calling a command line from within the app using subprocess. self.espeak = subprocess.Popen(['espeak', word],stdout = subprocess.PIPE).communicate()[0] > >> In other words, is a command line app different from >> bindings in a compiled app? > > What kind of bindings? To functions in libraries external to python. > And what do you mean by a compiled app? Basically the below. > Python is interpreted (or actually compiled to byte code > and the byte code is interpreted - but its the same principle). > So-called exe generators simply bundle the interpreter witrh > the code and auto run it. So it's basically just installing a sandbox version of python? > > And wxPython is irrelevant to that debate since it is just > a set of modules regardless of how you run it. I was just saying the module I was using for the apps framework > >> ? ? ?@ trace >> ? ? ?def play(self, event = None, text = None): >> ? ? ? ? ? ? ?if event == None: >> ? ? ? ? ? ? ? ? ? ? ?self.textlist = [] >> ? ? ? ? ? ? ? ? ? ? ?for item in text.split(' '): >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?self.textlist.append(item) >> ? ? ? ? ? ? ? ? ? ? ?print self.textlist >> ? ? ? ? ? ? ? ? ? ? ?for word in self.textlist: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?self.espeak = >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?subprocess.Popen(['espeak', word], >> stdout = >> >> subprocess.PIPE).communicate()[0] >> ? ? ? ? ? ? ?if event != None: >> ? ? ? ? ? ? ? ? ? ? ?self.textlist = [] >> ? ? ? ? ? ? ? ? ? ? ?for item in self.text2speech.GetValue().split(' '): >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?self.textlist.append(item) >> ? ? ? ? ? ? ? ? ? ? ?print self.textlist >> ? ? ? ? ? ? ? ? ? ? ?for word in self.textlist: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?self.espeak = >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? subprocess.Popen(['espeak', word], >> stdout = >> >> subprocess.PIPE).communicate()[0] > > Sorry, I'm missing the significance of this function? No significance, it was just an example to illustrate my question. Which ultimately is, if I have a standalone application, that doesn't come from a command line terminal launching(which I haven't gotten to yet), is using the command line calls going through subprocess going to be called without the terminal, or will it open a terminal automatically to make those calls? Or will all of my python apps need to have a command line terminal open to launch them. I haven't went all the way through the distutils docs, so this might be answered with further reading, but I wanted to know the answer before I did several basic apps like this. Although I'll probably still do them for my own personal usage. > > Confused,. I don't exactly ask the most well layed out questions, but I'm working on it. From tcl76 at hotmail.com Sun Jan 9 14:31:30 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 13:31:30 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: <4D29596A.7070509@pearwood.info> References: , <4D29596A.7070509@pearwood.info> Message-ID: hi, there is error when running the code: > Traceback (most recent call last): > File "C:/Python25/myscript/log/readfile9.py", line 5, in > port, channel, lane, eyvt = line.split() > ValueError: need more than 2 values to unpack the error is due to below line code: >port, channel, lane, eyvt = line.split() pls advise. thanks tcl76 > Date: Sun, 9 Jan 2011 17:44:58 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > Please excuse the double post, I had a problem with my email program. > > tee chwee liong wrote: > > hi, > > > > i have a sampledata as below. Pls refer to output, if found -1, how to list out all the Lane number? And if there is no -1, print PASS. My code is as below section. > > > ####Code#################### > > fname = "sampledata.txt" > > pattern = "-1" > > for search in open(fname): > > if pattern in search: > > print "FAIL" > > else: > > print "PASS" > > fname = "sampledata.txt" > pattern = "-1" > failed = False > for line in open(fname): > port, channel, lane, eyvt = line.split() > if int(eyvt) == -1: > failed = True > print "Lane %s failed." % lane > if not failed: > print "All lanes pass." > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jan 9 14:48:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 00:48:51 +1100 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , <4D29596A.7070509@pearwood.info> Message-ID: <4D29BCC3.4090402@pearwood.info> tee chwee liong wrote: > hi, > > there is error when running the code: >> Traceback (most recent call last): >> File "C:/Python25/myscript/log/readfile9.py", line 5, in >> port, channel, lane, eyvt = line.split() >> ValueError: need more than 2 values to unpack > > the error is due to below line code: >> port, channel, lane, eyvt = line.split() > > pls advise. You have a line with only 2 words, and you are trying to unpack it into four variables. Four variables on the left, 4 values on the right works: >>> a, b, c, d = "sentence with four words".split() >>> print a sentence >>> print b with >>> print c four >>> print d words But 4 variables on the left, 3 on the right does not: >>> a, b, c, d = "sentence with three".split() Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack Likewise: >>> a, b, c, d = "two words".split() Traceback (most recent call last): File "", line 1, in ValueError: need more than 2 values to unpack >>> a, b, c, d = "word".split() Traceback (most recent call last): File "", line 1, in ValueError: need more than 1 value to unpack -- Steven From tcl76 at hotmail.com Sun Jan 9 14:55:43 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 13:55:43 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: <4D2958A7.1030205@aim.com> References: , <4D2958A7.1030205@aim.com> Message-ID: hi, yes you are right, the output below is my desired outcome. the sampledata i have can't be added with #. i got syntax error when running this line: data = for line in open(filename) if not line.startswith("#") pls advise. thanks tcl76 > Date: Sun, 9 Jan 2011 01:41:43 -0500 > From: kb1pkl at aim.com > To: tutor at python.org > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > On 01/09/2011 01:25 AM, tee chwee liong wrote: > > hi, > > > > i have a sampledata as below. Pls refer to output, if found -1, how to > > list out all the Lane number? And if there is no -1, print PASS. My code > > is as below section. > > > > thanks > > tcl76 > > > > ####sampledata############ > > Platform: PC > > Tempt : 25 > > TAP0 :0 > > TAP1 :1 > > > > +++++++++++++++++++++++++++++++++++++++++++++ > > Port Chnl Lane EyVt > > +++++++++++++++++++++++++++++++++++++++++++++ > > 0 1 1 75 > > 0 1 2 -1 > > 0 1 3 10 > > 0 1 4 -1 > > 0 1 5 12 > > +++++++++++++++++++++++++++++++++++++++++++++ > > Time: 20s > > ############################ > > > > ####output################### > > case1: Found -1 > > Lane 2 FAIL > > Lane 4 FAIL > > > > case2: No -1 > > All Lanes PASS > > ########################## > You couldn't possibly have gotten that output from the code you > provided, so why did you list it under output? > > > > ####Code#################### > > fname = "sampledata.txt" > > pattern = "-1" > > for search in open(fname): > > if pattern in search: > > print "FAIL" > > else: > > print "PASS" > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > I'm not quite sure how your data file is supposed to be laid out. I > suggest you have it setup so that every line that isn't actually data is > commented out somehow, and you only search the actual data. So, your new > data file could look like: > > -------paste---------------------------------- > #Platform: PC > #Tempt : 25 > #TAP0 :0 > #TAP1 :1 > > #+++++++++++++++++++++++++++++++++++++++++++++ > #Port Chnl Lane EyVt > #+++++++++++++++++++++++++++++++++++++++++++++ > 0 1 1 75 > 0 1 2 -1 > 0 1 3 10 > 0 1 4 -1 > 0 1 5 12 > #+++++++++++++++++++++++++++++++++++++++++++++ > #Time: 20s > ---------end-paste---------------------------- > > Your script could look something like: > > data = [for line in open(filename) if not line.startswith("#") > for line in data: > line = line.split() > if line[3] == pattern: > print "Lane " + line[2] + " PASS" > else: > print "Lane " + line[2] + " FAIL" > > ~Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 9 15:07:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Jan 2011 14:07:39 -0000 Subject: [Tutor] Open a text file, read and print pattern matching References: , <4D2958A7.1030205@aim.com> Message-ID: "tee chwee liong" wrote > i got syntax error when running this line: > data = for line in open(filename) if not line.startswith("#") Should be: data = [ line for line in open(filename) if not line.startswith("#") ] Notice the extra line at the beginning and the fact that it is surrounded by [] which makes it a *list comprehension*. But that won't help if you can't put commment markers at the front... But you might get away with: data = [ line for line in open(filename) if '-1' in line ] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Jan 9 15:03:36 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 9 Jan 2011 14:03:36 +0000 (GMT) Subject: [Tutor] Command line scripts In-Reply-To: References: Message-ID: <198450.15065.qm@web86701.mail.ird.yahoo.com> > The following line is what I mean by calling a command line from within the >app > using subprocess. > > self.espeak = subprocess.Popen(['espeak', word],stdout = > subprocess.PIPE).communicate()[0] OK, Now I understand. You want to call an external application from within your code via subprocess. And you want to know if that will work ok in a wxPython application? > >> In other words, is a command line app different from > >> bindings in a compiled app? When you call an app using subprocess it spawns an entirely separate process in the OS. There is no linkage to your process apart from the redirection of stdin/stdout/stderr back to your app instead of to a console. > > So-called exe generators simply bundle the interpreter witrh > > the code and auto run it. > > So it's basically just installing a sandbox version of python? Sort of, its a minimalist version of python with only the modules needed to run the app. And you can't run the interpreter on its own you can only run the packaged app. > Which ultimately is, if I have a standalone application, that doesn't > come from a command line terminal launching(which I haven't gotten to > yet), is using the command line calls going through subprocess going > to be called without the terminal, or will it open a terminal > automatically to make those calls? The app (eSpeak in your example) will see your app as its "console". That is, it will send all output to your app and read all input from your app (so you need to make sure it gets any input it is expecting!) The other thing to watch in a wxPython (or any other GUI framework) is that if the app runs for a long time your app may "freeze" from the user's perspective, so you may want to run it in the background or as a separate thread in your app. > Or will all of my python apps need to have a command line terminal > open to launch them. No, your app takes over the job of the terminal. When you launch a program from the terninal the terminal app(for it is just an app like any other) is doing the same as you, it is spawning a subprocess that sends its output back to the teminal for it to display. In fact you might find it a useful exercise to build a very basic terminal app in wxPython first. Read commands from a command input field and display the output in a text widget... Execute the commands via subprocess. Its a good way to get used to using subprocess and experimenting with its various options. If you are very keen you can start adding command history and search etc to it too... HTH, Alan G. From tcl76 at hotmail.com Sun Jan 9 15:12:44 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 14:12:44 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: <4D29BCC3.4090402@pearwood.info> References: , , <4D29596A.7070509@pearwood.info>, , <4D29BCC3.4090402@pearwood.info> Message-ID: hi, thanks for the explanation. if i print out line=line.split(), below is the result: ['Platform:', 'PC'] ['Tempt', ':', '25'] ['TAP0', ':0'] ['TAP1', ':1'] [] ['+++++++++++++++++++++++++++++++++++++++++++++'] ['Port', 'Chnl', 'Lane', 'EyVt'] ['+++++++++++++++++++++++++++++++++++++++++++++'] ['0', '1', '1', '75'] ['0', '1', '2', '10'] ['0', '1', '3', '-1'] ['0', '1', '4', '-1'] ['0', '1', '5', '10'] ['+++++++++++++++++++++++++++++++++++++++++++++'] ['Time:', '20s'] that's why port, channel, lane, eyvt = line.split() will give traceback error due to there are only 2 values in the 1st line. how to make the line search at line Port, Chnl, Lane, EyVt? thanks tcl76 > Date: Mon, 10 Jan 2011 00:48:51 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > tee chwee liong wrote: > > hi, > > > > there is error when running the code: > >> Traceback (most recent call last): > >> File "C:/Python25/myscript/log/readfile9.py", line 5, in > >> port, channel, lane, eyvt = line.split() > >> ValueError: need more than 2 values to unpack > > > > the error is due to below line code: > >> port, channel, lane, eyvt = line.split() > > > > pls advise. > > > You have a line with only 2 words, and you are trying to unpack it into > four variables. Four variables on the left, 4 values on the right works: > > >>> a, b, c, d = "sentence with four words".split() > >>> print a > sentence > >>> print b > with > >>> print c > four > >>> print d > words > > But 4 variables on the left, 3 on the right does not: > > >>> a, b, c, d = "sentence with three".split() > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 3 values to unpack > > Likewise: > > >>> a, b, c, d = "two words".split() > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 2 values to unpack > > >>> a, b, c, d = "word".split() > Traceback (most recent call last): > File "", line 1, in > ValueError: need more than 1 value to unpack > > > > > -- > Steven > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 9 15:14:17 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Jan 2011 14:14:17 -0000 Subject: [Tutor] Open a text file, read and print pattern matching References: , <4D29596A.7070509@pearwood.info> Message-ID: "tee chwee liong" wrote > File "C:/Python25/myscript/log/readfile9.py", line 5, in > port, channel, lane, eyvt = line.split() > ValueError: need more than 2 values to unpack So you need to ensure that you unpack when you have the right number of fields: either: data = line.split() if len(data) = 4: port, channel, lane, eyvt = data else: continue # rest of your code here... or more pythonically: try: port, channel, lane, eyvt = line.split() # the rest of your code here except ValueError: continue HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From tcl76 at hotmail.com Sun Jan 9 15:19:09 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 14:19:09 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , , <4D2958A7.1030205@aim.com>, , Message-ID: thanks this solve the error but running the code produces another error ie index out of range. Traceback (most recent call last): File "C:\Python25\myscript\log\readfile9.py", line 22, in if line[3] == pattern: IndexError: list index out of range > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 9 Jan 2011 14:07:39 +0000 > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > > "tee chwee liong" wrote > > > i got syntax error when running this line: > > data = for line in open(filename) if not line.startswith("#") > > Should be: > > data = [ line for line in open(filename) if not line.startswith("#") ] > > Notice the extra line at the beginning and the fact that it is > surrounded by [] which makes it a *list comprehension*. > > > But that won't help if you can't put commment markers > at the front... But you might get away with: > > data = [ line for line in open(filename) if '-1' in line ] > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 9 15:34:22 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 9 Jan 2011 14:34:22 +0000 (GMT) Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , , <4D2958A7.1030205@aim.com>, , Message-ID: <749597.69214.qm@web86708.mail.ird.yahoo.com> > thanks this solve the error but running the code produces another error ie >index out of range. > if line[3] == pattern: > IndexError: list index out of range So you need to check that there are at least 4 elements in the line before trying to access it. Or else catch the exception (see my other post about unpacking the data) HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Sun Jan 9 15:40:02 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 14:40:02 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , , <4D29596A.7070509@pearwood.info>, , Message-ID: i modified the code to be: fname = "sampledata.txt" pattern = "-1" failed = False for line in open(fname): data=line.split() if len(data)==4: port, channel, lane, eyvt = data else: if int(eyvt) == -1: failed = True print "Lane %s failed." % lane if not failed: print "All lanes pass." there is traceback error: Traceback (most recent call last): File "C:\Python25\myscript\log\readfile9.py", line 10, in if int(eyvt) == -1: ValueError: invalid literal for int() with base 10: 'EyVt' pls help to advise. don't understand int() with base 10 mean? thanks tcl76 > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 9 Jan 2011 14:14:17 +0000 > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > > "tee chwee liong" wrote > > > File "C:/Python25/myscript/log/readfile9.py", line 5, in > > port, channel, lane, eyvt = line.split() > > ValueError: need more than 2 values to unpack > > So you need to ensure that you unpack when you have the right > number of fields: > > either: > > data = line.split() > if len(data) = 4: > port, channel, lane, eyvt = data > else: continue > # rest of your code here... > > > or more pythonically: > > try: > port, channel, lane, eyvt = line.split() > # the rest of your code here > except ValueError: continue > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Sun Jan 9 15:43:53 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 9 Jan 2011 14:43:53 +0000 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , , <4D29596A.7070509@pearwood.info>, , Message-ID: hi all, thanks for all your advice, i really learn a lot. finally i modified the code to be working as: fname = "sampledata.txt" pattern = "-1" failure = False for search in open(fname): if pattern in search: #print search #print failure failure=True print 'Lane', search.split()[2], 'Fail' if not failure: print "All Lanes Pass" thanks tcl76 > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Sun, 9 Jan 2011 14:14:17 +0000 > Subject: Re: [Tutor] Open a text file, read and print pattern matching > > > "tee chwee liong" wrote > > > File "C:/Python25/myscript/log/readfile9.py", line 5, in > > port, channel, lane, eyvt = line.split() > > ValueError: need more than 2 values to unpack > > So you need to ensure that you unpack when you have the right > number of fields: > > either: > > data = line.split() > if len(data) = 4: > port, channel, lane, eyvt = data > else: continue > # rest of your code here... > > > or more pythonically: > > try: > port, channel, lane, eyvt = line.split() > # the rest of your code here > except ValueError: continue > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Sun Jan 9 17:26:44 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 9 Jan 2011 07:26:44 -0900 Subject: [Tutor] Named-value formatting fails In-Reply-To: <4D293B83.5020509@pearwood.info> References: <20110109012437.GA10663@johnsons-web.com> <4D293B83.5020509@pearwood.info> Message-ID: <20110109162644.GA1837@johnsons-web.com> * Steven D'Aprano [110108 19:46]: > A more detailed response. > > Dear me... messing with globals and locals. That's always a bad sign. > But let's assume this is that one time in 100 that it is actually > justified... > >> if localvals is None: self.locals = >> sys._getframe(1).f_locals > > Are you aware that this is non-portable and subject to change without > notice? No! 1)Can you explain further? And you have convinced me, and furthermore given me enough to convince someone else that a different approach would be safer. 2)Can you recommend a *simple* templatting module? thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From kb1pkl at aim.com Sun Jan 9 18:28:54 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sun, 09 Jan 2011 12:28:54 -0500 Subject: [Tutor] __init__() - is it required? Message-ID: <4D29F056.9070307@aim.com> Do all classes need an __init__() method? I have classes that look much like this one starts out: class GenerateXML(object): """Defines methods to be inherited for StaticXML and AnimationXML""" def __init__(self): pass I would rather not do that. Code without it runs fine, but will there be any negative consequences down the road? Does object define an __init__ method for me? From davea at ieee.org Sun Jan 9 20:43:32 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 09 Jan 2011 14:43:32 -0500 Subject: [Tutor] Open a text file, read and print pattern matching In-Reply-To: References: , , <4D29596A.7070509@pearwood.info>, , Message-ID: <4D2A0FE4.3090005@ieee.org> (Don't top-post. You keep putting your responses out of order.) On 01/-10/-28163 02:59 PM, tee chwee liong wrote: > > i modified the code to be: > fname = "sampledata.txt" > pattern = "-1" > failed = False > for line in open(fname): > data=line.split() > if len(data)==4: > port, channel, lane, eyvt = data > else: > if int(eyvt) == -1: > failed = True > print "Lane %s failed." % lane > if not failed: > print "All lanes pass." > > there is traceback error: > Traceback (most recent call last): > File "C:\Python25\myscript\log\readfile9.py", line 10, in > if int(eyvt) == -1: > ValueError: invalid literal for int() with base 10: 'EyVt' > > pls help to advise. don't understand int() with base 10 mean? > > thanks > tcl76 > The int() function converts a string to an integer, using some base. By default it uses base 10 (decimal), so it'll do what you'd expect to a string like "42" (which would return 42). Apparently you don't have a valid string for an integer there. For example, there might be a letter mixed in with the digits. Your code doesn't make sense anyway, since at that line, eyvt might not even have a value. And it certainly won't have a value from the current line. You're in an 'else' clause, and only the if clause initializes that value. that test for -1 needs to be inside the same if-clause as the "port, channel, ..." line. I suspect the simplest way to do what you want is to have two loops. Loop inside the first one till you see a line that begins with "Port", then break out of that loop. The second one will then only see the subsequent data, and at that point, all lines with four elements will have four numbers. DaveA From steve at pearwood.info Sun Jan 9 22:27:16 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 08:27:16 +1100 Subject: [Tutor] __init__() - is it required? In-Reply-To: <4D29F056.9070307@aim.com> References: <4D29F056.9070307@aim.com> Message-ID: <4D2A2834.3080506@pearwood.info> Corey Richardson wrote: > Do all classes need an __init__() method? I have classes that look much > like this one starts out: > > class GenerateXML(object): > """Defines methods to be inherited for StaticXML and AnimationXML""" > def __init__(self): > pass > > I would rather not do that. Code without it runs fine, but will there be > any negative consequences down the road? Does object define an __init__ > method for me? You don't need to define an __init__ if you don't need one. A placeholder __init__ that does nothing, as above, is a waste of space. object includes an __init__ method that not only does nothing, but ignores any arguments you pass to it: >>> object.__init__ >>> object.__init__(1, 2, 3) >>> In Python 2.x, you can have "old-style" classes that don't inherit from object. They too don't need an __init__: >>> class Old: # *don't* inherit from object ... pass ... >>> o = Old() >>> -- Steven From alan.gauld at btinternet.com Sun Jan 9 22:42:39 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Jan 2011 21:42:39 -0000 Subject: [Tutor] __init__() - is it required? References: <4D29F056.9070307@aim.com> Message-ID: "Corey Richardson" wrote > Do all classes need an __init__() method? I have classes that look > much > like this one starts out: No, init() is only for initialising the object instance. If you have no local instance spwecific initialisation you can leave it to the inherited init() aor have no init() at all. OTOH If you do have no need for an init it implies you probably have no instance variables, which is somewhat unusual. Not unheard of - you may only be modifying the behaviour of an inherited class - but it is unusual. > class GenerateXML(object): > """Defines methods to be inherited for StaticXML and > AnimationXML""" > def __init__(self): > pass IN this case it is a waste of time. It could even do harm in cases where you ingherit from a superclass that does have an init() since the pass will mean it never gets called! Whereas if you omit the init() the suiperclass init(if it exists) will get called. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Jan 9 23:14:10 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 09:14:10 +1100 Subject: [Tutor] Named-value formatting fails In-Reply-To: <20110109162644.GA1837@johnsons-web.com> References: <20110109012437.GA10663@johnsons-web.com> <4D293B83.5020509@pearwood.info> <20110109162644.GA1837@johnsons-web.com> Message-ID: <4D2A3332.7080405@pearwood.info> Tim Johnson wrote: > * Steven D'Aprano [110108 19:46]: >> A more detailed response. >> >> Dear me... messing with globals and locals. That's always a bad sign. >> But let's assume this is that one time in 100 that it is actually >> justified... >> >>> if localvals is None: self.locals = >>> sys._getframe(1).f_locals >> Are you aware that this is non-portable and subject to change without >> notice? > No! > 1)Can you explain further? The convention in Python is that any name that starts with a single leading underscore is a private implementation detail, and therefore subject to change. _getframe starts with a single underscore. Of course, it's been around effectively forever -- it was introduced in Python 2.1, and is unlikely to be removed any time soon. But it *could* be, and it could happen without notice, so you have to weigh up the benefit you get from using an implementation detail against the risk of it disappearing. On the plus side, it is a *documented* internal detail, which suggests that it won't disappear without notice. http://docs.python.org/library/sys.html#sys._getframe But notice that it is specific to CPython (the version you are using). Other Pythons, such as Jython, IronPython, PyPy, Stackless, and many others, may not include this function. So code using it is non-portable. (E.g. IronPython only supports frames if you pass the commandline switch -X:Frames or -X:FullFrames.) (Also note that PyPy is now about twice as fast as CPython. I would expect that over the next few years, PyPy should start to take off as the preferred Python implementation.) > And you have convinced me, and furthermore given me enough to > convince someone else that a different approach would be safer. > 2)Can you recommend a *simple* templatting module? You haven't actually told us what you're trying to do, so I have to guess. That means I may have misunderstood something. But it looks like you want to be able to use templating of arbitrary variable names. Perhaps your Evalx class is overkill. Maybe this is all you need: >>> a = 42 >>> mydict = globals().copy() >>> mydict.update(locals()) >>> "value = %(a)s" % mydict 'value = 42' You might also like to look at the string.Template class, which is for substituting $ templates. If you want to stick with Evalx, the approach I'd consider is: * support globals() and locals() if they are explicitly given (*reading* is safer than *writing*); * support automatic lookup of globals and locals only when supported, otherwise fail gracefully; * don't use eval unless you really need to; * if you think you need to, you probably don't :) That means that instead of: if localvals is None: self.locals = sys._getframe(1).f_locals do something like this: if localvals is None: try: self.locals = sys._getframe(1).f_locals except AttributeError: self.locals = {} (and similarly for globals). Then get rid of the eval in your __getitem__. You probably don't *really* need to support cases like this, no matter how tempting it might be: a = 42 b = 23 "value = %(a+b)s" % Evalx() => "value 75" Instead: def __getitem__(self, key): if key in self.locals: return self.locals[key] elif key in self.globals: return self.globals[key] else: return "Key? What key?" # Or raise KeyError -- Steven From karim.liateni at free.fr Sun Jan 9 23:18:59 2011 From: karim.liateni at free.fr (Karim) Date: Sun, 09 Jan 2011 23:18:59 +0100 Subject: [Tutor] Try except really better than if? Message-ID: <4D2A3453.5040802@free.fr> Hello all, I am using more and more try except statement. But I discussed with a very experienced C++ programmer. And he told me that at least in C++ using too many try -catch statements are making the code slower. And it should does the same for python (C implementation). My simple question: Is this true? And why using try-except is indeed encouraged to code as a pythonista? Regards Karim From tim at johnsons-web.com Mon Jan 10 00:14:13 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Sun, 9 Jan 2011 14:14:13 -0900 Subject: [Tutor] Named-value formatting fails In-Reply-To: <4D2A3332.7080405@pearwood.info> References: <20110109012437.GA10663@johnsons-web.com> <4D293B83.5020509@pearwood.info> <20110109162644.GA1837@johnsons-web.com> <4D2A3332.7080405@pearwood.info> Message-ID: <20110109231413.GC1837@johnsons-web.com> * Steven D'Aprano [110109 13:23]: > Tim Johnson wrote: <...> >>> Are you aware that this is non-portable and subject to change without >>> notice? >> No! 1)Can you explain further? <.....> Wow! You've given me a huge amount of technical information. I can't thank you enough for the time and effort you have given this. FYI: I am adapting an "old" CGI-based system, much of it on a intranet to more of an MVC model. Where a complete rewrite is necessary I would probably use something like django. In this case, enormous forms (around 400 elements) are being managed. The part for which I was considering using an eval() wrapper is for relatively simple token replacement. I may get away with just using replace() or re.sub(). But first :) I must absorb and process what you have written on this subject. Thanks again -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From steve at pearwood.info Mon Jan 10 01:22:33 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 11:22:33 +1100 Subject: [Tutor] Try except really better than if? In-Reply-To: <4D2A3453.5040802@free.fr> References: <4D2A3453.5040802@free.fr> Message-ID: <4D2A5149.4080906@pearwood.info> Karim wrote: > > Hello all, > > I am using more and more try except statement. But I discussed with a > very experienced C++ programmer. > And he told me that at least in C++ using too many try -catch statements > are making the code slower. And it should > does the same for python (C implementation). He is right with the first part, wrong with the second. Python's exceptions are not the same as C++ or Java exceptions. Setting up a try...except block is *very* fast, unlike C++ and Java, where it is slow. In Python, this code: try: 1+1 # cannot fail except ValueError: pass is just as fast as: pass # null op, does nothing 1+1 # cannot fail So there is no speed penalty for setting up a try...except block. If you have something that will nearly always succeed, you don't need to be concerned about using an exception handler. However, *catching* the exception is more expensive. (Roughly ten times as expensive.) So you should avoid code that mostly fails. Remember, also, that the alternative to try...except also has a cost which might not be cheap. You can do this: try: something that might fail except Failure: do alternative or you can do this: if something should succeed: do something else: do alternative But this if...else test is not free. Depending on how expensive the test is, and how often you take each branch, it might be more expensive to "look before you leap". Also, remember that many tests are disguised exceptions, such as the builtin "hasattr" function: # pseudo-code def hasattr(obj, name): try: getattr(obj, name) except AttributeError: return False return True So there is no speed advantage to calling: if hasattr(obj, 'spam'): print(obj.spam) else: print("no spam in object") over this: try: print(obj.spam) except AttributeError: print("no spam in object") The first may even be slower because it has to look up the attribute twice -- this is what I call a pessimation, something done in the name of speed which actually makes your code *slower*. Catching exceptions are best in three circumstances: - You only care about the speed of a successful operation. Failures can be slow. If your program prints an error message and then exits, who cares if it takes 3 milliseconds longer than necessary? - Testing whether something will succeed is impossible, or expensive, or too hard to get right. - Failures are rare. As a *very* rough rule of thumb, I say that if you expect a failure less than one time in ten, it is better to use try...except. But mostly, don't worry about speed. If you are worried about *execution* speed, you shouldn't be using Python in the first place. Python is optimized for developer productivity, not execution speed. Write your code, and *if* it is too slow, then worry about finding the bottlenecks and optimizing them. Some very important quotes about optimization in general: ?More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity.? - W.A. Wulf ?We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.? - Donald Knuth ?Bottlenecks occur in surprising places, so don't try to second guess and put in a speed hack until you have proven that's where the bottleneck is.? - Rob Pike ?The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.? - Michael A. Jackson -- Steven From modulok at gmail.com Mon Jan 10 02:02:47 2011 From: modulok at gmail.com (Modulok) Date: Sun, 9 Jan 2011 18:02:47 -0700 Subject: [Tutor] Try except really better than if? In-Reply-To: <4D2A3453.5040802@free.fr> References: <4D2A3453.5040802@free.fr> Message-ID: On 1/9/11, Karim wrote: > > Hello all, > > I am using more and more try except statement. But I discussed with a > very experienced C++ programmer. > And he told me that at least in C++ using too many try -catch statements > are making the code slower. And it should > does the same for python (C implementation). My simple question: Is this > true? And why using try-except is indeed encouraged > to code as a pythonista? > > Regards > Karim Exceptions are almost always slower to catch. You can confirm this via the 'timeit' module in the standard library. However, if the performance of exceptions themselves become significant, there are bigger, more fundamental problems with your code. Python isn't a language chosen for execution speed. Python is chosen for ease of use and readability. If you find you have to sacrifice that for your project, you might look into a faster language, but not before trying a few things (which solves the problem 99% of the time): 1. Test it. Don't guess. Actually benchmark your code. (See the timeit module.) Is it fast enough? If you have a cron job that runs once every minute that turns over a few log files, having it run in 0.026 seconds is no better than having one that runs in 0.015. 2. Find where the bottleneck is. Again use timeit, and start to look at our iterative algorithms. Better algorithms can speed up some code significantly. (But again, only if you must!) Ask for help on this list, see if there's a module written by someone that does what you want, or research various algorithms that fit your purpose yourself. 3. Still not fast enough? Implement those speed-critical pieces of your code in C and call them from Python. This should be rarely needed. 4. Still not fast enough? You either didn't do step 1 or screwed up between step 2 and 3, or you need more hardware. A try...except...finally block is a lot easier to read, and more flexible than an if...elif block, for catching specific exceptions. Even if your code was twice as slow with exceptions, but your code still runs 'fast enough' for whatever purpose you've written it for, then it's fast enough. Don't obfuscate it. That said, don't use exceptions so liberally that you no longer worry about checking for good inputs. If something usually succeeds just go for it and use an exception as accident insurance. If it will usually fail, check it with an if statement first. -Modulok- From alan.gauld at btinternet.com Mon Jan 10 03:10:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 02:10:22 -0000 Subject: [Tutor] Try except really better than if? References: <4D2A3453.5040802@free.fr> Message-ID: "Karim" wrote > I am using more and more try except statement. But I discussed with > a very experienced C++ programmer. > And he told me that at least in C++ using too many try -catch > statements are making the code slower. That's true, but Bjarne Stroustrup put them in for a reason - and they are still the "official" error handling mechanism in C++. And Java and Object Pascal borrowed them from C++ (which actually borrowed them from ADA) - so there must be something good about them! They are good practice in Python for the same reasons they are good practice in ADA, C++, Java etc.... However, using exceptions like if/else blocks is bad practice. You need to use them like a commit in SQL - to protect a whole block of code. Putting try/except around every line of code defeats the purpose, wrap atomic blocks of code not the individual lines. ie try: something something else another the last except Error1: # do something except Error2: # do something except Error3: # do something finally: # tidy up is better to maintain than try: something except Error1: # do something try: something else except Error2: # do something try: another except Error1: # and again try: the last except Error3: do it tidy up In addition to the excellent caveats posted by Steven and Modulok, I'd also add the reminder that code has about 20% of its cost in initial development and the other 80% in "maintenance" (bug fixing and enhancement) so readability and flexibility really count. Finally, C++ virtual functions are slower than static functions, but that doesn't mean you should write switch statements rather than use polymorphism... Premature optimisation again - speed isn't everything... fast enough is good enough. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From coolankur2006 at gmail.com Mon Jan 10 05:44:22 2011 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Mon, 10 Jan 2011 10:14:22 +0530 Subject: [Tutor] Checkbox problem in Tkinter Message-ID: Hey I write this code up from Tkinter import * root=Tk() var=StringVar() c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh",offvalue="gggg") c.pack() root.mainloop() and i got the output as - [image: Screenshot.png] When i take the var as of string variable type i am unable to edit the checkbox. It comes slected predefined and the widget in kindof Invisible and u can say uneditable. Can anybody tell me whats i am doing wrong in this??? Its works fine if i take the var variable as the integer variable. I can deselect and select in that case and it gives me the desired result but in string case i am unable to do so as checkbox is invisible type. I am using Python 2.6 Thanks In Advance Ankur Aggarwal -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Jan 10 06:09:33 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Jan 2011 00:09:33 -0500 Subject: [Tutor] __init__() - is it required? In-Reply-To: References: <4D29F056.9070307@aim.com> Message-ID: <4D2A948D.20207@gmail.com> On 1/9/2011 4:42 PM, Alan Gauld wrote: > > "Corey Richardson" wrote > >> Do all classes need an __init__() method? I have classes that look much >> like this one starts out: > > No, init() is only for initialising the object instance. > If you have no local instance spwecific initialisation > you can leave it to the inherited init() aor have no init() > at all. Well I'd like to expand that a bit. There are cases where I create a class attribute and update it each time an instance is created. O > > OTOH If you do have no need for an init it implies you > probably have no instance variables, which is somewhat unusual. > Not unheard of - you may only be modifying the behaviour of an > inherited class - but it is unusual. > >> class GenerateXML(object): >> """Defines methods to be inherited for StaticXML and AnimationXML""" >> def __init__(self): >> pass > > > IN this case it is a waste of time. It could even do harm in cases > where you ingherit from a superclass that does have an init() > since the pass will mean it never gets called! Whereas if you > omit the init() the suiperclass init(if it exists) will get called. > > HTH, > > -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Mon Jan 10 10:03:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 09:03:50 -0000 Subject: [Tutor] __init__() - is it required? References: <4D29F056.9070307@aim.com> <4D2A948D.20207@gmail.com> Message-ID: "bob gailer" wrote >> No, init() is only for initialising the object instance. >> If you have no local instance spwecific initialisation >> you can leave it to the inherited init() aor have no init() >> at all. > > Well I'd like to expand that a bit. There are cases where I create a > class attribute and update it each time an instance is created. O Good point. init() can legitimately do things other than initialising instance variables, but conceptually those things are all part of initialising an instance. Updating class variables is a good example of such "other things". Alan G. From karim.liateni at free.fr Mon Jan 10 10:12:13 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 10 Jan 2011 10:12:13 +0100 Subject: [Tutor] Try except really better than if? In-Reply-To: References: <4D2A3453.5040802@free.fr> Message-ID: <4D2ACD6D.7010803@free.fr> Thank you Steven, Modulok and Alan for your precious and detailed explanations! I understood that I must not overuse try-except statement and usually when the exception could happen exceptionally. By the way I have this piece of code using elementTree standard module and according to Alan this is bad code I guess: *try: devdb.setDescription(dev.attrib['description']) except KeyError: pass try: devdb.setSymbolName(dev.attrib['symbolName']) except KeyError: pass try: devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList']) except KeyError: pass try: devdb.setLayoutName(dev.attrib['layoutName']) except KeyError: pass try: devdb.setLayoutType(dev.attrib['layoutType']) except KeyError: pass * In fact elementTree *attrib* dictionary attributes could not have optionally xml attribute (depending on my xml input file). Indeed to test existence I try to execute *dev.attrib['//'*]. But I can't use only one except because the other settings could not be processed if one given optional xml attribute is not present (except will be raised). I must did it for each possible attribute. Do you have an alternative or my way is ok? I know there is no special case which is enough special to break the rule ;o) Regards Karim On 01/10/2011 03:10 AM, Alan Gauld wrote: > ctions are slower than static functions, but that -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 10 10:30:03 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 09:30:03 -0000 Subject: [Tutor] Checkbox problem in Tkinter References: Message-ID: "ANKUR AGGARWAL" wrote > from Tkinter import * > root=Tk() > var=StringVar() > c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh",offvalue="gggg") > c.pack() > root.mainloop() FWIW I get a different problem, namely that the var does not seem to get updated nor does changling the var seem to alter the buuttons state. But at least the button displays OK with 'hello' in the label and I can select/deselect it with the mouse. its just the change to the variable that is broken. If I write an explicit event handler: def f(): var = 'hhhh' if var == 'gggg' else 'gggg' Then var changes OK. Here is my code(from Pythonwin): >>> def f(): global var; var = 'on' if var == 'off' else 'off';print >>> var ... >>> top = Tk() >>> var = StringVar() >>> c = Checkbutton(top,text='txt', variable=var, onvalue='on', >>> offvalue='off', command=f) >>> c.pack() >>> top.mainloop() off on off on off on HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 10 10:39:42 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 10 Jan 2011 09:39:42 +0000 (GMT) Subject: [Tutor] Try except really better than if? In-Reply-To: <4D2ACD6D.7010803@free.fr> References: <4D2A3453.5040802@free.fr> <4D2ACD6D.7010803@free.fr> Message-ID: <137099.13493.qm@web86703.mail.ird.yahoo.com> By the way I have this piece of code using elementTree standard module >and according to Alan this is bad code I guess: > > Which just proves there are no absolute rules in programming :-) try: devdb.setDescription(dev.attrib['description']) >except KeyError: pass >try: devdb.setSymbolName(dev.attrib['symbolName']) >except KeyError: pass >try: devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList']) >except KeyError: pass >try: devdb.setLayoutName(dev.attrib['layoutName']) >except KeyError: pass >try: devdb.setLayoutType(dev.attrib['layoutType']) >except KeyError: pass >Since you just use pass to ignore the error then you are kind of forced to do it this way. Its not bad each statement has to be treated individually, it is not a block where all the statements must pass or fail as a unit. > Do you have an alternative or my way is ok? This would also be a valid case for an if/else check but in readability terms I think try/except still wins because the handler is only a pass. If it were more complex I'd probably opt for if/else. I know there is no special case which is enough special to break the rule ;o) >I'm not sure I agree. In programming you can usually find a special case that validly breaks any "rule"! Even "Don't use goto!" :-) HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Mon Jan 10 11:14:20 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 10 Jan 2011 11:14:20 +0100 Subject: [Tutor] Try except really better than if? In-Reply-To: <137099.13493.qm@web86703.mail.ird.yahoo.com> References: <4D2A3453.5040802@free.fr> <4D2ACD6D.7010803@free.fr> <137099.13493.qm@web86703.mail.ird.yahoo.com> Message-ID: <4D2ADBFC.9010705@free.fr> Thanks Alan this reassures me! Regards Karim On 01/10/2011 10:39 AM, ALAN GAULD wrote: > > By the way I have this piece of code using elementTree standard > module > and according to Alan this is bad code I guess: > > Which just proves there are no absolute rules in programming :-) > > *try: devdb.setDescription(dev.attrib['description']) > except KeyError: pass > try: devdb.setSymbolName(dev.attrib['symbolName']) > except KeyError: pass > try: > devdb.setSymbolPinOrderMappingList(dev.attrib['symbolPinOrderMappingList']) > except KeyError: pass > try: devdb.setLayoutName(dev.attrib['layoutName']) > except KeyError: pass > try: devdb.setLayoutType(dev.attrib['layoutType']) > except KeyError: pass > * > > Since you just use pass to ignore the error then you are kind > of forced to do it this way. Its not bad each statement has to > be treated individually, it is not a block where all the statements > must pass or fail as a unit. > > > Do you have an alternative or my way is ok? > > This would also be a valid case for an if/else check but > in readability terms I think try/except still wins because > the handler is only a pass. If it were more complex I'd > probably opt for if/else. > > I know there is no special case which is enough special to break > the rule ;o) > > I'm not sure I agree. In programming you can usually find a special case > that validly breaks any "rule"! Even "Don't use goto!" :-) > > HTH, > > Alan G. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jan 10 11:32:28 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 21:32:28 +1100 Subject: [Tutor] Try except really better than if? In-Reply-To: <4D2ACD6D.7010803@free.fr> References: <4D2A3453.5040802@free.fr> <4D2ACD6D.7010803@free.fr> Message-ID: <4D2AE03C.30409@pearwood.info> Karim wrote: > > Thank you Steven, Modulok and Alan for your precious and detailed > explanations! > > I understood that I must not overuse try-except statement and usually > when the exception could happen exceptionally. > By the way I have this piece of code using elementTree standard module > and according to Alan this is bad code I guess: > > *try: devdb.setDescription(dev.attrib['description']) > except KeyError: pass [...] Whenever you have very similar code repeated many times, you should consider factoring out the common code into a helper function. Something like this: def try_or_pass(key): attr_name = 'set' + key[0].upper() + key[1:] try: getattr(devb, attr_name)(dev.attrib[key]) except KeyError: pass try_or_pass('description') try_or_pass('symbolName') etc. -- Steven From karim.liateni at free.fr Mon Jan 10 11:50:11 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 10 Jan 2011 11:50:11 +0100 Subject: [Tutor] Try except really better than if? In-Reply-To: <4D2AE03C.30409@pearwood.info> References: <4D2A3453.5040802@free.fr> <4D2ACD6D.7010803@free.fr> <4D2AE03C.30409@pearwood.info> Message-ID: <4D2AE463.6030204@free.fr> Steven many thanks for this useful hint! I will modify my code. Many thanks! Regards Karim On 01/10/2011 11:32 AM, Steven D'Aprano wrote: > Karim wrote: >> >> Thank you Steven, Modulok and Alan for your precious and detailed >> explanations! >> >> I understood that I must not overuse try-except statement and usually >> when the exception could happen exceptionally. >> By the way I have this piece of code using elementTree standard >> module and according to Alan this is bad code I guess: >> >> *try: devdb.setDescription(dev.attrib['description']) >> except KeyError: pass > [...] > > Whenever you have very similar code repeated many times, you should > consider factoring out the common code into a helper function. > Something like this: > > def try_or_pass(key): > attr_name = 'set' + key[0].upper() + key[1:] > try: > getattr(devb, attr_name)(dev.attrib[key]) > except KeyError: > pass > > try_or_pass('description') > try_or_pass('symbolName') > etc. > > > From steve at pearwood.info Mon Jan 10 11:58:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 10 Jan 2011 21:58:56 +1100 Subject: [Tutor] Try except really better than if? In-Reply-To: References: <4D2A3453.5040802@free.fr> Message-ID: <4D2AE670.3060704@pearwood.info> Alan Gauld wrote: > However, using exceptions like if/else blocks is bad practice. I'm afraid I disagree strongly with that! > You need to use them like a commit in SQL - to protect a whole > block of code. Putting try/except around every line of code > defeats the purpose, wrap atomic blocks of code not the > individual lines. Wrapping an atomic block of code, so long as it actually *can* be treated as atomic (including backing out any changes if it fails), is a good use of try...except. But otherwise, this is risky advice. Take your example: > try: > something > something else > another > the last > except Error1: # do something > except Error2: # do something > except Error3: # do something > finally: # tidy up Provided the entire try block needs to be treated as a single operation (in which case, why isn't it a function?) then that's not too bad. But the risk comes from people who wrap large blocks of code *without* making them atomic transactions: try: get_job_id() query_database() send_results() push_ticket() update_counter() except KeyError: print "job failed" And now an error in push_ticket means that the counter fails to be updated even though the results were sent. Problems occur. The try block must contain ONE operation. It doesn't matter if the operation is a simple, atomic operation: try: y = x + 1 except... or a large, complex transaction, so long as it can safely be treated as a single operation. That is, the individual sub-tasks should have no side-effects, or they must be backed out off on failure. The other problem is that large try blocks can mask bugs. Here's my example again: try: get_job_id() query_database() send_results() push_ticket() update_counter() except KeyError: print "job failed" The idea being that get_job_id or query_database might raise KeyError. But update_counter should never raise KeyError. If it does, that indicates a bug in update_counter, which will then be masked by the except as a normal error in processing. This would be better: try: get_job_id() query_database() except KeyError: print "job failed" else: send_results() push_ticket() update_counter() Now the else block is only executed if there is no KeyError, and any exceptions in those three will be detected and not masked. Of course, you can then wrap the entire code block in another try...except, try...else or try...finally block. Something like this perhaps? try: try: get_job_id() query_database() except KeyError: print "job failed" else: # no exception caught send_results() push_ticket() update_counter() failed = True finally: if transaction_succeeded(): commit_transaction() else: rollback() And now you are beginning to see why databases are so complicated. > is better to maintain than > > try: something > except Error1: # do something > try: something else > except Error2: # do something > try: another > except Error1: # and again > try: the last > except Error3: do it > tidy up That's what you have to do if something, something else, etc. need to be treated as independent operations that have to be done regardless of the success or failure of those that come before. Otherwise: try: something try: something_else try: another except Error1: ... except Error2: ... except Error1: ... It has been said that error handling is ten times harder than handling the rest of your code. -- Steven From __peter__ at web.de Mon Jan 10 12:01:46 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Jan 2011 12:01:46 +0100 Subject: [Tutor] Checkbox problem in Tkinter References: Message-ID: ANKUR AGGARWAL wrote: > and i got the output as - > [image: Screenshot.png] The image doesn't survive. > When i take the var as of string variable type i am unable to edit the > checkbox. It comes slected predefined and the widget in kindof Invisible > and > u can say uneditable. Can anybody tell me whats i am doing wrong in > this??? Its works fine if i take the var variable as the integer variable. > I can deselect and select in that case and it gives me the desired result > but in string case i am unable to do so as checkbox is invisible type. > I am using Python 2.6 I can't reproduce that behaviour. The widget appears greyed initially, but is still editible. You could try to initialise the StringVar with onvalue or offvalue: > from Tkinter import * > root=Tk() > var=StringVar() var.set("hhhh") > c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh", > offvalue="gggg") > c.pack() > root.mainloop() From __peter__ at web.de Mon Jan 10 12:35:40 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Jan 2011 12:35:40 +0100 Subject: [Tutor] Checkbox problem in Tkinter References: Message-ID: Alan Gauld wrote: > > "ANKUR AGGARWAL" wrote > >> from Tkinter import * >> root=Tk() >> var=StringVar() >> c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh",offvalue="gggg") >> c.pack() >> root.mainloop() > > FWIW I get a different problem, namely that the var does not seem > to get updated nor does changling the var seem to alter the buuttons > state. But at least the button displays OK with 'hello' in the label > and > I can select/deselect it with the mouse. its just the change to the > variable that is broken. > If I write an explicit event handler: > > def f(): > var = 'hhhh' if var == 'gggg' else 'gggg' > > Then var changes OK. Here is my code(from Pythonwin): > >>>> def f(): global var; var = 'on' if var == 'off' else 'off';print >>>> var > ... >>>> top = Tk() >>>> var = StringVar() >>>> c = Checkbutton(top,text='txt', variable=var, onvalue='on', >>>> offvalue='off', command=f) >>>> c.pack() >>>> top.mainloop() > off > on > off > on > off > on I think that is confusing. Tkinter is not supposed to rebind the global name 'var', it invokes its set() method. Try from Tkinter import * root = Tk() var = StringVar() def command(): print var.get() cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off", variable=var, command=command) cb.pack() root.mainloop() You can also monitor changes to var's value directly: from Tkinter import * root = Tk() var = StringVar() def show(*args): print var.get() var.trace_variable('w', show) cb = Checkbutton(root, text="yadda", onvalue="on", offvalue="off", variable=var) cb.pack() root.mainloop() From __peter__ at web.de Mon Jan 10 12:38:25 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 10 Jan 2011 12:38:25 +0100 Subject: [Tutor] Checkbox problem in Tkinter References: Message-ID: ANKUR AGGARWAL wrote: > Hey I write this code up > > from Tkinter import * > root=Tk() > var=StringVar() > c=Checkbutton(root,text="hello",variable=var,onvalue="hhhh",offvalue="gggg") > c.pack() > root.mainloop() > > and i got the output as - > [image: Screenshot.png] > > When i take the var as of string variable type i am unable to edit the > checkbox. It comes slected predefined and the widget in kindof Invisible > and > u can say uneditable. Can anybody tell me whats i am doing wrong in > this??? Its works fine if i take the var variable as the integer variable. > I can deselect and select in that case and it gives me the desired result > but in string case i am unable to do so as checkbox is invisible type. > I am using Python 2.6 > Thanks In Advance > Ankur Aggarwal The variable appears greyed out because initially var.get() == "", see http://www.tcl.tk/man/tcl8.5/TkCmd/checkbutton.htm#M-tristatevalue From arunkumar413 at gmail.com Mon Jan 10 13:58:00 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Mon, 10 Jan 2011 18:28:00 +0530 Subject: [Tutor] about import statement Message-ID: Hi Friends, I'm Arun Kumar from India, Just a month ago i started learning programming .learned some basics of python. I'm really enjoying programming in python. I have some doubts in python. When we write programs,we write some import statements at the beginning of the code. how to know that we should import something. How do we know that certain classes are in particular module? Thanks Arun Kumar From bgailer at gmail.com Mon Jan 10 15:34:48 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Jan 2011 09:34:48 -0500 Subject: [Tutor] about import statement In-Reply-To: References: Message-ID: <4D2B1908.9060709@gmail.com> On 1/10/2011 7:58 AM, arun kumar wrote: > Hi Friends, > > I'm Arun Kumar from India, Just a month ago i started learning > programming .learned some basics of python. I'm really enjoying > programming in python. > > I have some doubts in python. When we write programs,we write some > import statements at the beginning of the code. how to know that we > should import something. How do we know that certain classes are in > particular module? Python comes with basic functionality built-in. In addition there are many modules included in the Python distribution to supply additional functionality. See the Global Module Index in the Documentation. Unfortunately the list is large - and many of the modules are very specialized. I suggest reading (at minimum) the descriptions for collections, copy, decimal, exceptions, glob, itertools, math, operator, os, pickle (and shelve), re, shutil, sys, time. In addition there are many many other packages for extending Python that are not in the distribution that add more modules. You can also write your own modules. This is a way to - break a complex program into smaller pieces (that often can be independently tested) - create common code to be used by more than one main program. HTH. Please return with more questions. -- Bob Gailer 919-636-4239 Chapel Hill NC From maxc at me.com Mon Jan 10 15:09:46 2011 From: maxc at me.com (Max Countryman) Date: Mon, 10 Jan 2011 09:09:46 -0500 Subject: [Tutor] about import statement In-Reply-To: <5F8E12CA-A4DC-4C8C-8AFA-00338F4F1BC1@me.com> References: <5F8E12CA-A4DC-4C8C-8AFA-00338F4F1BC1@me.com> Message-ID: <81209C56-846C-41D1-855C-313993E7B04A@me.com> On Jan 10, 2011, at 7:58 AM, arun kumar wrote: > how to know that we > should import something. How do we know that certain classes are in > particular module? You know to import a module if you need part of that module. Perhaps you need a class or function defined in the module. There are several ways to see what a module provides. The documentation is usually a good place to start. You can also use dir(), e.g. import foo; dir(foo). From karim.liateni at free.fr Mon Jan 10 17:07:44 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 10 Jan 2011 17:07:44 +0100 Subject: [Tutor] Equality of numbers and Strings Message-ID: <4D2B2ED0.7030507@free.fr> Hello All, I am not a beginner in Python language but I discovered a hidden property of immutable elements as Numbers and Strings. s ='xyz' >>> t = str('xyz') >>> id(s) == id(t) True Thus if I create 2 different instances of string if the string is identical (numerically). I get the same object in py db. It could be evident but if I do the same (same elements) with a list it will not give the same result. Is-it because of immutable property of strings and numbers? Regards Karim From emile at fenx.com Mon Jan 10 17:51:10 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Jan 2011 08:51:10 -0800 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: <4D2B2ED0.7030507@free.fr> References: <4D2B2ED0.7030507@free.fr> Message-ID: On 1/10/2011 8:07 AM Karim said... > > Hello All, > > I am not a beginner in Python language but I discovered a hidden > property of immutable elements as Numbers and Strings. > > s ='xyz' > >>> t = str('xyz') > > >>> id(s) == id(t) > True > > Thus if I create 2 different instances of string if the string is > identical (numerically). well, not predictably unless you understand the specifics of the implementation you're running under. >>> from string import letters >>> longstring = letters*100 >>> otherstring = letters*100 >>> id(longstring) 12491608 >>> id (otherstring) 12100288 >>> shortstring = letters[:] >>> id(letters) 11573952 >>> id(shortstring) 11573952 >>> > I get the same object in py db. It could be evident but if I do the same > (same elements) with a list it > will not give the same result. Is-it because of immutable property of > strings and numbers? > It has to do with Interning -- see eg http://docs.python.org/library/functions.html#intern Generally, the shorter strings are interned to speed up dictionary access. At this point, I'd characterize the coincidence of id()s as more of an implementation detail side effect than anything else. Emile From bgailer at gmail.com Mon Jan 10 17:54:33 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Jan 2011 11:54:33 -0500 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: <4D2B2ED0.7030507@free.fr> References: <4D2B2ED0.7030507@free.fr> Message-ID: <4D2B39C9.8060806@gmail.com> On 1/10/2011 11:07 AM, Karim wrote: > > Hello All, > > I am not a beginner in Python language but I discovered a hidden > property of immutable elements as Numbers and Strings. > > s ='xyz' > >>> t = str('xyz') > > >>> id(s) == id(t) > True > > Thus if I create 2 different instances of string if the string is > identical (numerically). Python "interns" certain literal strings - so a 2nd attempt to create 'xyz' will refer back to the original object. I don't know all the rules - but the following program never prints n: for n in range(1,10000): s = eval("'" + 'wrtnjasdflkasjj'*n + "'") t = eval("'" + 'wrtnjasdflkasjj'*n + "'") if id(s) != id(t): print n; break whereas if I insert a ";" in the literal the program prints 1! Also note str() returns the argument object unchanged. -- Bob Gailer 919-636-4239 Chapel Hill NC From emile at fenx.com Mon Jan 10 18:01:26 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Jan 2011 09:01:26 -0800 Subject: [Tutor] about import statement In-Reply-To: References: Message-ID: On 1/10/2011 4:58 AM arun kumar said... > Hi Friends, > > I'm Arun Kumar from India, Just a month ago i started learning > programming .learned some basics of python. I'm really enjoying > programming in python. > > I have some doubts in python. When we write programs,we write some > import statements at the beginning of the code. how to know that we > should import something. How do we know that certain classes are in > particular module? I found effbot's guide to the standard library helpful -- and although it's nor current, you'll still get a good idea of where things are at and how to use them. See http://effbot.org/zone/librarybook-index.htm Also, experiment with help() from the python prompt. Once in the help system, type in 'modules' to see a list of installed available modules to explore, or a module name for more info on that module. HTH, Emile From bgailer at gmail.com Mon Jan 10 18:23:46 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Jan 2011 12:23:46 -0500 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: References: <4D2B2ED0.7030507@free.fr> Message-ID: <4D2B40A2.8090609@gmail.com> On 1/10/2011 11:51 AM, Emile van Sebille wrote: > > well, not predictably unless you understand the specifics of the > implementation you're running under. > > > >>> from string import letters > >>> longstring = letters*100 > >>> otherstring = letters*100 > >>> id(longstring) > 12491608 > >>> id (otherstring) > 12100288 > >>> shortstring = letters[:] > >>> id(letters) > 11573952 > >>> id(shortstring) > 11573952 > >>> > In my experiment I found that using * to replicate gave different results than using the exact literal. That is why in the program I posted I used the equivalent of eval("'" + letters*n + "'") which gives different results than eval("letters*n")! [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC From wescpy at gmail.com Mon Jan 10 18:32:06 2011 From: wescpy at gmail.com (wesley chun) Date: Mon, 10 Jan 2011 09:32:06 -0800 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: <4D2B39C9.8060806@gmail.com> References: <4D2B2ED0.7030507@free.fr> <4D2B39C9.8060806@gmail.com> Message-ID: On Mon, Jan 10, 2011 at 8:54 AM, bob gailer wrote: > On 1/10/2011 11:07 AM, Karim wrote: > >> >> s ='xyz' >> >>> t = str('xyz') >> >> >>> id(s) == id(t) >> True >> >> Thus if I create 2 different instances of string if the string is >> identical (numerically). >> > > Python "interns" certain literal strings - so a 2nd attempt to create 'xyz' > will refer back to the original object. > i haven't researched all the rules for strings either, but from my understanding, they're short(er) strings which are used often enough to warrant interning. the (current) rule for ints is: range(-5, 257). i say current because before 2.5, it was range(-1, 101). no one bothered to tell me when i updated Core Python to a 2nd ed. good thing i checked before it went to press! :P note that floats are also immutable, but they're never interned, so you'll never get the same one twice unless you're really referring to the same object. same goes for complex, etc. interning is strictly for commonly-used small ints and short strings. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Jan 10 18:42:23 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Jan 2011 09:42:23 -0800 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: <4D2B40A2.8090609@gmail.com> References: <4D2B2ED0.7030507@free.fr> <4D2B40A2.8090609@gmail.com> Message-ID: On 1/10/2011 9:23 AM bob gailer said... > On 1/10/2011 11:51 AM, Emile van Sebille wrote: >> >> well, not predictably unless you understand the specifics of the >> implementation you're running under. >> >> >> >>> from string import letters >> >>> longstring = letters*100 >> >>> otherstring = letters*100 >> >>> id(longstring) >> 12491608 >> >>> id (otherstring) >> 12100288 >> >>> shortstring = letters[:] >> >>> id(letters) >> 11573952 >> >>> id(shortstring) >> 11573952 >> >>> >> > In my experiment I found that using * to replicate gave different > results than using the exact literal. That is why in the program I > posted I used the equivalent of eval("'" + letters*n + "'") which gives > different results than eval("letters*n")! > > [snip] > Hence, not predictably. I also found it particularly interesting that an explicit copy didn't: shortstring = letters[:] Emile From stefan_ml at behnel.de Mon Jan 10 18:44:24 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Jan 2011 18:44:24 +0100 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: References: <4D2B2ED0.7030507@free.fr> <4D2B40A2.8090609@gmail.com> Message-ID: Emile van Sebille, 10.01.2011 18:42: > On 1/10/2011 9:23 AM bob gailer said... >> On 1/10/2011 11:51 AM, Emile van Sebille wrote: >>> >>> well, not predictably unless you understand the specifics of the >>> implementation you're running under. >>> >>> >>> >>> from string import letters >>> >>> longstring = letters*100 >>> >>> otherstring = letters*100 >>> >>> id(longstring) >>> 12491608 >>> >>> id (otherstring) >>> 12100288 >>> >>> shortstring = letters[:] >>> >>> id(letters) >>> 11573952 >>> >>> id(shortstring) >>> 11573952 >>> >>> >>> >> In my experiment I found that using * to replicate gave different >> results than using the exact literal. That is why in the program I >> posted I used the equivalent of eval("'" + letters*n + "'") which gives >> different results than eval("letters*n")! > > Hence, not predictably. > > I also found it particularly interesting that an explicit copy didn't: > shortstring = letters[:] There's no need to copy an immutable object. Stefan From stefan_ml at behnel.de Mon Jan 10 18:56:35 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 10 Jan 2011 18:56:35 +0100 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: <4D2B2ED0.7030507@free.fr> References: <4D2B2ED0.7030507@free.fr> Message-ID: Karim, 10.01.2011 17:07: > I am not a beginner in Python language but I discovered a hidden property > of immutable elements as Numbers and Strings. > > s ='xyz' > >>> t = str('xyz') > > >>> id(s) == id(t) > True > > Thus if I create 2 different instances of string if the string is > identical (numerically). I get the same object in py db. It could be > evident but if I do the same (same elements) with a list it will not > give the same result. Is-it because of immutable property of strings and > numbers? AFAIR, all string literals in a module are interned by the CPython compiler, and short strings that look like identifiers are also interned (to speed up dictionary lookups, e.g. for function names). So you will get identical objects in these cases, although it's not a good idea to rely on this as it's an implementation detail of the runtime. And the second thing that you can observe here is that str() never copies a string you pass in, which is reasonable behaviour for immutable objects. > Thus if I create 2 different instances of string if the string is > identical (numerically). There's no such thing as "numerically identical" strings. It's enough to say that they are identical as opposed to equal. Stefan From alan.gauld at btinternet.com Mon Jan 10 19:16:06 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 18:16:06 -0000 Subject: [Tutor] Try except really better than if? References: <4D2A3453.5040802@free.fr> <4D2AE670.3060704@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Wrapping an atomic block of code, so long as it actually *can* be > treated as atomic (including backing out any changes if it fails), > is a good use of try...except. That's exactly what I meant by atomic. A (smallish) group of instructions that must be treated as a group, if any one fails the whole block fails and must be backed out or aborted. > Provided the entire try block needs to be treated as a single > operation (in which case, why isn't it a function?) The point about the function is good and the try/except can live within the function. > a single operation. That is, the individual sub-tasks should have no > side-effects, or they must be backed out off on failure. Absolutely. That is the key criterion. > It has been said that error handling is ten times harder than > handling the rest of your code. Yep, and usually takes up about ten times as much code. I once analyzed a largish project - about 1.5 million lines of C++. Only ~250k lines were actual funcionality, the rest were split between GUI (before GUI Builders etc) and error handling (and some logging for our IT department's benefit). I can't recall the split between GUI and errors but it was scary to see how little was real functonal code... ( This didn't include any SQL or script files but it was before the days of stored procedures so most of the SQL was probably ermbedded in the C++ anyway). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 10 19:21:50 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 18:21:50 -0000 Subject: [Tutor] Checkbox problem in Tkinter References: Message-ID: "Peter Otten" <__peter__ at web.de> wrote >> I can select/deselect it with the mouse. its just the change to the >> variable that is broken. This was the problem using the Stringvar. >> Then var changes OK. Here is my code(from Pythonwin): >> >>>>> def f(): global var; var = 'on' if var == 'off' else 'off';print >>>>> var >> ... >>>>> top = Tk() >>>>> var = StringVar() >>>>> c = Checkbutton(top,text='txt', variable=var, onvalue='on', >>>>> offvalue='off', command=f) >>>>> c.pack() >>>>> top.mainloop() >> off >> on > > I think that is confusing. Tkinter is not supposed to rebind the > global name > 'var', it invokes its set() method. Try Yes, my bad, I should have removed the StringVar assigment it was just a carryover from the previous attempt. The problem was that the StringVar was never changing when the control was clicked. This was my attempt to create a manual solution that avoided the automated StringVar approach. > def command(): > print var.get() This raises an interesting point though. I was printing var - which never changed - I forgot about the need to go through a get() method. Time for another experiment.... Alan G. From alan.gauld at btinternet.com Mon Jan 10 19:28:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 10 Jan 2011 18:28:16 -0000 Subject: [Tutor] about import statement References: Message-ID: "arun kumar" wrote > I have some doubts in python. When we write programs,we write some > import statements at the beginning of the code. how to know that we > should import something. Trial and error, experience and mainly reading the documentation. You try to do something and there is no obvious direct solution in the basic Python built-in commands and functions, so we go to the module library to see if anything looks useful. Then we use dir() and help() to find out what is in the module and how to use it. If nothing exists in the library then we try Google and perhaps install a third party package. > How do we know that certain classes are in particular module? dir(), help() and reading the documents. Sorry, there are no easier answers, but that kind of research is one of the keys to programming. And sometimes you will probably write code that could have been done via a module but you just didn't know it existed. I've done that lots of times! Reading this list is a good way to discover some of the more obscure but useful modules available. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From karim.liateni at free.fr Mon Jan 10 20:03:20 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 10 Jan 2011 20:03:20 +0100 Subject: [Tutor] Equality of numbers and Strings In-Reply-To: References: <4D2B2ED0.7030507@free.fr> Message-ID: <4D2B57F8.6080401@free.fr> Many thanks Emile, Bob, Stefan, Wesley! Now, I see now that the point is more related to implementation details and optimization instead of a true property. But it could mistaken people not aware. Regards Karim On 01/10/2011 06:56 PM, Stefan Behnel wrote: > Karim, 10.01.2011 17:07: >> I am not a beginner in Python language but I discovered a hidden >> property >> of immutable elements as Numbers and Strings. >> >> s ='xyz' >> >>> t = str('xyz') >> >> >>> id(s) == id(t) >> True >> >> Thus if I create 2 different instances of string if the string is >> identical (numerically). I get the same object in py db. It could be >> evident but if I do the same (same elements) with a list it will not >> give the same result. Is-it because of immutable property of strings and >> numbers? > > AFAIR, all string literals in a module are interned by the CPython > compiler, and short strings that look like identifiers are also > interned (to speed up dictionary lookups, e.g. for function names). So > you will get identical objects in these cases, although it's not a > good idea to rely on this as it's an implementation detail of the > runtime. > > And the second thing that you can observe here is that str() never > copies a string you pass in, which is reasonable behaviour for > immutable objects. > > >> Thus if I create 2 different instances of string if the string is >> identical (numerically). > > There's no such thing as "numerically identical" strings. It's enough > to say that they are identical as opposed to equal. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kb1pkl at aim.com Mon Jan 10 22:25:24 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 10 Jan 2011 16:25:24 -0500 Subject: [Tutor] __init__() - is it required? In-Reply-To: <4D2A2834.3080506@pearwood.info> References: <4D29F056.9070307@aim.com> <4D2A2834.3080506@pearwood.info> Message-ID: <4D2B7944.9090700@aim.com> On 01/09/2011 04:27 PM, Steven D'Aprano wrote: > Corey Richardson wrote: >> Do all classes need an __init__() method? I have classes that look much >> like this one starts out: >> >> class GenerateXML(object): >> """Defines methods to be inherited for StaticXML and AnimationXML""" >> def __init__(self): >> pass >> >> I would rather not do that. Code without it runs fine, but will there be >> any negative consequences down the road? Does object define an __init__ >> method for me? > > You don't need to define an __init__ if you don't need one. A > placeholder __init__ that does nothing, as above, is a waste of space. > > object includes an __init__ method that not only does nothing, but > ignores any arguments you pass to it: > > >>> object.__init__ > > >>> object.__init__(1, 2, 3) > >>> > > In Python 2.x, you can have "old-style" classes that don't inherit from > object. They too don't need an __init__: > > >>> class Old: # *don't* inherit from object > ... pass > ... > >>> o = Old() > >>> > > Thank you very much Alan and Steven! ~Corey Richardson From Randall.Benson at iberdrolaren.com Tue Jan 11 01:10:35 2011 From: Randall.Benson at iberdrolaren.com (Benson, Randall) Date: Mon, 10 Jan 2011 16:10:35 -0800 Subject: [Tutor] Missing Data in Txt Files In-Reply-To: <4D2B7944.9090700@aim.com> References: <4D29F056.9070307@aim.com> <4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com> Message-ID: <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> Hello, Does anyone have a program that will read txt file data and insert -9999 or similar for missing data? I have 10minute data and there are hour chunks that are missing that need a missing data insert for that missing hour but not the 10min period. The txt file has a date column (yymmdd), a time (hhmm) column and the rest are data columns shown below. See column 1 below with i 080618 1000 4.62 7.00 227.0 -3.38 -3.15 0.00 9999.99 9999.99 0.91 080618 1410 5.19 7.30 232.0 -4.09 -3.20 0.00 9999.99 9999.99 1.03 Muchas gracias, Randall P. Benson, PhD Global Technical Division/Energy Resources O: 503-796-7129 M: 971-227-2477 -----Original Message----- From: tutor-bounces+randall.benson=iberdrolaren.com at python.org [mailto:tutor-bounces+randall.benson=iberdrolaren.com at python.org] On Behalf Of Corey Richardson Sent: Monday, January 10, 2011 1:25 PM To: tutor at python.org Subject: Re: [Tutor] __init__() - is it required? On 01/09/2011 04:27 PM, Steven D'Aprano wrote: > Corey Richardson wrote: >> Do all classes need an __init__() method? I have classes that look much >> like this one starts out: >> >> class GenerateXML(object): >> """Defines methods to be inherited for StaticXML and AnimationXML""" >> def __init__(self): >> pass >> >> I would rather not do that. Code without it runs fine, but will there be >> any negative consequences down the road? Does object define an __init__ >> method for me? > > You don't need to define an __init__ if you don't need one. A > placeholder __init__ that does nothing, as above, is a waste of space. > > object includes an __init__ method that not only does nothing, but > ignores any arguments you pass to it: > > >>> object.__init__ > > >>> object.__init__(1, 2, 3) > >>> > > In Python 2.x, you can have "old-style" classes that don't inherit from > object. They too don't need an __init__: > > >>> class Old: # *don't* inherit from object > ... pass > ... > >>> o = Old() > >>> > > Thank you very much Alan and Steven! ~Corey Richardson _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Please be advised that email addresses for Iberdrola Renewables personnel have changed to first.last at iberdrolaREN.com effective Aug. 16, 2010. Please make a note. Thank you. This message is intended for the exclusive attention of the recipient(s) indicated. Any information contained herein is strictly confidential and privileged. If you are not the intended recipient, please notify us by return e-mail and delete this message from your computer system. Any unauthorized use, reproduction, alteration, filing or sending of this message and/or any attached files may lead to legal action being taken against the party(ies) responsible for said unauthorized use. Any opinion expressed herein is solely that of the author(s) and does not necessarily represent the opinion of the Company. The sender does not guarantee the integrity, speed or safety of this message, and does not accept responsibility for any possible damage arising from the interception, incorporation of viruses, or any other damage as a result of manipulation. From emile at fenx.com Tue Jan 11 01:43:16 2011 From: emile at fenx.com (Emile van Sebille) Date: Mon, 10 Jan 2011 16:43:16 -0800 Subject: [Tutor] Missing Data in Txt Files In-Reply-To: <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> References: <4D29F056.9070307@aim.com> <4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com> <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> Message-ID: On 1/10/2011 4:10 PM Benson, Randall said... > Hello, > > Does anyone have a program that will read txt file data and insert -9999 > or similar for missing data? I have 10minute data and there are hour > chunks that are missing that need a missing data insert for that missing > hour but not the 10min period. The txt file has a date column (yymmdd), > a time (hhmm) column and the rest are data columns shown below. See > column 1 below with i > > 080618 1000 4.62 7.00 227.0 -3.38 -3.15 0.00 9999.99 9999.99 0.91 > 080618 1410 5.19 7.30 232.0 -4.09 -3.20 0.00 9999.99 9999.99 1.03 > Hi Randall, First, please start a new thread next time -- you replied to an existing thread which can cause your post to go unnoticed... I doubt anyone will have a specific program to do what you're asking, and for most of us writing this is what we'd expect to do. I think I'd put the data into a dictionary and access the keys in a loop with a default provided for missing keys. Something along the lines of: lines = open('data/file/name').readlines() D = dict((line{:11),line) for line in lines) for timestamp in timestampgenerator: data = D.get(timestamp,-9999) ... Of course it all depends.... Emile From alan.gauld at btinternet.com Tue Jan 11 02:00:11 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Jan 2011 01:00:11 -0000 Subject: [Tutor] Missing Data in Txt Files References: <4D29F056.9070307@aim.com> <4D2A2834.3080506@pearwood.info><4D2B7944.9090700@aim.com> <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> Message-ID: "Benson, Randall" wrote > hour but not the 10min period. The txt file has a date column > (yymmdd), > a time (hhmm) column and the rest are data columns shown below. See > column 1 below with i Not sure what the last sentence merans? Was there supposed to be more? Or what is the 'i' referred to? > 080618 1000 4.62 7.00 227.0 -3.38 -3.15 0.00 9999.99 9999.99 > 0.91 > 080618 1410 5.19 7.30 232.0 -4.09 -3.20 0.00 9999.99 9999.99 > 1.03 I'm not sure what this is telling me. Is there an example of such missing data here? Does 0.00 mean its missing? Or is it something else? What you want should be possible but we need a much clearer specification of the problem. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Tue Jan 11 02:15:31 2011 From: bgailer at gmail.com (bob gailer) Date: Mon, 10 Jan 2011 20:15:31 -0500 Subject: [Tutor] Missing Data in Txt Files In-Reply-To: <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> References: <4D29F056.9070307@aim.com> <4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com> <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us> Message-ID: <4D2BAF33.2040205@gmail.com> On 1/10/2011 7:10 PM, Benson, Randall wrote: > Hello, > > Does anyone have a program that will read txt file data and insert -9999 > or similar for missing data? I have 10minute data and there are hour > chunks that are missing that need a missing data insert for that missing > hour but not the 10min period. The txt file has a date column (yymmdd), > a time (hhmm) column and the rest are data columns shown below. See > column 1 below with i > > 080618 1000 4.62 7.00 227.0 -3.38 -3.15 0.00 9999.99 9999.99 0.91 > 080618 1410 5.19 7.30 232.0 -4.09 -3.20 0.00 9999.99 9999.99 1.03 > > Muchas gracias, > I agree with Alan. We need more detail. Why are you asking this question on the Python Tutor list? I presume you are using Python. We prefer to help you as you show us effort. Do you know enough Python to write a program that reads a file and creates another? I suggest you start with that, and also give us enough additional details so we fully understand what you want. Sample input - sample output would help a lot. -- Bob Gailer 919-636-4239 Chapel Hill NC From tcl76 at hotmail.com Tue Jan 11 10:03:26 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 11 Jan 2011 09:03:26 +0000 Subject: [Tutor] Change Font Size when print to screen In-Reply-To: <4D2BAF33.2040205@gmail.com> References: <4D29F056.9070307@aim.com>,<4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com>, <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us>, <4D2BAF33.2040205@gmail.com> Message-ID: hi, When I do print "Hello World", it will print to the cmd window with the standard font size. Is there a way we can increase the font size to larger when print out to the cmd window? thanks tcl76 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Tue Jan 11 10:21:26 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Jan 2011 09:21:26 +0000 Subject: [Tutor] Change Font Size when print to screen In-Reply-To: References: <4D29F056.9070307@aim.com>, <4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com>, <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us>, <4D2BAF33.2040205@gmail.com> Message-ID: <4D2C2116.8010408@timgolden.me.uk> On 11/01/2011 09:03, tee chwee liong wrote: > When I do print "Hello World", it will print to the cmd window with > the standard font size. Is there a way we can increase the font size > to larger when print out to the cmd window? I'm going to assume that you're using Windows, since you refer to the "cmd window". If you're on Linux or OS X the answer will be different. In short, this isn't straightforward. The Python interpreter simply sends text to the console and the console renders it using whatever font and size have been selected by the user. You can set the font & size of any console window (and save it as the default) by using the System Menu -- left-click at the top-left of the Window. But if you want a particular Python script to have the power to write smaller or larger text on demand, you're going to need to control the console functions directly. You can do this via the win32console module of the pywin32 modules: http://sourceforge.net/projects/pywin32/ or by rolling the same thing yourself from within Python via ctypes: http://docs.python.org/library/ctypes.html I'm not aware that you can have a mixture of smaller and larger (or different) fonts on one console window. AFAICT you can set the font/size for the whole console but nothing else. If you need more control, you're going to have to move to some kind of GUI solution. TJG From tcl76 at hotmail.com Tue Jan 11 10:42:11 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 11 Jan 2011 09:42:11 +0000 Subject: [Tutor] Change Font Size when print to screen In-Reply-To: <4D2C2116.8010408@timgolden.me.uk> References: <4D29F056.9070307@aim.com>,,<4D2A2834.3080506@pearwood.info> <4D2B7944.9090700@aim.com>, , <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us>, , <4D2BAF33.2040205@gmail.com>, , <4D2C2116.8010408@timgolden.me.uk> Message-ID: tim, you are right. i'm using Windows XP and Python 2.5. thanks tcl76 > Date: Tue, 11 Jan 2011 09:21:26 +0000 > From: mail at timgolden.me.uk > CC: tutor at python.org > Subject: Re: [Tutor] Change Font Size when print to screen > > On 11/01/2011 09:03, tee chwee liong wrote: > > When I do print "Hello World", it will print to the cmd window with > > the standard font size. Is there a way we can increase the font size > > to larger when print out to the cmd window? > > I'm going to assume that you're using Windows, since you > refer to the "cmd window". If you're on Linux or OS X the > answer will be different. > > In short, this isn't straightforward. The Python interpreter > simply sends text to the console and the console renders it > using whatever font and size have been selected by the user. > > You can set the font & size of any console window (and save > it as the default) by using the System Menu -- left-click at > the top-left of the Window. > > But if you want a particular Python script to have the power > to write smaller or larger text on demand, you're going to > need to control the console functions directly. You can do > this via the win32console module of the pywin32 modules: > > http://sourceforge.net/projects/pywin32/ > > or by rolling the same thing yourself from within Python via ctypes: > > http://docs.python.org/library/ctypes.html > > I'm not aware that you can have a mixture of smaller and larger > (or different) fonts on one console window. AFAICT you can set > the font/size for the whole console but nothing else. If you need > more control, you're going to have to move to some kind of > GUI solution. > > TJG > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From arunkumar413 at gmail.com Tue Jan 11 13:02:15 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Tue, 11 Jan 2011 17:32:15 +0530 Subject: [Tutor] about import statement In-Reply-To: References: Message-ID: I'm trying to program with google api i downloaded the libraries provided by the google. http://code.google.com/apis/gdata/docs/client-libraries.html In oder to write program with google api, i need to write some import statements. But i'm unable to understand the hierarchy of the modules,packages,which classes are in which package. From Randall.Benson at iberdrolaren.com Tue Jan 11 17:41:16 2011 From: Randall.Benson at iberdrolaren.com (Benson, Randall) Date: Tue, 11 Jan 2011 08:41:16 -0800 Subject: [Tutor] Filling in Missing Data from Txt Files - Resubmitted Message-ID: <16D31FA412A4424D9DA73028FDB6C9BC0A46BE5C@POREXUW03.ppmenergy.us> Thank you kindly in advance for help on this topic: I am almost finished with writing a program that averages 10-minute column data and outputs the 10-minute data into hourly averages in a separate txt file - the program executes and outputs to the output file perfectly for use by another program. A sample of the input file is attached below. The 0 column is the date in yymmdd, the 1st column is the time in hhmm form and the other columns are wind data. This last step of my program requires me to fill in missing hours with a value such as -9999 for the hour in which all of the data is missing for that hour as shown below. In the sample below there is no data for hours 1000, 1100, 1200 and 1300. For these missing data rows I need to insert the correct date, time and -9999 for the other missing data columns (columns 2-6). 080618 0950 5.10 7.40 224.0 -3.54 -3.67 080618 1000 4.62 7.00 227.0 -3.38 -3.15 080618 1410 5.19 7.30 232.0 -4.09 -3.20 In my program I am reading all the data from the input txt file in a large "for loop" shown below - whereby fileObj is my open statement to the txt data input file: for line in fileObj: lineList = line.strip().split() Thank you, Randall P. Benson Please be advised that email addresses for Iberdrola Renewables personnel have changed to first.last at iberdrolaREN.com effective Aug. 16, 2010. Please make a note. Thank you. This message is intended for the exclusive attention of the recipient(s) indicated. Any information contained herein is strictly confidential and privileged. If you are not the intended recipient, please notify us by return e-mail and delete this message from your computer system. Any unauthorized use, reproduction, alteration, filing or sending of this message and/or any attached files may lead to legal action being taken against the party(ies) responsible for said unauthorized use. Any opinion expressed herein is solely that of the author(s) and does not necessarily represent the opinion of the Company. The sender does not guarantee the integrity, speed or safety of this message, and does not accept responsibility for any possible damage arising from the interception, incorporation of viruses, or any other damage as a result of manipulation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 11 18:51:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Jan 2011 17:51:00 -0000 Subject: [Tutor] Change Font Size when print to screen References: <4D29F056.9070307@aim.com>, <4D2A2834.3080506@pearwood.info><4D2B7944.9090700@aim.com>, <16D31FA412A4424D9DA73028FDB6C9BC0A46BC96@POREXUW03.ppmenergy.us>, <4D2BAF33.2040205@gmail.com> Message-ID: "tee chwee liong" wrote > When I do print "Hello World", it will print to the cmd window > with the standard font size. Is there a way we can increase > the font size to larger when print out to the cmd window? If you want to control appearance other than bold/flashing/underline and color then your best bet is to create a minimal GUI app with just a Text widget and control the fonts etc there. But you will need to get familiar with the GUI toolkits to do that. A basic app in Tkinter can be found in my tutorial in the event driven programming topic. It looks like this: ######################## from Tkinter import * class KeysApp(Frame): def __init__(self): # use constructor to build GUI Frame.__init__(self) self.txtBox = Text(self) self.txtBox.bind("", self.doQuitEvent) self.txtBox.pack() self.pack() def doQuitEvent(self,event): import sys sys.exit() # Now create an instance and start the event loop running myApp = KeysApp() myApp.mainloop() ########################### As you see its a lot more work that a print! If you want to read user input you can use the standard dialog boxes or EasyGUI. You might want a button to start your code executing too. For that see my GUI topic... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Jan 11 19:00:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Jan 2011 18:00:23 -0000 Subject: [Tutor] Filling in Missing Data from Txt Files - Resubmitted References: <16D31FA412A4424D9DA73028FDB6C9BC0A46BE5C@POREXUW03.ppmenergy.us> Message-ID: "Benson, Randall" wrote > hour as shown below. In the sample below there is no data for hours > 1000, 1100, 1200 and 1300. For these missing data rows I need to > insert > the correct date, time and -9999 for the other missing data columns > (columns 2-6). > 080618 0950 5.10 7.40 224.0 -3.54 -3.67 > 080618 1000 4.62 7.00 227.0 -3.38 -3.15 > 080618 1410 5.19 7.30 232.0 -4.09 -3.20 OK, In pseudo code it could be something like prev_datetime = get startdate for line in file: extract datetime from line while datetime - prev_datetime > 10 minutes # missing data write dummy data prev_datetime += 10 minutes prev_datetime = datetime write data Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From knacktus at googlemail.com Tue Jan 11 19:57:54 2011 From: knacktus at googlemail.com (Knacktus) Date: Tue, 11 Jan 2011 19:57:54 +0100 Subject: [Tutor] about import statement In-Reply-To: References: Message-ID: <4D2CA832.5090308@googlemail.com> Am 11.01.2011 13:02, schrieb arun kumar: > I'm trying to program with google api i downloaded the libraries > provided by the google. > http://code.google.com/apis/gdata/docs/client-libraries.html > > In oder to write program with google api, i need to write some import > statements. But i'm unable to understand the hierarchy of the > modules,packages,which classes are in which package. Personaly, I don't get along with the pydoc style very well (as shown as PyDoc in your link). For an overview about packages and modules you can also browse the directory structure of the source code. You can recognize packages as directories with a __init__.py file and modules as *.py files. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kbailey at howlermonkey.net Tue Jan 11 19:17:53 2011 From: kbailey at howlermonkey.net (kbailey at howlermonkey.net) Date: Tue, 11 Jan 2011 18:17:53 +0000 Subject: [Tutor] test- why no traffic? Message-ID: <20110111181753.62052m8tzxoy73cw@howlermonkey.net> hmmm, wonder if my membership went belly up... no traffic arriving... hmmm... From rabidpoobear at gmail.com Tue Jan 11 20:20:33 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 11 Jan 2011 13:20:33 -0600 Subject: [Tutor] test- why no traffic? In-Reply-To: <20110111181753.62052m8tzxoy73cw@howlermonkey.net> References: <20110111181753.62052m8tzxoy73cw@howlermonkey.net> Message-ID: i see you. did you change your settings so you don't get e-mails? On Tue, Jan 11, 2011 at 12:17 PM, wrote: > hmmm, wonder if my membership went belly up... no traffic arriving... > hmmm... > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Jan 11 22:34:50 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 11 Jan 2011 21:34:50 +0000 (GMT) Subject: [Tutor] Filling in Missing Data from Txt Files - Resubmitted In-Reply-To: <16D31FA412A4424D9DA73028FDB6C9BC0A46C103@POREXUW03.ppmenergy.us> References: <16D31FA412A4424D9DA73028FDB6C9BC0A46BE5C@POREXUW03.ppmenergy.us> <16D31FA412A4424D9DA73028FDB6C9BC0A46C103@POREXUW03.ppmenergy.us> Message-ID: <395270.59708.qm@web86701.mail.ird.yahoo.com> forwarding to group. Please use Reply-All when responding to the group. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ----- Original Message ---- > From: "Benson, Randall" > To: Alan Gauld > Sent: Tuesday, 11 January, 2011 19:47:21 > Subject: RE: [Tutor] Filling in Missing Data from Txt Files - Resubmitted > > Hi Alan, > > I'm kind of new to Python but I think I understand your proposed code > below. However, I only need to write missing data to the output file if > there is no 10 min period of data available during any given hour. In > other words, write to the output file missing data when an entire hour > or 6 data records are missing. Otherwise, I use any and all available > 10 min periods to calculate the average for that hour. > > I've thought of reading all the data in first looking at the date and > time columns and then write -9999 to an output file with the missing > 10-min periods and the good data and then go back through the input file > to make the hourly averages of the 10-min data now with missing data > values and good data. Would that approach work? If so, how would you > set up the loop structure for finding the missing hours and then > inserting -9999's? > > > > > Randall P. Benson, PhD > Global Technical Division/Energy Resources > O: 503-796-7129 > M: 971-227-2477 > > > -----Original Message----- > From: tutor-bounces+randall.benson=iberdrolaren.com at python.org > [mailto:tutor-bounces+randall.benson=iberdrolaren.com at python.org] On > Behalf Of Alan Gauld > Sent: Tuesday, January 11, 2011 10:00 AM > To: tutor at python.org > Subject: Re: [Tutor] Filling in Missing Data from Txt Files - > Resubmitted > > > "Benson, Randall" wrote > > > hour as shown below. In the sample below there is no data for hours > > 1000, 1100, 1200 and 1300. For these missing data rows I need to > > insert > > the correct date, time and -9999 for the other missing data columns > > (columns 2-6). > > > 080618 0950 5.10 7.40 224.0 -3.54 -3.67 > > 080618 1000 4.62 7.00 227.0 -3.38 -3.15 > > 080618 1410 5.19 7.30 232.0 -4.09 -3.20 > > OK, In pseudo code it could be something like > > prev_datetime = get startdate > for line in file: > extract datetime from line > while datetime - prev_datetime > 10 minutes # missing data > write dummy data > prev_datetime += 10 minutes > prev_datetime = datetime > write data > > > Does that help? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > Please be advised that email addresses for Iberdrola Renewables personnel have >changed to first.last at iberdrolaREN.com effective Aug. 16, 2010. Please make a >note. Thank you. > > This message is intended for the exclusive attention of the recipient(s) >indicated. Any information contained herein is strictly confidential and >privileged. If you are not the intended recipient, please notify us by return >e-mail and delete this message from your computer system. Any unauthorized use, >reproduction, alteration, filing or sending of this message and/or any attached >files may lead to legal action being taken against the party(ies) responsible >for said unauthorized use. Any opinion expressed herein is solely that of the >author(s) and does not necessarily represent the opinion of the Company. The >sender does not guarantee the integrity, speed or safety of this message, and >does not accept responsibility for any possible damage arising from the >interception, incorporation of viruses, or any other damage as a result of >manipulation. > > > From vearasilp at gmail.com Wed Jan 12 14:11:34 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Wed, 12 Jan 2011 14:11:34 +0100 Subject: [Tutor] Ideas about global variables for accessing project's file Message-ID: Dear all, I am new to python and now having a tiny problem about accessing files from python modules I have in my project.. Here is my situation: Below is the structure of my project /src /src/modules/mod1 /src/modules/mod2 /src/data/file1 /src/data/file2 I wrote some codes in mod1 to access data in file1. And to read the file1, I am hard coding in the mod1, which is something like... open(blahblah/src/data/file1, "w") Now the problems arise when I share my code with other collaborators and the code is not working any more because his/her blahblah before /src is different. Is there a way to make a global variable for the project to make my life easier? Sometime like... PROJECT_PATH/src/modules/mod1 which PROJECT_PATH should work with every machines. All suggestions and advices will be much appreciated. Kann -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Jan 12 14:36:44 2011 From: wprins at gmail.com (Walter Prins) Date: Wed, 12 Jan 2011 13:36:44 +0000 Subject: [Tutor] Ideas about global variables for accessing project's file In-Reply-To: References: Message-ID: Hi, On 12 January 2011 13:11, Kann Vearasilp wrote: > Below is the structure of my project > > /src > /src/modules/mod1 > /src/modules/mod2 > /src/data/file1 > /src/data/file2 > > > I wrote some codes in mod1 to access data in file1. And to read the file1, > I am hard coding in the mod1, which is something like... > open(blahblah/src/data/file1, "w") > Now the problems arise when I share my code with other collaborators and > the code is not working any more because his/her blahblah before /src is > different. > > Is there a way to make a global variable for the project to make my life > easier? Sometime like... PROJECT_PATH/src/modules/mod1 which PROJECT_PATH > should work with every machines. > 1.) You should be able to use relative paths, e.g. something like: open("../data/file1", "w") 2.) You can set up configuration for your application to define where the data files live. See e.g. the "ConfigParser" module: http://wiki.python.org/moin/ConfigParser Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From Frank.Yaniga at GDIT.com Wed Jan 12 14:19:32 2011 From: Frank.Yaniga at GDIT.com (Yaniga, Frank) Date: Wed, 12 Jan 2011 08:19:32 -0500 Subject: [Tutor] question regarding regular expression compile Message-ID: <560FB3D6798A37478F7446CA627933085A3E6AE4B1@EXCHCCR04.ad.local> I am determining a regular expression that can recognize the any of the following strings: MAT file log\20101225 deleted MAT file billing\20101225 deleted MAT file util\20101225 deleted MAT file carrier\20101225 deleted I begin by creating a regular expression object so that I can reuse it in multiple operations: test = re.compile('MAT file for log, billing, util, and carrier I use an arbitrary match: (log|billing|util|carrier) for 20101225 I use decimal digit with repetition match: \d{8} and finish with: delete') My question is how do I handle the backslash (NOTE: the match must only be a backslash)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 12 14:59:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Jan 2011 13:59:07 -0000 Subject: [Tutor] Ideas about global variables for accessing project's file References: Message-ID: "Kann Vearasilp" wrote > Is there a way to make a global variable for the project to make my > life > easier? Sometime like... PROJECT_PATH/src/modules/mod1 which > PROJECT_PATH > should work with every machines. You can use a relative path based on your installatiojn root You can use a config file that the user edits to specify the root directory You can use an environment variable to specify the root directory If you are working with Windows you could also use a registry entry to store the root. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From adam.jtm30 at gmail.com Wed Jan 12 15:11:42 2011 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 12 Jan 2011 14:11:42 +0000 Subject: [Tutor] question regarding regular expression compile In-Reply-To: <560FB3D6798A37478F7446CA627933085A3E6AE4B1@EXCHCCR04.ad.local> References: <560FB3D6798A37478F7446CA627933085A3E6AE4B1@EXCHCCR04.ad.local> Message-ID: <4D2DB69E.1020902@gmail.com> On 12/01/11 13:19, Yaniga, Frank wrote: > I am determining a regular expression that can recognize the any of > the following strings: > MAT file log\20101225 deleted > MAT file billing\20101225 deleted > MAT file util\20101225 deleted > MAT file carrier\20101225 deleted > I begin by creating a regular expression object so that I can reuse it > in multiple operations: > test = re.compile('MAT file > for log, billing, util, and carrier I use an arbitrary match: > (log|billing|util|carrier) > for 20101225 I use decimal digit with repetition match: > \d{8} > and finish with: > delete') > My question is how do I handle the backslash (NOTE: the match must > only be a backslash)? Hi Frank, There are two things you need to know, the first is that \ is a special character in re's, which I think you probably know already. Also they are special characters in python strings unless you use raw strings. So to look for the backslash in your example you need to use a raw string (technically you could use twice as many backslashes to escape the python specialness and re but it looks horrible) by starting the string with r"your regular expression". Then you need to use two backslashes to give you a backslash character. So your re should now look like this: test = re.compile(r"MAT file (log|billing|util|carrier)\\\d{8} deleted") HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Wed Jan 12 15:10:39 2011 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 12 Jan 2011 14:10:39 +0000 Subject: [Tutor] question regarding regular expression compile In-Reply-To: <560FB3D6798A37478F7446CA627933085A3E6AE4B1@EXCHCCR04.ad.local> References: <560FB3D6798A37478F7446CA627933085A3E6AE4B1@EXCHCCR04.ad.local> Message-ID: > I am determining a regular expression that can recognize the any of the following strings: > > MAT file log\20101225 deleted > MAT file billing\20101225 deleted > MAT file util\20101225 deleted > MAT file carrier\20101225 deleted > > I begin by creating a regular expression object so that I can reuse it in multiple operations: > > test = re.compile(?MAT file > > for log, billing, util, and carrier I use an arbitrary match: > > (log|billing|util|carrier) > > for 20101225 I use decimal digit with repetition match: > > \d{8} > > and finish with: > > delete?) > > My question is how do I handle the backslash (NOTE: the match must only be a backslash)? Use a raw string (prepend 'r'): re.compile(r'MAT file (log|billing|util|carrier)\\\d{8} delete') You'll notice you need to escape the backslash first, and then use a raw string by prepending an 'r' in front of the string, so the backslash gets interpreted correctly (or rather, not interpreted) by the regular expression. Cheers, Evert From kpguy1975 at gmail.com Wed Jan 12 16:24:21 2011 From: kpguy1975 at gmail.com (Vikram K) Date: Wed, 12 Jan 2011 10:24:21 -0500 Subject: [Tutor] python hyperlinks question Message-ID: I have a bunch of symbols in one of the columns in my program's output file (a csv file which can be opened in excel). I wish to add hyperlinks to each entry in this particular column in my output file. A sample symbol/entry in the specific column of interest in the output file is USP8 and it needs to be hyperlinked to http://www.ncbi.nlm.nih.gov/gene/9101. (So, when you click on 'USP8' in the output file, your browser automatically opens the site http://www.ncbi.nlm.nih.gov/gene/9101). Could you please tell me how to add hyperlinks to my output? From tommy.kaas at kaasogmulvad.dk Wed Jan 12 16:39:46 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Wed, 12 Jan 2011 16:39:46 +0100 Subject: [Tutor] how avoid writing a newline? Message-ID: <00a001cbb26e$f9dbf640$ed93e2c0$@kaasogmulvad.dk> I'm using Activepython 2.6.6 on PC/Win7 I have made a small scraper script as an exercise for myself. It scrapes the name and some details of the first 25 billionaires on the Forbes list. It works and write the result in a text file, with the columns separated by "#" It takes the name from the link (t = i.string) - open the link and scrape details from the next page. But I can't find a way to write the name (the variable t) one and only one time in the beginning of the line. As t is written now I get it in the beginning of the line but I also get a newline. Can I avoid that in a simple way? Thanks in advance for any help Tommy from BeautifulSoup import BeautifulSoup from mechanize import Browser f = open("forbes.txt", "w") br = Browser() url = "http://www.forbes.com/lists/2010/10/billionaires-2010_The-Worlds-Billionair es_Rank.html" page = br.open(url) html = page.read() soup = BeautifulSoup(html) table = soup.find("table") l = table.findAll('a') for i in l[5:]: t = i.string print t #to the monitor br.follow_link(text_regex=r"(.*?)"+t+"(.*?)") tekst = br.response().read() soup = BeautifulSoup(tekst) table1 = soup.find('table', id='billTable') rows = table1.findAll('tr') print >> f, t,"#" for tr in rows: tds = tr.findAll(text=True) print >> f, tds[1].string,"#",tds[2].string,"#", print >> f, '\r\n' f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Wed Jan 12 16:51:23 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 12 Jan 2011 09:51:23 -0600 Subject: [Tutor] python hyperlinks question In-Reply-To: References: Message-ID: <741D5E41-D5BF-4BEE-9924-52C1AEE57919@gmail.com> Not really a python question, but maybe look at that pyexcel or whatever. Should be able to add links to it that way. Csv is jus a data interchange format though, if excel supports passing links thru it then you can do it, otherwise don't use csv for this. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 12, 2011, at 9:24 AM, Vikram K wrote: > I have a bunch of symbols in one of the columns in my program's output > file (a csv file which can be opened in excel). I wish to add > hyperlinks to each entry in this particular column in my output file. > A sample symbol/entry in the specific column of interest in the output > file is USP8 and it needs to be hyperlinked to > http://www.ncbi.nlm.nih.gov/gene/9101. (So, when you click on 'USP8' > in the output file, your browser automatically opens the site > http://www.ncbi.nlm.nih.gov/gene/9101). > > Could you please tell me how to add hyperlinks to my output? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From jasons at adventureaquarium.com Wed Jan 12 16:49:36 2011 From: jasons at adventureaquarium.com (Jason Staudenmayer) Date: Wed, 12 Jan 2011 10:49:36 -0500 Subject: [Tutor] how avoid writing a newline? In-Reply-To: <00a001cbb26e$f9dbf640$ed93e2c0$@kaasogmulvad.dk> Message-ID: You should have a comma after the "#" in the highlighted print statement, that should repress the new line (I'm guessing that's the line you're talking about) print >> f,t,"#", Jason ..?><((((?> -----Original Message----- From: tutor-bounces+jasons=adventureaquarium.com at python.org [mailto:tutor-bounces+jasons=adventureaquarium.com at python.org] On Behalf Of Tommy Kaas Sent: Wednesday, January 12, 2011 10:40 AM To: tutor at python.org Subject: [Tutor] how avoid writing a newline? I'm using Activepython 2.6.6 on PC/Win7 I have made a small scraper script as an exercise for myself. It scrapes the name and some details of the first 25 billionaires on the Forbes list. It works and write the result in a text file, with the columns separated by "#" It takes the name from the link (t = i.string) - open the link and scrape details from the next page. But I can't find a way to write the name (the variable t) one and only one time in the beginning of the line. As t is written now I get it in the beginning of the line but I also get a newline. Can I avoid that in a simple way? Thanks in advance for any help Tommy from BeautifulSoup import BeautifulSoup from mechanize import Browser f = open("forbes.txt", "w") br = Browser() url = "http://www.forbes.com/lists/2010/10/billionaires-2010_The-Worlds-Billionaires_Rank.html" page = br.open(url) html = page.read() soup = BeautifulSoup(html) table = soup.find("table") l = table.findAll('a') for i in l[5:]: t = i.string print t #to the monitor br.follow_link(text_regex=r"(.*?)"+t+"(.*?)") tekst = br.response().read() soup = BeautifulSoup(tekst) table1 = soup.find('table', id='billTable') rows = table1.findAll('tr') print >> f, t,"#" for tr in rows: tds = tr.findAll(text=True) print >> f, tds[1].string,"#",tds[2].string,"#", print >> f, '\r\n' f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From tommy.kaas at kaasogmulvad.dk Wed Jan 12 17:00:52 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Wed, 12 Jan 2011 17:00:52 +0100 Subject: [Tutor] how avoid writing a newline? In-Reply-To: References: <00a001cbb26e$f9dbf640$ed93e2c0$@kaasogmulvad.dk> Message-ID: <00c301cbb271$e63606a0$b2a213e0$@kaasogmulvad.dk> Yes ? you?re right! Thanks, Tommy Fra: Jason Staudenmayer [mailto:jasons at adventureaquarium.com] Sendt: 12. januar 2011 16:50 Til: Tommy Kaas; tutor at python.org Emne: RE: [Tutor] how avoid writing a newline? You should have a comma after the "#" in the highlighted print statement, that should repress the new line (I'm guessing that's the line you're talking about) print >> f,t,"#", Jason ..?><((((?> -----Original Message----- From: tutor-bounces+jasons=adventureaquarium.com at python.org [mailto:tutor-bounces+jasons=adventureaquarium.com at python.org] On Behalf Of Tommy Kaas Sent: Wednesday, January 12, 2011 10:40 AM To: tutor at python.org Subject: [Tutor] how avoid writing a newline? I?m using Activepython 2.6.6 on PC/Win7 I have made a small scraper script as an exercise for myself. It scrapes the name and some details of the first 25 billionaires on the Forbes list. It works and write the result in a text file, with the columns separated by ?#? It takes the name from the link (t = i.string) ? open the link and scrape details from the next page. But I can?t find a way to write the name (the variable t) one and only one time in the beginning of the line. As t is written now I get it in the beginning of the line but I also get a newline. Can I avoid that in a simple way? Thanks in advance for any help Tommy from BeautifulSoup import BeautifulSoup from mechanize import Browser f = open("forbes.txt", "w") br = Browser() url = "http://www.forbes.com/lists/2010/10/billionaires-2010_The-Worlds-Billionair es_Rank.html" page = br.open(url) html = page.read() soup = BeautifulSoup(html) table = soup.find("table") l = table.findAll('a') for i in l[5:]: t = i.string print t #to the monitor br.follow_link(text_regex=r"(.*?)"+t+"(.*?)") tekst = br.response().read() soup = BeautifulSoup(tekst) table1 = soup.find('table', id='billTable') rows = table1.findAll('tr') print >> f, t,"#" for tr in rows: tds = tr.findAll(text=True) print >> f, tds[1].string,"#",tds[2].string,"#", print >> f, '\r\n' f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From vearasilp at gmail.com Wed Jan 12 17:18:51 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Wed, 12 Jan 2011 17:18:51 +0100 Subject: [Tutor] Ideas about global variables for accessing project's file In-Reply-To: References: Message-ID: <1294849131.27677.3.camel@lagrange> The ConfigParser works perfectly! Thanks a bunch! Kann On Wed, 2011-01-12 at 13:59 +0000, Alan Gauld wrote: > "Kann Vearasilp" wrote > > > Is there a way to make a global variable for the project to make my > > life > > easier? Sometime like... PROJECT_PATH/src/modules/mod1 which > > PROJECT_PATH > > should work with every machines. > > You can use a relative path based on your installatiojn root > You can use a config file that the user edits to specify the root > directory > You can use an environment variable to specify the root directory > > If you are working with Windows you could also use a registry entry to > store the root. > > HTH, > > From egilead at gmail.com Wed Jan 12 20:41:25 2011 From: egilead at gmail.com (Enih Gilead) Date: Wed, 12 Jan 2011 17:41:25 -0200 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? Message-ID: <4D2E03E5.6020302@gmail.com> Hi, all ! I've being strugling a lot trying to insert (just as exemple) a quit-Button in a Tkinter class App with no success... What I get is the clock runing ok, but, the App simply ignores the quit-Button... Why? _*Remark*_: I took this minimalist digital clock just to illustrate the "bad :-)" class behavior, but it didn't work in any other Apps I tried. I searched a lot (indeed!) in the net but I couldn't find the reason. Could any of you tell me, please, _*what's the problem?*_ Thanks, enihgil ################################### import Tkinter import time class App(): def __init__(self): self.root = Tkinter.Tk() self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() self.root.mainloop() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.root.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app=App() -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Wed Jan 12 20:45:25 2011 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 12 Jan 2011 11:45:25 -0800 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? In-Reply-To: <4D2E03E5.6020302@gmail.com> References: <4D2E03E5.6020302@gmail.com> Message-ID: <4D2E04D5.4090201@alchemy.com> On 12-Jan-11 11:41, Enih Gilead wrote: > Hi, all ! > > I've being strugling a lot trying to insert (just as exemple) a > quit-Button in a Tkinter class App with no success... What I get is the > clock runing ok, but, the App simply ignores the quit-Button... Why? Maybe I'm missing something, but you define your own class (not inheriting from a parent class which might give you inherited methods), and then bind the "Quit" button to the quit() method of your class: > class App(): ... > self.quitButton = Button( self, text='Quit', command=self.quit ) But where is the quit() method actually defined? -- Steve Willoughby / steve at alchemy.com "A ship in harbor is safe, but that is not what ships are built for." PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 From karim.liateni at free.fr Wed Jan 12 21:23:20 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 12 Jan 2011 21:23:20 +0100 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? In-Reply-To: <4D2E03E5.6020302@gmail.com> References: <4D2E03E5.6020302@gmail.com> Message-ID: <4D2E0DB8.2040306@free.fr> Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: > Hi, all ! > > I've being strugling a lot trying to insert (just as exemple) a > quit-Button in a Tkinter class App with no success... What I get is > the clock runing ok, but, the App simply ignores the quit-Button... Why? > > _*Remark*_: > I took this minimalist digital clock just to illustrate the "bad :-)" > class behavior, but it didn't work in any other Apps I tried. I > searched a lot (indeed!) in the net but I couldn't find the reason. > > Could any of you tell me, please, _*what's the problem?*_ > Thanks, > enihgil > > ################################### > > import Tkinter > import time > > class App(): > def __init__(self): > self.root = Tkinter.Tk() > self.label = Tkinter.Label(text="") > self.label.grid() > self.update_clock() > self.root.mainloop() > > def update_clock(self): > now = time.strftime("%H:%M:%S") > self.label.configure(text=now) > self.root.after(1000, self.update_clock) > > def createButton(self): > self.quitButton = Button( self, text='Quit', command=self.quit ) > self.quitButton.grid() > > app=App() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Jan 12 21:23:57 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 12 Jan 2011 21:23:57 +0100 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? In-Reply-To: <4D2E03E5.6020302@gmail.com> References: <4D2E03E5.6020302@gmail.com> Message-ID: <4D2E0DDD.3020703@free.fr> Hello, Inherit from Frame see below: from Tkinter import * class App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createLabel() self.createButton() def createLabel(self): self.label = Tkinter.Label(text="") self.label.grid() self.update_clock() def update_clock(self): now = time.strftime("%H:%M:%S") self.label.configure(text=now) self.after(1000, self.update_clock) def createButton(self): self.quitButton = Button( self, text='Quit', command=self.quit ) self.quitButton.grid() app = App() app.master.title("Clock Time!") app.mainloop() Regards Karim On 01/12/2011 08:41 PM, Enih Gilead wrote: > Hi, all ! > > I've being strugling a lot trying to insert (just as exemple) a > quit-Button in a Tkinter class App with no success... What I get is > the clock runing ok, but, the App simply ignores the quit-Button... Why? > > _*Remark*_: > I took this minimalist digital clock just to illustrate the "bad :-)" > class behavior, but it didn't work in any other Apps I tried. I > searched a lot (indeed!) in the net but I couldn't find the reason. > > Could any of you tell me, please, _*what's the problem?*_ > Thanks, > enihgil > > ################################### > > import Tkinter > import time > > class App(): > def __init__(self): > self.root = Tkinter.Tk() > self.label = Tkinter.Label(text="") > self.label.grid() > self.update_clock() > self.root.mainloop() > > def update_clock(self): > now = time.strftime("%H:%M:%S") > self.label.configure(text=now) > self.root.after(1000, self.update_clock) > > def createButton(self): > self.quitButton = Button( self, text='Quit', command=self.quit ) > self.quitButton.grid() > > app=App() > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Jan 12 21:34:47 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 12 Jan 2011 21:34:47 +0100 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? In-Reply-To: <4D2E0DB8.2040306@free.fr> References: <4D2E03E5.6020302@gmail.com> <4D2E0DB8.2040306@free.fr> Message-ID: <4D2E1067.9050103@free.fr> /_Sorry my mistake in createLabel() method:_/ self.label = Label(text="") instead of : self.label = *Tkinter*.Label(text="") On 01/12/2011 09:23 PM, Karim wrote: > > Hello, > > Inherit from Frame see below: > > from Tkinter import * > > class App(Frame): > def __init__(self, master=None): > Frame.__init__(self, master) > self.grid() > self.createLabel() > self.createButton() > > def createLabel(self): > self.label = Tkinter.Label(text="") > self.label.grid() > self.update_clock() > > def update_clock(self): > now = time.strftime("%H:%M:%S") > self.label.configure(text=now) > self.after(1000, self.update_clock) > > def createButton(self): > self.quitButton = Button( self, text='Quit', command=self.quit ) > self.quitButton.grid() > > app = App() > app.master.title("Clock Time!") > app.mainloop() > > Regards > Karim > > On 01/12/2011 08:41 PM, Enih Gilead wrote: >> Hi, all ! >> >> I've being strugling a lot trying to insert (just as exemple) a >> quit-Button in a Tkinter class App with no success... What I get is >> the clock runing ok, but, the App simply ignores the quit-Button... Why? >> >> _*Remark*_: >> I took this minimalist digital clock just to illustrate the "bad >> :-)" class behavior, but it didn't work in any other Apps I tried. I >> searched a lot (indeed!) in the net but I couldn't find the reason. >> >> Could any of you tell me, please, _*what's the problem?*_ >> Thanks, >> enihgil >> >> ################################### >> >> import Tkinter >> import time >> >> class App(): >> def __init__(self): >> self.root = Tkinter.Tk() >> self.label = Tkinter.Label(text="") >> self.label.grid() >> self.update_clock() >> self.root.mainloop() >> >> def update_clock(self): >> now = time.strftime("%H:%M:%S") >> self.label.configure(text=now) >> self.root.after(1000, self.update_clock) >> >> def createButton(self): >> self.quitButton = Button( self, text='Quit', command=self.quit ) >> self.quitButton.grid() >> >> app=App() >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From Frank.Yaniga at GDIT.com Wed Jan 12 15:02:37 2011 From: Frank.Yaniga at GDIT.com (Yaniga, Frank) Date: Wed, 12 Jan 2011 09:02:37 -0500 Subject: [Tutor] question regarding regular expression compile In-Reply-To: References: Message-ID: <560FB3D6798A37478F7446CA627933085A3E6AE4F7@EXCHCCR04.ad.local> I believe I had epiphany: test = re.compile('MAT file (billing|carrier|log|util)' r'\\' '\d{8} deleted') is this correct? _____________________________________________ From: Yaniga, Frank Sent: Wednesday, January 12, 2011 8:20 AM To: 'tutor at python.org'; 'help at python.org' Subject: question regarding regular expression compile I am determining a regular expression that can recognize the any of the following strings: MAT file log\20101225 deleted MAT file billing\20101225 deleted MAT file util\20101225 deleted MAT file carrier\20101225 deleted I begin by creating a regular expression object so that I can reuse it in multiple operations: test = re.compile('MAT file for log, billing, util, and carrier I use an arbitrary match: (log|billing|util|carrier) for 20101225 I use decimal digit with repetition match: \d{8} and finish with: delete') My question is how do I handle the backslash (NOTE: the match must only be a backslash)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From Wynn.Stinson at tinker.af.mil Wed Jan 12 17:55:32 2011 From: Wynn.Stinson at tinker.af.mil (Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED) Date: Wed, 12 Jan 2011 10:55:32 -0600 Subject: [Tutor] question Message-ID: <9EEFD038DD01ED4D8ADBFD0CD6C487B90777E104@VFOKMLAO13.Enterprise.afmc.ds.af.mil> Can someone give me some sample code to use to determine if a checkbox has been selected using Tkinter? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Thu Jan 13 00:43:10 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 13 Jan 2011 00:43:10 +0100 Subject: [Tutor] question In-Reply-To: <9EEFD038DD01ED4D8ADBFD0CD6C487B90777E104@VFOKMLAO13.Enterprise.afmc.ds.af.mil> References: <9EEFD038DD01ED4D8ADBFD0CD6C487B90777E104@VFOKMLAO13.Enterprise.afmc.ds.af.mil> Message-ID: <4D2E3C8E.2050209@free.fr> Hello, "You can even use a StringVar as the checkbutton's variable, and supply string values for the offvalue and onvalue. Here's an example: self.spamVar = StringVar() self.spamCB = Checkbutton ( self, text="Spam?", variable=self.spamVar, onvalue="yes", offvalue="no" ) If this checkbutton is on, self.spamVar.get() will return the string "yes"; if the checkbutton is off, that same call will return the string "no". Furthermore, your program can turn the checkbutton on by calling .set("yes")." Regards Karim On 01/12/2011 05:55 PM, Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED wrote: > > Can someone give me some sample code to use to determine if a checkbox > has been selected using Tkinter? thanks > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 13 01:12:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jan 2011 00:12:38 -0000 Subject: [Tutor] python hyperlinks question References: Message-ID: "Vikram K" wrote > Could you please tell me how to add hyperlinks to my output? The output is just text so all you need to do is find out how Excel populates hyperlinks in a CSV file... If that is actually possible. The easiest way will be to create an Excel file with hyperlinks, save as CSV and then open the CSV file and look at how Excel does it. Then write your python code to do the same. But it may be asking too much of CSV, you may need to create a native Excel file to do this. There are Python modules available that can do that, or you could (with some pain) use native COM. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rabidpoobear at gmail.com Thu Jan 13 01:06:37 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 12 Jan 2011 18:06:37 -0600 Subject: [Tutor] question regarding regular expression compile In-Reply-To: <560FB3D6798A37478F7446CA627933085A3E6AE4F7@EXCHCCR04.ad.local> References: <560FB3D6798A37478F7446CA627933085A3E6AE4F7@EXCHCCR04.ad.local> Message-ID: <3EC7BCE7-A90C-40F3-808D-9E8F6B460E70@gmail.com> No. Did you try that? It doesn't evn look like valid python code to me. You want a single string with the r before it, not 3 separate strings. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 12, 2011, at 8:02 AM, "Yaniga, Frank" wrote: > I believe I had epiphany: > > test = re.compile('MAT file (billing|carrier|log|util)' r'\\' '\d{8} deleted') > > is this correct? > > _____________________________________________ > From: Yaniga, Frank > Sent: Wednesday, January 12, 2011 8:20 AM > To: 'tutor at python.org'; 'help at python.org' > Subject: question regarding regular expression compile > > > I am determining a regular expression that can recognize the any of the following strings: > > MAT file log\20101225 deleted > MAT file billing\20101225 deleted > MAT file util\20101225 deleted > MAT file carrier\20101225 deleted > > I begin by creating a regular expression object so that I can reuse it in multiple operations: > > test = re.compile(?MAT file > > for log, billing, util, and carrier I use an arbitrary match: > > (log|billing|util|carrier) > > for 20101225 I use decimal digit with repetition match: > > \d{8} > > and finish with: > > delete?) > > > My question is how do I handle the backslash (NOTE: the match must only be a backslash)? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Thu Jan 13 01:56:31 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 12 Jan 2011 19:56:31 -0500 Subject: [Tutor] Sorting a List Message-ID: <4D2E4DBF.10409@aim.com> Hello Tutors, I am generating XML definitions for animations to be used in a FIFE-based game. I need to sort the frames of the animations, and I am currently using: sorted([image for image in os.listdir(path) if image.endswith('.png')]) The final output in the XML is: Having frame 10 and 11 between frame 1 and 2 is not desired behavior; how can I sort all of these with walk_10.png and company (this isn't the only animation like this) being after walk_9.png? A google search doesn't return anything I could use. I tried just using [image for image in os.listdir(path) if image.endswith('.png')], but that doesn't appear to have any order. Thanks, Corey Richardson From emile at fenx.com Thu Jan 13 02:41:19 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 12 Jan 2011 17:41:19 -0800 Subject: [Tutor] Sorting a List In-Reply-To: <4D2E4DBF.10409@aim.com> References: <4D2E4DBF.10409@aim.com> Message-ID: On 1/12/2011 4:56 PM Corey Richardson said... > Hello Tutors, > > I am generating XML definitions for animations to be used in a > FIFE-based game. I need to sort the frames of the animations, and I am > currently using: > sorted([image for image in os.listdir(path) if image.endswith('.png')]) I might use use glob in two steps: ( sorted([image for image in glob.glob('walk_?.png')]) + sorted([image for image in glob.glob('walk_??.png')]) ) Emile > > The final output in the XML is: > > > > > > > > > > > > > > > Having frame 10 and 11 between frame 1 and 2 is not desired behavior; > how can I sort all of these with walk_10.png and company (this isn't the > only animation like this) being after walk_9.png? A google search > doesn't return anything I could use. I tried just using > [image for image in os.listdir(path) if image.endswith('.png')], > but that doesn't appear to have any order. > > Thanks, > Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From bill at celestial.net Thu Jan 13 02:53:53 2011 From: bill at celestial.net (Bill Campbell) Date: Wed, 12 Jan 2011 17:53:53 -0800 Subject: [Tutor] Sorting a List In-Reply-To: <4D2E4DBF.10409@aim.com> References: <4D2E4DBF.10409@aim.com> Message-ID: <20110113015353.GA27886@ayn.mi.celestial.com> On Wed, Jan 12, 2011, Corey Richardson wrote: >Hello Tutors, > >I am generating XML definitions for animations to be used in a >FIFE-based game. I need to sort the frames of the animations, and I am >currently using: >sorted([image for image in os.listdir(path) if image.endswith('.png')]) > >The final output in the XML is: > > > > > > > > > > > > > > >Having frame 10 and 11 between frame 1 and 2 is not desired behavior; >how can I sort all of these with walk_10.png and company (this isn't the >only animation like this) being after walk_9.png? A google search >doesn't return anything I could use. I tried just using >[image for image in os.listdir(path) if image.endswith('.png')], >but that doesn't appear to have any order. This is discussed in the Python Cookbook from O'Reilly. If I remember correctly, it deals exactly with the problem of sorting file names containing numbers as you have above. Here's a bit of code I use in a module I wrote for dealing with RPM versions. import re _digits = re.compile(r'(\d+)') def ver(s): r = _digits.split(s) r[1::2] = map(lambda x: int(x), r[1::2]) return(tuple(r)) class FileInfo(object): def __init__(self, fname) self.fname = fname self.cmp = ver(fname) def __cmp__(self, othr): return cmp(self.cmp, othr.cmp) Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Skype: jwccsllc (206) 855-5792 Government is the great fiction, through which everbody endeavors to live at the expense of everybody else. -- Frederic Bastiat From wallenpb at gmail.com Thu Jan 13 03:17:51 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 12 Jan 2011 20:17:51 -0600 Subject: [Tutor] Sorting a List In-Reply-To: References: <4D2E4DBF.10409@aim.com> Message-ID: Corey, I have a bit of code that use in a CGI that sorts some picture files, perhaps something like this will work for you. The file sorting bit: dir_list = os.listdir("/localhost/html/pics") dir_list.sort() #sorts the list of filenames in place Just in case there is something else useful in the routine I am using, here is the total code. It not produces a sorted list of the file names, it keeps the amount of files in the directory from growing out of control in my particular Python CGI app. In this case, I keep only the 5 most recent files. The code does not have to look at the file timestamps to do this because I am using the epoch time at time of the file's creation as the file's name i.e. from time import time; new_filename = str(int(time())) . file_list = "" count = 0 dir_list = os.listdir("/localhost/html/pics") dir_list.sort() for file in dir_list: count = count + 1 if count < 5: pass else: basename = os.path.basename(file) if basename.endswith('.png'): file_list = file_list + basename+'\n' os.remove("/localhost/html/pics/"+dir_list[0]) --Bill Allen On Wed, Jan 12, 2011 at 6:56 PM, Corey Richardson wrote: > Hello Tutors, > > I am generating XML definitions for animations to be used in a > FIFE-based game. I need to sort the frames of the animations, and I am > currently using: > sorted([image for image in os.listdir(path) if image.endswith('.png')]) > > The final output in the XML is: > > > > > > > > > > > > > > > Having frame 10 and 11 between frame 1 and 2 is not desired behavior; > how can I sort all of these with walk_10.png and company (this isn't the > only animation like this) being after walk_9.png? A google search > doesn't return anything I could use. I tried just using > [image for image in os.listdir(path) if image.endswith('.png')], > but that doesn't appear to have any order. > > Thanks, > Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Thu Jan 13 03:29:10 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 12 Jan 2011 21:29:10 -0500 Subject: [Tutor] Command line scripts In-Reply-To: <198450.15065.qm@web86701.mail.ird.yahoo.com> References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: On Sun, Jan 9, 2011 at 9:03 AM, ALAN GAULD wrote: > > >> The following line is what I mean by calling a ?command line from within the >>app >> using subprocess. >> >> self.espeak = ?subprocess.Popen(['espeak', word],stdout ?= >> subprocess.PIPE).communicate()[0] > > OK, Now I understand. > You want to call an external application from within your code > via subprocess. And you want to know if that will work ok in a > wxPython application? > >> >> In other words, ?is a command line app different from >> >> bindings in a compiled ?app? > > When you call an app using subprocess it spawns an entirely > separate process in the OS. There is no linkage to your process > apart from the redirection of stdin/stdout/stderr back to your > app instead of to a console. > >> > So-called exe generators simply bundle the interpreter ?witrh >> > the code and auto run it. >> >> So it's basically just installing ?a sandbox version of python? > > Sort of, its a minimalist version of python with only the modules > needed to run the app. And you can't run the interpreter on its > own you can only run the packaged app. > >> Which ultimately is, if I have a standalone ?application, that doesn't >> come from a command line terminal launching(which I ?haven't gotten to >> yet), is using the command line calls going through ?subprocess going >> to be called without the terminal, or will it open a ?terminal >> automatically to make those calls? > > The app (eSpeak in your example) will see your app as its "console". > That is, it will send all output to your app and read all input from your > app I was thinking that since the app is called from the command line with python(which is no different, than using any other command line script-just like espeak 'word' -> python script.py), it would be go back to the shell window it was spawned/called from through python and utilize the command line there. Similar to how when I run the app, my data can be through the app text/label fields, or, through the terminal window itself. (so you need to make sure it gets any input it is expecting!) > The other thing to watch in a wxPython (or any other GUI framework) > is that if the app runs for a long time your app may "freeze" from > the user's perspective, so you may want to run it in the background > or as a separate thread in your app. > >> Or will all of my python ?apps need to have a command line terminal >> open to launch them. > > No, your app takes over the job of the terminal. When you launch > a program from the terninal the terminal app(for it is just an app like > any other) is doing the same as you, it is spawning a subprocess > that sends its output back to the teminal for it to display. > > In fact you might find it a useful exercise to build a very basic terminal > app in wxPython first. Read commands from a command input field > and display the output in a text widget... Execute the commands > via subprocess. Its a good way to get used to using subprocess > and experimenting with its various options. If you are very keen > you can start adding command history and search etc to it too... > I'll eventually get to the above(I have a lot of projects, some will involve command line/subprocess:), but thanks for the explanation. I'm guessing that something like cxfreezeI haven't looked it over thoroughly) might be what I was looking for. Although in the end, it's just for other to see your work, because most of my own apps are for me personally, which might be a good thing. From rabidpoobear at gmail.com Thu Jan 13 03:42:56 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 12 Jan 2011 20:42:56 -0600 Subject: [Tutor] Sorting a List In-Reply-To: References: <4D2E4DBF.10409@aim.com> Message-ID: <6D563191-D5D0-4E5F-A7E3-D84788DDE8FC@gmail.com> Remember the sorted() method takes a key function, have this key function take in each filename and compare the numbers and you're all set! ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 12, 2011, at 8:17 PM, Bill Allen wrote: > > Corey, > > I have a bit of code that use in a CGI that sorts some picture files, perhaps something like this will work for you. > > The file sorting bit: > dir_list = os.listdir("/localhost/html/pics") > dir_list.sort() #sorts the list of filenames in place > > Just in case there is something else useful in the routine I am using, here is the total code. It not produces a sorted list of the file names, it keeps the amount of files in the directory from growing out of control in my particular Python CGI app. In this case, I keep only the 5 most recent files. The code does not have to look at the file timestamps to do this because I am using the epoch time at time of the file's creation as the file's name i.e. from time import time; new_filename = str(int(time())) . > > file_list = "" > count = 0 > dir_list = os.listdir("/localhost/html/pics") > dir_list.sort() > for file in dir_list: > count = count + 1 > if count < 5: > pass > else: > basename = os.path.basename(file) > if basename.endswith('.png'): > file_list = file_list + basename+'\n' > os.remove("/localhost/html/pics/"+dir_list[0]) > > --Bill Allen > > > > On Wed, Jan 12, 2011 at 6:56 PM, Corey Richardson wrote: > Hello Tutors, > > I am generating XML definitions for animations to be used in a > FIFE-based game. I need to sort the frames of the animations, and I am > currently using: > sorted([image for image in os.listdir(path) if image.endswith('.png')]) > > The final output in the XML is: > > > > > > > > > > > > > > > Having frame 10 and 11 between frame 1 and 2 is not desired behavior; > how can I sort all of these with walk_10.png and company (this isn't the > only animation like this) being after walk_9.png? A google search > doesn't return anything I could use. I tried just using > [image for image in os.listdir(path) if image.endswith('.png')], > but that doesn't appear to have any order. > > Thanks, > Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at pythontoo.com Thu Jan 13 04:23:40 2011 From: david at pythontoo.com (David Abbott) Date: Wed, 12 Jan 2011 22:23:40 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: On Wed, Jan 12, 2011 at 9:29 PM, David Hutto wrote: > On Sun, Jan 9, 2011 at 9:03 AM, ALAN GAULD wrote: >> >> >>> The following line is what I mean by calling a ?command line from within the >>>app >>> using subprocess. >>> >>> self.espeak = ?subprocess.Popen(['espeak', word],stdout ?= >>> subprocess.PIPE).communicate()[0] >> I came up with this as an example, I am still learning also :) [code] #!/usr/bin/python # wx python + espeak from subprocess import call import sys import wx class ESpeak(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(360, 370)) panel = wx.Panel(self, -1) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) st1 = wx.StaticText(panel, -1, 'Enter Saying: ') self.tc1 = wx.TextCtrl(panel, -1, size=(180, -1)) button_send = wx.Button(panel, 1, 'Say') hbox1.Add(st1, 0, wx.LEFT, 10) hbox1.Add(self.tc1, 0, wx.LEFT, 10) vbox.Add(hbox1, 0, wx.TOP, 50) vbox.Add(button_send, 0, wx.ALIGN_CENTER | wx.TOP | wx.TOP | wx.BOTTOM, 100) self.Bind(wx.EVT_BUTTON, self.OnSpeak, id=1) panel.SetSizer(vbox) self.Centre() self.ShowModal() self.Destroy() def OnSpeak(self, event): say = self.tc1.GetValue() if say != "": espeak = "/usr/bin/espeak" call([espeak, say]) else: dlg = wx.MessageDialog(self, 'What did you say?', 'Error', wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() app = wx.App() ESpeak(None, -1, 'wxESpeak') app.MainLoop() [/code] -david From smokefloat at gmail.com Thu Jan 13 04:35:47 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 12 Jan 2011 22:35:47 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: I think it works great as an easy integration for the blind(although I'm sure there is already a python module for that somewhere), as long as they have espeak(or it can be easily adapted), but also if you just like the ai feel of a voice in your apps. From smokefloat at gmail.com Thu Jan 13 04:48:52 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 12 Jan 2011 22:48:52 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: Although, I'd just go with a function that gets passed the text, that way it was reusable, like the one I gave. From smokefloat at gmail.com Thu Jan 13 04:51:01 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 12 Jan 2011 22:51:01 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: Although, you did just that, didn't pay attention to the whole thing. From kb1pkl at aim.com Thu Jan 13 05:07:02 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 12 Jan 2011 23:07:02 -0500 Subject: [Tutor] Sorting a List In-Reply-To: <6D563191-D5D0-4E5F-A7E3-D84788DDE8FC@gmail.com> References: <4D2E4DBF.10409@aim.com> <6D563191-D5D0-4E5F-A7E3-D84788DDE8FC@gmail.com> Message-ID: <4D2E7A66.6060807@aim.com> On 01/12/2011 09:42 PM, Luke Paireepinart wrote: > Remember the sorted() method takes a key function, have this key > function take in each filename and compare the numbers and you're all set! > > ----------------------------- > Sent from a mobile device. Apologies for brevity and top-posting. > ----------------------------- > > [snip] Thanks everyone - I didn't get anything out of glob, but playing with key and using a function that parsed the frame number out worked. Thanks again, ~Corey From __peter__ at web.de Thu Jan 13 08:55:13 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Jan 2011 08:55:13 +0100 Subject: [Tutor] Sorting a List References: <4D2E4DBF.10409@aim.com> <20110113015353.GA27886@ayn.mi.celestial.com> Message-ID: Bill Campbell wrote: > On Wed, Jan 12, 2011, Corey Richardson wrote: >>Hello Tutors, >> >>I am generating XML definitions for animations to be used in a >>FIFE-based game. I need to sort the frames of the animations, and I am >>currently using: >>sorted([image for image in os.listdir(path) if image.endswith('.png')]) >> >>The final output in the XML is: >> >> >> >> >> >> >> >> >> >> >> >> >> >> >>Having frame 10 and 11 between frame 1 and 2 is not desired behavior; >>how can I sort all of these with walk_10.png and company (this isn't the >>only animation like this) being after walk_9.png? A google search >>doesn't return anything I could use. I tried just using >>[image for image in os.listdir(path) if image.endswith('.png')], >>but that doesn't appear to have any order. > > This is discussed in the Python Cookbook from O'Reilly. If I > remember correctly, it deals exactly with the problem of sorting > file names containing numbers as you have above. > > Here's a bit of code I use in a module I wrote for dealing with > RPM versions. > > import re > _digits = re.compile(r'(\d+)') > > def ver(s): > r = _digits.split(s) > r[1::2] = map(lambda x: int(x), r[1::2]) > return(tuple(r)) Instead of map(lambda x: int(x), ...) just use map(int, ...) > class FileInfo(object): > def __init__(self, fname) > self.fname = fname > self.cmp = ver(fname) > > def __cmp__(self, othr): > return cmp(self.cmp, othr.cmp) You don't need the FileInfo object, you can make ver() the key argument to list.sort() or sorted(): sorted(filenames, key=ver) Peter From __peter__ at web.de Thu Jan 13 09:30:14 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Jan 2011 09:30:14 +0100 Subject: [Tutor] Determinw Tkinter checkbox state, was Re: question References: <9EEFD038DD01ED4D8ADBFD0CD6C487B90777E104@VFOKMLAO13.Enterprise.afmc.ds.af.mil> Message-ID: Stinson, Wynn A Civ USAF AFMC 556 SMXS/MXDED wrote: [In the future please take the time to choose a meaningful subject] > Can someone give me some sample code to use to determine if a checkbox > has been selected using Tkinter? thanks Method 1: check the state of the underlying variable: import Tkinter as tk root = tk.Tk() var = tk.IntVar() cb = tk.Checkbutton(root, text="the lights are on", variable=var) cb.pack() def showstate(): if var.get(): print "the lights are on" else: print "the lights are off" button = tk.Button(root, text="show state", command=showstate) button.pack() root.mainloop() Method 2: trigger a function when the underlying variable changes import Tkinter as tk root = tk.Tk() var = tk.IntVar() cb = tk.Checkbutton(root, text="the lights are on", variable=var) cb.pack() def showstate(*args): if var.get(): print "the lights are on" else: print "the lights are off" var.trace_variable("w", showstate) root.mainloop() From bouncingcats at gmail.com Thu Jan 13 10:50:51 2011 From: bouncingcats at gmail.com (David) Date: Thu, 13 Jan 2011 20:50:51 +1100 Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) In-Reply-To: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> References: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> Message-ID: On 5 January 2011 08:50, Patty wrote: > Hi David - I was looking for the book you recomended below - "Python 3 > Object Oriented Programming" by Dusty Phillips - and found it on Amazon for > $43 new on up and $70 for used but maybe that was hardback? ?Do you happen > to know of some other way to obtain it for less than $45? Hi Patty I obtained my paperback copy from the publisher's website www.packtpub.com It is also available there as an e-book. Also I notice there is a free sample chapter there which will give an idea of its content. Regards David From steve at pearwood.info Thu Jan 13 12:31:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 13 Jan 2011 22:31:08 +1100 Subject: [Tutor] question regarding regular expression compile In-Reply-To: <3EC7BCE7-A90C-40F3-808D-9E8F6B460E70@gmail.com> References: <560FB3D6798A37478F7446CA627933085A3E6AE4F7@EXCHCCR04.ad.local> <3EC7BCE7-A90C-40F3-808D-9E8F6B460E70@gmail.com> Message-ID: <4D2EE27C.2020409@pearwood.info> Luke Paireepinart wrote: > No. Did you try that? It doesn't evn look like valid python code to me. > You want a single string with the r before it, not 3 separate strings. The line of code in question is: >> test = re.compile('MAT file (billing|carrier|log|util)' r'\\' '\d{8} deleted') If you actually try it, it is perfectly valid Python code :) However, I agree with Luke: this would be better written as a single string: 'MAT file (billing|carrier|log|util)\\\\\d{8} deleted' or even better, a raw string r'MAT file (billing|carrier|log|util)\\\d{8} deleted' Little know Python fact: Python includes implicit concatenation of string literals. If you have two or more string literals (but not variables) written next to each other, Python will automatically concatenate them at compile time. You can mix quotation marks and raw and ordinary strings as needed: >>> print "Hello" 'world' Helloworld Here's a more useful example: if condition: raise ValueError("this is a very long" " error message with much useful detail," " far too much to fit on a single line of" " source code.") which is equivalent to this: if condition: s = "this is a very long" s += " error message with much useful detail," s += " far too much to fit on a single line of" s += " source code." raise ValueError(s) except the string is constructed once, at compile time, and no variable s is created. -- Steven From swiftone at swiftone.org Thu Jan 13 13:24:30 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Thu, 13 Jan 2011 07:24:30 -0500 Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) In-Reply-To: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> References: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> Message-ID: On Tue, Jan 4, 2011 at 4:50 PM, Patty wrote: > Hi David - I was looking for the book you recomended below - "Python 3 > Object Oriented Programming" by Dusty Phillips - and found it on Amazon for > $43 new on up and $70 for used but maybe that was hardback? ?Do you happen > to know of some other way to obtain it for less than $45? Half.com is always my stop of choice for programming books. I see a copy there for $16. -- Brett Ritter / SwiftOne swiftone at swiftone.org From ingoogni at gmail.com Thu Jan 13 13:33:39 2011 From: ingoogni at gmail.com (ingo) Date: Thu, 13 Jan 2011 13:33:39 +0100 Subject: [Tutor] turn a path into nested list Message-ID: Dear all, a probably simple problem I can't get my head around at the moment (old age?), some input would be appreciated. I have a path >>> path = 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj' I'd like to turn taht into a list with a certain structure and order: [['Audio', 'Audio'], ['site-packages', ''Audio/site-packages'], ['pygame', 'Audio/site-packages/pygame'], ['examples', 'Audio/site-packages/pygame/examples'], ['macosx', ''Audio/site-packages/pygame/examples/macosx'], . . ] How to approach this? TIA, ingo From cwitts at compuscan.co.za Thu Jan 13 13:51:00 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Thu, 13 Jan 2011 14:51:00 +0200 Subject: [Tutor] turn a path into nested list In-Reply-To: References: Message-ID: <4D2EF534.7060209@compuscan.co.za> On 13/01/2011 14:33, ingo wrote: > Dear all, > > a probably simple problem I can't get my head around at the moment > (old age?), some input would be appreciated. > > I have a path > > >>>> path = 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj' >>>> > I'd like to turn taht into a list with a certain structure and order: > > [['Audio', 'Audio'], > ['site-packages', ''Audio/site-packages'], > ['pygame', 'Audio/site-packages/pygame'], > ['examples', 'Audio/site-packages/pygame/examples'], > ['macosx', ''Audio/site-packages/pygame/examples/macosx'], > . > . > ] > > How to approach this? > > TIA, > > ingo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > First split your path into segments, then iterate over those segments and build your new list (item one being the current segment, and part two a joined string of previous segments). -- Kind Regards, Christian Witts From ingoogni at gmail.com Thu Jan 13 14:19:35 2011 From: ingoogni at gmail.com (ingo) Date: Thu, 13 Jan 2011 14:19:35 +0100 Subject: [Tutor] turn a path into nested list In-Reply-To: <4D2EF534.7060209@compuscan.co.za> References: <4D2EF534.7060209@compuscan.co.za> Message-ID: On Thu, Jan 13, 2011 at 1:51 PM, Christian Witts wrote: > First split your path into segments, then iterate over those segments and > build your new list (item one being the current segment, and part two a > joined string of previous segments). > thanks Christian, path = 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj' path=urllib.url2pathname(path) print '\n',path pathlist=[] dir='' for item in path.split("\\"): dir=os.path.join(dir,item) a=[item,dir] pathlist.append(a) print pathlist From smokefloat at gmail.com Thu Jan 13 14:41:30 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 13 Jan 2011 08:41:30 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: As you can tell, I was excited, and impressed by my own work, and therefore thought you should follow my wise and almighty work. From smokefloat at gmail.com Thu Jan 13 16:11:00 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 13 Jan 2011 10:11:00 -0500 Subject: [Tutor] Command line scripts In-Reply-To: References: <198450.15065.qm@web86701.mail.ird.yahoo.com> Message-ID: On Thu, Jan 13, 2011 at 8:41 AM, David Hutto wrote: > As you can tell, I was excited, and impressed by my own work, and > therefore thought you should follow my wise and almighty work. On the flip side, it's like being an electrician, and seeing the lights come on when you hook the box up. From egilead at gmail.com Thu Jan 13 18:24:41 2011 From: egilead at gmail.com (Enih Gilead) Date: Thu, 13 Jan 2011 15:24:41 -0200 Subject: [Tutor] How to insert a quit-Button in a Tkinter class? In-Reply-To: <4D2E0DB8.2040306@free.fr> References: <4D2E03E5.6020302@gmail.com> <4D2E0DB8.2040306@free.fr> Message-ID: <4D2F3559.9040004@gmail.com> Hi All ! Thanks a lot for the great help. As a beginner, I was forgetting to see the "Inheritance from Frame", but now it's all runing ok. Thankfull, enihgil On 01/12/2011 06:23 PM, Karim wrote: > > Hello, > > Inherit from Frame see below: > > from Tkinter import * > > class App(Frame): > def __init__(self, master=None): > Frame.__init__(self, master) > self.grid() > self.createLabel() > self.createButton() > > def createLabel(self): > self.label = Tkinter.Label(text="") > self.label.grid() > self.update_clock() > > def update_clock(self): > now = time.strftime("%H:%M:%S") > self.label.configure(text=now) > self.after(1000, self.update_clock) > > def createButton(self): > self.quitButton = Button( self, text='Quit', command=self.quit ) > self.quitButton.grid() > > app = App() > app.master.title("Clock Time!") > app.mainloop() > > Regards > Karim > > On 01/12/2011 08:41 PM, Enih Gilead wrote: >> Hi, all ! >> >> I've being strugling a lot trying to insert (just as exemple) a >> quit-Button in a Tkinter class App with no success... What I get is >> the clock runing ok, but, the App simply ignores the quit-Button... Why? >> >> _*Remark*_: >> I took this minimalist digital clock just to illustrate the "bad >> :-)" class behavior, but it didn't work in any other Apps I tried. I >> searched a lot (indeed!) in the net but I couldn't find the reason. >> >> Could any of you tell me, please, _*what's the problem?*_ >> Thanks, >> enihgil >> >> ################################### >> >> import Tkinter >> import time >> >> class App(): >> def __init__(self): >> self.root = Tkinter.Tk() >> self.label = Tkinter.Label(text="") >> self.label.grid() >> self.update_clock() >> self.root.mainloop() >> >> def update_clock(self): >> now = time.strftime("%H:%M:%S") >> self.label.configure(text=now) >> self.root.after(1000, self.update_clock) >> >> def createButton(self): >> self.quitButton = Button( self, text='Quit', command=self.quit ) >> self.quitButton.grid() >> >> app=App() >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 13 18:30:25 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jan 2011 17:30:25 -0000 Subject: [Tutor] turn a path into nested list References: Message-ID: "ingo" wrote > I have a path > >>>> path = >>>> 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj' > > I'd like to turn taht into a list with a certain structure and > order: Its not clear what exactly the sort criteria is, however have you looked at the os.walk() function for traversing directory trees? It may be all you need. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokefloat at gmail.com Thu Jan 13 18:36:43 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 13 Jan 2011 12:36:43 -0500 Subject: [Tutor] turn a path into nested list In-Reply-To: References: Message-ID: > Its not clear what exactly the sort criteria is, however have you looked > at the os.walk() function for traversing directory trees? It may be all > you need. it's amazing what the designers of the builtins left for your disposal. From smokefloat at gmail.com Thu Jan 13 18:37:22 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 13 Jan 2011 12:37:22 -0500 Subject: [Tutor] turn a path into nested list In-Reply-To: References: Message-ID: It's like the were psychic...or intuitive . From wynnstinson at rocketmail.com Thu Jan 13 19:02:33 2011 From: wynnstinson at rocketmail.com (W S) Date: Thu, 13 Jan 2011 10:02:33 -0800 (PST) Subject: [Tutor] creating a text widget Message-ID: <488609.54184.qm@web120905.mail.ne1.yahoo.com> could someone please provide me some code that would create a text widget that i could open a text file in? much thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Jan 13 19:08:20 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 13 Jan 2011 12:08:20 -0600 Subject: [Tutor] creating a text widget In-Reply-To: <488609.54184.qm@web120905.mail.ne1.yahoo.com> References: <488609.54184.qm@web120905.mail.ne1.yahoo.com> Message-ID: On Thu, Jan 13, 2011 at 12:02 PM, W S wrote: > could someone please provide me some code that would create a text widget > that i could open a text file in? much thanks > Dear Google: Please insert all the results of "simple python GUI text editor" into my brain. Learning is so tiresome! Sincerely, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rfquerin at gmail.com Thu Jan 13 19:10:42 2011 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 13 Jan 2011 13:10:42 -0500 Subject: [Tutor] How to find a substring within a list of items Message-ID: I have an object that contains about 3500 list items, each list containing various data, some strings and some floats, like so: ['D', 123.4,'This is a project description', 'type', 52.1,'title'] What is the easiest way to search this list for a given string? So I want to find out if this list contains the string 'scrip' anywhere within it (case insensitive and including being just part of a larger string). Incidentally, I'm using the xlrd module to read in a spreadsheet. I effectively want to quickly pull out a list of lines from that spreadsheet that contain that substring anywhere within them. Maybe there is a better/faster way I should be doing this? I'm trying to give employees here a better/faster way of filtering through the company project list rather than opening up excel and doing a find search each time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Jan 13 20:27:17 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 13 Jan 2011 13:27:17 -0600 Subject: [Tutor] How to find a substring within a list of items In-Reply-To: References: Message-ID: On Thu, Jan 13, 2011 at 12:10 PM, Richard Querin wrote: > I have an object that contains about 3500 list items, each list containing > various data, some strings and some floats, like so: > > ['D', 123.4,'This is a project description', 'type', 52.1,'title'] > > What is the easiest way to search this list for a given string? So I want > to find out if this list contains the string 'scrip' anywhere within it > (case insensitive and including being just part of a larger string). > > Incidentally, I'm using the xlrd module to read in a spreadsheet. I > effectively want to quickly pull out a list of lines from that spreadsheet > that contain that substring anywhere within them. Maybe there is a > better/faster way I should be doing this? > > I'm trying to give employees here a better/faster way of filtering through > the company project list rather than opening up excel and doing a find > search each time. > Well, the easiest (maybe not fastest) way would be something like: rows_found = [] for row in rows: for element in row: try: if 'scrip' in element: rows_found.append(row) break # Once we find an element, no need to check others except TypeError: pass #can't iterate over int's & such That should give you the correct results. Alternatively, if you have something against try/except you could do for row in rows if 'scrip' in str(row): #str(row) turns the list into the same thing you get when you print(row) rows_found.append(row) I'm not sure which one is faster, though I presume the first one would be. I don't know if either of these are the best options (they probably aren't), but they should work, and for 3500 it will probably loop faster than opening up excel. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 13 20:35:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jan 2011 19:35:08 -0000 Subject: [Tutor] creating a text widget References: <488609.54184.qm@web120905.mail.ne1.yahoo.com> Message-ID: "W S" wrote > could someone please provide me some code that would > create a text widget that i could open a text file in? You don;t open the text file in the widget as such, you open the file in Python as usual and copy its contents into the text widget. When you are done making changes (if you are making changes) then you have to copy the content back out to the file (or rename the original to .bak and create a new version) So the question is which part do you not understand? - Creating a text widget - opening the file - copying the file to the widget - copying changes to the file HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ingoogni at gmail.com Thu Jan 13 20:36:59 2011 From: ingoogni at gmail.com (ingo) Date: Thu, 13 Jan 2011 20:36:59 +0100 Subject: [Tutor] turn a path into nested list In-Reply-To: References: Message-ID: On Thu, Jan 13, 2011 at 6:30 PM, Alan Gauld wrote: > Its not clear what exactly the sort criteria is, sorry Alan, I meant that I want to keep the order as is. > however have you looked > at the os.walk() function for traversing directory trees? It may be all > you need. Yes, but I'm not confident with it (the more reason to use it you will say :) ). Below the script I'm working on, rather unstable still. It will be put to work in Cherrypy so I browse through my media directories and send playlists to my media player(s). Very preliminary still. ingo --- %< --- %< --- import os, string, urllib topdirs={ 'Audio': 'c:', 'Video': 'd:', 'Photo': 'e:' } path = 'c:\\Python27' path = os.path.abspath(path) print path topdir = 'Audio' def mkPATH(path, topdirs=topdirs): path=urllib.url2pathname(path) path=string.split(path,'\\',1) return os.path.join(topdirs[path[0]],path[1]) def mkURL(dir): return urllib.pathname2url(dir) def mk_alias(dir, old=topdirs[topdir], new=topdir): return string.replace(dir,old,new) def mk_aliasURL(dir): return mkURL(mk_alias(dir)) def mk_pathlist(path): pathlist=[] dir='' for item in path.split("\\"): dir=os.path.join(dir,item) dir=mkURL(dir) a=[item,dir] pathlist.append(a) return pathlist aliaspath = mk_alias(path) directories = mk_pathlist(aliaspath) files = [] content = os.listdir(path) content.sort() for item in content: fullpath = os.path.join(path, item) if os.path.isdir(fullpath): directories.append([item, mk_aliasURL(fullpath)]) else: files.append([item, mk_aliasURL(fullpath)]) print '\n Path \n', path print '\n AliasPath \n', aliaspath print '\n Dirs \n', directories print '\n Files \n', files From alan.gauld at btinternet.com Thu Jan 13 20:42:15 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Jan 2011 19:42:15 -0000 Subject: [Tutor] How to find a substring within a list of items References: Message-ID: "Richard Querin" wrote >I have an object that contains about 3500 list items, each list >containing > various data, some strings and some floats, like so: > > ['D', 123.4,'This is a project description', 'type', 52.1,'title'] > What is the easiest way to search this list for a given string? Is the format constant? In other words are items 2 and 5 always numbers and therefore can be ignored? If so it might be something as simple as: result = [] for item in data: for index in [0,2,3,5]: if 'scrip' in item[index].lower(): result.append( item) break And you can optimise that as much as you like... :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rfquerin at gmail.com Thu Jan 13 21:23:59 2011 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 13 Jan 2011 15:23:59 -0500 Subject: [Tutor] How to find a substring within a list of items In-Reply-To: References: Message-ID: On Thu, Jan 13, 2011 at 2:27 PM, Wayne Werner wrote: > > I don't know if either of these are the best options (they probably > aren't), but they should work, and for 3500 it will probably loop faster > than opening up excel. > > HTH, > Wayne > Thanks Wayne. This would definitely be faster than getting Excel opened and doing it there. Given Alan's great suggestion in only stepping through string fields (this *does* have constant object formats) things should be even quicker. Now to give them a nice simple GUI to do it in. :) Thinking about wxPython (what I'm most used to), though it's been a while. Not sure if there are better options for something simple like this. Great help guys. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From lmhosie at jacks.sdstate.edu Thu Jan 13 21:59:11 2011 From: lmhosie at jacks.sdstate.edu (lmhosie at jacks.sdstate.edu) Date: Thu, 13 Jan 2011 20:59:11 +0000 Subject: [Tutor] (no subject) Message-ID: Hello All, I am having an issue with lists and am not sure where to go from here any advice appreciated. I colored the areas of concern. blue my comments purple example of output red area area concerned theoretically written not tested Sorry if its messy still a newbie. Thanks in advance! Lynn # Import native arcgisscripting module import arcgisscripting, sys, string, os, math # Create the geoprocessor object gp = arcgisscripting.create(9.3) gp.overwriteoutput = 1 # Check out any necessary licenses gp.CheckOutExtension("spatial") # Load required toolboxes... gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx") gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx") gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx") gp.workspace = "D:\model" # Table and field name inputs inTable = "D:\model\Files.mdb\Last" inPath="D:\model\Path.lyr" inField = "PATH" PRField = "PR" # Variables ECOAG = "D:\\model\\Files.mdb\\ECOAG" # Eco Ag combined with con statment t= string.Template("D:\\model\\Files.mdb\\T$Num") p = string.Template('"PATH" = $Path') prow = string.Template('"PR" = $PRow') wrs_season_shp="D:\model_workspace\wrs_season.shp" wrs_season_Layer="wrs_season_Layer" Files_mdb = "D:\\model\\Files.mdb" paths = gp.SearchCursor(inTable) path = paths.Next() # Create an empty list PathList = [] while path: # If the value is not already in the list, append it if path.GetValue(inField) not in PathList: PathList.append(path.GetValue(inField)) path = paths.Next() # Sort the list alphanumerically PathList.sort() print PathList[0] print PathList logfile=open('listfile.txt', 'w') logfile.write (str(PathList)) logfile.write('goodbye') This is the area that I am having complications with I am getting the correct output at the end of print PRList however because of the loop it overwrites the list each time. Ultimately I need to get a PR list of evens and odds but when I put the EVEN Odd Check in the loop it will only calculate the first even number then give an error. Traceback (most recent call last): File "C:\Users\lwood\Desktop\MODEL SCRIPTS\E\oddeven.py", line 65, in if PR.GetValue(PRField) not in PRList: AttributeError: 'int' object has no attribute 'GetValue' There are 233 paths and within each a different number of rows. I need a list to make a feature layer of just odds and of evens per each path. It works fine when it is out of the loop but only gives me the last path list. I realize that this it is looping over the list each time and that is why the output is for the last path only. I would just like it all in one loop is possible but not necessary. I'm not sure but what I have thought may work is writing the list to a file and appending it each time then reopenning it for the calculations but that seems a little much. Perhaps a Mapping technique or dictionary? Or like I mentioned before it would be fine to do it all in one loop as well. for path in PathList: gp.MakeFeatureLayer_management(wrs_season_shp, wrs_season_Layer,p.substitute(Path = str(path)), Files_mdb,) print path gp.savetolayerfile("wrs_season_Layer", "Path.1yr") PRS = gp.SearchCursor(inPath) PR = PRS.Next() PRList = [path] while PR: # If the value is not already in the list, append it if PR.GetValue(PRField) not in PRList: PRList.append(PR.GetValue(PRField)) PR = PRS.Next() # Sort the list alphanumerically PRList.sort() print PRList This is part of the output each path is listed first then each row within it and if I call PRList[5] is works fine as well 233008 it begins with [1,1001,1002] etc until this is the last output [233, 233005, 233006, 233007, 233008, 233009, 233010, 233011, 233012, 233013, 233014, 233015, 233016, 233017, 233018, 233050, 233051, 233052, 233053, 233054, 233055, 233056, 233057, 233058, 233059, 233060, 233061, 233062, 233063, 233064, 233065, 233066, 233067, 233068, 233069, 233070, 233071, 233072, 233073, 233074, 233075, 233076, 233077, 233078, 233079, 233080, 233081, 233082, 233083, 233084, 233085, 233086, 233087, 233088, 233089, 233090, 233091, 233092, 233093, 233094, 233095] #Even Odd Check for PR in PRList: if PR%2==0: print "Evens" print PR if PR%2>0: print "Odds" print PR Odds 233 Odds 233005 Evens 233006 Odds 233007 Evens etc What I need the list for is here to enter each even or odd PR as a string for a SQL selection such as this I have not written yet but I figure it would work something like this...... for path in PathList: for PR in PRList[path]: if PR%2==0: print "Evens" ##for calculation ## gp.MakeFeatureLayer_management(wrs_season_shp, inPath, prow.substitute(PRow = str(PR[1]or PRow = str(PR[2] etc....) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jan 13 22:15:42 2011 From: wescpy at gmail.com (wesley chun) Date: Thu, 13 Jan 2011 13:15:42 -0800 Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) In-Reply-To: References: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> Message-ID: >> Object Oriented Programming" by Dusty Phillips - and found it on Amazon for >> $43 new on up and $70 for used but maybe that was hardback? ?Do you happen >> to know of some other way to obtain it for less than $45? the retail price of the book is $49.99, and Packt books are usually POD (print on-demand), and they don't discount them very much because... they're not mass-produced. > I obtained my paperback copy from the publisher's website > www.packtpub.com It is also available there as an e-book. Also I > notice there is a free sample chapter there which will give an idea of > its content. the free material is chapter 7 of the book, called "object-oriented shortcuts." it's a nice intro/summary of every day Python tools like various utility built-in functions (len, enumerate, reversed, zip), list and other comprehensions leading to generator expressions then generators proper. continuing the functional programming feel from there, it goes into the various features available in your function signature, e.g., default args, varargs; then functions themselves as objects. based on this theme, it sounds like a book that introduces Python (specifically Python 3) from an "object-based" approach. it doesn't mean that the whole book will be about *writing classes* in Python, but to have more object-awareness as you're learning the language. (this wasn't a book review as much as it was getting a feel for the book based on looking through one sample chapter.) :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ? http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rabidpoobear at gmail.com Thu Jan 13 23:07:44 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 13 Jan 2011 16:07:44 -0600 Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) In-Reply-To: References: <737BFD65545B4D9F910BEC26C25747C5@mycomputer> Message-ID: Also check bigwords.com, they aggregate lots of other book sites and will get you a great deal, especially if you are buying multiple books because it smartly combines shipping and all. ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 13, 2011, at 6:24 AM, Brett Ritter wrote: > On Tue, Jan 4, 2011 at 4:50 PM, Patty wrote: >> Hi David - I was looking for the book you recomended below - "Python 3 >> Object Oriented Programming" by Dusty Phillips - and found it on Amazon for >> $43 new on up and $70 for used but maybe that was hardback? Do you happen >> to know of some other way to obtain it for less than $45? > > Half.com is always my stop of choice for programming books. I see a > copy there for $16. > > -- > Brett Ritter / SwiftOne > swiftone at swiftone.org > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Thu Jan 13 23:53:30 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 14 Jan 2011 09:53:30 +1100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <4D2F826A.2040808@pearwood.info> lmhosie at jacks.sdstate.edu wrote: > Hello All, > I am having an issue with lists and am not sure where to go from here any advice appreciated. I colored the areas of concern. > blue my comments > purple example of output > red area area concerned You may have coloured the text before you sent it, but the colours did not survive being sent to a mailing list. Everything you have written is a nice, plain black. Colouring text is no substitute for actually taking the time to explain: * what you tried; * what you expected to happen; * what happened instead. It is good practice to try to reduce the code to the smallest amount that actually demonstrates the same problem. For example, in your code you have this: [...] > # Check out any necessary licenses > gp.CheckOutExtension("spatial") > # Load required toolboxes... > gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Spatial Analyst Tools.tbx") > gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Conversion Tools.tbx") > gp.AddToolbox("C:/Program Files (x86)/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx") > gp.workspace = "D:\model" This is almost certainly irrelevant to the problem. To us, this is just noise -- we can't run it, because we don't have the arcgisscripting module, we don't have any way of testing for a licence, we can't load the toolboxes. For us to help you, you have to help us -- don't ask us to debug code we can't run. (We can sometimes try, if the bug is obvious, but usually it is just frustrating for everybody involved.) Spending the time to simplify the problem to the point we can run the code will help us to help you, and it might even let you solve the problem yourself. Some further comments: > # Table and field name inputs > inTable = "D:\model\Files.mdb\Last" > inPath="D:\model\Path.lyr" In *this* particular case, this way of writing file names is safe, but in general, it risks clashing with Python's "character escapes". String literals like \t \n \r and many others have special meaning to Python, and are turned into special characters like tab, newline, etc. Fortunately, Windows accepts both backslash and forward slash for file names, so the safest and easiest way to write those files names is: inTable = "D:/model/Files.mdb/Last" inPath = "D:/model/Path.lyr" Further comments: > paths = gp.SearchCursor(inTable) > path = paths.Next() > # Create an empty list > PathList = [] > while path: > # If the value is not already in the list, append it > if path.GetValue(inField) not in PathList: > PathList.append(path.GetValue(inField)) > path = paths.Next() [...] > This is the area that I am having complications with I am getting the correct output at the end of print PRList however because of the loop it overwrites the list each time. Ultimately I need to get a PR list of evens and odds > but when I put the EVEN Odd Check in the loop it will only calculate the first even number then give an error. Traceback (most recent call last): > File "C:\Users\lwood\Desktop\MODEL SCRIPTS\E\oddeven.py", line 65, in > if PR.GetValue(PRField) not in PRList: > AttributeError: 'int' object has no attribute 'GetValue' This error does not match the code you have written: the error talks about PR.GetValue, your code says path.GetValue. What other differences are there? What is PR? How does it differ from path? It is a waste of time to ask us to debug code that is not the code that is failing! The problem is, you have a line that *may or may not* look like this: paths = gp.SearchCursor(inTable) We don't know what paths will equal! It could be anything. But from the name, it should be some sort of collection of path objects, whatever they are. Each path object should have a method GetValue, but apparently (guessing from your error) some of them are plain int objects instead of path objects. > There are 233 paths and within each a different number of rows. I need a list to make a feature layer of just odds and of evens per each path. > It works fine when it is out of the loop but only gives me the last path list. I don't understand how you can say it works fine, when a moment ago you said it gives an error. > I realize that this it is looping over the list each time and that is why the output is for the last path only. I would just like it all in one loop is possible but not necessary. I don't understand what this means. > I'm not sure but what I have thought may work is writing the list to a file and appending it each time then reopenning it for the calculations but that seems a little much. Perhaps a Mapping technique or dictionary? Or like I mentioned before it would be fine to do it all in one loop as well. There shouldn't be any need to write to a file. But I can't suggest an alternative because I don't understand what you are trying to do. I'm sorry that I can't be of more assistance, but unfortunately my crystal ball is broken this week *wink* -- Steven From rabidpoobear at gmail.com Fri Jan 14 00:00:58 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 13 Jan 2011 17:00:58 -0600 Subject: [Tutor] (no subject) In-Reply-To: <4D2F826A.2040808@pearwood.info> References: <4D2F826A.2040808@pearwood.info> Message-ID: On Thu, Jan 13, 2011 at 4:53 PM, Steven D'Aprano wrote: > lmhosie at jacks.sdstate.edu wrote: >> >> Hello All, >> I am having an issue with lists and am not sure where to go from here any >> advice appreciated. I colored the areas of concern. >> blue my comments >> purple example of output >> red area area concerned > > You may have coloured the text before you sent it, but the colours did not > survive being sent to a mailing list. Everything you have written is a nice, > plain black. > > Colouring text is no substitute for actually taking the time to explain: > > * what you tried; > * what you expected to happen; > * what happened instead. > > It is good practice to try to reduce the code to the smallest amount that > actually demonstrates the same problem. Actually the color survived on my end, but all of steven's other comments about noise and unnecessary text applies. Even with the color, I didn't bother reading your question because it seemed to me like you didn't bother formulating a good question either. From alan.gauld at btinternet.com Fri Jan 14 01:21:01 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jan 2011 00:21:01 -0000 Subject: [Tutor] turn a path into nested list References: Message-ID: "ingo" wrote >> at the os.walk() function for traversing directory trees? It may be >> all >> you need. > > Yes, but I'm not confident with it (the more reason to use it you > will say :) ). Quite. A simple tree printout looks like this: >>> for t in os.walk('Root'): ... print t ... And the result is:('Root', ['D1', 'D2', 'D3'], ['FA.txt', 'FB.txt']) ('Root/D1', ['D1-1'], ['FC.txt']) ('Root/D1/D1-1', [], ['FF.txt']) ('Root/D2', [], ['FD.txt']) ('Root/D3', ['D3-1'], ['FE.txt']) ('Root/D3/D3-1', [], ['target.txt']) >>>That's a lot of work done for just 2 lines of code...Thats taken >>>from the OS topic in my tutorial(V2 only as yet)It goes into >>>slightly more detail and more examples.But it looks like it will >>>sace you a lot of work! -- Alan GauldAuthor of the Learn to Program web sitehttp://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jan 14 01:29:43 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 14 Jan 2011 00:29:43 +0000 (GMT) Subject: [Tutor] creating a text widget In-Reply-To: <308752.49258.qm@web120909.mail.ne1.yahoo.com> References: <488609.54184.qm@web120905.mail.ne1.yahoo.com> <308752.49258.qm@web120909.mail.ne1.yahoo.com> Message-ID: <878628.79060.qm@web86702.mail.ird.yahoo.com> Forwarding to list... > none of it actually. i am brand new to Tk/Python. Actually, i don't have a >need to do any editing on the file. OK, display is pretty easy. Take a look in my tutorial under Event Driven Programming. There you will see a simple text widget with text being inserted. Or look in the Case Study topic for a more extensive GUI with more text being inserted into a text widget. But perhaps you should try first to write a program that simply pages data from your file onto the screen using print() - perhaps limited to 25 lines at a time? Hitting space should bring up the next 25 lines, and so on. That will give you experience of working with files. HTH, Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Alan Gauld To: tutor at python.org Sent: Thu, January 13, 2011 1:35:08 PM Subject: Re: [Tutor] creating a text widget "W S" wrote > could someone please provide me some code that would create a text widget that >i could open a text file in? > You don;t open the text file in the widget as such, you open the file in Python as usual and copy its contents into the text widget. When you are done making changes (if you are making changes) then you have to copy the content back out to the file (or rename the original to .bak and create a new version) So the question is which part do you not understand? - Creating a text widget - opening the file - copying the file to the widget - copying changes to the file HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Fri Jan 14 02:50:56 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Thu, 13 Jan 2011 17:50:56 -0800 (PST) Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? Message-ID: <781392.91281.qm@web130205.mail.mud.yahoo.com> I am going through the book mentioned in the subject line, and I have found a couple of things that don't seem to work the way the author shows in the book. So, either I am doing something wrong, or what he is saying isn't quite right. I am using Python 2.7.1 on Mac OS X Leopard. The first thing is what he has for getting keyboard input (this is non-GUI stuff). Several times he does something like this: x = input('type something: ") But when I do the above and type something in, I get an error message saying that whatever I have typed in response to the above input() command, is an undefined name, unless I put it in quotes when I type it. I did a bit of poking around on the net and found out that input() actually appears to treat whatever is typed as an actual python command, i.e. as if it was being "eval"ed. If this is the case...why does he describe the usage this way in his book? On the other hand, raw_input() works just as exected, is it a typo? Seems like kind of a bad error to have in a Python book for beginners. And I just found another one that doesn't appear to work as he describes. print("some text here", end = ' ') He says this is supposed to control the end character on a print statement, allowing one to choose what the last character printed will be, other than a newline. But when I try it, I get a syntax error on the "=" after "end". So is this not a valid command format? Or is he using perhaps an earlier version of python? The copyright date on the book is 2010, and it is the 3rd Edition of the book. From kb1pkl at aim.com Fri Jan 14 02:55:38 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 13 Jan 2011 20:55:38 -0500 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: <781392.91281.qm@web130205.mail.mud.yahoo.com> References: <781392.91281.qm@web130205.mail.mud.yahoo.com> Message-ID: <4D2FAD1A.8090702@aim.com> On 01/13/2011 08:50 PM, Elwin Estle wrote: > I am going through the book mentioned in the subject line, and I have found a couple of things that don't seem to work the way the author shows in the book. So, either I am doing something wrong, or what he is saying isn't quite right. > > I am using Python 2.7.1 on Mac OS X Leopard. > > The first thing is what he has for getting keyboard input (this is non-GUI stuff). > > Several times he does something like this: > > x = input('type something: ") > > But when I do the above and type something in, I get an error message saying that whatever I have typed in response to the above input() command, is an undefined name, unless I put it in quotes when I type it. I did a bit of poking around on the net and found out that input() actually appears to treat whatever is typed as an actual python command, i.e. as if it was being "eval"ed. If this is the case...why does he describe the usage this way in his book? > > On the other hand, raw_input() works just as exected, is it a typo? Seems like kind of a bad error to have in a Python book for beginners. > > And I just found another one that doesn't appear to work as he describes. > > print("some text here", end = ' ') > > He says this is supposed to control the end character on a print statement, allowing one to choose what the last character printed will be, other than a newline. But when I try it, I get a syntax error on the "=" after "end". > > So is this not a valid command format? Or is he using perhaps an earlier version of python? The copyright date on the book is 2010, and it is the 3rd Edition of the book. > > > He's not using an older version - you are! That book was written for Python 3.x, you are using Python 2.x. As you have found, replace input with raw_input, and for that print statement you can use: print "Some text", The comma suppresses the newline from being printed. HTH, ~Corey From carroll at tjc.com Fri Jan 14 03:55:54 2011 From: carroll at tjc.com (Terry Carroll) Date: Thu, 13 Jan 2011 18:55:54 -0800 (PST) Subject: [Tutor] module to parse XMLish text? Message-ID: Does anyone know of a module that can parse out text with XML-like tags as in the example below? I emphasize the "-like" in "XML-like". I don't think I can parse this as XML (can I?). Sample text between the dashed lines:: --------------------------------- Blah, blah, blah SOMETHING ELSE SOMETHING DIFFERENT --------------------------------- I'd like to be able to have a dictionary (or any other structure, really; as long as I can get to the parsed-out pieces) that would look smoothing like: {"BING" : "ZEBRA", "BANG" : "ROOSTER" "BOOM" : "GARBONZO BEAN" "BLIP" : "SOMETHING ELSE" "BASH" : "SOMETHING DIFFERENT"} The "Blah, blah, blah" can be tossed away, for all I care. The basic rule is that the tag either has an operand (e.g., ), in which case the name is the first word and the content is everything else that follows in the tag; or else the tag has no operand, in which case it is matched to a corresponding closing tag (e.g., SOMETHING ELSE), and the content is the material between the two tags. I think I can assume there are no nested tags. I could write a state machine to do this, I suppose, but life's short, and I'd rather not re-invent the wheel, if there's a wheel laying around somewhere. From wallenpb at gmail.com Fri Jan 14 04:29:55 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 13 Jan 2011 21:29:55 -0600 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: <4D2FAD1A.8090702@aim.com> References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> Message-ID: That is correct about the difference between Python 2 and Python 3 syntax. However, I am surprised that with 2.7.1 these do not work. I have found that on my Ubuntu system with Python 2.6.5 these Python 3 syntax items do seem to work properly. I am assuming they were back ported or something. I would have expected the same for 2.7.1. --Bill On Thu, Jan 13, 2011 at 7:55 PM, Corey Richardson wrote: > On 01/13/2011 08:50 PM, Elwin Estle wrote: > > I am going through the book mentioned in the subject line, and I have > found a couple of things that don't seem to work the way the author shows in > the book. So, either I am doing something wrong, or what he is saying isn't > quite right. > > > > I am using Python 2.7.1 on Mac OS X Leopard. > > > > The first thing is what he has for getting keyboard input (this is > non-GUI stuff). > > > > Several times he does something like this: > > > > x = input('type something: ") > > > > But when I do the above and type something in, I get an error message > saying that whatever I have typed in response to the above input() command, > is an undefined name, unless I put it in quotes when I type it. I did a bit > of poking around on the net and found out that input() actually appears to > treat whatever is typed as an actual python command, i.e. as if it was being > "eval"ed. If this is the case...why does he describe the usage this way in > his book? > > > > On the other hand, raw_input() works just as exected, is it a typo? > Seems like kind of a bad error to have in a Python book for beginners. > > > > And I just found another one that doesn't appear to work as he describes. > > > > print("some text here", end = ' ') > > > > He says this is supposed to control the end character on a print > statement, allowing one to choose what the last character printed will be, > other than a newline. But when I try it, I get a syntax error on the "=" > after "end". > > > > So is this not a valid command format? Or is he using perhaps an earlier > version of python? The copyright date on the book is 2010, and it is the > 3rd Edition of the book. > > > > > > > > He's not using an older version - you are! That book was written for > Python 3.x, you are using Python 2.x. As you have found, replace input > with raw_input, and for that print statement you can use: > > print "Some text", > > The comma suppresses the newline from being printed. > > HTH, > ~Corey > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Fri Jan 14 04:31:41 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Thu, 13 Jan 2011 22:31:41 -0500 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> Message-ID: <4D2FC39D.7090600@aim.com> On 01/13/2011 10:29 PM, Bill Allen wrote: > That is correct about the difference between Python 2 and Python 3 > syntax. However, I am surprised that with 2.7.1 these do not work. I > have found that on my Ubuntu system with Python 2.6.5 these Python 3 > syntax items do seem to work properly. I am assuming they were back > ported or something. I would have expected the same for 2.7.1. > > --Bill I'm using Python 2.6.6 and I have a feeling you are not using python 2.6.5 with Python3 syntax working. I could be very wrong, but just a hunch ;) ~Corey From wallenpb at gmail.com Fri Jan 14 05:18:28 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 13 Jan 2011 22:18:28 -0600 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: <4D2FC39D.7090600@aim.com> References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> <4D2FC39D.7090600@aim.com> Message-ID: I will agree that it seems odd, but here is a sample run from my system. I promise I am not pulling anyone's leg! :-)) wallenpb at Ubuntu-D810:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print("hello world") hello world >>> x = input("how many?") how many?5 >>> x 5 On Thu, Jan 13, 2011 at 9:31 PM, Corey Richardson wrote: > On 01/13/2011 10:29 PM, Bill Allen wrote: > > That is correct about the difference between Python 2 and Python 3 > > syntax. However, I am surprised that with 2.7.1 these do not work. I > > have found that on my Ubuntu system with Python 2.6.5 these Python 3 > > syntax items do seem to work properly. I am assuming they were back > > ported or something. I would have expected the same for 2.7.1. > > > > --Bill > > I'm using Python 2.6.6 and I have a feeling you are not using python > 2.6.5 with Python3 syntax working. I could be very wrong, but just a > hunch ;) > > ~Corey > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at gmail.com Fri Jan 14 05:31:50 2011 From: vceder at gmail.com (Vern Ceder) Date: Thu, 13 Jan 2011 23:31:50 -0500 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> <4D2FC39D.7090600@aim.com> Message-ID: Bill, Try this: >>> print("hello", "Bill") ('Hello', 'Bill') >>> x = input("Your name?") Your name?Bill Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: name 'Bill' is not defined and see if those work (my results on 2.6 shown). In Python 3 the results are: >>> print ("Hello", "Bill") Hello Bill >>> x = input("Your name?") Your name?Bill >>> Cheers, Vern The two examples you show would work on any Python 2.x (or even 1.5) system. The parens around the single string won't cause an error nor will using input to get an integer. Cheers, Vern On Thu, Jan 13, 2011 at 11:18 PM, Bill Allen wrote: > I will agree that it seems odd, but here is a sample run from my system. I > promise I am not pulling anyone's leg! :-)) > > wallenpb at Ubuntu-D810:~$ python > Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) > [GCC 4.4.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> print("hello world") > hello world > >>> x = input("how many?") > how many?5 > >>> x > 5 > > On Thu, Jan 13, 2011 at 9:31 PM, Corey Richardson wrote: > >> On 01/13/2011 10:29 PM, Bill Allen wrote: >> > That is correct about the difference between Python 2 and Python 3 >> > syntax. However, I am surprised that with 2.7.1 these do not work. I >> > have found that on my Ubuntu system with Python 2.6.5 these Python 3 >> > syntax items do seem to work properly. I am assuming they were back >> > ported or something. I would have expected the same for 2.7.1. >> > >> > --Bill >> >> I'm using Python 2.6.6 and I have a feeling you are not using python >> 2.6.5 with Python3 syntax working. I could be very wrong, but just a >> hunch ;) >> >> ~Corey >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vern Ceder vceder at gmail.com, vceder at dogsinmotion.com The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Fri Jan 14 05:38:14 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 13 Jan 2011 22:38:14 -0600 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> <4D2FC39D.7090600@aim.com> Message-ID: Vern, Quite right! I see what you mean. I quite inadvertently stumbled into examples that would work without realizing it. I typically program in Python 3, so not as familiar with the limitations on Python 2x. I've had quite a chuckle over this! Thanks, Bill On Thu, Jan 13, 2011 at 10:31 PM, Vern Ceder wrote: > Bill, > > Try this: > > >>> print("hello", "Bill") > ('Hello', 'Bill') > >>> x = input("Your name?") > Your name?Bill > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in > NameError: name 'Bill' is not defined > > and see if those work (my results on 2.6 shown). In Python 3 the results > are: > > >>> print ("Hello", "Bill") > Hello Bill > >>> x = input("Your name?") > Your name?Bill > >>> > > Cheers, > Vern > The two examples you show would work on any Python 2.x (or even 1.5) > system. The parens around the single string won't cause an error nor will > using input to get an integer. > > Cheers, > Vern > > On Thu, Jan 13, 2011 at 11:18 PM, Bill Allen wrote: > >> I will agree that it seems odd, but here is a sample run from my system. >> I promise I am not pulling anyone's leg! :-)) >> >> wallenpb at Ubuntu-D810:~$ python >> Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) >> [GCC 4.4.3] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> print("hello world") >> hello world >> >>> x = input("how many?") >> how many?5 >> >>> x >> 5 >> >> On Thu, Jan 13, 2011 at 9:31 PM, Corey Richardson wrote: >> >>> On 01/13/2011 10:29 PM, Bill Allen wrote: >>> > That is correct about the difference between Python 2 and Python 3 >>> > syntax. However, I am surprised that with 2.7.1 these do not work. >>> I >>> > have found that on my Ubuntu system with Python 2.6.5 these Python 3 >>> > syntax items do seem to work properly. I am assuming they were back >>> > ported or something. I would have expected the same for 2.7.1. >>> > >>> > --Bill >>> >>> I'm using Python 2.6.6 and I have a feeling you are not using python >>> 2.6.5 with Python3 syntax working. I could be very wrong, but just a >>> hunch ;) >>> >>> ~Corey >>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > -- > Vern Ceder > vceder at gmail.com, vceder at dogsinmotion.com > The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Fri Jan 14 07:06:37 2011 From: wescpy at gmail.com (wesley chun) Date: Thu, 13 Jan 2011 22:06:37 -0800 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> <4D2FC39D.7090600@aim.com> Message-ID: input() must be avoided at all costs in Python 2.x. if you find any Python (2.x) book which employs that, consider the author uninformed. it is a huge security risk and the main reason why in Python 3 raw_input() is renamed to and replaces input(). cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ? http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wallenpb at gmail.com Fri Jan 14 05:15:44 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 13 Jan 2011 22:15:44 -0600 Subject: [Tutor] errors in "Python Programming for the Absolute Beginner"?? In-Reply-To: <4D2FC39D.7090600@aim.com> References: <781392.91281.qm@web130205.mail.mud.yahoo.com> <4D2FAD1A.8090702@aim.com> <4D2FC39D.7090600@aim.com> Message-ID: I will agree that it seems odd, but here is a sample run from my system. I promise I am not pulling anyone's leg! :-)) wallenpb at Ubuntu-D810:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print("hello world") hello world >>> x = input("how many?") how many?5 >>> x 5 >>> On Thu, Jan 13, 2011 at 9:31 PM, Corey Richardson wrote: > On 01/13/2011 10:29 PM, Bill Allen wrote: > > That is correct about the difference between Python 2 and Python 3 > > syntax. However, I am surprised that with 2.7.1 these do not work. I > > have found that on my Ubuntu system with Python 2.6.5 these Python 3 > > syntax items do seem to work properly. I am assuming they were back > > ported or something. I would have expected the same for 2.7.1. > > > > --Bill > > I'm using Python 2.6.6 and I have a feeling you are not using python > 2.6.5 with Python3 syntax working. I could be very wrong, but just a > hunch ;) > > ~Corey > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Jan 14 09:27:49 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 14 Jan 2011 09:27:49 +0100 Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: <4D300905.4040302@free.fr> Hello, *from xml.etree.ElementTree import ElementTree _/#Parsing:/_ doc = ElementTree() doc.parse(xmlFile) * /_*#Find tag element:*_/ *doc.find('mytag')* *_/#iteration over tag element:/_ lname = [] for lib in doc.iter('LibTag'): libName = lib.attrib['name'] lname.append(libName) * Regards Karim On 01/14/2011 03:55 AM, Terry Carroll wrote: > Does anyone know of a module that can parse out text with XML-like > tags as in the example below? I emphasize the "-like" in "XML-like". > I don't think I can parse this as XML (can I?). > > Sample text between the dashed lines:: > > --------------------------------- > Blah, blah, blah > > > > > SOMETHING ELSE > SOMETHING DIFFERENT > > --------------------------------- > > I'd like to be able to have a dictionary (or any other structure, > really; as long as I can get to the parsed-out pieces) that would look > smoothing like: > > {"BING" : "ZEBRA", > "BANG" : "ROOSTER" > "BOOM" : "GARBONZO BEAN" > "BLIP" : "SOMETHING ELSE" > "BASH" : "SOMETHING DIFFERENT"} > > The "Blah, blah, blah" can be tossed away, for all I care. > > The basic rule is that the tag either has an operand (e.g., ZEBRA>), in which case the name is the first word and the content is > everything else that follows in the tag; or else the tag has no > operand, in which case it is matched to a corresponding closing tag > (e.g., SOMETHING ELSE), and the content is the material > between the two tags. > > I think I can assume there are no nested tags. > > I could write a state machine to do this, I suppose, but life's short, > and I'd rather not re-invent the wheel, if there's a wheel laying > around somewhere. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Fri Jan 14 10:24:34 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 14 Jan 2011 10:24:34 +0100 Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: Terry Carroll, 14.01.2011 03:55: > Does anyone know of a module that can parse out text with XML-like tags as > in the example below? I emphasize the "-like" in "XML-like". I don't think > I can parse this as XML (can I?). > > Sample text between the dashed lines:: > > --------------------------------- > Blah, blah, blah > > > > > SOMETHING ELSE > SOMETHING DIFFERENT > > --------------------------------- You can't parse this as XML because it's not XML. The three initial child tags are not properly closed. If the format is really as you describe, i.e. one line per tag, regular expressions will work nicely. Something like (untested) import re parse_tag_and_text = re.compile( # accept a tag name and then either space+tag or '>'+text+' ]+)(?: ([^>]+)>\s*|>([^<]+) References: Message-ID: On Fri, Jan 14, 2011 at 1:21 AM, Alan Gauld wrote: >>>> for t in os.walk('Root'): > > ... ? ?print t > ... > And the result is:('Root', ['D1', 'D2', 'D3'], ['FA.txt', 'FB.txt']) > ('Root/D1', ['D1-1'], ['FC.txt']) As I only need the first result presented I didn't favor os.walk, yet tried it anyway. Below both versions: 1. aliaspath = mk_alias(path) directories = mk_pathlist(aliaspath) files = [] content = os.listdir(path) content.sort() for item in content: fullpath = os.path.join(path, item) if os.path.isdir(fullpath): directories.append((item, mk_aliasURL(fullpath))) else: files.append((item, mk_aliasURL(fullpath))) 2. content = list(os.walk(path).next()) content[0] = mk_alias(content[0]) directories = mk_pathlist(content[0]) directories.extend([(item, mkURL(os.path.join(content[0], item))) for item in content[1]]) files = [(item, mkURL(os.path.join(content[0], item))) for item in content[2]] And both with the same output: Path c:\Python25\Lib\site-packages\pygame\examples\macosx\aliens_app_example AliasPath Audio\site-packages\pygame\examples\macosx\aliens_app_example Dirs [('Audio', 'Audio'), ('site-packages', 'Audio/site-packages'), ('pygame', 'Audio/site-packages/pygame'), ('examples', 'Audio/site-packages/pygame/examples'), ('macosx', 'Audio/site-packages/pygame/examples/macosx'), ('aliens_app_example', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example'), ('English.lproj', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/English.lproj')] Files [('aliens.py', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/aliens.py'), ('aliens.pyc', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/aliens.pyc'), ('aliens.pyo', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/aliens.pyo'), ('README.txt', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/README.txt'), ('setup.py', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/setup.py'), ('setup.pyc', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/setup.pyc'), ('setup.pyo', 'Audio/site-packages/pygame/examples/macosx/aliens_app_example/setup.pyo')] ingo From tommy.kaas at kaasogmulvad.dk Fri Jan 14 17:43:22 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Fri, 14 Jan 2011 17:43:22 +0100 Subject: [Tutor] no luck with sqlinsert Message-ID: <000901cbb40a$28238440$786a8cc0$@kaasogmulvad.dk> I get a invalid syntax error when I try to run this script - and it's con.commit() which is highlighted when I get the error. I can't see what is wrong. I think it looks like other scripts I'm running without problems. The scraping part works fine. And the table exists in the mysql db. I have just separated in an attempt to locate the problem. But no luck. I hope someone can spot the problem. (ActivePython 2.6.6. on pc/win) TIA import urllib2 import MySQLdb from BeautifulSoup import BeautifulSoup con = MySQLdb.connect(host='mysql2.dicar.dk', user='python1', passwd='python1', db='python') cur = con.cursor() sqlinsert = ''' INSERT INTO tkindbtal (kommune, komnr, i2005, i2006, i2007, i2008, i2009, i2010) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ''' soup = BeautifulSoup(urllib2.urlopen('http://www.kaasogmulvad.dk/unv/python/kom_ind btal.htm').read()) rows = soup.findAll('tr') print rows for tr in rows[1:]: cols = tr.findAll('td') try: cur.execute(sqlinsert, (cols[0], cols[1], int(cols[2]), int(cols[3]), int(cols[4]), int(cols[5]), int(cols[6]), int(cols[7])) con.commit() except: con.rollback() con.close() Tommy Kaas -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Fri Jan 14 17:52:56 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Fri, 14 Jan 2011 17:52:56 +0100 Subject: [Tutor] Refcount in C extensions Message-ID: Hello, I am writing a Python C extension and I have some trouble understanding how reference counting works exactly. Though I think I understand the practice on simple operations (see my question at stackoverflow: http://stackoverflow.com/questions/4657764/py-incref-decref-when), but on more "complex" operations I cannot quite grasp it yet. For example, in the following helper function, do I need to DECREF or are all the references automatically destroyed when the function returns? double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr) { if ((PyObject_GetAttrString(obj, attr) == False) || (PyObject_HasAttrString(obj, attr) == False)) { return -9999.0; } return PyFloat_AsDouble(PyNumber_Float(PyObject_GetAttrString(obj, attr))); } Please share your thoughts, thanks in advance, kind regards, Izz ad-Din -------------- next part -------------- An HTML attachment was scrubbed... URL: From jasons at adventureaquarium.com Fri Jan 14 18:03:21 2011 From: jasons at adventureaquarium.com (Jason Staudenmayer) Date: Fri, 14 Jan 2011 12:03:21 -0500 Subject: [Tutor] no luck with sqlinsert In-Reply-To: <000901cbb40a$28238440$786a8cc0$@kaasogmulvad.dk> Message-ID: Don't build you sql separate from the execute (or so I was told when I was doing something similar) cur.execute(INSERT INTO tkindbtal (kommune, komnr, i2005, i2006, i2007 \ , i2008, i2009, i2010) VALUES (%s, %s, %s, %s, %s, %s,\ %s, %s) % (cols[0], cols[1], int(cols[2]), int(cols[3]), int(cols[4]), \ int(cols[5]), int(cols[6]), int(cols[7])) Jason ..?><((((?> -----Original Message----- From: tutor-bounces+jasons=adventureaquarium.com at python.org [mailto:tutor-bounces+jasons=adventureaquarium.com at python.org] On Behalf Of Tommy Kaas Sent: Friday, January 14, 2011 11:43 AM To: tutor at python.org Subject: [Tutor] no luck with sqlinsert I get a invalid syntax error when I try to run this script - and it's con.commit() which is highlighted when I get the error. I can't see what is wrong. I think it looks like other scripts I'm running without problems. The scraping part works fine. And the table exists in the mysql db. I have just separated in an attempt to locate the problem. But no luck. I hope someone can spot the problem. (ActivePython 2.6.6. on pc/win) TIA import urllib2 import MySQLdb from BeautifulSoup import BeautifulSoup con = MySQLdb.connect(host='mysql2.dicar.dk', user='python1', passwd='python1', db='python') cur = con.cursor() sqlinsert = ''' INSERT INTO tkindbtal (kommune, komnr, i2005, i2006, i2007, i2008, i2009, i2010) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ''' soup = BeautifulSoup(urllib2.urlopen('http://www.kaasogmulvad.dk/unv/python/kom_indbtal.htm').read()) rows = soup.findAll('tr') print rows for tr in rows[1:]: cols = tr.findAll('td') try: cur.execute(sqlinsert, (cols[0], cols[1], int(cols[2]), int(cols[3]), int(cols[4]), int(cols[5]), int(cols[6]), int(cols[7])) con.commit() except: con.rollback() con.close() Tommy Kaas -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 14 18:08:13 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Jan 2011 17:08:13 -0000 Subject: [Tutor] no luck with sqlinsert References: <000901cbb40a$28238440$786a8cc0$@kaasogmulvad.dk> Message-ID: "Tommy Kaas" wrote >I get a invalid syntax error when I try to run this script - and it's > con.commit() which is highlighted when I get the error. Aren't you one closing parenthesis short? > cur.execute(sqlinsert, (cols[0], cols[1], int(cols[2]), int(cols[3]), int(cols[4]), int(cols[5]), int(cols[6]), int(cols[7]) ) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From stefan_ml at behnel.de Fri Jan 14 18:08:54 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 14 Jan 2011 18:08:54 +0100 Subject: [Tutor] Refcount in C extensions In-Reply-To: References: Message-ID: Izz ad-Din Ruhulessin, 14.01.2011 17:52: > I am writing a Python C extension and I have some trouble understanding how > reference counting works exactly. Though I think I understand the practice > on simple operations (see my question at stackoverflow: > http://stackoverflow.com/questions/4657764/py-incref-decref-when), but on > more "complex" operations I cannot quite grasp it yet. > > For example, in the following helper function, do I need to DECREF or are > all the references automatically destroyed when the function returns? > > double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr) > { > if ((PyObject_GetAttrString(obj, attr) == False) || > (PyObject_HasAttrString(obj, attr) == False)) { > return -9999.0; > } This is C, nothing is done automatically. So you need to take care to properly DECREF the references. one or two references are leaked in the above. BTW, what's "False"? Did you mean "Py_False"? > return PyFloat_AsDouble(PyNumber_Float(PyObject_GetAttrString(obj, attr))); This leaks two references. > Please share your thoughts, thanks in advance, kind regards, Consider taking a look at Cython. It's an extension language that lets you write Python code and generates C code for you. In Cython, your code above simply spells cdef double Py_GetAttr_DoubleFromFloat(obj, attr): value = getattr(obj, attr, False) if value is False: return -9999.0 return value Note that I'm using a Python object for 'attr' for performance reasons (and for Python 3 portability). I would expect that the above is at least a bit faster than your code, but it handles ref-counting correctly. Having said that, I'd frown a bit about an API that returns either False or a double value ... Stefan From steve at alchemy.com Fri Jan 14 18:16:34 2011 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 14 Jan 2011 09:16:34 -0800 Subject: [Tutor] no luck with sqlinsert In-Reply-To: References: Message-ID: <4D3084F2.3010405@alchemy.com> On 14-Jan-11 09:03, Jason Staudenmayer wrote: > Don't build you sql separate from the execute (or so I was told when I > was doing something similar) > cur.execute(INSERT INTO tkindbtal (kommune, komnr, i2005, i2006, i2007 \ > , i2008, i2009, i2010) VALUES (%s, %s, %s, %s, %s, %s,\ > %s, %s)% (cols[0], cols[1], int(cols[2]), int(cols[3]), int(cols[4]), \ > int(cols[5]), int(cols[6]), int(cols[7])) It's generally bad practice to simply paste string values together to include values into SQL, such as the code above (using % formatting). You need to properly escape the data strings. Most SQL interfaces in Python offer methods for this, either as individual string operation or by allowing "place holder" values in the SQL query which discrete values are then added to as separate arguments (so the SQL library escapes them for you automatically). The danger is if the data strings include SQL syntax like quotes or whatever, it can invalidate your SQL query, making it fail. A malicious user who can feed you those data values can deliberately design them to actually do whatever they want to your database. From izzaddin.ruhulessin at gmail.com Fri Jan 14 19:49:16 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Fri, 14 Jan 2011 19:49:16 +0100 Subject: [Tutor] Refcount in C extensions In-Reply-To: References: Message-ID: Hi Stefan, Thanks for your quick reply and clearing the issue up for me. Using your answer, I rewrote the function to this: double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr) > > { > > PyObject *get_attr, *py_float; > > int has_attr; > > >> //Check if the given object has the given attribute. > > has_attr = PyObject_HasAttrString(obj, attr); > > if (has_attr == False) { > > return -9999.0; > > } > > >> //Get our attribute and convert it to a double. > > get_attr = PyObject_GetAttrString(obj, attr); > > py_float = PyNumber_Float(get_attr); > > if (py_float == NULL) { > > Py_DECREF(get_attr); > > Py_XDECREF(py_float); > > return -9999.0; > > } > > double output = PyFloat_AsDouble(py_float); > > >> //Garbage collect > > Py_DECREF(get_attr); > > Py_XDECREF(py_float); > > >> return output; > > } > > (False is 0) Regarding your Cython suggestion, as a matter of coincidence I have been reading about it in the past few days. I'm in doubt of using it however, because I have a lot of native C code that would require rewriting if I switched to Cython. On the other hand, your example shows that such a one-time rewrite will pay-off big time in future development speed. Kind regards, Izz ad-Din -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Fri Jan 14 20:11:51 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 14 Jan 2011 20:11:51 +0100 Subject: [Tutor] Refcount in C extensions In-Reply-To: References: Message-ID: Izz ad-Din Ruhulessin, 14.01.2011 19:49: > Thanks for your quick reply and clearing the issue up for me. Using your > answer, I rewrote the function to this: > > double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr) >> >> { >> >> PyObject *get_attr, *py_float; >> >> int has_attr; >> >> >>> //Check if the given object has the given attribute. >> >> has_attr = PyObject_HasAttrString(obj, attr); >> >> if (has_attr == False) { >> >> return -9999.0; >> >> } >> >> >>> //Get our attribute and convert it to a double. >> >> get_attr = PyObject_GetAttrString(obj, attr); Note that HasAttr() calls GetAttr() internally, so it's actually faster to call GetAttr() and check for an exception (and clear it). That's basically how HasAttr() works, except that it doesn't tell you the result if the attribute existed. >> py_float = PyNumber_Float(get_attr); >> >> if (py_float == NULL) { >> >> Py_DECREF(get_attr); >> >> Py_XDECREF(py_float); You already know that py_float is NULL, so Py_XDECREF() is a no-op. >> return -9999.0; >> >> } >> >> double output = PyFloat_AsDouble(py_float); >> >> >>> //Garbage collect >> >> Py_DECREF(get_attr); >> >> Py_XDECREF(py_float); py_float cannot be NULL at this point, so the Py_XDECREF() will compile into Py_DECREF(). > (False is 0) In that case, better write 0 instead. > Regarding your Cython suggestion, as a matter of coincidence I have been > reading about it in the past few days. I'm in doubt of using it however, > because I have a lot of native C code that would require rewriting if I > switched to Cython. No need for that, Cython can call external C code natively. So you can make the switch step by step. > On the other hand, your example shows that such a > one-time rewrite will pay-off big time in future development speed. It usually does, yes. It often even pays off immediately because a rewrite tends to be pretty straight forward (basically, read and understand the C code, rip out all low-level stuff and replace the rest with simpler code), and while doing so, some bugs tend to disappear, the code becomes simpler, safer and often also faster, and new features appear while you're at it. Stefan From ben.ganzfried at gmail.com Fri Jan 14 19:53:11 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Fri, 14 Jan 2011 13:53:11 -0500 Subject: [Tutor] Object/Class Beginner Questions Message-ID: Hey guys, I'm using a tutorial geared for a 2.x version of Python and I am currently using Python 3.1-- so it is possible that my confusion has to do with different notations between them. But in any case, here is what I have: >>> type(Time) >>> t1 = Time() >>> type(t1) where: class Time: def __init__(self, hours = 0, minutes = 0, seconds = 0): self.hours = hours self.minutes = minutes self.seconds = seconds def print_time(t1): print(t.hours, ":", t.minutes, ":", t.seconds) Now the book I am working with has the following example: >>> type(Point) >>> p = Point() >>> type(p) My questions are the following: 1) Why is the type for my class Time : >>> type(Time) when the type for their class Point is: Also, what is the difference between "class" and "classobj" in this case? 2) Why does my t1 object give the following as its type: And in their p object example the type is: ? 3) What is happening such that when I try to call my print_time(t1) function I get the following error: >>> t1 = Time() >>> t1.hours = 3 >>> t1.minutes = 30 >>> t1.seconds = 45 >>> print_time(t1) Traceback (most recent call last): File "", line 1, in print_time(t1) NameError: name 'print_time' is not defined Thank you very much. Sincerely, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jan 14 22:28:16 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 14 Jan 2011 16:28:16 -0500 Subject: [Tutor] Object/Class Beginner Questions In-Reply-To: References: Message-ID: On 1/14/11, Ben Ganzfried wrote: > Hey guys, > > I'm using a tutorial geared for a 2.x version of Python and I am currently > using Python 3.1-- so it is possible that my confusion has to do with > different notations between them. But in any case, here is what I have: > >>>> type(Time) > >>>> t1 = Time() >>>> type(t1) > > > where: > > class Time: > def __init__(self, hours = 0, minutes = 0, seconds = 0): > self.hours = hours > self.minutes = minutes > self.seconds = seconds > > def print_time(t1): > print(t.hours, ":", t.minutes, ":", t.seconds) > > Now the book I am working with has the following example: > >>>> type(Point) > >>>> p = Point() >>>> type(p) > > > My questions are the following: > 1) Why is the type for my class Time : >>> type(Time) > > when the type for their class Point is: > Also, what is the difference between "class" and "classobj" in this case? I am not sure as I thought something changed about this in 3.x, but try: class time(object) instead of simply class time and see what happens. > 2) Why does my t1 object give the following as its type: '__main__.Time'> > And in their p object example the type is: ? I am not sure, and am curious to see the answer as well. > 3) What is happening such that when I try to call my print_time(t1) function > I get the following error: >>>> t1 = Time() >>>> t1.hours = 3 >>>> t1.minutes = 30 >>>> t1.seconds = 45 >>>> print_time(t1) > Traceback (most recent call last): > File "", line 1, in > print_time(t1) > NameError: name 'print_time' is not defined You made a time object. This means that everything about the object (class) is accessed through the dot notation. Currently, you are calling print_time(t1) where t1 is an object. You have to, as they say, call print_time on an instance of the time class. You have an instance, t1 (an instance is just a variable representing the class), so call print_time on the instance: t1.print_time() HTH. > > > Thank you very much. > > Sincerely, > > Ben > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Fri Jan 14 22:39:06 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jan 2011 08:39:06 +1100 Subject: [Tutor] Object/Class Beginner Questions In-Reply-To: References: Message-ID: <4D30C27A.40002@pearwood.info> Ben Ganzfried wrote: > Hey guys, > > I'm using a tutorial geared for a 2.x version of Python and I am currently > using Python 3.1-- so it is possible that my confusion has to do with > different notations between them. But in any case, here is what I have: > My questions are the following: > 1) Why is the type for my class Time : >>> type(Time) > > when the type for their class Point is: In Python 2.x, objects are divided into two broad families of objects: 1. "classic classes" and their instances; 2. "new-style" types and their instances (including built-ins like str, int, float, and similar). There are some small, but significant differences between them, but in general they do mostly the same kind of things. In Python 2.x, a class definition like: class Point: ... defines a classic class (or "old style class"), while inheriting from "object" or a built-in type defines a new-style class: class Point(object): # Tells Python to construct a new-style class ... The type of an instance is the instance's class; the type of a class object is "classobj" for old-style classes and (usually) "type" for new-style classes and types. Calling type() on old-style classes returns , and on new-style, . But in Python 3, old-style classic classes are gone. Point will be a "type" object, which is what you are seeing. > Also, what is the difference between "class" and "classobj" in this case? Every object has a type, even classes. `class` is the keyword that you use for creating new classes, and type() is what you use to find out what they are. So: type(42) -> int # 42 is an int type(int) -> type # int is a new-style class, or "type" In Python 2.x, the type of a classic class is called "classobj", and the type of a new-style class is called "type". > 2) Why does my t1 object give the following as its type: '__main__.Time'> > And in their p object example the type is: ? Again, this boils down to old-style vs. new-style. > 3) What is happening such that when I try to call my print_time(t1) function > I get the following error: >>>> t1 = Time() >>>> t1.hours = 3 >>>> t1.minutes = 30 >>>> t1.seconds = 45 >>>> print_time(t1) > Traceback (most recent call last): > File "", line 1, in > print_time(t1) > NameError: name 'print_time' is not defined You don't have a print_time function, as Python correctly reports. You have a print_time *method*, which means it lives inside Time objects. You can't access it directly as a global function: print_time(something) does not work, because print_time doesn't live in the global namespace. You need to call it as a method of a Time instance: t1.print_time() # no additional arguments needed -- Steven From ben.ganzfried at gmail.com Fri Jan 14 20:37:33 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Fri, 14 Jan 2011 14:37:33 -0500 Subject: [Tutor] Object/Class Beginner Questions In-Reply-To: References: Message-ID: I actually just figured it out (since the tutorial talks about the difference in indentation between a method and a function in a later chapter). Basically, a method is within a class and therefore cannot be called from the command prompt whereas a function that stands by itself in a script can be called from the command prompt. Although if this isn't quite right or there's more to it, I would still definitely appreciate any advice you have. Thanks again, Ben On Fri, Jan 14, 2011 at 1:53 PM, Ben Ganzfried wrote: > Hey guys, > > I'm using a tutorial geared for a 2.x version of Python and I am currently > using Python 3.1-- so it is possible that my confusion has to do with > different notations between them. But in any case, here is what I have: > > >>> type(Time) > > >>> t1 = Time() > >>> type(t1) > > > where: > > class Time: > def __init__(self, hours = 0, minutes = 0, seconds = 0): > self.hours = hours > self.minutes = minutes > self.seconds = seconds > > def print_time(t1): > print(t.hours, ":", t.minutes, ":", t.seconds) > > Now the book I am working with has the following example: > > >>> type(Point) > > >>> p = Point() > >>> type(p) > > > My questions are the following: > 1) Why is the type for my class Time : >>> type(Time) > 'type'> > when the type for their class Point is: > Also, what is the difference between "class" and "classobj" in this case? > 2) Why does my t1 object give the following as its type: '__main__.Time'> > And in their p object example the type is: ? > 3) What is happening such that when I try to call my print_time(t1) > function I get the following error: > >>> t1 = Time() > >>> t1.hours = 3 > >>> t1.minutes = 30 > >>> t1.seconds = 45 > >>> print_time(t1) > Traceback (most recent call last): > File "", line 1, in > print_time(t1) > NameError: name 'print_time' is not defined > > > Thank you very much. > > Sincerely, > > Ben > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben.ganzfried at gmail.com Fri Jan 14 20:39:10 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Fri, 14 Jan 2011 14:39:10 -0500 Subject: [Tutor] Object/Class Beginner Questions In-Reply-To: References: Message-ID: * I meant that*: A method actually can be called from the command prompt, but the syntax is quite different than that used to call a function from the command prompt. On Fri, Jan 14, 2011 at 2:37 PM, Ben Ganzfried wrote: > I actually just figured it out (since the tutorial talks about the > difference in indentation between a method and a function in a later > chapter). Basically, a method is within a class and therefore cannot be > called from the command prompt whereas a function that stands by itself in a > script can be called from the command prompt. > > Although if this isn't quite right or there's more to it, I would still > definitely appreciate any advice you have. > > Thanks again, > > Ben > > > On Fri, Jan 14, 2011 at 1:53 PM, Ben Ganzfried wrote: > >> Hey guys, >> >> I'm using a tutorial geared for a 2.x version of Python and I am currently >> using Python 3.1-- so it is possible that my confusion has to do with >> different notations between them. But in any case, here is what I have: >> >> >>> type(Time) >> >> >>> t1 = Time() >> >>> type(t1) >> >> >> where: >> >> class Time: >> def __init__(self, hours = 0, minutes = 0, seconds = 0): >> self.hours = hours >> self.minutes = minutes >> self.seconds = seconds >> >> def print_time(t1): >> print(t.hours, ":", t.minutes, ":", t.seconds) >> >> Now the book I am working with has the following example: >> >> >>> type(Point) >> >> >>> p = Point() >> >> >>> type(p) >> >> >> My questions are the following: >> 1) Why is the type for my class Time : >>> type(Time) >> > 'type'> >> when the type for their class Point is: >> Also, what is the difference between "class" and "classobj" in this case? >> 2) Why does my t1 object give the following as its type: > '__main__.Time'> >> And in their p object example the type is: ? >> 3) What is happening such that when I try to call my print_time(t1) >> function I get the following error: >> >>> t1 = Time() >> >>> t1.hours = 3 >> >>> t1.minutes = 30 >> >>> t1.seconds = 45 >> >>> print_time(t1) >> Traceback (most recent call last): >> File "", line 1, in >> print_time(t1) >> NameError: name 'print_time' is not defined >> >> >> Thank you very much. >> >> Sincerely, >> >> Ben >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Fri Jan 14 23:42:55 2011 From: carroll at tjc.com (Terry Carroll) Date: Fri, 14 Jan 2011 14:42:55 -0800 (PST) Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: On Fri, 14 Jan 2011, Stefan Behnel wrote: > Terry Carroll, 14.01.2011 03:55: >> Does anyone know of a module that can parse out text with XML-like tags as >> in the example below? I emphasize the "-like" in "XML-like". I don't think >> I can parse this as XML (can I?). >> >> Sample text between the dashed lines:: >> >> --------------------------------- >> Blah, blah, blah >> >> >> >> >> SOMETHING ELSE >> SOMETHING DIFFERENT >> >> --------------------------------- > > You can't parse this as XML because it's not XML. The three initial child > tags are not properly closed. Yeah, that's what I figured. > If the format is really as you describe, i.e. one line per tag, regular > expressions will work nicely. Now there's an idea! I hadn't thought of using regexs, probably because I'm terrible at all but the most simple ones. As it happens, I'm only interested in four of the tags' contents, so I could probably manage to write a seried of regexes that even I could maintain, one for each of the pieces of data I want to extract; if I try to write a grand unified regex, I'm bound to shoot myself in the foot. Thanks very much. On Fri, 14 Jan 2011, Karim wrote: > from xml.etree.ElementTree import ElementTree I don't think straight XML parsing will work on this, as it's not valid XML; it just looks XML-like enough to cause confusion. From hacker0100 at hotmail.com Sat Jan 15 01:46:57 2011 From: hacker0100 at hotmail.com (walter weston) Date: Fri, 14 Jan 2011 17:46:57 -0700 Subject: [Tutor] how to print random number multiply Message-ID: I have mostly studied python and now I'm ready to start writing code. I want to print random numbers a certain ammount of times I am using the code import random print (random.random()) I tried bind the print statement to a variable and when I call x for example I want it to print new numbers when I store the print statement in a variable x everytime I call x it's the same number and does change I wanted it to change when I call it could someone show me the code to do that thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill.debroglie at gmail.com Sat Jan 15 01:48:10 2011 From: bill.debroglie at gmail.com (Bill DeBroglie) Date: Fri, 14 Jan 2011 19:48:10 -0500 Subject: [Tutor] color of "print" function Message-ID: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Hello all, I don't have a problem per se, but have noticed something that I'd like to figure out... Sometimes the "print" function appears orange for me, sometimes it appears purple. Why does this happen and what's the difference anyway? This seems to be the only function that varies like this, but I'm just starting really so perhaps I'll come across more. The coloring seems to be fairly arbitrary. At least, I haven't noticed a pattern yet. Using Mac OS X 10.5.8 and Python 2.7.1 Thank you for the help, bdb From kb1pkl at aim.com Sat Jan 15 01:57:50 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 14 Jan 2011 19:57:50 -0500 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: <4D30F10E.6000806@aim.com> On 01/14/2011 07:46 PM, walter weston wrote: > I have mostly studied python and now I'm ready to start writing code. I > want to print random numbers a certain ammount of times I am using the > code > > import random > print (random.random()) > > I tried bind the print statement to a variable and when I call x for > example I want it to print new numbers when I store the print statement > in a variable x everytime I call x it's the same number and does change > I wanted it to change when I call it could someone show me the code to > do that thanks! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor When you do: x = print(random.random()) that evaluates random.random() once, and not every time you type in x. What you want it is for loop: for number in range(50): print(random.random()) Coming from other languages you might think: cntr = 0 while cntr < 50: print(random.random()) cntr += 1 which is correct, but not pythonic. HTH, ~Corey Richardson From smokefloat at gmail.com Sat Jan 15 01:58:58 2011 From: smokefloat at gmail.com (David Hutto) Date: Fri, 14 Jan 2011 19:58:58 -0500 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: > ?import random for x in range(1,10) > print (random.random()) -- Sometimes...my mama...says I get over excited about technology. From steve at pearwood.info Sat Jan 15 01:58:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jan 2011 11:58:52 +1100 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: <4D30F14C.5020303@pearwood.info> walter weston wrote: > I have mostly studied python and now I'm ready to start writing code. I want to print random numbers a certain ammount of times I am using the code > > import random > print (random.random()) > > I tried bind the print statement to a variable and when I call x for example I want it to print new numbers when I store the print statement in a variable x everytime I call x it's the same number and does change I wanted it to change when I call it could someone show me the code to do that thanks! I'm sorry, I don't understand this. Can you try explaining more clearly what you want to do? -- Steven From kb1pkl at aim.com Sat Jan 15 01:59:04 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 14 Jan 2011 19:59:04 -0500 Subject: [Tutor] color of "print" function In-Reply-To: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Message-ID: <4D30F158.2050707@aim.com> On 01/14/2011 07:48 PM, Bill DeBroglie wrote: > Hello all, > > I don't have a problem per se, but have noticed something that I'd > like to figure out... > > Sometimes the "print" function appears orange for me, sometimes it > appears purple. Why does this happen and what's the difference anyway? > This seems to be the only function that varies like this, but I'm just > starting really so perhaps I'll come across more. > > The coloring seems to be fairly arbitrary. At least, I haven't noticed > a pattern yet. > > Using Mac OS X 10.5.8 and Python 2.7.1 > > Thank you for the help, > bdb > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Is that specifically with Idle, or some other IDE? AFAIK the interpreter has no coloring, unless you're using something like bpython or ipython. From steve at pearwood.info Sat Jan 15 02:00:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jan 2011 12:00:40 +1100 Subject: [Tutor] color of "print" function In-Reply-To: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Message-ID: <4D30F1B8.70305@pearwood.info> Bill DeBroglie wrote: > Hello all, > > I don't have a problem per se, but have noticed something that I'd like > to figure out... > > Sometimes the "print" function appears orange for me, sometimes it > appears purple. Why does this happen and what's the difference anyway? Can you explain the context? Do you mean in your editor? If so, perhaps you're using two different editors, and one is configured to show print in purple and the other orange. -- Steven From smokefloat at gmail.com Sat Jan 15 02:01:03 2011 From: smokefloat at gmail.com (David Hutto) Date: Fri, 14 Jan 2011 20:01:03 -0500 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: Sorry , the tab button doesn't work for text in google mail, and it jumped to send >> ?import random > for x in range(1,10): print (random.random()) This assigns a new random each time, where as outside the for loop it assigns it once. From bgailer at gmail.com Sat Jan 15 02:03:43 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Jan 2011 20:03:43 -0500 Subject: [Tutor] color of "print" function In-Reply-To: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Message-ID: <4D30F26F.30406@gmail.com> On 1/14/2011 7:48 PM, Bill DeBroglie wrote: > Hello all, > > I don't have a problem per se, but have noticed something that I'd > like to figure out... > > Sometimes the "print" function appears orange for me, sometimes it > appears purple. Why does this happen and what's the difference anyway? > This seems to be the only function that varies like this, but I'm just > starting really so perhaps I'll come across more. > > The coloring seems to be fairly arbitrary. At least, I haven't noticed > a pattern yet. > > Using Mac OS X 10.5.8 and Python 2.7.1 I'm stumped. Could it be the glasses you are wearing. Or could you tell us just a bit more about your situation - such as WHERE does this happen? An editor, IDLE, what? -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sat Jan 15 02:07:44 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Jan 2011 20:07:44 -0500 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: <4D30F360.5000407@gmail.com> On 1/14/2011 7:46 PM, walter weston wrote: > I have mostly studied python and now I'm ready to start writing code. > I want to print random numbers a certain ammount of times I am using > the code > > import random > print (random.random()) > > I tried bind the print statement to a variable and when I call x for > example I want it to print new numbers when I store the print > statement in a variable x everytime I call x it's the same number and > does change I wanted it to change when I call it could someone show me > the code to do that thanks! Sorry - but we are not mind readers. Post the code you wrote, so we have some idea of what you mean by "bind" and "call". I could guess but you should learn to provide sufficient information so we don't have to. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 15 02:07:38 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 01:07:38 -0000 Subject: [Tutor] color of "print" function References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Message-ID: "Bill DeBroglie" wrote > Sometimes the "print" function appears orange for me, sometimes it > appears purple. Why does this happen and what's the difference > anyway? THere is probably no difference but one of several things could be causing it. First though, the colouring is done by your editing tool not Python. So a lot depends on the tool you use. If you use different editors then you can expect to see different colours - reason 1. The colouring is derived from the context so if your print command is accidentally put inside a string it will be coloured the same as the string - uindicating an error! - Reason 2. You may have mismatched parentheses somewhere which may cause the editor to consider your print as a value, hence a different colour - Reason 3. Some editors are sensitive to their context to the point of allowing different colour schemes inside class definitions from out, maybe yours does too. Reason 4 And there are probably others... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokefloat at gmail.com Sat Jan 15 02:14:26 2011 From: smokefloat at gmail.com (David Hutto) Date: Fri, 14 Jan 2011 20:14:26 -0500 Subject: [Tutor] how to print random number multiply In-Reply-To: References: Message-ID: On Fri, Jan 14, 2011 at 8:01 PM, David Hutto wrote: > Sorry , the tab button doesn't work for text in google mail, and it > jumped to send > >>> > > ??import random >> for x in range(1,10): num = random.random() > ? ? ??print (num) this should 'bind' your variable to a knew random each time > > This assigns a new random each time, where as outside the for loop it > assigns it once. > -- Sometimes...my mama...says I get over excited about technology. From alan.gauld at btinternet.com Sat Jan 15 02:09:58 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 01:09:58 -0000 Subject: [Tutor] how to print random number multiply References: Message-ID: "walter weston" wrote > I have mostly studied python and now I'm ready to > start writing code. Its usually best to study programming languages *by* writing code. However since you have now reached that stage of readiness that's irrelevant advice :-) > I want to print random numbers a certain ammount of times > I am using the code > > import random > print (random.random()) print just prints once. It returns None so if you try to assign print to a variable it will store None > I tried bind the print statement to a variable and when > I call x for example I want it to print new numbers when > I store the print statement in a variable x everytime I > call x it's the same number and does change I wanted > it to change when I call it Since we are not psychic it would be more usefuil to send your actual code and output so that we can see exactly what you did and what Python produced. It would also be helpful to tell us which Python version you are using (and OS too). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From mindarson at live.com Sat Jan 15 02:17:18 2011 From: mindarson at live.com (Joel Knoll) Date: Fri, 14 Jan 2011 20:17:18 -0500 Subject: [Tutor] Python on Ubuntu 10.10? Message-ID: Hello, I am new to programming and to Python. I've been using Python with IDLE on Windows Vista for a few weeks now. (And I'm loving it!) However, I'm thinking about switching to Ubuntu 10.10. If I download Ubuntu, will I still be able to use the IDLE environment? I am really quite fond of it (mostly because it's what I know!). To use Python in Ubuntu, will I have to do any additional downloading, or do Python and IDLE come built in and ready to use? Thanks for your time, JC Knoll -------------- next part -------------- An HTML attachment was scrubbed... URL: From bill.debroglie at gmail.com Sat Jan 15 02:18:56 2011 From: bill.debroglie at gmail.com (Bill DeBroglie) Date: Fri, 14 Jan 2011 20:18:56 -0500 Subject: [Tutor] color of "print" function In-Reply-To: <4D30F26F.30406@gmail.com> References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> <4D30F26F.30406@gmail.com> Message-ID: On Jan 14, 2011, at 8:03 PM, bob gailer wrote: > On 1/14/2011 7:48 PM, Bill DeBroglie wrote: >> Hello all, >> >> I don't have a problem per se, but have noticed something that I'd >> like to figure out... >> >> Sometimes the "print" function appears orange for me, sometimes it >> appears purple. Why does this happen and what's the difference >> anyway? This seems to be the only function that varies like this, >> but I'm just starting really so perhaps I'll come across more. >> >> The coloring seems to be fairly arbitrary. At least, I haven't >> noticed a pattern yet. >> >> Using Mac OS X 10.5.8 and Python 2.7.1 > > I'm stumped. Could it be the glasses you are wearing. > > Or could you tell us just a bit more about your situation - such as > WHERE does this happen? An editor, IDLE, what? > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > It happens in IDLE. If I change the spacing (delete an empty line say) the color will change. Experimenting a little bit, the default seems to be orange. When I indent at all, it changes to purple. However, occasionally, it's purple without being indented (can't figure out anything in particular that causes this), though in every instance where this happens, I can change it back to orange by manipulating the spacing (adding an empty line, and then deleting it seems to do the trick). Thanks. From kb1pkl at aim.com Sat Jan 15 02:36:09 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Fri, 14 Jan 2011 20:36:09 -0500 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: Message-ID: <4D30FA09.1030302@aim.com> On 01/14/2011 08:17 PM, Joel Knoll wrote: > Hello, > > I am new to programming and to Python. I've been using Python with IDLE > on Windows Vista for a few weeks now. > (And I'm loving it!) However, I'm thinking about switching to Ubuntu > 10.10. If I download Ubuntu, will I still be able to use the > IDLE environment? I am really quite fond of it (mostly because it's > what I know!). To use Python in Ubuntu, > will I have to do any additional downloading, or do Python and IDLE come > built in and ready to use? > > Thanks for your time, > > JC Knoll > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Python (2.6.6) comes default with Ubuntu IIRC. You'll need to: sudo apt-get install idle to download and install Idle, but it does all the lifting for you. From hacker0100 at hotmail.com Sat Jan 15 03:22:58 2011 From: hacker0100 at hotmail.com (walter weston) Date: Fri, 14 Jan 2011 19:22:58 -0700 Subject: [Tutor] how come this doesnt work Message-ID: I generate a random number(supposedly a password, in my case its just a long floating point lol),I want the user to reinput that number and I want to print a string if the number entered is correct. so if m==num(num is the number generated and m is the variable which stores the input ) then I want to print 'you entered correctly, proceed'. here is my code.. import random for x in range(0,1): num = random.random() print (num) m=input('input pass:') if m==num: print('you entered correctly, proceed') It's very noobish dont give me complex replys, and dont be to rude or laugh at me, as I am a beginner In the programming domain. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Jan 15 03:25:51 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 14 Jan 2011 20:25:51 -0600 Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: On Fri, Jan 14, 2011 at 4:42 PM, Terry Carroll wrote: > > > On Fri, 14 Jan 2011, Karim wrote: > > from xml.etree.ElementTree import ElementTree >> > > I don't think straight XML parsing will work on this, as it's not valid > XML; it just looks XML-like enough to cause confusion. > > It's worth trying out - most (good) parsers "do the right thing" even when they don't have strictly valid code. I don't know if xml.etree is one, but I'm fairly sure both lxml and BeautifulSoup would probably parse it correctly. Only one way to find out ;) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Jan 15 03:40:47 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 14 Jan 2011 21:40:47 -0500 Subject: [Tutor] how come this doesnt work In-Reply-To: References: Message-ID: On 1/14/11, walter weston wrote: > > I generate a random number(supposedly a password, in my case its just a long > floating point lol),I want the user to reinput that number and I want to > print a string if the number entered is correct. so if m==num(num is the > number generated and m is the variable which stores the input ) then I want > to print 'you entered correctly, proceed'. > > here is my code.. > > import random > for x in range(0,1): Note that you could just say: for x in range(1) since range() starts at 0 automatically. Note, too, that this will run once, so you really do not need a for loop at all. > num = random.random() > print (num) > m=input('input pass:') "m" is currently a string since it is what is returned by input. Your num, though, is an integer... > if m==num: > print('you entered correctly, proceed') I assume the problem is that it never prints? If not, this is because m is a string while num is an integer (int for short). Add: m=int(m) just before the if statement. This causes m to turn from a string into an integer and is what is known as "casting" or "type casting", if I have my vocabulary correct. Essentially, while you see a number in both m and num, Python sees two very different binary values and so they are never equal. Here goes a very odd example, but it is all I can come up with at the moment. Imagine two boxes, each the same size and each the same color. If you weigh them, though, you find one to be much heavier than the other; they look the same, but they are not. Casting is like adding weight to the lighter box until it equals the weight of the heavier box; now they *are* equal, with the same dimensions, color, and weight. I told you it would not be a great example. HTH. > > It's very noobish dont give me complex replys, and dont be to rude or laugh > at me, as I am a beginner In the programming domain. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From enalicho at gmail.com Sat Jan 15 03:45:44 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 15 Jan 2011 02:45:44 +0000 Subject: [Tutor] how come this doesnt work In-Reply-To: References: Message-ID: > import random > for x in range(0,1): > ??? num = random.random() > ??? print (num) > ??? m=input('input pass:') > ??? if m==num: > ??????? print('you entered correctly, proceed') Your problem lines in the differences in between the types - your num variable is a float, whereas your m variable is a string. In order to compare them here, you need to either use the float() function or the str() function to convert one to a comparable data type, for example - if m==str(num): print('you entered correctly, proceed') Might I also note that your for loop does nothing except run once, and the 0 is unnecessary. HTH From hacker0100 at hotmail.com Sat Jan 15 04:02:12 2011 From: hacker0100 at hotmail.com (walter weston) Date: Fri, 14 Jan 2011 20:02:12 -0700 Subject: [Tutor] When I print random.random Message-ID: when I print random.random() it always returns a float why is this? how do I change it to a whole number? -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Sat Jan 15 04:06:47 2011 From: enalicho at gmail.com (Noah Hall) Date: Sat, 15 Jan 2011 03:06:47 +0000 Subject: [Tutor] how come this doesnt work In-Reply-To: References: Message-ID: Adding reply to list - On Sat, Jan 15, 2011 at 2:55 AM, walter weston wrote: > I only want to generate a random number once > Then you don't need a for loop. Think of a for loop as something you need when you want to run a piece of code several times, for example for x in range(1,6): print('This is message number %d' % (x)) HTH From bgailer at gmail.com Sat Jan 15 04:25:00 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 14 Jan 2011 22:25:00 -0500 Subject: [Tutor] When I print random.random In-Reply-To: References: Message-ID: <4D31138C.9000107@gmail.com> On 1/14/2011 10:02 PM, walter weston wrote: > when I print random.random() it always returns a float why is this? > how do I change it to a whole number? That depends on what behavior you want. If you RTFM you will see: random.random() Return the next random floating point number in the range [0.0, 1.0). The Python tool for converting float to integer is the int function. However int(random.random() ) will always return 0. In what range do you want the integers to fall? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sat Jan 15 05:39:35 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Jan 2011 23:39:35 -0500 Subject: [Tutor] how come this doesnt work In-Reply-To: References: Message-ID: <4D312507.9050905@ieee.org> On 01/-10/-28163 02:59 PM, walter weston wrote: > > I generate a random number(supposedly a password, in my case its just a long floating point lol),I want the user to reinput that number and I want to print a string if the number entered is correct. so if m==num(num is the number generated and m is the variable which stores the input ) then I want to print 'you entered correctly, proceed'. > > here is my code.. > > import random > for x in range(0,1): > num = random.random() > print (num) > m=input('input pass:') > if m==num: > print('you entered correctly, proceed') > > It's very noobish dont give me complex replys, and dont be to rude or laugh at me, as I am a beginner In the programming domain. > You left out a few details, like what version of Python you're using. However, i suspect you're using version 3.x, and will respond accordingly. input() returns a string, while random.random() returns a float. So they'll never be equal. Because floats are stored in binary floating point, you run a risk in comparing them in any case. So rather than converting the user's input to float, I'd suggest converting the random value to a string. And if you do it before printing it, your user should be able to get an exact match every time. Just change the num assignment to: num = str(random.random()) DaveA From waynejwerner at gmail.com Sat Jan 15 06:15:27 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 14 Jan 2011 23:15:27 -0600 Subject: [Tutor] When I print random.random In-Reply-To: <4D31138C.9000107@gmail.com> References: <4D31138C.9000107@gmail.com> Message-ID: On Fri, Jan 14, 2011 at 9:25 PM, bob gailer wrote: > On 1/14/2011 10:02 PM, walter weston wrote: > > when I print random.random() it always returns a float why is this? how do > I change it to a whole number? > > > That depends on what behavior you want. > > If you RTFM you will see: > random.random() Return the next random floating point number in the range > [0.0, 1.0). The Python tool for converting float to integer is the int > function. > > However int(random.random() ) will always return 0. > > In what range do you want the integers to fall? > The documentation in general is a fine source for learning new functionality: http://docs.python.org/library/random.html HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Jan 15 06:19:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jan 2011 16:19:24 +1100 Subject: [Tutor] When I print random.random In-Reply-To: References: Message-ID: <4D312E5C.2030700@pearwood.info> walter weston wrote: > when I print random.random() it always returns a float why is this? how do I change it to a whole number? Because random.random() is defined to always return a float between 0 and 1. That's what it does. If you want a random whole number, you can call random.randint or random.randrange. See the Fine Manual for the difference between them, or at the interactive interpreter, call: help(random.randint) help(random.randrange) and read what they say. Then if you still have any questions, ask. -- Steven From bgailer at gmail.com Sat Jan 15 06:42:13 2011 From: bgailer at gmail.com (bob gailer) Date: Sat, 15 Jan 2011 00:42:13 -0500 Subject: [Tutor] When I print random.random In-Reply-To: References: , <4D31138C.9000107@gmail.com> Message-ID: <4D3133B5.3080500@gmail.com> Please always reply to the list, not just to me. On 1/14/2011 10:42 PM, walter weston wrote: > I want a whole number thats 5 digits long, I want to use it as a > password and if I just type random.random() I get a long float. random.randint(a, b) Return a random integer N such that a <= N <= b. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Sat Jan 15 07:53:33 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 15 Jan 2011 07:53:33 +0100 Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: Wayne Werner, 15.01.2011 03:25: > On Fri, Jan 14, 2011 at 4:42 PM, Terry Carroll wrote: >> On Fri, 14 Jan 2011, Karim wrote: >> >> from xml.etree.ElementTree import ElementTree >> >> I don't think straight XML parsing will work on this, as it's not valid >> XML; it just looks XML-like enough to cause confusion. > > It's worth trying out - most (good) parsers "do the right thing" even when > they don't have strictly valid code. I don't know if xml.etree is one, but > I'm fairly sure both lxml and BeautifulSoup would probably parse it > correctly. They wouldn't. For the first tags, the text values would either not come out at all or they would be read as attributes and thus loose their order and potentially their whitespace as well. The other tags would likely get parsed properly, but the parser may end up nesting them as it hasn't found a closing tag for the previous tags yet. So, in any case, you'd end up with data loss and/or a structure that would be much harder to handle than the (relatively) simple file structure. Stefan From nstinemates at gmail.com Sat Jan 15 09:33:12 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Sat, 15 Jan 2011 00:33:12 -0800 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: Message-ID: Python comes pre installed on Ubuntu, as most of the GUI is written in it. Nick On Friday, January 14, 2011, Joel Knoll wrote: > > > > > > Hello, > > I am new to programming and to Python.? I've been using Python with IDLE on Windows Vista for a few weeks now. > (And I'm loving it!)? However, I'm thinking about switching to Ubuntu 10.10.? If I download Ubuntu, will I still be able to use the > IDLE environment?? I am really quite fond of it (mostly because it's what I know!).? To use Python in Ubuntu, > will I have to do any additional downloading, or do Python and IDLE come built in and ready to use? > > Thanks for your time, > > JC Knoll > > > > From timomlists at gmail.com Sat Jan 15 10:59:51 2011 From: timomlists at gmail.com (Timo) Date: Sat, 15 Jan 2011 10:59:51 +0100 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: Message-ID: <4D317017.4050504@gmail.com> On 15-01-11 02:17, Joel Knoll wrote: > Hello, > > I am new to programming and to Python. I've been using Python with > IDLE on Windows Vista for a few weeks now. > (And I'm loving it!) However, I'm thinking about switching to Ubuntu > 10.10. If I download Ubuntu, will I still be able to use the > IDLE environment? I am really quite fond of it (mostly because it's > what I know!). To use Python in Ubuntu, > will I have to do any additional downloading, or do Python and IDLE > come built in and ready to use? > You should try the default text editor that comes with Ubuntu, called Gedit. You can tweak it very nicely so it shows linenumbers and so on. There are also very useful plugins. It is all I ever use and when I need to write some code in Windows, it bugs me how bad IDLE really is. Cheers, Timo > Thanks for your time, > > JC Knoll > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From brettmurch at gmail.com Sat Jan 15 11:10:15 2011 From: brettmurch at gmail.com (Brett Murch) Date: Sat, 15 Jan 2011 23:10:15 +1300 Subject: [Tutor] defining functions and classes Message-ID: <1295086215.6283.4.camel@norad> Hi everyone, I'm just starting to learn Python and am starting by creating a text game but am having trouble with classes and funtions. I want to create a class or function where someone creates a charater and has a choice of their name or os. This is what I have so far; class Administrator(): def Skills(name,os): name = raw_input('What is your name') os = raw_input('What is your os') self.name = name self.os = os Skills(name,os) I keep getting a syntax error on calling it. any ideas on what I'm doing wrong? Should it not be a class and should I just define it as a function or what? Thank you in advance From vearasilp at gmail.com Sat Jan 15 11:26:33 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Sat, 15 Jan 2011 11:26:33 +0100 Subject: [Tutor] defining functions and classes In-Reply-To: <1295086215.6283.4.camel@norad> References: <1295086215.6283.4.camel@norad> Message-ID: Do you also have to define the class attributes? class Administrator(): name = "" os = "" def Skills(name,os): name = raw_input('What is your name') os = raw_input('What is your os') self.name = name self.os = os Skills(name,os) On Sat, Jan 15, 2011 at 11:10 AM, Brett Murch wrote: > Hi everyone, > > I'm just starting to learn Python and am starting by creating a text > game but am having trouble with classes and funtions. I want to create a > class or function where someone creates a charater and has a choice of > their name or os. This is what I have so far; > > class Administrator(): > def Skills(name,os): > name = raw_input('What is your name') > os = raw_input('What is your os') > self.name = name > self.os = os > > Skills(name,os) > > I keep getting a syntax error on calling it. any ideas on what I'm doing > wrong? Should it not be a class and should I just define it as a > function or what? > > Thank you in advance > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Jan 15 11:34:46 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 15 Jan 2011 21:34:46 +1100 Subject: [Tutor] defining functions and classes In-Reply-To: <1295086215.6283.4.camel@norad> References: <1295086215.6283.4.camel@norad> Message-ID: <4D317846.9060003@pearwood.info> Brett Murch wrote: > I keep getting a syntax error on calling it. any ideas on what I'm doing > wrong? Should we *guess*, or would you like to share with us the actual error you are getting? My guess is that you're not getting a syntax error at all, you're getting a NameError that Skills is not defined. Am I close? If my guess is wrong, please copy the *full* error, don't paraphrase it, retype it from memory, summarise it, or otherwise change it in any way. -- Steven From hacker0100 at hotmail.com Sat Jan 15 02:00:48 2011 From: hacker0100 at hotmail.com (walter weston) Date: Fri, 14 Jan 2011 18:00:48 -0700 Subject: [Tutor] help Message-ID: how comes when I run code from a new window in python IDLE the text highlighting dissapears -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 15 12:57:26 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 11:57:26 -0000 Subject: [Tutor] help References: Message-ID: "walter weston" wrote > how comes when I run code from a new window in python > IDLE the text highlighting dissapears No idea, it doesn't do that for me. Can you be more specific about what you are doing. Also which version of Python, which OS etc? How exactly are you running the code? And when you say text highlighting, do you mean the coloured syntax highlighting? Or something else? Any information you can provide will help us work out what is happening. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 15 13:07:00 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 12:07:00 -0000 Subject: [Tutor] how come this doesnt work References: Message-ID: "Alex Hall" wrote > m=int(m) > just before the if statement. This causes m to turn from a string > into > an integer and is what is known as "casting" or "type casting", if I > have my vocabulary correct. Sadly you don't although its a common error. This is type conversion. You are actually changing the type of m. Type casting is something very different and is not really available in Python (except by underhand use of the struct module!). In type casting you tell the intertpreter to treat the bit pattern of one variable as if it were a different type but do not actually change the underlying bit pattern. Its used a lot in low level languages such as C but is not very useful in Python. Sorry to be pedantic, and if you hadn't mentioned correct vocabulary I probably wouldn't have bothered correcting it. :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 15 13:11:41 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 12:11:41 -0000 Subject: [Tutor] defining functions and classes References: <1295086215.6283.4.camel@norad> Message-ID: "Brett Murch" wrote > game but am having trouble with classes and funtions. I want to > create a > class or function where someone creates a charater and has a choice > of > their name or os. This is what I have so far; > > class Administrator(): > def Skills(name,os): OK, You have a ways to go to undertsatand classes so give up on that and focus on functions for now. You need to underestand functions well before you start messing with classes. > I keep getting a syntax error on calling it. any ideas on what I'm > doing > wrong? Should it not be a class and should I just define it as a > function or what? Yes, just make it a function for now. Life will be easier. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at ieee.org Sat Jan 15 14:23:24 2011 From: davea at ieee.org (Dave Angel) Date: Sat, 15 Jan 2011 08:23:24 -0500 Subject: [Tutor] defining functions and classes In-Reply-To: <1295086215.6283.4.camel@norad> References: <1295086215.6283.4.camel@norad> Message-ID: <4D319FCC.8000106@ieee.org> On 01/-10/-28163 02:59 PM, Brett Murch wrote: > Hi everyone, > > I'm just starting to learn Python and am starting by creating a text > game but am having trouble with classes and funtions. I want to create a > class or function where someone creates a charater and has a choice of > their name or os. This is what I have so far; > > class Administrator(): > def Skills(name,os): > name = raw_input('What is your name') > os = raw_input('What is your os') > self.name = name > self.os = os > > Skills(name,os) > > I keep getting a syntax error on calling it. any ideas on what I'm doing > wrong? Should it not be a class and should I just define it as a > function or what? > > Thank you in advance > > What previous experience in programming do you have? You say you're a beginner in Python, but what other object orientation experience do you have? I don't see any syntax error there. Looks to me like a NameError. When you get errors, you should copy/paste the whole error into your message, not just paraphrase it. Anyway, the NameError would occur since Skills is not a valid global name, it's a method name within a class. And if you got past that, then the same error would occur with the two arguments. They're not defined anywhere either. You're defining a class called Administrator. That implies you're going to have many Administrator instances, and presumably each will have attributes called name and os. If that's true, we can start refining. The function to call to create an Administrator instance is called Administrator(). When you call Administrator(), it will implicitly call the __init__() method, not the Skills() method. So you probably want to define such a method. Once such an instance is created, you might call the Skills() method to change the original name and os for it. But Skills() has the wrong method signature. The first parameter of such a method is 'self', and you're missing that. And the other two parameters are never used. Perhaps you intended something like (untested): class Administrator(): def __init__(self, name="unknown", os="nevernever"): self.name = name self.os = os def change_skills(self): name = raw_input('What is your new name') os = raw_input('What is your new os') self.name = name self.os = os admin1 = Administrator("Harry", "Windoze") admin1.change_skills() DaveA From tommy.kaas at kaasogmulvad.dk Sat Jan 15 15:07:36 2011 From: tommy.kaas at kaasogmulvad.dk (Tommy Kaas) Date: Sat, 15 Jan 2011 15:07:36 +0100 Subject: [Tutor] no luck with sqlinsert In-Reply-To: References: <000901cbb40a$28238440$786a8cc0$@kaasogmulvad.dk> Message-ID: <011201cbb4bd$8fc8c7f0$af5a57d0$@kaasogmulvad.dk> > >I get a invalid syntax error when I try to run this script - and it's > > con.commit() which is highlighted when I get the error. > > Aren't you one closing parenthesis short? > > Alan Gauld Yes, you're absolutely right. Thanks. Tommy From bill.debroglie at gmail.com Sat Jan 15 18:35:48 2011 From: bill.debroglie at gmail.com (Bill DeBroglie) Date: Sat, 15 Jan 2011 12:35:48 -0500 Subject: [Tutor] end parameter in 2.7.1? Message-ID: Twice in two days...! Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which is using Python 3.1. The author uses the end parameter in numerous programs but this doesn't seem to translate to 2.7. Any advice as to how I can specify the final string of the print function? Thank you, bdb From izzaddin.ruhulessin at gmail.com Sat Jan 15 18:41:56 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Sat, 15 Jan 2011 18:41:56 +0100 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: <4D317017.4050504@gmail.com> References: <4D317017.4050504@gmail.com> Message-ID: Install Eclipse via Synaptic and then PyDev via Eclipse. 2011/1/15 Timo > On 15-01-11 02:17, Joel Knoll wrote: > >> Hello, >> >> I am new to programming and to Python. I've been using Python with IDLE >> on Windows Vista for a few weeks now. >> (And I'm loving it!) However, I'm thinking about switching to Ubuntu >> 10.10. If I download Ubuntu, will I still be able to use the >> IDLE environment? I am really quite fond of it (mostly because it's what >> I know!). To use Python in Ubuntu, >> will I have to do any additional downloading, or do Python and IDLE come >> built in and ready to use? >> >> You should try the default text editor that comes with Ubuntu, called > Gedit. You can tweak it very nicely so it shows linenumbers and so on. There > are also very useful plugins. It is all I ever use and when I need to write > some code in Windows, it bugs me how bad IDLE really is. > > Cheers, > Timo > > Thanks for your time, >> >> JC Knoll >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Jan 15 18:46:10 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jan 2011 09:46:10 -0800 Subject: [Tutor] color of "print" function In-Reply-To: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> References: <474D51DC-7EAA-49F0-A442-9360B6DF66A9@gmail.com> Message-ID: On 1/14/2011 4:48 PM Bill DeBroglie said... > Hello all, > > I don't have a problem per se, but have noticed something that I'd like > to figure out... Ths best way to figure it out is 'use the source Luke' Idle is written in python, and in python27/Lib/idlelib there's colordelegator.py, where you'll find def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] keyword is imported above, and looking there you find python27/Lib/keyword.py which defines kwlist to include print. >>> import __builtin__ >>> dir(__builtin__) also includes print, so print is defined twice. Further in ColorDelegator you find "KEYWORD": idleConf.GetHighlight(theme, "keyword"), "BUILTIN": idleConf.GetHighlight(theme, "builtin"), So, keywords and builtins have their own colors defined in theme (whatever that is...) So, I'll venture at this point that the source of the problem lies in print being defined in two sets having two colorization definitions. The easy way to fix it would be to remove it from one list or the other in ColorDelegator to clear up the problem. HTH, Emile > > Sometimes the "print" function appears orange for me, sometimes it > appears purple. Why does this happen and what's the difference anyway? > This seems to be the only function that varies like this, but I'm just > starting really so perhaps I'll come across more. > > The coloring seems to be fairly arbitrary. At least, I haven't noticed a > pattern yet. > > Using Mac OS X 10.5.8 and Python 2.7.1 > > Thank you for the help, > bdb > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From emile at fenx.com Sat Jan 15 18:56:56 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jan 2011 09:56:56 -0800 Subject: [Tutor] When I print random.random In-Reply-To: <4D312E5C.2030700@pearwood.info> References: <4D312E5C.2030700@pearwood.info> Message-ID: On 1/14/2011 9:19 PM Steven D'Aprano said... > walter weston wrote: >> when I print random.random() it always returns a float why is this? >> how do I change it to a whole number? > > Because random.random() is defined to always return a float between 0 > and 1. That's what it does. > > If you want a random whole number, you can call random.randint or > random.randrange. See the Fine Manual for the difference between them, > or at the interactive interpreter, call: > > help(random.randint) > help(random.randrange) > You can discover that randint and randrange exist interactively by typing in dir(random), which is generally a good place to start. Most python libraries are reasonably complete in the functionality they provide, and if you want some particular capability, you're not likely to be the first so you'll find it's already there. Once you find names that sound like they may provide what you're looking for, use help as Steven illustrates above. If you don't see anything close, use help(module_name) and browse the help contents for addition info. then... > and read what they say. Then if you still have any questions, ask. > > > From scarolan at gmail.com Sat Jan 15 18:51:27 2011 From: scarolan at gmail.com (Sean Carolan) Date: Sat, 15 Jan 2011 11:51:27 -0600 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: <4D317017.4050504@gmail.com> Message-ID: >>> I am new to programming and to Python. ?I've been using Python with IDLE >>> on Windows Vista for a few weeks now. >>> (And I'm loving it!) ?However, I'm thinking about switching to Ubuntu >>> 10.10. ?If I download Ubuntu, will I still be able to use the >>> IDLE environment? ?I am really quite fond of it (mostly because it's what >>> I know!). ?To use Python in Ubuntu, >>> will I have to do any additional downloading, or do Python and IDLE come >>> built in and ready to use? Bite the bullet and learn how to use vim; you won't regret it. There's a steep learning curve at first but once you get the hang of it you'll be coding like a boss. This blog post also has some great tips on how to make vim into an IDE: http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/ From emile at fenx.com Sat Jan 15 19:05:11 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jan 2011 10:05:11 -0800 Subject: [Tutor] end parameter in 2.7.1? In-Reply-To: References: Message-ID: On 1/15/2011 9:35 AM Bill DeBroglie said... > Twice in two days...! > > Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which is > using Python 3.1. The author uses the end parameter What's an 'end' parameter? Emile > in numerous programs > but this doesn't seem to translate to 2.7. Any advice as to how I can > specify the final string of the print function? > > Thank you, > bdb > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From izzaddin.ruhulessin at gmail.com Sat Jan 15 19:21:02 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Sat, 15 Jan 2011 19:21:02 +0100 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: <4D317017.4050504@gmail.com> Message-ID: Although I probably wont switch from Eclipse to vim, that looks nevertheless very, very nice, bookmarked. 2011/1/15 Sean Carolan > >>> I am new to programming and to Python. I've been using Python with > IDLE > >>> on Windows Vista for a few weeks now. > >>> (And I'm loving it!) However, I'm thinking about switching to Ubuntu > >>> 10.10. If I download Ubuntu, will I still be able to use the > >>> IDLE environment? I am really quite fond of it (mostly because it's > what > >>> I know!). To use Python in Ubuntu, > >>> will I have to do any additional downloading, or do Python and IDLE > come > >>> built in and ready to use? > > Bite the bullet and learn how to use vim; you won't regret it. > There's a steep learning curve at first but once you get the hang of > it you'll be coding like a boss. This blog post also has some great > tips on how to make vim into an IDE: > > http://dancingpenguinsoflight.com/2009/02/python-and-vim-make-your-own-ide/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Jan 15 19:38:31 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 15 Jan 2011 13:38:31 -0500 Subject: [Tutor] how come this doesnt work In-Reply-To: References: Message-ID: On 1/15/11, Alan Gauld wrote: > "Alex Hall" wrote > >> m=int(m) >> just before the if statement. This causes m to turn from a string >> into >> an integer and is what is known as "casting" or "type casting", if I >> have my vocabulary correct. > > Sadly you don't although its a common error. > > This is type conversion. You are actually changing the type of m. > > Type casting is something very different and is not really available > in Python (except by underhand use of the struct module!). In type > casting you tell the intertpreter to treat the bit pattern of one > variable > as if it were a different type but do not actually change the > underlying > bit pattern. Its used a lot in low level languages such as C but is > not > very useful in Python. Thanks. That is very interesting, and I never knew that! > > > Sorry to be pedantic, and if you hadn't mentioned correct > vocabulary I probably wouldn't have bothered correcting it. :-) Don't be sorry; it is always good to get terms right, and now I know the difference between casting and type conversion. Very cool. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From karim.liateni at free.fr Sat Jan 15 21:34:20 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 15 Jan 2011 21:34:20 +0100 Subject: [Tutor] end parameter in 2.7.1? In-Reply-To: References: Message-ID: <4D3204CC.7090300@free.fr> IN 3.1 for print(): >>> print('hello', end =' ') hello>>> It suppress the newline character. On 01/15/2011 07:05 PM, Emile van Sebille wrote: > On 1/15/2011 9:35 AM Bill DeBroglie said... >> Twice in two days...! >> >> Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which is >> using Python 3.1. The author uses the end parameter > > What's an 'end' parameter? > > Emile > >> in numerous programs >> but this doesn't seem to translate to 2.7. Any advice as to how I can >> specify the final string of the print function? >> >> Thank you, >> bdb >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From daan.raemdonck at telenet.be Sat Jan 15 18:02:49 2011 From: daan.raemdonck at telenet.be (Daan Raemdonck) Date: Sat, 15 Jan 2011 18:02:49 +0100 Subject: [Tutor] Add rownumber to list of .arff files Message-ID: <4d31d32f.cc7e0e0a.5448.ffff953d@mx.google.com> Dear all, I am reaching out to you because I have a small issue I need to deal with, yet I feel that it requires pretty advanced coding to solve. I have a whole lot of .arff files that would simply need a case number added to every line of data. I've been able to do this for 1 file, but now I need to extend the coding to all files (as there are 100+ files). I have pretty much all the coding, except for the last part of the puzzle, being writing the data back to a file that takes the previous file name and simply adds a prefix 'TRE'. This is the code I have so far: import os, glob path = 'blablabla' for infile in glob.glob( os.path.join(path, '*.arff') ): print "current file is: " + infile lines=infile.readlines() infile.close() outtext = ['%d %s' % (i, line) for i, line in enumerate(lines)] outfile = open("TRE_previous file-name.arff","w") outfile.writelines(outtext) outfile.close() Is there anyone who could give me some guidance on where to take it from here? Thanks in advance. Sincerely, Daan -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Jan 15 21:42:50 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 15 Jan 2011 21:42:50 +0100 Subject: [Tutor] end parameter in 2.7.1? References: Message-ID: Bill DeBroglie wrote: > Twice in two days...! > > Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which > is using Python 3.1. The author uses the end parameter in numerous > programs but this doesn't seem to translate to 2.7. Any advice as to > how I can specify the final string of the print function? You can trick 2.7 into behaving similar to 3.x in that respect with a from __future__ import: Python 2.7.1 (r271:86832, Jan 5 2011, 10:42:58) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from __future__ import print_function >>> print("you are asking for trouble", end="!\n") you are asking for trouble! However, I recommend that you install Python 3.1 in addition to 2.7 and use 3.1 to learn the language. If you don't you'll run into a lot of tiny but frustrating differences. From alan.gauld at btinternet.com Sat Jan 15 21:44:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Jan 2011 20:44:22 -0000 Subject: [Tutor] end parameter in 2.7.1? References: Message-ID: "Bill DeBroglie" wrote > Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which > is using Python 3.1. In 2.7 there should be a way to get print() to work like 3.1... > The author uses the end parameter in numerous programs but this > doesn't seem to translate to 2.7. Any advice as to how I can > specify the final string of the print function? In general terms you need to use string formatting or catenation to add the appropriate end string. In the most common case of simply suppressing the newline just add a comma: v3.1 # suppress newline print(spam end='') v2.x print spam, v3.1 # add arbirary postfix print(value, end=' cents') v2.x print value, " cents", HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From shantanoo at gmail.com Sat Jan 15 21:45:51 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Sun, 16 Jan 2011 02:15:51 +0530 Subject: [Tutor] end parameter in 2.7.1? In-Reply-To: <4D3204CC.7090300@free.fr> References: <4D3204CC.7090300@free.fr> Message-ID: <038E92D3-C6B2-4237-94FD-019DF386DCDF@gmail.com> Python 2.7.1 (r271:86832, Jan 13 2011, 22:08:21) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print('hello', end='') File "", line 1 print('hello', end='') ^ SyntaxError: invalid syntax >>> from __future__ import print_function >>> print('hello', end='') hello>>> HTH. On 16-Jan-2011, at 2:04 AM, Karim wrote: > > IN 3.1 for print(): > > >>> print('hello', end =' ') > hello>>> > > It suppress the newline character. > > > On 01/15/2011 07:05 PM, Emile van Sebille wrote: >> On 1/15/2011 9:35 AM Bill DeBroglie said... >>> Twice in two days...! >>> >>> Using Mac OS X 10.5.8 and Python 2.7.1 but am following a book which is >>> using Python 3.1. The author uses the end parameter >> >> What's an 'end' parameter? >> >> Emile >> >>> in numerous programs >>> but this doesn't seem to translate to 2.7. Any advice as to how I can >>> specify the final string of the print function? >>> >>> Thank you, >>> bdb >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Sat Jan 15 21:48:40 2011 From: karim.liateni at free.fr (Karim) Date: Sat, 15 Jan 2011 21:48:40 +0100 Subject: [Tutor] module to parse XMLish text? In-Reply-To: References: Message-ID: <4D320828.70904@free.fr> Hello, I did not see the XML code in details before I gave the code with ElementTree. In fact with unclosing tags you will get errors at parse time and it will give you the location of errors. You could use the module from Stefan which is way way superior than ElementTree which can validate against DTD or XSD and many many other features (speed, etc...) Regards Karim On 01/15/2011 07:53 AM, Stefan Behnel wrote: > Wayne Werner, 15.01.2011 03:25: >> On Fri, Jan 14, 2011 at 4:42 PM, Terry Carroll wrote: >>> On Fri, 14 Jan 2011, Karim wrote: >>> >>> from xml.etree.ElementTree import ElementTree >>> >>> I don't think straight XML parsing will work on this, as it's not valid >>> XML; it just looks XML-like enough to cause confusion. >> >> It's worth trying out - most (good) parsers "do the right thing" even >> when >> they don't have strictly valid code. I don't know if xml.etree is >> one, but >> I'm fairly sure both lxml and BeautifulSoup would probably parse it >> correctly. > > They wouldn't. For the first tags, the text values would either not > come out at all or they would be read as attributes and thus loose > their order and potentially their whitespace as well. The other tags > would likely get parsed properly, but the parser may end up nesting > them as it hasn't found a closing tag for the previous tags yet. > > So, in any case, you'd end up with data loss and/or a structure that > would be much harder to handle than the (relatively) simple file > structure. > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From brettmurch at gmail.com Sat Jan 15 22:04:10 2011 From: brettmurch at gmail.com (Brett Murch) Date: Sun, 16 Jan 2011 10:04:10 +1300 Subject: [Tutor] defining functions and classes In-Reply-To: <4D319FCC.8000106@ieee.org> References: <1295086215.6283.4.camel@norad> <4D319FCC.8000106@ieee.org> Message-ID: <1295125450.2769.3.camel@norad> On Sat, 2011-01-15 at 08:23 -0500, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Brett Murch wrote: > > Hi everyone, > > > > I'm just starting to learn Python and am starting by creating a text > > game but am having trouble with classes and funtions. I want to create a > > class or function where someone creates a charater and has a choice of > > their name or os. This is what I have so far; > > > > class Administrator(): > > def Skills(name,os): > > name = raw_input('What is your name') > > os = raw_input('What is your os') > > self.name = name > > self.os = os > > > > Skills(name,os) > > > > I keep getting a syntax error on calling it. any ideas on what I'm doing > > wrong? Should it not be a class and should I just define it as a > > function or what? > > > > Thank you in advance > > > > > > What previous experience in programming do you have? You say you're a > beginner in Python, but what other object orientation experience do you > have? > > I don't see any syntax error there. Looks to me like a NameError. When > you get errors, you should copy/paste the whole error into your message, > not just paraphrase it. Anyway, the NameError would occur since Skills > is not a valid global name, it's a method name within a class. And if > you got past that, then the same error would occur with the two > arguments. They're not defined anywhere either. > > You're defining a class called Administrator. That implies you're going > to have many Administrator instances, and presumably each will have > attributes called name and os. If that's true, we can start refining. > > The function to call to create an Administrator instance is called > Administrator(). When you call Administrator(), it will implicitly call > the __init__() method, not the Skills() method. So you probably want to > define such a method. > > Once such an instance is created, you might call the Skills() method to > change the original name and os for it. But Skills() has the wrong > method signature. The first parameter of such a method is 'self', and > you're missing that. And the other two parameters are never used. > > Perhaps you intended something like (untested): > > class Administrator(): > def __init__(self, name="unknown", os="nevernever"): > self.name = name > self.os = os > def change_skills(self): > name = raw_input('What is your new name') > os = raw_input('What is your new os') > self.name = name > self.os = os > > admin1 = Administrator("Harry", "Windoze") > admin1.change_skills() > > > DaveA > Yes thank you it is something like this that I was trying to do. I will have to test this. I don't have any programming experience but have read that Python is the best for beginners. I have a few books that I have been reading but sometimes need things explained a bit better. Thank you for your help on this. BrettM From brettmurch at gmail.com Sat Jan 15 22:07:23 2011 From: brettmurch at gmail.com (Brett Murch) Date: Sun, 16 Jan 2011 10:07:23 +1300 Subject: [Tutor] defining functions and classes In-Reply-To: <4D317846.9060003@pearwood.info> References: <1295086215.6283.4.camel@norad> <4D317846.9060003@pearwood.info> Message-ID: <1295125643.2769.5.camel@norad> Yes you are right it is a Name error because skills was not defined. Sorry will make things more clear in the future. I have it sorted now. Will just start from the beginning and try not to go to fast. On Sat, 2011-01-15 at 21:34 +1100, Steven D'Aprano wrote: > Brett Murch wrote: > > > I keep getting a syntax error on calling it. any ideas on what I'm doing > > wrong? > > Should we *guess*, or would you like to share with us the actual error > you are getting? > > My guess is that you're not getting a syntax error at all, you're > getting a NameError that Skills is not defined. Am I close? > > If my guess is wrong, please copy the *full* error, don't paraphrase it, > retype it from memory, summarise it, or otherwise change it in any way. > > From smokefloat at gmail.com Sat Jan 15 22:42:00 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 15 Jan 2011 16:42:00 -0500 Subject: [Tutor] Add rownumber to list of .arff files In-Reply-To: <4d31d32f.cc7e0e0a.5448.ffff953d@mx.google.com> References: <4d31d32f.cc7e0e0a.5448.ffff953d@mx.google.com> Message-ID: On Sat, Jan 15, 2011 at 12:02 PM, Daan Raemdonck wrote: > Dear all, > > > > I am reaching out to you because I have a small issue I need to deal with, > yet I feel that it requires pretty advanced coding to solve. > > I have a whole lot of .arff files that would simply need a case number added > to every line of data. > > I?ve been able to do this for 1 file, but now I need to extend the coding to > all files (as there are 100+ files). > > > > I have pretty much all the coding, except for the last part of the puzzle, > being writing the data back to a file that takes the previous file name and > simply adds a prefix ?TRE?. > > > > This is the code I have so far: > > > > import os, glob > > path = 'blablabla? > > for infile in glob.glob( os.path.join(path, '*.arff') ): > > ??????????????? print "current file is: " + infile > > ??????????????? lines=infile.readlines() > > ??????????????? infile.close() > > ??????????????? outtext = ['%d %s' % (i, line) for i, line in > enumerate(lines)] > > ??????????????? outfile = open("%s%s"%('TRE',previousfilename,"w") > > ??????????????? outfile.writelines(outtext) > > ??????????????? outfile.close() > If you want to add it in seperately. > > > Is there anyone who could give me some guidance on where to take it from > here? > > > > Thanks in advance. > > > > Sincerely, > > Daan > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Sometimes...my mama...says I get over excited about technology. From smokefloat at gmail.com Sat Jan 15 22:50:20 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 15 Jan 2011 16:50:20 -0500 Subject: [Tutor] Add rownumber to list of .arff files In-Reply-To: References: <4d31d32f.cc7e0e0a.5448.ffff953d@mx.google.com> Message-ID: >>> filename = ['file1','file2','file3'] >>> fileprefix = 'TRE_' >>> for item in filename: print('%s%s'%(fileprefix,item)) ... TRE_file1 TRE_file2 TRE_file3 or with list comp >>> combined = [('%s%s'%(fileprefix,item)) for item in filename] >>> combined ['TRE_file1', 'TRE_file2', 'TRE_file3'] >>> From hacker0100 at hotmail.com Sat Jan 15 23:02:21 2011 From: hacker0100 at hotmail.com (walter weston) Date: Sat, 15 Jan 2011 15:02:21 -0700 Subject: [Tutor] TKinter help Message-ID: I am just starting to learn Tkinter and I was wondering if I should just run tkinter in pythons new findow and run the program. Iv done this before and my python crashed.. plus I want to create a text widget that has a quit box. will pythons IDLE be able to handle this and display the widget ? or are there other IDE's that I need to use? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sat Jan 15 23:21:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jan 2011 09:21:32 +1100 Subject: [Tutor] Python on Ubuntu 10.10? In-Reply-To: References: <4D317017.4050504@gmail.com> Message-ID: <4D321DEC.2090205@pearwood.info> Sean Carolan wrote: > Bite the bullet and learn how to use vim; you won't regret it. > There's a steep learning curve at first but once you get the hang of > it you'll be coding like a boss. Well, I don't know about you, but I've worked for a number of bosses over the years and only one of them could code *at all*, and that not very well. So I'd rather program like a programmer, not a boss, and for that, I find kwrite and kate are just what I'm looking for. (If only they would support plugins written in Python, as gedit does, I'd be set for life.) In any case, fi on your vim. Ed is the only standard text editor: http://www.gnu.org/fun/jokes/ed.msg.html -- Steven From hacker0100 at hotmail.com Sat Jan 15 23:45:29 2011 From: hacker0100 at hotmail.com (walter weston) Date: Sat, 15 Jan 2011 15:45:29 -0700 Subject: [Tutor] Anyone interested in making a Python Help hotline? Message-ID: I thought creating a Python help hotline would help programmers exponential! I think they should make a help hotline for every programming language. and since I havent discovered something similar It would probably be lucretive! -------------- next part -------------- An HTML attachment was scrubbed... URL: From hacker0100 at hotmail.com Sat Jan 15 23:48:19 2011 From: hacker0100 at hotmail.com (walter weston) Date: Sat, 15 Jan 2011 15:48:19 -0700 Subject: [Tutor] Anyone interested in creating a python help hotline? Message-ID: I thought creating a Python help hotline would help programmers exponential! I think they should make a help hotline for every programming language. and since I havent discovered something similar It would probably be lucretive! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Sat Jan 15 23:52:38 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 15 Jan 2011 17:52:38 -0500 Subject: [Tutor] Anyone interested in making a Python Help hotline? In-Reply-To: References: Message-ID: <4D322536.7080103@aim.com> On 01/15/2011 05:45 PM, walter weston wrote: > I thought creating a Python help hotline would help programmers > exponential! I think they should make a help hotline for every > programming language. and since I havent discovered something similar It > would probably be lucretive! > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor irc.freenode.net/python From hacker0100 at hotmail.com Sun Jan 16 00:14:35 2011 From: hacker0100 at hotmail.com (walter weston) Date: Sat, 15 Jan 2011 16:14:35 -0700 Subject: [Tutor] Explain to me Initializing Message-ID: Please explain to me what initializing is,like when you _init_ a function or class . what is _init_ and what does it really do ? do you need it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sun Jan 16 00:28:34 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Jan 2011 15:28:34 -0800 Subject: [Tutor] Anyone interested in making a Python Help hotline? In-Reply-To: References: Message-ID: On 1/15/2011 2:45 PM walter weston said... > > It would probably be lucretive! Really? You'd pay? From kb1pkl at aim.com Sun Jan 16 00:30:56 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 15 Jan 2011 18:30:56 -0500 Subject: [Tutor] Anyone interested in making a Python Help hotline? In-Reply-To: References: Message-ID: <4D322E30.6030903@aim.com> On 01/15/2011 05:45 PM, walter weston wrote: > I thought creating a Python help hotline would help programmers > exponential! I think they should make a help hotline for every > programming language. and since I havent discovered something similar It > would probably be lucretive! > irc.freenode.net/python From kb1pkl at aim.com Sun Jan 16 00:35:16 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 15 Jan 2011 18:35:16 -0500 Subject: [Tutor] Anyone interested in making a Python Help hotline? In-Reply-To: <4D322E30.6030903@aim.com> References: <4D322E30.6030903@aim.com> Message-ID: <4D322F34.60702@aim.com> On 01/15/2011 06:30 PM, Corey Richardson wrote: > On 01/15/2011 05:45 PM, walter weston wrote: >> I thought creating a Python help hotline would help programmers >> exponential! I think they should make a help hotline for every >> programming language. and since I havent discovered something similar It >> would probably be lucretive! >> > > irc.freenode.net/python > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Forgive the double post, having issues with my MUA. From enalicho at gmail.com Sun Jan 16 01:21:29 2011 From: enalicho at gmail.com (Noah Hall) Date: Sun, 16 Jan 2011 00:21:29 +0000 Subject: [Tutor] Explain to me Initializing In-Reply-To: References: Message-ID: Based on the number of emails you're sending to the mailing list, I suggest you read a tutorial, work your way through it, and return with any further issues you come across. http://docs.python.org/tutorial/ is a good start, and I recommend any of the tutorials on http://wiki.python.org/moin/BeginnersGuide/NonProgrammers as a good start. Anyway, to answer your question, read http://docs.python.org/tutorial/classes.html#class-objects http://docs.python.org/reference/datamodel.html#object.__init__ and http://docs.python.org/tutorial/modules.html#packages From steve at pearwood.info Sun Jan 16 02:01:19 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 16 Jan 2011 12:01:19 +1100 Subject: [Tutor] Explain to me Initializing In-Reply-To: References: Message-ID: <4D32435F.6070507@pearwood.info> walter weston wrote: > Please explain to me what initializing is,like when you _init_ a function or class . what is _init_ and what does it really do ? do you need it? Do you know how it is when you get in a car, and turn the key in the ignition, and change into gear, and only then the car is ready to drive forward? That's initializing. As for whether you need to initialize or not, that depends on whether you're driving a car or pedaling a push-bike. Not everything needs special steps before it is ready to use. In Python, when you create a new instance, *if* the class defines __init__, then it will be run to perform the initialization. If you don't need one, don't bother with a pointless "do nothing" __init__. -- Steven From alan.gauld at btinternet.com Sun Jan 16 02:07:49 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jan 2011 01:07:49 -0000 Subject: [Tutor] TKinter help References: Message-ID: "walter weston" wrote > I am just starting to learn Tkinter and I was wondering if I should > just run tkinter in pythons new window and run the program. You don;t run Tkinter, it is just a set of modules like any other. So you run Python as normal, whether from ODLE or from the command line. Older versions of IDLE, being written in Tkinter, got confused so the best advice was wriite the code in IDLE but run it separately. However newer version of IDLE seem better able to cope. Personally, however, I'd still recommend running the code outside IDLE. > ...I want to create a text widget that has a quit box. > will pythons IDLE be able to handle this and display the widget ? IDLE won't display anything but it will run the program which will display the widgets in a separate window. > or are there other IDE's that I need to use? IDLE should be fine if you like it. Just if in doubt try running the code from a command line (or file explorer window). If you are having difficulty it is best to post actual code with actual errors and we can give specific answers. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Jan 16 02:18:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jan 2011 01:18:21 -0000 Subject: [Tutor] Explain to me Initializing References: Message-ID: "walter weston" wrote in message news:BLU151-w4251D1FB9896DC3F8266C5D8F20 at phx.gbl... Please explain to me what initializing is,like when you _init_ a function or class . what is _init_ and what does it really do ? First you don;t init a function, you can init an object. Initializing means setting up the data ready to do work. Its a bit like filling your car with fuel before going on a journey. If there is no fuel the car won't work. Similarly with an object, if the initial values have not been set up properly you will get wrong results. Take a very simple object - a toggle switch. You need to know whether the switch is currently on or off. and you need to toggle it to the opposite setting. But before you can start doing anything you need to set the initial value to either on or off. Otherwise the toggle option makes no sense. class ToggleSwitch: def switch(self): if self.state == 'on': self.state= 'off' else: self.state = 'on' return self.state ts = ToggleSwitch() print ts.state print ts.switch() This code will fail because we have not created a valid variable state which is needed fotr the switch function to work. So we need to initialise the object: class ToggleSwitch: def __init__(self): self.state = 'off' def switch(self): if self.state == 'on': self.state= 'off' else: self.state = 'on' return self.state ts = ToggleSwitch() print ts.state print ts.switch() Now it should work... (but its late so I haven't tested it!) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jamesadrian at globalfreeenterprise.com Sun Jan 16 11:24:52 2011 From: jamesadrian at globalfreeenterprise.com (jamesadrian at globalfreeenterprise.com) Date: Sun, 16 Jan 2011 03:24:52 -0700 Subject: [Tutor] Mac python 3.1.3 installation Message-ID: <20110116032452.9850b4a9ee9f06d3f46ee532e55017ad.aa61694a4f.wbe@email05.secureserver.net> I'm having a lot of trouble getting started. I believe that I have successfully installed python 3.1.3 for Mac on my iMac computer. I have read the readme files that come with the download. I think that Idle is the initial text editor. I know how to use the terminal. I cannot find a written procedure that gets me to the point that I can find a way to write a program. What should I read or do? Thank you for your help. Jim Adrian jamesadrian at globalfreeenterprise.com http://www.globalfreeenterprise.com/ From sksridevnair at gmail.com Sun Jan 16 11:59:13 2011 From: sksridevnair at gmail.com (Sridev Nair) Date: Sun, 16 Jan 2011 16:29:13 +0530 Subject: [Tutor] pySerial port write problem - Windows Error 2 - The system cannot find the file specified Message-ID: Hi all, I am trying to use pySerial to connect to a USB over Serial device. Using, USB monitoring tool, I see that I am able to connect to the port. I could also read data relayed by the device. However, any write on the com port handle is throwing Windows Error 2, The system cannot find the file specified" I am working with pySerial 2.5, Python 2.7 on Windows XP Prof. SP2 Any idea why the write is failing? Any help much appreciated. Regards, Sridev --------------------Code------------------------------ import serial try: port = serial.Serial('\\\\.\\COM10',timeout=2) print "Successfully opened the com port." print port except: print "Failed to initialize com port" print port.write("020200013803") ---------------Code--------------------------------------- ----------------Output------------------------------------ Serial(port='\\\\.\\COM10', baudrate=9600, bytesize=8, p arity='N', stopbits=1, timeout=2, xonxoff=0, rtscts=0, dsrdtr=0) WriteFile failed, 2: The system cannot find the file specified ------------------Output---------------------------------- On digging into serialwin32.py line >>err = win32.WriteFile(self.hComPort, data, len(data), ctypes.byref(n), self._overlappedWrite) I see that self.hComPort = 1948 which is the valid handle created while opening the port. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 16 12:17:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Jan 2011 11:17:42 -0000 Subject: [Tutor] Mac python 3.1.3 installation References: <20110116032452.9850b4a9ee9f06d3f46ee532e55017ad.aa61694a4f.wbe@email05.secureserver.net> Message-ID: wrote > successfully installed python 3.1.3 for Mac on my iMac computer. I > have > read the readme files that come with the download. I think that > Idle is > the initial text editor. I know how to use the terminal. I cannot > find > a written procedure that gets me to the point that I can find a way > to > write a program. What should I read or do? Have you programmed before in any other language? If so just follow through the official tutorial on the Python web site. If not go to the Non Programmers page and pick a tutorial from there. They should all help you get started, although perhaps not Mac specific. The fast answer to your question is that you create a text file with an extension of .py (Textpad could be used but IDLE or any other Python-aware editor would be better). Then from the command prompt run it by typing: $ python myscript.py If you use IDLE you can run the script from inside IDLE too. Look at the "Getting Started" and "More Sequences" topics in my tutorial for more details. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From daan.raemdonck at telenet.be Sun Jan 16 13:03:03 2011 From: daan.raemdonck at telenet.be (Daan Raemdonck) Date: Sun, 16 Jan 2011 13:03:03 +0100 Subject: [Tutor] Add rownumber to list of .arff files In-Reply-To: References: <4d31d32f.cc7e0e0a.5448.ffff953d@mx.google.com> Message-ID: <4d32de6f.ce7c0e0a.6d2d.ffffbaeb@mx.google.com> Thank you David! I've incorporated your parts into my code, and after some fiddling it worked! I've kept the glob.glob though because having to type all filenames (as in your code) would take me too long. Solved problem: Add a casenumber to every line in a directory filled with .arff files, write back to same filename prefixed with TRE_ Code: import os, glob fileprefix = 'TRE_' path = '/bla/example/' for infile in glob.glob( os.path.join(path, '*.arff') ): print "current file is: " + infile lines= open(infile).readlines() (filepath, filename) = os.path.split(infile) outname = ('%s%s'%(fileprefix,filename)) outtext = ['%d %s' % (i, line) for i, line in enumerate(lines)] outfile = open(outname, "w") outfile.writelines(outtext) outfile.close() Sincerely, Daan -----Original Message----- From: David Hutto [mailto:smokefloat at gmail.com] Sent: zaterdag 15 januari 2011 22:50 To: Daan Raemdonck Cc: tutor at python.org Subject: Re: [Tutor] Add rownumber to list of .arff files >>> filename = ['file1','file2','file3'] >>> fileprefix = 'TRE_' >>> for item in filename: print('%s%s'%(fileprefix,item)) ... TRE_file1 TRE_file2 TRE_file3 or with list comp >>> combined = [('%s%s'%(fileprefix,item)) for item in filename] >>> combined ['TRE_file1', 'TRE_file2', 'TRE_file3'] >>> From hacker0100 at hotmail.com Mon Jan 17 00:40:20 2011 From: hacker0100 at hotmail.com (walter weston) Date: Sun, 16 Jan 2011 16:40:20 -0700 Subject: [Tutor] Calaculating a monthly total of earning Message-ID: Heres my code: def income_report(yearly_income,hourly_income): """ this will count the average of your total monthly income""" sum_of_monthly=int(yearly_income/12)# his yearly income dividing by 12. minus_weekends=hourly_income*64 #the 64 is the two days off for the weekend(assuming working an 8 hour shift) #and there are 4 weekends in a month so 1 weekend=16 hours so 4 weekends would be 64 hours now working #now I must subtract that from the monthly income(sum_of_monthly) total_income=int(minus_weekends-sum_of_monthly) #this is the money thats subtracted to the monthly total not working from the weekends return sum_of_monthly,total_income I call income_report with some like income_report(200000,12) and I get numbers printed like (16666, -15898) the second argument is to much and its negative and when I multiply 16666 by 12 to see if sum_of_monthly did its job correctly I get a number thats off , I got 199992 not 200000.Python is so tempormential what is wrong with my code? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 17 01:32:45 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Jan 2011 00:32:45 -0000 Subject: [Tutor] Calaculating a monthly total of earning References: Message-ID: "walter weston" wrote > def income_report(yearly_income,hourly_income): > sum_of_monthly=int(yearly_income/12)# his yearly income dividing > by 12. > minus_weekends=hourly_income*64 > total_income=int(minus_weekends-sum_of_monthly) > return sum_of_monthly,total_income When you divide you get a decimal result which you then convert to an integer - a whole number - so you lose the fractional part. When you multiply by 12 you get 12 times the integer not the original number. And for total_income shouldn't the subraction be the other way around? > Python is so tempormential what is wrong with my code? Python is not temperamental, it is just doing exactly what you ask it to do. It makes no judgement about whether what you are asking is sensible or not. One of the more humbling things about programming is that you become accutely aware of your own ability to screw things up! ;-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From enalicho at gmail.com Mon Jan 17 01:41:26 2011 From: enalicho at gmail.com (Noah Hall) Date: Mon, 17 Jan 2011 00:41:26 +0000 Subject: [Tutor] Calaculating a monthly total of earning In-Reply-To: References: Message-ID: > ??? minus_weekends=hourly_income*64 > ??? total_income=int(minus_weekends-sum_of_monthly) Here's problem number 1 - you're taking the values the wrong way around :) It should be total_income=int(sum_of_monthly-minus_weekends) > ??? sum_of_monthly=int(yearly_income/12) Here's the second problem you encountered. The problem derives from the fact that the operation is using two integers, which returns an integer. Integer division and the int function rounds down, as it were - 7/6 will give you 1, int(5.9) will give you 5. This gives you 16666 when you use 200000, due to rounding down, whereas the answer you want is 200000/12.0 (16666.666666666668). I suggest you don't use int here yet, and use 12.0 instead of 12, in order to get a float as you are performing further operations with the result, which will suffer due to a loss of accuracy. From beachkidken at gmail.com Mon Jan 17 02:40:36 2011 From: beachkidken at gmail.com (Ken Green) Date: Sun, 16 Jan 2011 20:40:36 -0500 Subject: [Tutor] Calaculating a monthly total of earning In-Reply-To: References: Message-ID: <4D339E14.40500@gmail.com> Alan, the last two paragraphs you wrote is classic. Very, very true. LOL. Ken On 01/16/2011 07:32 PM, Alan Gauld wrote: > >> Python is so tempormential what is wrong with my code? > > Python is not temperamental, it is just doing exactly what you ask it > to do. > It makes no judgement about whether what you are asking is sensible or > not. > > One of the more humbling things about programming is that you become > acutely aware of your own ability to screw things up! ;-) > From zhengqinggan at gmail.com Mon Jan 17 05:37:04 2011 From: zhengqinggan at gmail.com (zhengqing gan) Date: Sun, 16 Jan 2011 20:37:04 -0800 Subject: [Tutor] question about manipulate images! Message-ID: Hi, All: I have a question about manipulating images. If I have a image, is there a kind of algorithm to convert it into kind of Iphone icon style? part transparent, gradient.... Thanks! From chester_lab at fltg.net Mon Jan 17 04:01:34 2011 From: chester_lab at fltg.net (FT) Date: Sun, 16 Jan 2011 22:01:34 -0500 Subject: [Tutor] Writing Python Script to read battery level Message-ID: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> Allan, Is there a way to read the battery level using Python? I am totally blind and want to write a script to capture the battery level and send it through the voice activeX so I can speak it... Bruce From alan.gauld at btinternet.com Mon Jan 17 10:57:20 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 17 Jan 2011 09:57:20 +0000 (GMT) Subject: [Tutor] Writing Python Script to read battery level In-Reply-To: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> References: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> Message-ID: <748499.34940.qm@web86704.mail.ird.yahoo.com> > Is there a way to read the battery level using Python? > > I am totally blind and want to write a script to capture > the battery level and send it through the voice activeX so I can speak it... An interesting project. Unfortunately I don't know enough about how PCs do that kind of low level monitoring. Given that Windows displays the battery level in the system tray I'm assuming there will be a Windows API Call that can do it. If thats the case then yes you should be able to do that from Python via Pythonwin or ctypes. You will need to do some searching of the Microsoft documentation. I'd start with the MDSN web site... It will probably take a bit of experimentation to get right but Pytthon is good for doing that kind of work using the interactive prompt. Somebody else might have a more specific answer. Alan G. From mail at timgolden.me.uk Mon Jan 17 11:07:30 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Jan 2011 10:07:30 +0000 Subject: [Tutor] Writing Python Script to read battery level In-Reply-To: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> References: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> Message-ID: <4D3414E2.1080207@timgolden.me.uk> On 17/01/2011 03:01, FT wrote: > Is there a way to read the battery level using Python? > > I am totally blind and want to write a script to capture the battery > level and send it through the voice activeX so I can speak it... WMI should be able to query the battery information: import wmi c = wmi.WMI () for battery in c.Win32_Battery (): print battery.Caption, battery.EstimatedChargeRemaining The pure-python wmi module is based here: http://timgolden.me.uk/python/wmi/index.html and can be installed via easy_install / pip. Information on the attributes of the Win32_Battery class are available here: http://msdn.microsoft.com/en-us/library/aa394074%28v=vs.85%29.aspx You might also be interested in the pyttsx project (successor to the Windows-specific pytts): http://pypi.python.org/pypi/pyttsx/1.0 although if you have existing code to work with an ActiveX control then I doubt it brings you any advantages. TJG From python at bdurham.com Mon Jan 17 12:02:50 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 17 Jan 2011 06:02:50 -0500 Subject: [Tutor] Writing Python Script to read battery level In-Reply-To: <748499.34940.qm@web86704.mail.ird.yahoo.com> References: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> <748499.34940.qm@web86704.mail.ird.yahoo.com> Message-ID: <1295262170.26155.1415686221@webmail.messagingengine.com> FT, > Is there a way to read the battery level using Python? Check out the following code snippet: Get info on power/battery status http://nullege.com/codes/show/src at jaraco.windows-1.6@jaraco at windows@power.py/14/ctypes.wintypes.BOOL This code snippet requires the following 3rd party packages: 1. Mark Hammond's pywin32 (comes bundled with ActiveState versions of Python) https://sourceforge.net/projects/pywin32/ 2. Tim Golden's wmi (requires pywin32) http://timgolden.me.uk/python/wmi.html There's also a Python mailing list dedicated to Windows API questions: http://mail.python.org/mailman/listinfo/python-win32 Good luck! Malcolm From chrysalis_reborn at yahoo.com Mon Jan 17 12:33:47 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 17 Jan 2011 03:33:47 -0800 (PST) Subject: [Tutor] question about manipulate images! In-Reply-To: Message-ID: <365802.74399.qm@web130203.mail.mud.yahoo.com> --- On Sun, 1/16/11, zhengqing gan wrote: > From: zhengqing gan > Subject: [Tutor] question about manipulate images! > To: tutor at python.org > Date: Sunday, January 16, 2011, 11:37 PM > Hi, All: > ? ???I have a question about > manipulating images. > ? ???If I have a image, is there a kind > of algorithm to convert it > into kind of Iphone icon style? part transparent, > gradient.... > ? ???Thanks! You might be better off using a program like Photoshop, The Gimp, or perhaps even Inkscape for this. From alan.gauld at btinternet.com Mon Jan 17 12:55:10 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Jan 2011 11:55:10 -0000 Subject: [Tutor] question about manipulate images! References: Message-ID: "zhengqing gan" wrote > I have a question about manipulating images. In Python that usually translates to use PIL... > If I have a image, is there a kind of algorithm to convert it > into kind of Iphone icon style? part transparent, gradient.... PIL can do most of that but you will need to understand exactly which transformations you need to apply which will require some background research on your part. wikipedia is always a good starting point. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From izzaddin.ruhulessin at gmail.com Mon Jan 17 14:07:22 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 17 Jan 2011 14:07:22 +0100 Subject: [Tutor] Refcount in C extensions In-Reply-To: References: Message-ID: Hi Steve, Your remarks about Cython pushed me over the edge into the Unknown, this weekend I decided to download it and check it out. I've been using it the past few days and it totally rocks. It really feels like I was chained before and now I'm not; like where some simple Python operations could require tens or even hundreds of lines of code, Cython make life easi?r. A real life-saver, thanks! I also like how simple it is to import C functions to python, btw. Kind regards, Izz ad-Din 2011/1/14 Stefan Behnel > Izz ad-Din Ruhulessin, 14.01.2011 19:49: > > Thanks for your quick reply and clearing the issue up for me. Using your >> answer, I rewrote the function to this: >> >> double Py_GetAttr_DoubleFromFloat(PyObject *obj, const char *attr) >> >>> >>> { >>> >>> PyObject *get_attr, *py_float; >>> >>> int has_attr; >>> >>> >>> //Check if the given object has the given attribute. >>>> >>> >>> has_attr = PyObject_HasAttrString(obj, attr); >>> >>> if (has_attr == False) { >>> >>> return -9999.0; >>> >>> } >>> >>> >>> //Get our attribute and convert it to a double. >>>> >>> >>> get_attr = PyObject_GetAttrString(obj, attr); >>> >> > Note that HasAttr() calls GetAttr() internally, so it's actually faster to > call GetAttr() and check for an exception (and clear it). That's basically > how HasAttr() works, except that it doesn't tell you the result if the > attribute existed. > > > > py_float = PyNumber_Float(get_attr); >>> >>> if (py_float == NULL) { >>> >>> Py_DECREF(get_attr); >>> >>> Py_XDECREF(py_float); >>> >> > You already know that py_float is NULL, so Py_XDECREF() is a no-op. > > > > return -9999.0; >>> >>> } >>> >>> double output = PyFloat_AsDouble(py_float); >>> >>> >>> //Garbage collect >>>> >>> >>> Py_DECREF(get_attr); >>> >>> Py_XDECREF(py_float); >>> >> > py_float cannot be NULL at this point, so the Py_XDECREF() will compile > into Py_DECREF(). > > > (False is 0) >> > > In that case, better write 0 instead. > > > > Regarding your Cython suggestion, as a matter of coincidence I have been >> reading about it in the past few days. I'm in doubt of using it however, >> because I have a lot of native C code that would require rewriting if I >> switched to Cython. >> > > No need for that, Cython can call external C code natively. So you can make > the switch step by step. > > > > On the other hand, your example shows that such a >> one-time rewrite will pay-off big time in future development speed. >> > > It usually does, yes. It often even pays off immediately because a rewrite > tends to be pretty straight forward (basically, read and understand the C > code, rip out all low-level stuff and replace the rest with simpler code), > and while doing so, some bugs tend to disappear, the code becomes simpler, > safer and often also faster, and new features appear while you're at it. > > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zhengqinggan at gmail.com Mon Jan 17 16:34:53 2011 From: zhengqinggan at gmail.com (zhengqing gan) Date: Mon, 17 Jan 2011 07:34:53 -0800 Subject: [Tutor] question about manipulate images! In-Reply-To: <365802.74399.qm@web130203.mail.mud.yahoo.com> References: <365802.74399.qm@web130203.mail.mud.yahoo.com> Message-ID: Hi, Thanks for the reply. But I found that there are some website which can convert images into iphone icon style images, there should be an kind of algorithm to manipulate. Thanks! On Mon, Jan 17, 2011 at 3:33 AM, Elwin Estle wrote: > > > --- On Sun, 1/16/11, zhengqing gan wrote: > >> From: zhengqing gan >> Subject: [Tutor] question about manipulate images! >> To: tutor at python.org >> Date: Sunday, January 16, 2011, 11:37 PM >> Hi, All: >> ? ???I have a question about >> manipulating images. >> ? ???If I have a image, is there a kind >> of algorithm to convert it >> into kind of Iphone icon style? part transparent, >> gradient.... >> ? ???Thanks! > > You might be better off using a program like Photoshop, The Gimp, or perhaps even Inkscape for this. > > > > From eduardo.susan at gmail.com Mon Jan 17 19:30:45 2011 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 17 Jan 2011 11:30:45 -0700 Subject: [Tutor] question about manipulate images! Message-ID: Hi. Try to find a tutorial on the steps to achieve such effect in a graphic program. Then map it to the scrpting steps to do the same with pil, python for gimp, for inkscape or simply Imagemagick. On 2011-01-17 8:37 AM, "zhengqing gan" wrote: Hi, Thanks for the reply. But I found that there are some website which can convert images into iphone icon style images, there should be an kind of algorithm to manipulate. Thanks! On Mon, Jan 17, 2011 at 3:33 AM, Elwin Estle wrote: > > > --- On Sun,... -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Mon Jan 17 19:35:52 2011 From: wallenpb at gmail.com (Bill Allen) Date: Mon, 17 Jan 2011 12:35:52 -0600 Subject: [Tutor] Writing Python Script to read battery level In-Reply-To: <4D3414E2.1080207@timgolden.me.uk> References: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> <4D3414E2.1080207@timgolden.me.uk> Message-ID: Tim, Thanks for posting this. I have several uses for this WMI module at my work. --Bill On Mon, Jan 17, 2011 at 04:07, Tim Golden wrote: > On 17/01/2011 03:01, FT wrote: > >> Is there a way to read the battery level using Python? >> >> I am totally blind and want to write a script to capture the battery >> level and send it through the voice activeX so I can speak it... >> > > WMI should be able to query the battery information: > > > import wmi > > c = wmi.WMI () > for battery in c.Win32_Battery (): > print battery.Caption, battery.EstimatedChargeRemaining > > > > The pure-python wmi module is based here: > > http://timgolden.me.uk/python/wmi/index.html > > and can be installed via easy_install / pip. > > Information on the attributes of the Win32_Battery class are > available here: > > http://msdn.microsoft.com/en-us/library/aa394074%28v=vs.85%29.aspx > > > You might also be interested in the pyttsx project > (successor to the Windows-specific pytts): > > http://pypi.python.org/pypi/pyttsx/1.0 > > although if you have existing code to work with an ActiveX > control then I doubt it brings you any advantages. > > TJG > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Mon Jan 17 19:40:37 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 17 Jan 2011 18:40:37 +0000 Subject: [Tutor] Writing Python Script to read battery level In-Reply-To: References: <4FFD499F5BB64C24A65844E8796D54D1@1B1B1L1> <4D3414E2.1080207@timgolden.me.uk> Message-ID: <4D348D25.5020603@timgolden.me.uk> On 17/01/2011 18:35, Bill Allen wrote: > Tim, > > Thanks for posting this. I have several uses for this WMI module at > my work. Glad it's useful... TJG From kb1pkl at aim.com Mon Jan 17 19:47:48 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Mon, 17 Jan 2011 13:47:48 -0500 Subject: [Tutor] question about manipulate images! In-Reply-To: References: <365802.74399.qm@web130203.mail.mud.yahoo.com> Message-ID: <4D348ED4.40802@aim.com> On 01/17/2011 10:34 AM, zhengqing gan wrote: > Hi, > Thanks for the reply. > But I found that there are some website which can convert images > into iphone icon style images, there should be an kind of algorithm to > manipulate. > Thanks! > > >From playing with http://wizardtoolkit.com/shooter/iPhone-Icon-Generator, it appears all that needs to be done is add a semi- or completely-transparent ovalish blob on the top, and possibly a metallic looking frame. While I'm sure you could take the (probably) tens to hundreds of hours finding a mathematical formula to define that, you can probably just whip up some semi-transparent blobs in GIMP/Photoshop/what-have-you and a metallic frame. Then you can use PIL to combine them. Try: http://python-forum.com/pythonforum/viewtopic.php?f=3&t=3462&start=0 http://stackoverflow.com/questions/3374878/with-the-python-imaging-library-pil-how-does-one-compose-an-image-with-an-alph ~Corey From izzaddin.ruhulessin at gmail.com Mon Jan 17 20:29:47 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 17 Jan 2011 20:29:47 +0100 Subject: [Tutor] Exactly duplicating strftime behavior? Message-ID: Hi all, I'm designing a module which aims to provide full compatibility with Pythons' datetime module. However, I can't find out how some operators in strftime function, namely: those who use the locale. (%a, %A, %b, etc.) How do I access this locale and it's values? Thanks in advance. Kind regards, Izz ad-Din -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Mon Jan 17 20:39:45 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 17 Jan 2011 20:39:45 +0100 Subject: [Tutor] What is __weakref__ ? Message-ID: <4D349B01.1030004@free.fr> Hello, I am wondering what is this special class attribut. I know __dict__, slots. I use slots = [] when I want to use a read only class. But is anyone could explain with a little example the use of __weakref__? Regards karim From karim.liateni at free.fr Mon Jan 17 22:47:48 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 17 Jan 2011 22:47:48 +0100 Subject: [Tutor] Why super does not work ! Message-ID: <4D34B904.5090100@free.fr> Hello, I implemented Observer DP on a listbox (Tkinter) as follows and I don't understand why super() is not working and Observable.__init__(self) is working, cf below: class ListObservable(Listbox, Observable): """Creation de widget Listbox""" def __init__(self): super(ListObservable, self).__init__() #Observable.__init__(self) self._value = None self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys()))) self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') self.liste.grid(row=0, column=1, sticky=N+S+W) self.liste.bind('', self.onSelect) _The error is:_ Traceback (most recent call last): File "./observerAppliGraphique.py", line 118, in app=App() File "./observerAppliGraphique.py", line 37, in __init__ self.sujet.attach(self.nom) File "/home/karim/guiObserver/observable.py", line 11, in attach self._observers.append(observer) AttributeError: 'ListObservable' object has no attribute '_observers' And the Observable class is: class Observable(object): """Sujet a observer""" def __init__(self): self._observers = [] print('constructeur observable') def attach(self, observer): """Attache un nouvel observateur""" self._observers.append(observer) def detach(self, observer): """Retire un nouvel observateur""" self._observers.remove(observer) def notify(self): """Avertit tous les observateurs que l'observable change d'etat""" for observer in self._observers: observer.update() -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Mon Jan 17 22:53:08 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Mon, 17 Jan 2011 22:53:08 +0100 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D34B904.5090100@free.fr> References: <4D34B904.5090100@free.fr> Message-ID: It looks like because of something Observable doesn't have that attribute. Could you post the ListBox class? 2011/1/17 Karim > > > Hello, > > I implemented Observer DP on a listbox (Tkinter) as follows and I don't > understand why super() is not working and Observable.__init__(self) is > working, cf below: > > class ListObservable(Listbox, Observable): > """Creation de widget Listbox""" > def __init__(self): > super(ListObservable, self).__init__() > #Observable.__init__(self) > self._value = None > self.listeContenu = StringVar() > self.listeContenu.set(' '.join(sorted(data_base.keys()))) > self.liste = Listbox(listvariable=self.listeContenu, > selectmode='single') > self.liste.grid(row=0, column=1, sticky=N+S+W) > self.liste.bind('', self.onSelect) > > *The error is:* > Traceback (most recent call last): > File "./observerAppliGraphique.py", line 118, in > app=App() > File "./observerAppliGraphique.py", line 37, in __init__ > self.sujet.attach(self.nom) > File "/home/karim/guiObserver/observable.py", line 11, in attach > self._observers.append(observer) > AttributeError: 'ListObservable' object has no attribute '_observers' > > And the Observable class is: > > class Observable(object): > """Sujet a observer""" > def __init__(self): > self._observers = [] > print('constructeur observable') > > def attach(self, observer): > """Attache un nouvel observateur""" > self._observers.append(observer) > > def detach(self, observer): > """Retire un nouvel observateur""" > self._observers.remove(observer) > > def notify(self): > """Avertit tous les observateurs que l'observable change d'etat""" > for observer in self._observers: > observer.update() > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Jan 17 23:22:50 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Jan 2011 09:22:50 +1100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D349B01.1030004@free.fr> References: <4D349B01.1030004@free.fr> Message-ID: <4D34C13A.2060409@pearwood.info> Karim wrote: > > Hello, > > I am wondering what is this special class attribut. I know __dict__, > slots. I use slots = [] when I want to use a read only class. (1) slots = [] doesn't do anything special. You have misspelled __slots__. (2) Classes don't become read only just because you add __slots__ to them. All you prevent is adding extra attributes, and why would you wish to do that? What harm does it do to you if the caller wants to add extra information to your class instances? All that does is make your class less useful. I have often wished I could add extra attributes to builtins like strings, ints, lists and so forth, but you can't: >>> result = 42 >>> result.extra_info = 0.1 Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'extra_info' I understand why this is the case -- it's a memory optimization -- but it's a bloody nuisance. Don't repeat it if you don't have to. (3) Even if it worked the way you think it works, it is an abuse of __slots__. __slots__ is not a mechanism for "read only classes", it is a memory optimization for when you need tens or hundreds of millions of instances. > But is anyone could explain with a little example the use of __weakref__? Have you read the Fine Manual? http://docs.python.org/reference/datamodel.html#slots >>> class K1(object): ... __slots__ = [] # Don't support weak-refs. ... >>> class K2(object): ... __slots__ = '__weakref__' # Do support weak-refs. ... >>> import weakref >>> k1 = K1() >>> k2 = K2() >>> weakref.ref(k1) Traceback (most recent call last): File "", line 1, in TypeError: cannot create weak reference to 'K1' object >>> weakref.ref(k2) -- Steven From davea at ieee.org Mon Jan 17 23:36:32 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 17 Jan 2011 17:36:32 -0500 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D34B904.5090100@free.fr> References: <4D34B904.5090100@free.fr> Message-ID: <4D34C470.8070600@ieee.org> On 01/-10/-28163 02:59 PM, Karim wrote: > > > Hello, > > I implemented Observer DP on a listbox (Tkinter) as follows and I don't > understand why super() is not working and Observable.__init__(self) is > working, cf below: > > class ListObservable(Listbox, Observable): > """Creation de widget Listbox""" > def __init__(self): > super(ListObservable, self).__init__() > #Observable.__init__(self) > self._value = None > self.listeContenu = StringVar() > self.listeContenu.set(' '.join(sorted(data_base.keys()))) > self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') > self.liste.grid(row=0, column=1, sticky=N+S+W) > self.liste.bind('', self.onSelect) > > _The error is:_ > Traceback (most recent call last): > File "./observerAppliGraphique.py", line 118, in > app=App() > File "./observerAppliGraphique.py", line 37, in __init__ > self.sujet.attach(self.nom) > File "/home/karim/guiObserver/observable.py", line 11, in attach > self._observers.append(observer) > AttributeError: 'ListObservable' object has no attribute '_observers' > > And the Observable class is: > > class Observable(object): > """Sujet a observer""" > def __init__(self): > self._observers = [] > print('constructeur observable') > > def attach(self, observer): > """Attache un nouvel observateur""" > self._observers.append(observer) > > def detach(self, observer): > """Retire un nouvel observateur""" > self._observers.remove(observer) > > def notify(self): > """Avertit tous les observateurs que l'observable change d'etat""" > for observer in self._observers: > observer.update() > Just looking at what you supply, I'd suppose that ListBox doesn't correctly call super() in its own __init__() method. So I took a look at Tkinter.py, and sure enough, it just calls its own direct parent, Widget.l super() only works if all the classes you use are done consistently. DaveA From rabidpoobear at gmail.com Mon Jan 17 23:37:23 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 17 Jan 2011 16:37:23 -0600 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D34B904.5090100@free.fr> References: <4D34B904.5090100@free.fr> Message-ID: I think it might be related to your multiple inheritance, maybe super is calling the init of observable on the listbox portion or something? I hardly ever do multiple inheritance so I'm not sure. What happens if you swap observable to be the first one? ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 17, 2011, at 3:47 PM, Karim wrote: > > > Hello, > > I implemented Observer DP on a listbox (Tkinter) as follows and I don't understand why super() is not working and Observable.__init__(self) is working, cf below: > > class ListObservable(Listbox, Observable): > """Creation de widget Listbox""" > def __init__(self): > super(ListObservable, self).__init__() > #Observable.__init__(self) > self._value = None > self.listeContenu = StringVar() > self.listeContenu.set(' '.join(sorted(data_base.keys()))) > self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') > self.liste.grid(row=0, column=1, sticky=N+S+W) > self.liste.bind('', self.onSelect) > > The error is: > Traceback (most recent call last): > File "./observerAppliGraphique.py", line 118, in > app=App() > File "./observerAppliGraphique.py", line 37, in __init__ > self.sujet.attach(self.nom) > File "/home/karim/guiObserver/observable.py", line 11, in attach > self._observers.append(observer) > AttributeError: 'ListObservable' object has no attribute '_observers' > > And the Observable class is: > > class Observable(object): > """Sujet a observer""" > def __init__(self): > self._observers = [] > print('constructeur observable') > > def attach(self, observer): > """Attache un nouvel observateur""" > self._observers.append(observer) > > def detach(self, observer): > """Retire un nouvel observateur""" > self._observers.remove(observer) > > def notify(self): > """Avertit tous les observateurs que l'observable change d'etat""" > for observer in self._observers: > observer.update() > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From hugo.yoshi at gmail.com Mon Jan 17 23:58:32 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 17 Jan 2011 23:58:32 +0100 Subject: [Tutor] Exactly duplicating strftime behavior? In-Reply-To: References: Message-ID: On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin wrote: > Hi all, > I'm designing a module which aims to provide full compatibility with > Pythons' datetime module. > However, I can't find out how some operators in strftime function, namely: > those who use the locale. (%a, %A, %b, etc.) > How do I access this locale and it's values? > Thanks in advance. > Kind regards, > Izz ad-Din Check out the locale module: http://docs.python.org/library/locale.html#locale.nl_langinfo HTH, Hugo From steve at pearwood.info Tue Jan 18 00:09:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 18 Jan 2011 10:09:35 +1100 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D34B904.5090100@free.fr> References: <4D34B904.5090100@free.fr> Message-ID: <4D34CC2F.1010707@pearwood.info> Karim wrote: > > > Hello, > > I implemented Observer DP on a listbox (Tkinter) as follows and I don't > understand why super() is not working and Observable.__init__(self) is > working, cf below: You seem to be confused about your class design. On the one hand, you inherit from Listbox, but then you *also* use composition and/or delegation on a Listbox instance: class ListObservable(Listbox, Observable): def __init__(self): [...] self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') That means that a ListObservable instance both *is* a Listbox and *contains* a Listbox at the same time. I'm not saying this is necessarily wrong, but it is unusual, and confuses the model. At the very least, you need to document why you have done this. > class ListObservable(Listbox, Observable): > """Creation de widget Listbox""" > def __init__(self): > super(ListObservable, self).__init__() > #Observable.__init__(self) Are both Listbox and Observable documented as suitable for multiple inheritance? My guess is that Listbox is not, and I can see from your source code that Observable is *not* suitable for multiple inheritance. If Listbox is documented as suitable for multiple inheritance, then it is a bug in Listbox. If it is not, then it is a bug in your code, by using it for multiple inheritance. Multiple inheritance in Python is cooperative, not enforced, and it is tricky to get right and is *very* sensitive to any class which fails to cooperate. Thousands and thousands of words have been written on the perils and difficulties of multiple inheritance, particularly by Michele Simionato who I consider to be THE authority on MI in Python. Some of the most important articles are: Michele Simionato: Things to Know About Python Super http://www.artima.com/weblogs/viewpost.jsp?thread=236275 http://www.artima.com/weblogs/viewpost.jsp?thread=236278 http://www.artima.com/weblogs/viewpost.jsp?thread=237121 Mixins considered harmful: http://www.artima.com/weblogs/viewpost.jsp?thread=246341 http://www.artima.com/weblogs/viewpost.jsp?thread=246483 http://www.artima.com/weblogs/viewpost.jsp?thread=254367 http://www.artima.com/weblogs/viewpost.jsp?thread=254507 Generic functions vs mixins: http://www.artima.com/weblogs/viewpost.jsp?thread=237764 Straits: http://www.artima.com/weblogs/viewpost.jsp?thread=246488 James Knight: Python's Super Considered Harmful http://fuhm.net/super-harmful/ Summary: this is *not* a bug in super. It's really a side-effect of the fact that multiple inheritance itself is often the wrong thing to use, and even when it is right, it is often tricky to get it right. To put it another way: don't use multiple inheritance unless you have to, there are better ways, such as by composition. -- Steven From alan.gauld at btinternet.com Tue Jan 18 02:32:39 2011 From: alan.gauld at btinternet.com (Alan G) Date: Tue, 18 Jan 2011 01:32:39 +0000 (UTC) Subject: [Tutor] Why super does not work ! References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> Message-ID: Steven D'Aprano pearwood.info> writes: > fact that multiple inheritance itself is often the wrong thing to use, > and even when it is right, it is often tricky to get it right. To put it > another way: don't use multiple inheritance unless you have to, there > are better ways, such as by composition. Or use a language where MI is the normal and idiomatic way to do things because the language assumes it and so it just works. There are very few such languages but Lisp is one :-) Sadly Python isn't, and when using MI I always avoid super() Which is a huge shame since MI is where super() should be most useful... But in my experience MI in Python is definitely a place where explicit is better than implicit. Alan G. From karim.liateni at free.fr Tue Jan 18 07:31:10 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 07:31:10 +0100 Subject: [Tutor] Why super does not work ! In-Reply-To: References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> Message-ID: <4D3533AE.4050702@free.fr> Thanks Izz, Luke, Steven and Alan! That's I figured out with MI and super. Steven I understand the point to have Listbox contains a Listbox. Before the code was in App class and I extracted it to do an outside class making the mistake. But magic of Python it's working (but I know it's awful). The code is working but I am not totally happy because of many EntryObserver almost identical objects (except from update and grid() options) Is it possible to simplify this structure? Regards Karim The rest of the code is below: #!/usr/bin/env python2.7 """Module ObserverGraphique.py Une implementation du design pattern Observer. """ from Tkinter import * from observable import Observable from observer import AbstractObserver data_base = { 'Employe1': ['Joel', 'Durant', '0623'], 'Employe2': ['Marc', 'Donce', '0624'], 'Employe3': ['George', 'Roux', '0625'], 'Employe4': ['Alain', 'Richard', '0626'] } __all__ = ['App', 'ListObservable', 'Entry1Observer', 'Entry2Observer', 'Entry3Observer'] class App(Frame): """Application graphique avec Tkinter implementant un Observer Design Pattern.""" def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Exemple : Observer Design Pattern") self.grid() self.createLabels() self.createObservable() self.createObservers() self.registerObservers() def createLabels(self): """Creation de widgets Label""" self.label1 = Label(text="Nom :") self.label2 = Label(text="Prenom :") self.label3 = Label(text="Poste :") self.label1.grid(row=1, column=1, sticky=W) self.label2.grid(row=2, column=1, sticky=W) self.label3.grid(row=3, column=1, sticky=W) def createObservable(self): """Creation de la listBox observable.""" self.sujet = ListObservable() def createObservers(self): """Creation des champs d'entre texte observateurs de la liste.""" self.nom = Entry1Observer(self.sujet) self.prenom = Entry2Observer(self.sujet) self.poste = Entry3Observer(self.sujet) def registerObservers(self): """Enregistrement des observateurs.""" self.sujet.attach(self.nom) self.sujet.attach(self.prenom) self.sujet.attach(self.poste) class ListObservable(Listbox, Observable): """Creation de widget Listbox""" def __init__(self): #super(ListObservable, self).__init__() Observable.__init__(self) self._value = None self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys()))) self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') self.liste.grid(row=0, column=1, sticky=N+S+W) self.liste.bind('', self.onSelect) self.liste.selection_set(0) def onSelect(self, e): if not self.liste.curselection(): self.setValue(0) else: self.setValue(self.liste.get(self.liste.curselection())) self.notify() def setValue(self, select): self._value = select def getValue(self): return self._value class Entry1Observer(Entry, AbstractObserver): """Creation de widget Entry 1""" def __init__(self, sujet=None): #super(Entry1Observer, self).__init__(sujet) AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=1, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][1]) print a class Entry2Observer(Entry, AbstractObserver): """Creation de widget Entry 2""" def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=2, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][0]) class Entry3Observer(Entry, AbstractObserver): """Creation de widget Entry""" def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() self.entry = Entry(textvariable=self.text) self.entry.grid(row=3, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][2]) if __name__ == '__main__': app=App() app.mainloop() # ----- end of file ----- # class AbstractObserver(object): """Interface general des observateurs""" def __init__(self, sujet): """Constructeur""" self.sujet = sujet def update(self): """Methode a implementer par les observateurs""" pass On 01/18/2011 02:32 AM, Alan G wrote: > Steven D'Aprano pearwood.info> writes: > >> fact that multiple inheritance itself is often the wrong thing to use, >> and even when it is right, it is often tricky to get it right. To put it >> another way: don't use multiple inheritance unless you have to, there >> are better ways, such as by composition. > Or use a language where MI is the normal and idiomatic way > to do things because the language assumes it and so it just > works. There are very few such languages but Lisp is one :-) > > Sadly Python isn't, and when using MI I always avoid super() > Which is a huge shame since MI is where super() should > be most useful... But in my experience MI in Python is > definitely a place where explicit is better than implicit. > > Alan G. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From izzaddin.ruhulessin at gmail.com Tue Jan 18 07:35:30 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Tue, 18 Jan 2011 07:35:30 +0100 Subject: [Tutor] Exactly duplicating strftime behavior? In-Reply-To: References: Message-ID: Hi Hugo, Problem solved, thanks! Kind regards, Izz ad-Din 2011/1/17 Hugo Arts > On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin > wrote: > > Hi all, > > I'm designing a module which aims to provide full compatibility with > > Pythons' datetime module. > > However, I can't find out how some operators in strftime function, > namely: > > those who use the locale. (%a, %A, %b, etc.) > > How do I access this locale and it's values? > > Thanks in advance. > > Kind regards, > > Izz ad-Din > > Check out the locale module: > > http://docs.python.org/library/locale.html#locale.nl_langinfo > > HTH, > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Tue Jan 18 11:30:53 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Tue, 18 Jan 2011 10:30:53 +0000 Subject: [Tutor] How to plot graph? In-Reply-To: References: , , Message-ID: hi all, i'm new to python and this is advanced for me. is there a way to plot data with python? i want to plot EyVt, EyHt on the Y-axis and Lane on the X-axis as attached or below. currently i'm using Python2.5 and Win XP. thanks a lot. Eg: Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 55 0 1 2 10 35 0 1 3 25 35 0 1 4 35 25 0 1 5 10 20 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sampledata.txt URL: From artclamedia at yahoo.com Tue Jan 18 12:32:21 2011 From: artclamedia at yahoo.com (Art Cla Media) Date: Tue, 18 Jan 2011 03:32:21 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 83, Issue 74 In-Reply-To: Message-ID: <127177.51808.qm@web114415.mail.gq1.yahoo.com> mai ?date ?ma in morti ?mati ?cu ?masurile ?tale ?de handicapat --- On Tue, 1/18/11, tutor-request at python.org wrote: From: tutor-request at python.org Subject: Tutor Digest, Vol 83, Issue 74 To: tutor at python.org Date: Tuesday, January 18, 2011, 10:32 AM Send Tutor mailing list submissions to ??? tutor at 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 at python.org You can reach the person managing the list at ??? tutor-owner at 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: Why super does not work ! (Steven D'Aprano) ???2. Re: Why super does not work ! (Alan G) ???3. Re: Why super does not work ! (Karim) ???4. Re: Exactly duplicating strftime behavior? (Izz ad-Din Ruhulessin) ???5. How to plot graph? (tee chwee liong) ---------------------------------------------------------------------- Message: 1 Date: Tue, 18 Jan 2011 10:09:35 +1100 From: Steven D'Aprano To: python mail list Subject: Re: [Tutor] Why super does not work ! Message-ID: <4D34CC2F.1010707 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Karim wrote: > > > Hello, > > I implemented Observer DP on a listbox (Tkinter) as follows and I don't > understand why super() is not working and Observable.__init__(self) is > working, cf below: You seem to be confused about your class design. On the one hand, you inherit from Listbox, but then you *also* use composition and/or delegation on a Listbox instance: class ListObservable(Listbox, Observable): ? ???def __init__(self): ? ???[...] ? ???self.liste = Listbox(listvariable=self.listeContenu, ? ? ? ? ? ? ? ? ? selectmode='single') That means that a ListObservable instance both *is* a Listbox and *contains* a Listbox at the same time. I'm not saying this is necessarily wrong, but it is unusual, and confuses the model. At the very least, you need to document why you have done this. > class ListObservable(Listbox, Observable): >? ???"""Creation de widget Listbox""" >? ???def __init__(self): >? ? ? ???super(ListObservable, self).__init__() >? ? ? ???#Observable.__init__(self) Are both Listbox and Observable documented as suitable for multiple inheritance? My guess is that Listbox is not, and I can see from your source code that Observable is *not* suitable for multiple inheritance. If Listbox is documented as suitable for multiple inheritance, then it is a bug in Listbox. If it is not, then it is a bug in your code, by using it for multiple inheritance. Multiple inheritance in Python is cooperative, not enforced, and it is tricky to get right and is *very* sensitive to any class which fails to cooperate. Thousands and thousands of words have been written on the perils and difficulties of multiple inheritance, particularly by Michele Simionato who I consider to be THE authority on MI in Python. Some of the most important articles are: Michele Simionato: Things to Know About Python Super ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=236275 ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=236278 ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=237121 Mixins considered harmful: ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=246341 ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=246483 ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=254367 ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=254507 Generic functions vs mixins: ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=237764 Straits: ? ???http://www.artima.com/weblogs/viewpost.jsp?thread=246488 James Knight: Python's Super Considered Harmful ? ???http://fuhm.net/super-harmful/ Summary: this is *not* a bug in super. It's really a side-effect of the fact that multiple inheritance itself is often the wrong thing to use, and even when it is right, it is often tricky to get it right. To put it another way: don't use multiple inheritance unless you have to, there are better ways, such as by composition. -- Steven ------------------------------ Message: 2 Date: Tue, 18 Jan 2011 01:32:39 +0000 (UTC) From: Alan G To: tutor at python.org Subject: Re: [Tutor] Why super does not work ! Message-ID: Content-Type: text/plain; charset=us-ascii Steven D'Aprano pearwood.info> writes: > fact that multiple inheritance itself is often the wrong thing to use, > and even when it is right, it is often tricky to get it right. To put it > another way: don't use multiple inheritance unless you have to, there > are better ways, such as by composition. Or use a language where MI is the normal and idiomatic way to do things because the language assumes it and so it just works. There are very few such languages but Lisp is one :-) Sadly Python isn't, and when using MI I always avoid super() Which is a huge shame since MI is where super() should be most useful... But in my experience MI in Python is definitely a place where explicit is better than implicit. Alan G. ------------------------------ Message: 3 Date: Tue, 18 Jan 2011 07:31:10 +0100 From: Karim Cc: tutor at python.org Subject: Re: [Tutor] Why super does not work ! Message-ID: <4D3533AE.4050702 at free.fr> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Thanks Izz, Luke, Steven and Alan! That's I figured out with MI and super. Steven I understand the point to have Listbox contains a Listbox. Before the code was in App class and I extracted it to do an outside class making the mistake. But magic of Python it's working (but I know it's awful). The code is working but I am not totally happy because of many EntryObserver almost identical objects (except from update and grid() options) Is it possible to simplify this structure? Regards Karim The rest of the code is below: #!/usr/bin/env python2.7 """Module ObserverGraphique.py Une implementation du design pattern Observer. """ from Tkinter import * from observable import Observable from observer import AbstractObserver data_base = { ? ? ? ? ? ???'Employe1': ['Joel',???'Durant',? '0623'], ? ? ? ? ? ???'Employe2': ['Marc',???'Donce',???'0624'], ? ? ? ? ? ???'Employe3': ['George', 'Roux',? ? '0625'], ? ? ? ? ? ???'Employe4': ['Alain',? 'Richard', '0626'] ? ? ? ? ? ???} __all__ = ['App', 'ListObservable', 'Entry1Observer', 'Entry2Observer', 'Entry3Observer'] class App(Frame): ? ???"""Application graphique avec Tkinter implementant un Observer Design Pattern.""" ? ???def __init__(self, master=None): ? ? ? ???Frame.__init__(self, master) ? ? ? ???self.master.title("Exemple : Observer Design Pattern") ? ? ? ???self.grid() ? ? ? ???self.createLabels() ? ? ? ???self.createObservable() ? ? ? ???self.createObservers() ? ? ? ???self.registerObservers() ? ? def createLabels(self): ? ? ? ???"""Creation de widgets Label""" ? ? ? ???self.label1 = Label(text="Nom :") ? ? ? ???self.label2 = Label(text="Prenom :") ? ? ? ???self.label3 = Label(text="Poste :") ? ? ? ???self.label1.grid(row=1, column=1, sticky=W) ? ? ? ???self.label2.grid(row=2, column=1, sticky=W) ? ? ? ???self.label3.grid(row=3, column=1, sticky=W) ? ???def createObservable(self): ? ? ? ???"""Creation de la listBox observable.""" ? ? ? ???self.sujet? = ListObservable() ? ???def createObservers(self): ? ? ? ???"""Creation des champs d'entre texte observateurs de la liste.""" ? ? ? ???self.nom? ? = Entry1Observer(self.sujet) ? ? ? ???self.prenom = Entry2Observer(self.sujet) ? ? ? ???self.poste? = Entry3Observer(self.sujet) ? ???def registerObservers(self): ? ? ? ???"""Enregistrement des observateurs.""" ? ? ? ???self.sujet.attach(self.nom) ? ? ? ???self.sujet.attach(self.prenom) ? ? ? ???self.sujet.attach(self.poste) class ListObservable(Listbox, Observable): ? ???"""Creation de widget Listbox""" ? ???def __init__(self): ? ? ? ???#super(ListObservable, self).__init__() ? ? ? ???Observable.__init__(self) ? ? ? ???self._value = None ? ? ? ???self.listeContenu = StringVar() ? ? ? ???self.listeContenu.set(' '.join(sorted(data_base.keys()))) ? ? ? ???self.liste = Listbox(listvariable=self.listeContenu, selectmode='single') ? ? ? ???self.liste.grid(row=0, column=1, sticky=N+S+W) ? ? ? ???self.liste.bind('', self.onSelect) ? ? ? ???self.liste.selection_set(0) ? ???def onSelect(self, e): ? ? ? ???if not self.liste.curselection(): ? ? ? ? ? ???self.setValue(0) ? ? ? ???else: ? ? ? ? ? ???self.setValue(self.liste.get(self.liste.curselection())) ? ? ? ???self.notify() ? ???def setValue(self, select): ? ? ? ???self._value = select ? ???def getValue(self): ? ? ? ???return self._value class Entry1Observer(Entry, AbstractObserver): ? ???"""Creation de widget Entry 1""" ? ???def __init__(self, sujet=None): ? ? ? ???#super(Entry1Observer, self).__init__(sujet) ? ? ? ???AbstractObserver.__init__(self, sujet) ? ? ? ???self.text = StringVar() ? ? ? ???self.entry = Entry(textvariable=self.text) ? ? ? ???self.entry.grid(row=1, column=2) ? ???def update(self): ? ? ? ???a = self.sujet.getValue() ? ? ? ???self.text.set(data_base[a][1]) ? ? ? ???print a class Entry2Observer(Entry, AbstractObserver): ? ???"""Creation de widget Entry 2""" ? ???def __init__(self, sujet=None): ? ? ? ???AbstractObserver.__init__(self, sujet) ? ? ? ???self.text? = StringVar() ? ? ? ???self.entry = Entry(textvariable=self.text) ? ? ? ???self.entry.grid(row=2, column=2) ? ???def update(self): ? ? ? ???a = self.sujet.getValue() ? ? ? ???self.text.set(data_base[a][0]) class Entry3Observer(Entry, AbstractObserver): ? ???"""Creation de widget Entry""" ? ???def __init__(self, sujet=None): ? ? ? ???AbstractObserver.__init__(self, sujet) ? ? ? ???self.text? = StringVar() ? ? ? ???self.entry = Entry(textvariable=self.text) ? ? ? ???self.entry.grid(row=3, column=2) ? ???def update(self): ? ? ? ???a = self.sujet.getValue() ? ? ? ???self.text.set(data_base[a][2]) if __name__ == '__main__': ? ???app=App() ? ???app.mainloop() # ----- end of file ----- # class AbstractObserver(object): ? ???"""Interface general des observateurs""" ? ???def __init__(self, sujet): ? ? ? ???"""Constructeur""" ? ? ? ???self.sujet = sujet ? ???def update(self): ? ? ? ???"""Methode a implementer par les observateurs""" ? ? ? ???pass On 01/18/2011 02:32 AM, Alan G wrote: > Steven D'Aprano? pearwood.info>? writes: > >> fact that multiple inheritance itself is often the wrong thing to use, >> and even when it is right, it is often tricky to get it right. To put it >> another way: don't use multiple inheritance unless you have to, there >> are better ways, such as by composition. > Or use a language where MI is the normal and idiomatic way > to do things because the language assumes it and so it just > works. There are very few such languages but Lisp is one :-) > > Sadly Python isn't, and when using MI I always avoid super() > Which is a huge shame since MI is where super() should > be most useful... But in my experience MI in Python is > definitely a place where explicit is better than implicit. > > Alan G. > > > > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 4 Date: Tue, 18 Jan 2011 07:35:30 +0100 From: Izz ad-Din Ruhulessin To: Hugo Arts Cc: tutor at python.org Subject: Re: [Tutor] Exactly duplicating strftime behavior? Message-ID: ??? Content-Type: text/plain; charset="iso-8859-1" Hi Hugo, Problem solved, thanks! Kind regards, Izz ad-Din 2011/1/17 Hugo Arts > On Mon, Jan 17, 2011 at 8:29 PM, Izz ad-Din Ruhulessin > wrote: > > Hi all, > > I'm designing a module which aims to provide full compatibility with > > Pythons' datetime module. > > However, I can't find out how some operators in strftime function, > namely: > > those who use the locale. (%a, %A, %b, etc.) > > How do I access this locale and it's values? > > Thanks in advance. > > Kind regards, > > Izz ad-Din > > Check out the locale module: > > http://docs.python.org/library/locale.html#locale.nl_langinfo > > HTH, > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Tue, 18 Jan 2011 10:30:53 +0000 From: tee chwee liong To: Subject: [Tutor] How to plot graph? Message-ID: Content-Type: text/plain; charset="iso-8859-1" hi all, i'm new to python and this is advanced for me. is there a way to plot data with python? i want to plot EyVt, EyHt on the Y-axis and Lane on the X-axis as attached or below. currently i'm using Python2.5 and Win XP. thanks a lot. Eg: Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0? 1? 1? 75? 55 0? 1? 2? 10 35 0? 1? 3? 25 35 0? 1? 4? 35 25 0? 1? 5? 10 20 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s ??? ???????? ?????? ??? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sampledata.txt URL: ------------------------------ _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 83, Issue 74 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Tue Jan 18 13:14:07 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 18 Jan 2011 06:14:07 -0600 Subject: [Tutor] How to plot graph? In-Reply-To: References: Message-ID: On Tue, Jan 18, 2011 at 4:30 AM, tee chwee liong wrote: > hi all, > > i'm new to python and this is advanced for me. is there a way to plot data > with python? i want to plot EyVt, EyHt on the Y-axis and Lane on the X-axis > as attached or below. > currently i'm using Python2.5 and Win XP. thanks a lot. > Take a look at the matplotlib library: http://matplotlib.sourceforge.net/ Especially the gallery page - there are several examples of what you can do. It may not be the easiest thing to start into as a beginner, but it's definitely available. If you're interested in doing a lot of scientific stuff, I'd also recommend using Python(X, Y): http://www.pythonxy.com/ as it bundles most of the tools you'll need (such as matplotlib) into one easy installer. Give it a try and if you get stuck, send us another email with what you've done, what you expect it to do, and what it actually does instead (including the full text of any and all tracebacks). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 18 13:23:40 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 13:23:40 +0100 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D3533AE.4050702@free.fr> References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> <4D3533AE.4050702@free.fr> Message-ID: <4D35864C.1010106@free.fr> By the way Tkinter does not support super() seems to be an 'old style' class, this is perhaps the raison why MI does not work in this context: *Python 2.7.1rc1 (r271rc1:86455, Nov 16 2010, 21:53:40) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Tkinter.Frame Traceback (most recent call last): File "", line 1, in ImportError: No module named Frame >>> from Tkinter import Frame >>> class App(Frame): ... def __init__(self): ... super(App, self).__init__() ... >>> a=App() Traceback (most recent call last): File "", line 1, in File "", line 3, in __init__ TypeError: must be type, not classobj >>> * Steven, I corrected my code (even if I have a double Inheritance which is ok in this context): * class ListObservable(Listbox, Observable): def __init__(self): Observable.__init__(self) self.listeContenu = StringVar() self.listeContenu.set(' '.join(sorted(data_base.keys()))) Listbox.__init__(self, listvariable=self.listeContenu, selectmode='single') self.grid(row=0, column=1, sticky=N+S+W) self.bind('<>', self.onSelect) self._value = None def onSelect(self, e): if not self.curselection(): self.setValue(0) else: self.setValue(self.get(self.curselection())) self.notify() def setValue(self, select): self._value = select def getValue(self): return self._value class Entry1Observer(Entry, AbstractObserver): def __init__(self, sujet=None): AbstractObserver.__init__(self, sujet) self.text = StringVar() Entry.__init__(self, textvariable=self.text) self.grid(row=2, column=2) def update(self): a = self.sujet.getValue() self.text.set(data_base[a][0])* I still need a advice about the possible improvement specially for Entry observer object. Regards Karim On 01/18/2011 07:31 AM, Karim wrote: > > Thanks Izz, Luke, Steven and Alan! > That's I figured out with MI and super. > Steven I understand the point to have Listbox contains a Listbox. > Before the code was in App class and I extracted it to do an outside > class making the mistake. > But magic of Python it's working (but I know it's awful). > The code is working but I am not totally happy because of many > EntryObserver almost identical objects (except from update and grid() > options) > Is it possible to simplify this structure? > > Regards > Karim > > The rest of the code is below: > > #!/usr/bin/env python2.7 > """Module ObserverGraphique.py > > Une implementation du design pattern Observer. > """ > > > from Tkinter import * > from observable import Observable > from observer import AbstractObserver > > > data_base = { > 'Employe1': ['Joel', 'Durant', '0623'], > 'Employe2': ['Marc', 'Donce', '0624'], > 'Employe3': ['George', 'Roux', '0625'], > 'Employe4': ['Alain', 'Richard', '0626'] > } > > > __all__ = ['App', 'ListObservable', 'Entry1Observer', > 'Entry2Observer', 'Entry3Observer'] > > > class App(Frame): > """Application graphique avec Tkinter implementant un Observer > Design Pattern.""" > def __init__(self, master=None): > Frame.__init__(self, master) > self.master.title("Exemple : Observer Design Pattern") > self.grid() > self.createLabels() > self.createObservable() > self.createObservers() > self.registerObservers() > > def createLabels(self): > """Creation de widgets Label""" > self.label1 = Label(text="Nom :") > self.label2 = Label(text="Prenom :") > self.label3 = Label(text="Poste :") > self.label1.grid(row=1, column=1, sticky=W) > self.label2.grid(row=2, column=1, sticky=W) > self.label3.grid(row=3, column=1, sticky=W) > > def createObservable(self): > """Creation de la listBox observable.""" > self.sujet = ListObservable() > > def createObservers(self): > """Creation des champs d'entre texte observateurs de la liste.""" > self.nom = Entry1Observer(self.sujet) > self.prenom = Entry2Observer(self.sujet) > self.poste = Entry3Observer(self.sujet) > > def registerObservers(self): > """Enregistrement des observateurs.""" > self.sujet.attach(self.nom) > self.sujet.attach(self.prenom) > self.sujet.attach(self.poste) > > class ListObservable(Listbox, Observable): > """Creation de widget Listbox""" > def __init__(self): > #super(ListObservable, self).__init__() > Observable.__init__(self) > self._value = None > self.listeContenu = StringVar() > self.listeContenu.set(' '.join(sorted(data_base.keys()))) > self.liste = Listbox(listvariable=self.listeContenu, > selectmode='single') > self.liste.grid(row=0, column=1, sticky=N+S+W) > self.liste.bind('', self.onSelect) > self.liste.selection_set(0) > > def onSelect(self, e): > if not self.liste.curselection(): > self.setValue(0) > else: > self.setValue(self.liste.get(self.liste.curselection())) > self.notify() > > def setValue(self, select): > self._value = select > > def getValue(self): > return self._value > > class Entry1Observer(Entry, AbstractObserver): > """Creation de widget Entry 1""" > def __init__(self, sujet=None): > #super(Entry1Observer, self).__init__(sujet) > AbstractObserver.__init__(self, sujet) > self.text = StringVar() > self.entry = Entry(textvariable=self.text) > self.entry.grid(row=1, column=2) > > def update(self): > a = self.sujet.getValue() > self.text.set(data_base[a][1]) > print a > > class Entry2Observer(Entry, AbstractObserver): > """Creation de widget Entry 2""" > def __init__(self, sujet=None): > AbstractObserver.__init__(self, sujet) > self.text = StringVar() > self.entry = Entry(textvariable=self.text) > self.entry.grid(row=2, column=2) > > def update(self): > a = self.sujet.getValue() > self.text.set(data_base[a][0]) > > class Entry3Observer(Entry, AbstractObserver): > """Creation de widget Entry""" > def __init__(self, sujet=None): > AbstractObserver.__init__(self, sujet) > self.text = StringVar() > self.entry = Entry(textvariable=self.text) > self.entry.grid(row=3, column=2) > > def update(self): > a = self.sujet.getValue() > self.text.set(data_base[a][2]) > > > if __name__ == '__main__': > app=App() > app.mainloop() > > # ----- end of file ----- # > > class AbstractObserver(object): > """Interface general des observateurs""" > def __init__(self, sujet): > """Constructeur""" > self.sujet = sujet > > def update(self): > """Methode a implementer par les observateurs""" > pass > > > On 01/18/2011 02:32 AM, Alan G wrote: >> Steven D'Aprano pearwood.info> writes: >> >>> fact that multiple inheritance itself is often the wrong thing to use, >>> and even when it is right, it is often tricky to get it right. To >>> put it >>> another way: don't use multiple inheritance unless you have to, there >>> are better ways, such as by composition. >> Or use a language where MI is the normal and idiomatic way >> to do things because the language assumes it and so it just >> works. There are very few such languages but Lisp is one :-) >> >> Sadly Python isn't, and when using MI I always avoid super() >> Which is a huge shame since MI is where super() should >> be most useful... But in my experience MI in Python is >> definitely a place where explicit is better than implicit. >> >> Alan G. >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lintao.im at gmail.com Tue Jan 18 13:45:44 2011 From: lintao.im at gmail.com (Tom Lin) Date: Tue, 18 Jan 2011 20:45:44 +0800 Subject: [Tutor] Convert an IP address from binary to decimal Message-ID: <4D358B78.6000607@gmail.com> Hi guys, Please help me with this: Convert an IP address from binary string to decimal format.There are some preconditions: 1.IP address is in the form of '000010010....001100'.32 bits with no dot. 2.int(string, base) is not allowed, You have to implement the conversion . 3.Performance should be considered. For example an IP address like '11111111111111111111111111111111 ' would be converted to '255.255.255.255' That's how I implement it. But I think it looks ugly and I wonder if there is a better way to do this. import re import sys def convert(bin_ip): patt = re.compile(r'\d{8}') bin_list = patt.findall(str(bin_ip)) dec_list = [] for bin in bin_list: sum = 0 i = 7 for n in bin: if int(n): sum = sum + 2**i i = i - 1 dec_list.append(str(sum)) dec_ip = '.'.join(dec_list) print dec_ip if __name__ == '__main__': bin_ip = sys.argv[1:] convert(bin_ip) Thanks in advance and excuse my poor English. Best regards, Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Tue Jan 18 14:08:24 2011 From: cwitts at compuscan.co.za (Christian Witts) Date: Tue, 18 Jan 2011 15:08:24 +0200 Subject: [Tutor] Convert an IP address from binary to decimal In-Reply-To: <4D358B78.6000607@gmail.com> References: <4D358B78.6000607@gmail.com> Message-ID: <4D3590C8.5080905@compuscan.co.za> On 18/01/2011 14:45, Tom Lin wrote: > Hi guys, > > Please help me with this: > Convert an IP address from binary string to decimal format.There are > some preconditions: > 1.IP address is in the form of '000010010....001100'.32 bits with no dot. > 2.int(string, base) is not allowed, You have to implement the conversion . > 3.Performance should be considered. > > For example an IP address like '11111111111111111111111111111111 ' > would be converted to '255.255.255.255' > > That's how I implement it. But I think it looks ugly and I wonder if > there is a better way to do this. > > import re > import sys > > def convert(bin_ip): > patt = re.compile(r'\d{8}') > bin_list = patt.findall(str(bin_ip)) > > dec_list = [] > for bin in bin_list: > sum = 0 > i = 7 > for n in bin: > if int(n): > sum = sum + 2**i > i = i - 1 > dec_list.append(str(sum)) > > dec_ip = '.'.join(dec_list) > print dec_ip > > if __name__ == '__main__': > bin_ip = sys.argv[1:] > convert(bin_ip) > > > Thanks in advance and excuse my poor English. > > > Best regards, > Tom > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If I knew the input to be perfect it would be a simple matter '.'.join((str(int(input_ip[x:x+8], 2)) for x in range(4))) -- Kind Regards, Christian Witts From karim.liateni at free.fr Tue Jan 18 14:08:29 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 14:08:29 +0100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D34C13A.2060409@pearwood.info> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> Message-ID: <4D3590CD.5070402@free.fr> Hello Steven, > (1) slots = [] doesn't do anything special. You have misspelled > __slots__. Yes sorry my mistake :-[ > (2) Classes don't become read only just because you add __slots__ to > them. All you prevent is adding extra attributes, and why would you > wish to do that? I know this is ugly but until now it is the only way (with this side effect) I found to declare Enums class that I _understand_: *class CategoryType(object): """Implements the enumeration and prevent associated newly created instances to redefine enums value via special class variable '__slots__' definition. It makes also, instances have no attributes at all. """ __slots__ = () TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \ COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14) def toString ( self, litteral ): """Convert the litteral integer number to its associated string representation.""" if litteral == self.TRANSISTOR: return 'transistor' elif litteral == self.MOS: return 'mos' elif litteral == self.BIPOLAR:* [...] I discovered recently that I could configure __setattr__(self, name, value) by raising AttributeError to prevent to set up a new attribute value. Or use an conditional statement to avoid to define it twice. If you have good advice for enum (I hope I could understand) you welcome ;-) . Thus I use __slots__, __dict__ (in __setattr__) and I wanted to about much for __weakref__ > Have you read the Fine Manual? > > http://docs.python.org/reference/datamodel.html#slots > In fact, I already read that. But I am searching for doc about what is a weak reference. > > >>> class K1(object): > ... __slots__ = [] # Don't support weak-refs. > ... > >>> class K2(object): > ... __slots__ = '__weakref__' # Do support weak-refs. > ... > >>> import weakref > >>> k1 = K1() > >>> k2 = K2() > >>> weakref.ref(k1) > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot create weak reference to 'K1' object > >>> weakref.ref(k2) > Same thing I don't know what to do with this object weakref :-[ as I don't know its meaning. That was my true question in fact; Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Jan 18 13:36:14 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Jan 2011 07:36:14 -0500 Subject: [Tutor] How to plot graph? In-Reply-To: References: , , Message-ID: <4D35893E.9060602@gmail.com> Thank you for seeking help. Next time please start a new thread rather than "hijacking" an existing one. -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Tue Jan 18 13:48:53 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Jan 2011 07:48:53 -0500 Subject: [Tutor] Convert an IP address from binary to decimal In-Reply-To: <4D3590C8.5080905@compuscan.co.za> References: <4D358B78.6000607@gmail.com> <4D3590C8.5080905@compuscan.co.za> Message-ID: <4D358C35.1030806@gmail.com> On 1/18/2011 8:08 AM, Christian Witts wrote: > On 18/01/2011 14:45, Tom Lin wrote: >> Hi guys, >> >> Please help me with this: >> Convert an IP address from binary string to decimal format.There are >> some preconditions: >> 1.IP address is in the form of '000010010....001100'.32 bits with no dot. >> 2.int(string, base) is not allowed, You have to implement the conversion . Christian: note rule 2! >> 3.Performance should be considered. >> >> For example an IP address like '11111111111111111111111111111111 ' >> would be converted to '255.255.255.255' >> >> That's how I implement it. But I think it looks ugly Tom: What exactly do you mean by "ugly"? >> and I wonder if there is a better way to do this. What do you mean by "better"? The algorithm you programmed is one good way to accomplish your result. The only problems I see are using re, ** and int() which are less efficient than other ways. The best might be - use slicing to get the 8 "bit" substrings, == to test for "1" and bit shifting. Start with 0, add1 if current bit == "1" and shift left. Then try * 2 instead of shift left. Run timing tests on the various approaches. Given that this is a very fast algorithm timing tests might not be useful. >> import re >> import sys >> >> def convert(bin_ip): >> patt = re.compile(r'\d{8}') >> bin_list = patt.findall(str(bin_ip)) >> >> dec_list = [] >> for bin in bin_list: >> sum = 0 >> i = 7 >> for n in bin: >> if int(n): >> sum = sum + 2**i >> i = i - 1 >> dec_list.append(str(sum)) >> >> dec_ip = '.'.join(dec_list) >> print dec_ip >> >> if __name__ == '__main__': >> bin_ip = sys.argv[1:] >> convert(bin_ip) >> > If I knew the input to be perfect it would be a simple matter > '.'.join((str(int(input_ip[x:x+8], 2)) for x in range(4))) > -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Tue Jan 18 15:01:11 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 01:01:11 +1100 Subject: [Tutor] Convert an IP address from binary to decimal In-Reply-To: <4D358B78.6000607@gmail.com> References: <4D358B78.6000607@gmail.com> Message-ID: <4D359D27.1080401@pearwood.info> Tom Lin wrote: > Hi guys, > > Please help me with this: We don't do homework. We'll give you some hints but not do the work. > Convert an IP address from binary string to decimal format.There are > some preconditions: > 1.IP address is in the form of '000010010....001100'.32 bits with no dot. > 2.int(string, base) is not allowed, You have to implement the conversion . > 3.Performance should be considered. > > For example an IP address like '11111111111111111111111111111111 ' > would be converted to '255.255.255.255' > > That's how I implement it. But I think it looks ugly and I wonder if > there is a better way to do this. > > import re > import sys > > def convert(bin_ip): > patt = re.compile(r'\d{8}') > bin_list = patt.findall(str(bin_ip)) The question does not say "Search a string for zero or more IP addresses in binary and convert them all". It says to convert an IP address written in binary to dotted format. So throw away the regular expression. It's wrong anyway: it would accept input like this: "9999xxxxxxxx1234" and try to convert that to an IP address. Think about the problem you have. You are given as input a string of 32 0 or 1 characters. Anything else is an error -- there is no need to go searching through a string looking for sequences of digits. Once you have 32 characters, you can split it into four lots of eight characters. How? Not with a regular expression!!! That is like using a sledge-hammer to crack a peanut. Use slicing: >>> s = "00001111" + "x"*24 >>> s '00001111xxxxxxxxxxxxxxxxxxxxxxxx' >>> s[0:8] '00001111' So you can take one 32-character string and slice it into four 8-character strings. Then *each* of the substrings can be converted from binary into decimal. If you find a character other than 0 or 1, stop immediately and raise an exception. In pseudo-code: Is the string exactly 32 characters? If not, then FAIL. Split the string into four groups of eight. For each group of eight, convert from binary to decimal. If you find something other than 0 or 1, then FAIL. Join the four groups with dots. -- Steven From bgailer at gmail.com Tue Jan 18 14:24:07 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Jan 2011 08:24:07 -0500 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D3590CD.5070402@free.fr> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> Message-ID: <4D359477.8070309@gmail.com> On 1/18/2011 8:08 AM, Karim wrote: > > I know this is ugly but until now it is the only way (with this side > effect) I found to declare Enums class that I _understand_: > > *class CategoryType(object): > """Implements the enumeration and prevent associated newly created > instances to redefine enums value via special class variable > '__slots__' > definition. It makes also, instances have no attributes at all. > """ > __slots__ = () > > TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \ > COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14) > > def toString ( self, litteral ): > """Convert the litteral integer number to its associated > string representation.""" > if litteral == self.TRANSISTOR: > return 'transistor' > elif litteral == self.MOS: > return 'mos' > elif litteral == self.BIPOLAR:* > [...] IMHO this just cries out for a dictionary: class CategoryType(object): __slots__ = () enums = { 0: 'transistor', 1: 'mos', ... } def toString(self, literal): """Convert the literal integer number to its associated string representation.""" return self.enums[literal] Note this does not handle invalid literal. If you are happy with range 14) you could alternatively use a list: enums = ['transistor, 'mos', ...] -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 18 15:34:12 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 15:34:12 +0100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D359477.8070309@gmail.com> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> <4D359477.8070309@gmail.com> Message-ID: <4D35A4E4.8000302@free.fr> Hello Bob, Thanks for this better and simple approach! To be perfect I would like to be able to do. >>> type = CategoryType() >>> type.TRANSISTOR 0 I will use your enums declaration and the range part to use as keys for enums. And I will raise a KeyError in toString() to handle invalid litteral. Thanks! Regards Karim On 01/18/2011 02:24 PM, bob gailer wrote: > On 1/18/2011 8:08 AM, Karim wrote: >> >> I know this is ugly but until now it is the only way (with this side >> effect) I found to declare Enums class that I _understand_: >> >> *class CategoryType(object): >> """Implements the enumeration and prevent associated newly created >> instances to redefine enums value via special class variable >> '__slots__' >> definition. It makes also, instances have no attributes at all. >> """ >> __slots__ = () >> >> TRANSISTOR, MOS, BIPOLAR, CAPACITOR, RESISTOR, DIODE, ESD, PAD, \ >> COMPARATOR, OPAMP, ADC, DAC, PLL, OTHER = range(14) >> >> def toString ( self, litteral ): >> """Convert the litteral integer number to its associated >> string representation.""" >> if litteral == self.TRANSISTOR: >> return 'transistor' >> elif litteral == self.MOS: >> return 'mos' >> elif litteral == self.BIPOLAR:* >> [...] > IMHO this just cries out for a dictionary: > > class CategoryType(object): > __slots__ = () > enums = { > 0: 'transistor', > 1: 'mos', > ... > } > def toString(self, literal): > """Convert the literal integer number to its associated string > representation.""" > return self.enums[literal] > > Note this does not handle invalid literal. > > If you are happy with range 14) you could alternatively use a list: > enums = ['transistor, 'mos', ...] > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From lintao.im at gmail.com Tue Jan 18 15:48:44 2011 From: lintao.im at gmail.com (Tom Lin) Date: Tue, 18 Jan 2011 22:48:44 +0800 Subject: [Tutor] Convert an IP address from binary to decimal In-Reply-To: <4D3590C8.5080905@compuscan.co.za> References: <4D358B78.6000607@gmail.com> <4D3590C8.5080905@compuscan.co.za> Message-ID: <4D35A84C.1050302@gmail.com> ? 2011-1-18 21:08, Christian Witts ??: > On 18/01/2011 14:45, Tom Lin wrote: >> Hi guys, >> >> Please help me with this: >> Convert an IP address from binary string to decimal format.There are >> some preconditions: >> 1.IP address is in the form of '000010010....001100'.32 bits with no dot. >> 2.int(string, base) is not allowed, You have to implement the conversion . >> 3.Performance should be considered. >> >> For example an IP address like '11111111111111111111111111111111 ' >> would be converted to '255.255.255.255' >> >> That's how I implement it. But I think it looks ugly and I wonder if >> there is a better way to do this. >> >> import re >> import sys >> >> def convert(bin_ip): >> patt = re.compile(r'\d{8}') >> bin_list = patt.findall(str(bin_ip)) >> >> dec_list = [] >> for bin in bin_list: >> sum = 0 >> i = 7 >> for n in bin: >> if int(n): >> sum = sum + 2**i >> i = i - 1 >> dec_list.append(str(sum)) >> >> dec_ip = '.'.join(dec_list) >> print dec_ip >> >> if __name__ == '__main__': >> bin_ip = sys.argv[1:] >> convert(bin_ip) >> >> >> Thanks in advance and excuse my poor English. >> >> >> Best regards, >> Tom >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > If I knew the input to be perfect it would be a simple matter > '.'.join((str(int(input_ip[x:x+8], 2)) for x in range(4))) > Thanks, Chris. Your code looks pretty simple. Awesome! But one precondition is not to use int(string, base). How would you implement the conversion? From steve at pearwood.info Tue Jan 18 16:10:26 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 02:10:26 +1100 Subject: [Tutor] Why super does not work ! In-Reply-To: References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> Message-ID: <4D35AD62.5020904@pearwood.info> Alan G wrote: > Steven D'Aprano pearwood.info> writes: > >> fact that multiple inheritance itself is often the wrong thing to use, >> and even when it is right, it is often tricky to get it right. To put it >> another way: don't use multiple inheritance unless you have to, there >> are better ways, such as by composition. > > Or use a language where MI is the normal and idiomatic way > to do things because the language assumes it and so it just > works. There are very few such languages but Lisp is one :-) I'm sorry, but I don't believe you :/ If it "just works" in Lisp, why does Lisp allow you to override the default linearization? I point you again at the series of articles by Michele Simionato in my previous post. The problems he points out with MI are mostly general to MI itself, and not to any one specific language implementation. Here's another one where he discusses implementing mixins without inheritance, and traits: http://www.artima.com/weblogs/viewpost.jsp?thread=246488 One problem with MI (another is that it encourages huge hierarchies that are impractical to use) is when you have diamond diagrams. This is unavoidable in languages where all objects have a common superclass, such as Python (new style classes only) and Lisp. http://en.wikipedia.org/wiki/Diamond_problem As you can see from the multiple designs chosen by different languages, there is no one "right" way to resolve the problem, but it's generally agreed that the least-worst (or most desirable, if you prefer) resolution is the so-called C3 linearization pioneered in Dylan and implemented by Python. The problem with Lisp's default linearization is that it is not monotomic. See this paper for details: http://192.220.96.201/dylan/linearization-oopsla96.html Converted to Python, if you have this class hierarchy: class Boat(object): pass class Dayboat(Boat): pass class Wheelboat(Boat): pass class Engineless(Dayboat): pass class SmallMultihull(Dayboat): pass class PedalWheelboat(Engineless, Wheelboat): pass class SmallCatamaran(SmallMultihull): pass class Pedalo(PedalWheelboat, SmallCatamaran): pass both Dylan and Python generate the optimal linearization: Pedalo, PedalWheelboat, Engineless, SmallCatamaran, SmallMultihull, Dayboat, Wheelboat, Boat, object while CLOS gives (or at least gave, at the time the paper was written) the surprising result that Wheelboat is promoted ahead of Dayboat: Pedalo, PedalWheelboat, Engineless, Wheelboat, SmallCatamaran, SmallMultihull, Dayboat, Boat, object Why is this surprising? Because Dayboat is more specific in the linearization of *both* of Pedalo's direct parents, and yet it is less specific in Pedalo itself. This is a bad thing. Both Lisp and Python/Dylan agree that there are potential class diagrams that are inconsistent. Here's an example from Python: >>> class A(object): ... pass ... >>> class B(object): ... pass ... >>> class C(A, B): ... pass ... >>> class D(B, A): ... pass ... >>> class E(C, D): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases B, A This gives you a clue as to part of the problem with MI: in general, multiple inheritance is inconsistent. It's only usable at all by imposing certain restrictions on it. Clearly there are no such impossible or inconsistent class diagrams if you limit yourself to single inheritance. MI is inherently more complicated. > Sadly Python isn't, and when using MI I always avoid super() Diamonds were rare in old-style classes in Python, but when they occurred, Python's MI was potentially buggy. That is, there were combinations of class order that lead to real bugs (although other combinations did not). Unfortunately, *all* new-style classes form a diamond in MI. This is the problem that linearization solves for new-style classes, but only if you use super(). If you call the methods explicitly, you're doing it wrong, and it's only by chance (or by hard work, or by duplicating the logic of Python's MRO!) that your class hierarchy is not buggy. One problem with MI is that automatic method resolution does not play well with manual method resolution, and so mixing classes that use super() with classes that don't is a recipe for trouble. This is not a problem with MI, or with super, but with the classes that don't use super(). So if you're avoiding super(), you're classes are unsafe for others to inherit from using MI. In practice, unless you control the class and can take responsibility for it, or if it is documented as being MI friendly, you should never inherit from it except using single inheritance. -- Steven From steve at pearwood.info Tue Jan 18 16:21:56 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 02:21:56 +1100 Subject: [Tutor] Convert an IP address from binary to decimal In-Reply-To: <4D35A84C.1050302@gmail.com> References: <4D358B78.6000607@gmail.com> <4D3590C8.5080905@compuscan.co.za> <4D35A84C.1050302@gmail.com> Message-ID: <4D35B014.2030406@pearwood.info> Tom Lin wrote: > But one precondition is not to use int(string, base). How would you > implement the conversion? It's not hard. You have two choices: each character of the string represents a bit, and should be either a "0" or a "1" (anything else is an error). In which case its numeric value is either 0 or 1. if bit == '0': value = 0 elif bit == '1': value = 1 else: raise ValueError("not a binary IP address") If you are allowed to assume that the characters will only by 0 or 1, and that there will never be anything else, you can do something even smarter and faster. Here's a clue: >>> total = 0 >>> s = "abaa" >>> for c in s: ... total += (c == "a") ... >>> total 3 The boolean flags True and False are actually disguised numbers with values 1 and 0. -- Steven From bgailer at gmail.com Tue Jan 18 15:38:52 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 18 Jan 2011 09:38:52 -0500 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D35A4E4.8000302@free.fr> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> <4D359477.8070309@gmail.com> <4D35A4E4.8000302@free.fr> Message-ID: <4D35A5FC.9040809@gmail.com> On 1/18/2011 9:34 AM, Karim wrote: > > Hello Bob, > > Thanks for this better and simple approach! > To be perfect I would like to be able to do. > >>> type = CategoryType() > >>> type.TRANSISTOR Add to the class: def __getattr__(self, name): return self.enums[name] Note this does not handle the upper/lower case issue. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben.ganzfried at gmail.com Tue Jan 18 18:25:59 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Tue, 18 Jan 2011 12:25:59 -0500 Subject: [Tutor] OOP question Message-ID: Hey guys, I'm trying to get a version of Roulette working and I had a quick question. Here is my code: class Outcome: def __init__(self, name, odds): self.name = name self.odds = odds def winAmount(self, amount): return odds*amount def __eq__(self, other): if (self == other): return True else: return False def __ne__(self, other): if (self != other): return True else: return False def __str__(self): return "%s (%d:1)" % ( self.name, self.odds ) Now whenever I try to call the winAmount method, I get the following error: NameError: global name 'odds' is not defined I'm wondering the following: I had thought that by initializing "odds" in the first initialization method that "odds" should then be accessible to all the other methods in the class. This does not seem to be the case. So what is the ideal fix? On the one hand I still need to initialize "odds", right? But if "odds" is within the initialization method, how else can it be accessed by the other methods? Thanks so much! Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From nstinemates at gmail.com Tue Jan 18 18:52:26 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Tue, 18 Jan 2011 09:52:26 -0800 Subject: [Tutor] OOP question In-Reply-To: References: Message-ID: Updated inline. Check the updated definiton of winAmount. Nick On Tue, Jan 18, 2011 at 9:25 AM, Ben Ganzfried wrote: > Hey guys, > > I'm trying to get a version of Roulette working and I had a quick > question. Here is my code: > > class Outcome: > > def __init__(self, name, odds): > self.name = name > self.odds = odds > > def winAmount(self, amount): > return self.odds*amount > > def __eq__(self, other): > if (self == other): > return True > else: > return False > > def __ne__(self, other): > if (self != other): > return True > else: > return False > > def __str__(self): > return "%s (%d:1)" % ( self.name, self.odds ) > > Now whenever I try to call the winAmount method, I get the following error: > NameError: global name 'odds' is not defined > > I'm wondering the following: I had thought that by initializing "odds" in > the first initialization method that "odds" should then be accessible to all > the other methods in the class. This does not seem to be the case. So what > is the ideal fix? On the one hand I still need to initialize "odds", > right? But if "odds" is within the initialization method, how else can it > be accessed by the other methods? > > Thanks so much! > > Ben > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 18 20:16:17 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 20:16:17 +0100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D35A5FC.9040809@gmail.com> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> <4D359477.8070309@gmail.com> <4D35A4E4.8000302@free.fr> <4D35A5FC.9040809@gmail.com> Message-ID: <4D35E701.4050404@free.fr> On 01/18/2011 03:38 PM, bob gailer wrote: > > def __getattr__(self, name): > return self.enums[name] > > Note this does not handle the upper/lower case issue. Thanks for the trick! works perfect! Regards Karim From thiplat at gmail.com Tue Jan 18 20:59:41 2011 From: thiplat at gmail.com (Thierry Platini) Date: Tue, 18 Jan 2011 14:59:41 -0500 Subject: [Tutor] Trying to import matplotlib : ImportError: No module named dateutil.rrule Message-ID: Hello everyone, I am completely new in learning python and have a little background in programing. My problem occurs with the importation of matplotlib. I did download the module from http://sourceforge.net/projects/matplotlib/ . and I believe successfully install the corresping .egg file. a simple "import matplotlib" does not generate any errors. However, "import matplotlib.pyplot" or "import pylab" does generate the following error. Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/matplotlib.egg/pylab.py", line 1, in from matplotlib.pylab import * File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/matplotlib.egg/matplotlib/pylab.py", line 220, in from matplotlib import mpl # pulls in most modules File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/matplotlib.egg/matplotlib/mpl.py", line 3, in from matplotlib import axes File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/matplotlib.egg/matplotlib/axes.py", line 19, in import matplotlib.dates as mdates File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/site-packages/matplotlib.egg/matplotlib/dates.py", line 119, in from dateutil.rrule import rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, \ ImportError: No module named dateutil.rrule I would really appreciate if someone can help me out with this. As I said, I am pretty new and would need detailed explanation about how to solve the problem. I might need to let you know that I'm working on mac OS X version 10.5.8 Thanks by advance, Thierry From karim.liateni at free.fr Tue Jan 18 22:22:20 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 18 Jan 2011 22:22:20 +0100 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D34C470.8070600@ieee.org> References: <4D34B904.5090100@free.fr> <4D34C470.8070600@ieee.org> Message-ID: <4D36048C.5060902@free.fr> On 01/17/2011 11:36 PM, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Karim wrote: >> >> >> Hello, >> >> I implemented Observer DP on a listbox (Tkinter) as follows and I don't >> understand why super() is not working and Observable.__init__(self) is >> working, cf below: >> >> class ListObservable(Listbox, Observable): >> """Creation de widget Listbox""" >> def __init__(self): >> super(ListObservable, self).__init__() >> #Observable.__init__(self) >> self._value = None >> self.listeContenu = StringVar() >> self.listeContenu.set(' '.join(sorted(data_base.keys()))) >> self.liste = Listbox(listvariable=self.listeContenu, >> selectmode='single') >> self.liste.grid(row=0, column=1, sticky=N+S+W) >> self.liste.bind('', self.onSelect) >> >> _The error is:_ >> Traceback (most recent call last): >> File "./observerAppliGraphique.py", line 118, in >> app=App() >> File "./observerAppliGraphique.py", line 37, in __init__ >> self.sujet.attach(self.nom) >> File "/home/karim/guiObserver/observable.py", line 11, in attach >> self._observers.append(observer) >> AttributeError: 'ListObservable' object has no attribute '_observers' >> >> And the Observable class is: >> >> class Observable(object): >> """Sujet a observer""" >> def __init__(self): >> self._observers = [] >> print('constructeur observable') >> >> def attach(self, observer): >> """Attache un nouvel observateur""" >> self._observers.append(observer) >> >> def detach(self, observer): >> """Retire un nouvel observateur""" >> self._observers.remove(observer) >> >> def notify(self): >> """Avertit tous les observateurs que l'observable change d'etat""" >> for observer in self._observers: >> observer.update() >> > Just looking at what you supply, I'd suppose that ListBox doesn't > correctly call super() in its own __init__() method. > > So I took a look at Tkinter.py, and sure enough, it just calls its own > direct parent, Widget.l > > super() only works if all the classes you use are done consistently. > > DaveA > Thanks for this precision! Regards Karim From steve at pearwood.info Tue Jan 18 22:38:00 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 08:38:00 +1100 Subject: [Tutor] OOP question In-Reply-To: References: Message-ID: <4D360838.4050105@pearwood.info> Ben Ganzfried wrote: > Hey guys, > > I'm trying to get a version of Roulette working and I had a quick question. There's a quick answer and long answer. The quick answer is, you have to refer to self.odds, not just odds. The long answer is below: > Here is my code: [...] > Now whenever I try to call the winAmount method, I get the following error: > NameError: global name 'odds' is not defined > > I'm wondering the following: I had thought that by initializing "odds" in > the first initialization method that "odds" should then be accessible to all > the other methods in the class. This does not seem to be the case. So what > is the ideal fix? On the one hand I still need to initialize "odds", > right? But if "odds" is within the initialization method, how else can it > be accessed by the other methods? The relevant method here is: def winAmount(self, amount): return odds*amount This tells Python: "Look up the value for the name 'odds', and the name 'amount', multiply the two values, and return the result." How does Python look up names? It looks in *namespaces* -- first it looks in the function's local namespace (local variables like 'amount'), then it looks in the global namespace (global variables), and finally it looks in the builtin namespace (built-in functions like len, min, max, etc). You get a NameError, because there is no name 'odds' in any of those namespaces. To look for attributes, you have to look in the instance namespace: return self.odds*amount This looks up 'self' as above, and finds it as a local variable. Then it looks for an attribute 'odds' inside self, which is the result you want. This is much more general than just methods inside classes. The same process occurs whenever you use attribute access: import math math.sin(x) s = "hello sailor" s.upper() -- Steven From davholla2002 at yahoo.co.uk Tue Jan 18 22:36:14 2011 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue, 18 Jan 2011 21:36:14 +0000 (GMT) Subject: [Tutor] Problems passing a parameter in a GUI Message-ID: <162770.6452.qm@web25602.mail.ukl.yahoo.com> Hi All, I hope this makes sense I am trying to write a GUI where you click on a button and each time you click on the button it shows in the entry text how many times you have clicked.? However when I changed an earlier version of the code to pass a parameter it errors. This works :- from Tkinter import * class Application(Frame): ??? """GUI App""" ??? def __init__(self, master): ??????? """Initialize the frame.""" ??????? Frame.__init__(self, master) ??????? self.grid() ??????? self.create_widgets() ??? def create_widgets(self): ??????? self.inst_lbl=Label(self, text="Click on the button to get instructions") ??????? self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) ??????? self.pw_lbl=Label(self, text="Password") ??????? self.submit_bttn=Button(self, text="Submit", command=self.reveal) ??????? self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) ??????? self.secret_text=Text(self, width=35, height=5, wrap=WORD) ??????? self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) ??????? self.helpinfo() ??? def reveal(self): ??????? Calmexob = Calmex() ??????? results = Calmexob.getmess() ??????? self.secret_text.delete(0.0, END) ??????? self.secret_text.insert(0.0,results) ??? def helpinfo(self): ??????????? self.secret_text.insert(0.0,"Start") class Calmex(object): ??? ??? def __init__(self): ??????? """Default arg""" ??????? ??? ??? def getmess(self): ??????? mesg="Test" ??????? return mesg #main root=Tk() root.title("Test") root.geometry("400x300") app=Application(root) root.mainloop() ??????? But when I changed it to use a number I get an error message. Here is the code from Tkinter import * class Application(Frame): ??? """GUI App""" ??? def __init__(self, master): ??????? """Initialize the frame.""" ??????? Frame.__init__(self, master) ??????? self.grid() ??????? x=0 ??????? self.create_widgets(x) ??? def create_widgets(self,x): ??????? self.inst_lbl=Label(self, text="Click on the button to get instructions") ??????? self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) ??????? self.pw_lbl=Label(self, text="Password") ??????? x=?? self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) ??????? self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) ??????? self.secret_text=Text(self, width=35, height=5, wrap=WORD) ??????? self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) ??????? self.helpinfo() ??? def reveal(self, x): ??????? Calmexob = Calmex(x) ??????? results = Calmexob.getmess(x) ??????? self.secret_text.delete(0.0, END) ??????? self.secret_text.insert(0.0,results) ??????? x=x+1 ??????? return x ??? def helpinfo(self): ??????????? self.secret_text.insert(0.0,"Start") class Calmex(object): ??? ??? def __init__(self,x): ??????? """Default arg""" ??????? ??? ??? def getmess(self,x): ??????? mesg="Test"+str(x) ??????? return mesg #main root=Tk() root.title("Test") root.geometry("400x300") app=Application(root) root.mainloop() ??????? ??????? ??????? ??????? The error message is AttributeError: Application instance has no attribute 'secret_text' The only change is that I have declared x and changed the function ? reveal to take and pass x as an arguement. Thanks in advance.? I hope this makes sense. ????? -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Jan 18 22:40:13 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 08:40:13 +1100 Subject: [Tutor] Why super does not work ! In-Reply-To: <4D35AD62.5020904@pearwood.info> References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> <4D35AD62.5020904@pearwood.info> Message-ID: <4D3608BD.60907@pearwood.info> Steven D'Aprano wrote: > Alan G wrote: >> Or use a language where MI is the normal and idiomatic way to do >> things because the language assumes it and so it just works. There are >> very few such languages but Lisp is one :-) > > I'm sorry, but I don't believe you :/ That's a bit harsh... Let me rephrase that as "I'm sorry, I find that hard to believe". -- Steven From steve at pearwood.info Tue Jan 18 22:49:49 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 19 Jan 2011 08:49:49 +1100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D3590CD.5070402@free.fr> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> Message-ID: <4D360AFD.6040208@pearwood.info> Karim wrote: > Same thing I don't know what to do with this object weakref :-[ as I > don't know its meaning. That was my true question in fact; http://mindtrove.info/python-weak-references/ http://www.doughellmann.com/PyMOTW-ja/weakref/index.html -- Steven From eire1130 at gmail.com Tue Jan 18 23:02:25 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 18 Jan 2011 17:02:25 -0500 Subject: [Tutor] Problems passing a parameter in a GUI In-Reply-To: <162770.6452.qm@web25602.mail.ukl.yahoo.com> References: <162770.6452.qm@web25602.mail.ukl.yahoo.com> Message-ID: You have other issues at play here, but to answer your question from below: You are calling the method "reveal" prior to creating the global object "secret_text" You can try moving: x= self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) below self.secret_text = "...." You will also find that you have not defined something called "self.submit_bttn" and there are more errors beyond that, but that's past the scope of your question. On Tue, Jan 18, 2011 at 4:36 PM, David Holland wrote: > Hi All, > I hope this makes sense > > I am trying to write a GUI where you click on a button and each time you > click on the button it shows in the entry text how many times you have > clicked. However when I changed an earlier version of the code to pass a > parameter it errors. > This works :- > > from Tkinter import * > class Application(Frame): > """GUI App""" > def __init__(self, master): > """Initialize the frame.""" > Frame.__init__(self, master) > self.grid() > self.create_widgets() > > def create_widgets(self): > self.inst_lbl=Label(self, text="Click on the button to get > instructions") > self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > self.pw_lbl=Label(self, text="Password") > self.submit_bttn=Button(self, text="Submit", command=self.reveal) > self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > self.secret_text=Text(self, width=35, height=5, wrap=WORD) > self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > self.helpinfo() > > def reveal(self): > Calmexob = Calmex() > results = Calmexob.getmess() > self.secret_text.delete(0.0, END) > self.secret_text.insert(0.0,results) > > def helpinfo(self): > self.secret_text.insert(0.0,"Start") > > class Calmex(object): > > def __init__(self): > """Default arg""" > > > def getmess(self): > mesg="Test" > return mesg > > #main > root=Tk() > root.title("Test") > root.geometry("400x300") > app=Application(root) > root.mainloop() > > > But when I changed it to use a number I get an error message. > Here is the code > from Tkinter import * > class Application(Frame): > """GUI App""" > def __init__(self, master): > """Initialize the frame.""" > Frame.__init__(self, master) > self.grid() > x=0 > self.create_widgets(x) > > def create_widgets(self,x): > self.inst_lbl=Label(self, text="Click on the button to get > instructions") > self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > self.pw_lbl=Label(self, text="Password") > x= self.submit_bttn=Button(self, text="Submit", > command=self.reveal(x)) > self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > self.secret_text=Text(self, width=35, height=5, wrap=WORD) > self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > self.helpinfo() > > def reveal(self, x): > Calmexob = Calmex(x) > results = Calmexob.getmess(x) > self.secret_text.delete(0.0, END) > self.secret_text.insert(0.0,results) > x=x+1 > return x > > def helpinfo(self): > self.secret_text.insert(0.0,"Start") > > class Calmex(object): > > def __init__(self,x): > """Default arg""" > > > def getmess(self,x): > mesg="Test"+str(x) > return mesg > > #main > root=Tk() > root.title("Test") > root.geometry("400x300") > app=Application(root) > root.mainloop() > > > > > > > > > > The error message is > AttributeError: Application instance has no attribute 'secret_text' > > The only change is that I have declared x and changed the function reveal > to take and pass x as an arguement. > > Thanks in advance. I hope this makes sense. > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eire1130 at gmail.com Tue Jan 18 23:19:40 2011 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 18 Jan 2011 17:19:40 -0500 Subject: [Tutor] Problems passing a parameter in a GUI In-Reply-To: References: <162770.6452.qm@web25602.mail.ukl.yahoo.com> Message-ID: I took another look at what you are trying to do, and if I wanted to count the number of times the button was pressed in the same way you are trying I would do something like this instead: from Tkinter import * class Application(Frame): """GUI App""" def __init__(self, master): """Initialize the frame.""" Frame.__init__(self, master) self.grid() self.create_widgets() self.c = Counter() > def create_widgets(self): self.inst_lbl=Label(self, text="Click on the button to get > instructions") self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) self.pw_lbl=Label(self, text="Password") self.submit_bttn=Button(self, text="Submit", command=self.reveal) self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) self.secret_text=Text(self, width=35, height=5, wrap=WORD) self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) self.helpinfo() > def reveal(self): self.c.a +=1 Calmexob = Calmex(self.c.a) results = Calmexob.getmess() self.secret_text.delete(0.0, END) self.secret_text.insert(0.0,results) > def helpinfo(self): self.secret_text.insert(0.0,"Start") > class Counter: a = 0 > class Calmex(object): def __init__(self,a): """Default arg""" self.a = a def getmess(self): mesg="Test" + str(self.a) return mesg > #main root=Tk() root.title("Test") root.geometry("400x300") app=Application(root) root.mainloop() I haven't looked at the whole program, just what you have already done. Really, all you want to do is keep track of how many times "reveal" gets called, or at least I think that is what you are trying to do, so just add a simple counter, which I chose to use an object to do. I then passed the attribute holding this value to instantiate your Calmex instance and once getmess gets called it should do the right thing. This might not be what you are after though, at the end of the day. On Tue, Jan 18, 2011 at 5:02 PM, James Reynolds wrote: > You have other issues at play here, but to answer your question from below: > > You are calling the method "reveal" prior to creating the global object > "secret_text" > > You can try moving: > > x= self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) > > > below self.secret_text = "...." > > You will also find that you have not defined something called > "self.submit_bttn" > > and there are more errors beyond that, but that's past the scope of your > question. > > On Tue, Jan 18, 2011 at 4:36 PM, David Holland wrote: > >> Hi All, >> I hope this makes sense >> >> I am trying to write a GUI where you click on a button and each time you >> click on the button it shows in the entry text how many times you have >> clicked. However when I changed an earlier version of the code to pass a >> parameter it errors. >> This works :- >> >> from Tkinter import * >> class Application(Frame): >> """GUI App""" >> def __init__(self, master): >> """Initialize the frame.""" >> Frame.__init__(self, master) >> self.grid() >> self.create_widgets() >> >> def create_widgets(self): >> self.inst_lbl=Label(self, text="Click on the button to get >> instructions") >> self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) >> self.pw_lbl=Label(self, text="Password") >> self.submit_bttn=Button(self, text="Submit", command=self.reveal) >> self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) >> self.secret_text=Text(self, width=35, height=5, wrap=WORD) >> self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) >> self.helpinfo() >> >> def reveal(self): >> Calmexob = Calmex() >> results = Calmexob.getmess() >> self.secret_text.delete(0.0, END) >> self.secret_text.insert(0.0,results) >> >> def helpinfo(self): >> self.secret_text.insert(0.0,"Start") >> >> class Calmex(object): >> >> def __init__(self): >> """Default arg""" >> >> >> def getmess(self): >> mesg="Test" >> return mesg >> >> #main >> root=Tk() >> root.title("Test") >> root.geometry("400x300") >> app=Application(root) >> root.mainloop() >> >> >> But when I changed it to use a number I get an error message. >> Here is the code >> from Tkinter import * >> class Application(Frame): >> """GUI App""" >> def __init__(self, master): >> """Initialize the frame.""" >> Frame.__init__(self, master) >> self.grid() >> x=0 >> self.create_widgets(x) >> >> def create_widgets(self,x): >> self.inst_lbl=Label(self, text="Click on the button to get >> instructions") >> self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) >> self.pw_lbl=Label(self, text="Password") >> x= self.submit_bttn=Button(self, text="Submit", >> command=self.reveal(x)) >> self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) >> self.secret_text=Text(self, width=35, height=5, wrap=WORD) >> self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) >> self.helpinfo() >> >> def reveal(self, x): >> Calmexob = Calmex(x) >> results = Calmexob.getmess(x) >> self.secret_text.delete(0.0, END) >> self.secret_text.insert(0.0,results) >> x=x+1 >> return x >> >> def helpinfo(self): >> self.secret_text.insert(0.0,"Start") >> >> class Calmex(object): >> >> def __init__(self,x): >> """Default arg""" >> >> >> def getmess(self,x): >> mesg="Test"+str(x) >> return mesg >> >> #main >> root=Tk() >> root.title("Test") >> root.geometry("400x300") >> app=Application(root) >> root.mainloop() >> >> >> >> >> >> >> >> >> >> The error message is >> AttributeError: Application instance has no attribute 'secret_text' >> >> The only change is that I have declared x and changed the function >> reveal to take and pass x as an arguement. >> >> Thanks in advance. I hope this makes sense. >> >> >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Tue Jan 18 23:39:04 2011 From: davea at ieee.org (Dave Angel) Date: Tue, 18 Jan 2011 17:39:04 -0500 Subject: [Tutor] Problems passing a parameter in a GUI In-Reply-To: <162770.6452.qm@web25602.mail.ukl.yahoo.com> References: <162770.6452.qm@web25602.mail.ukl.yahoo.com> Message-ID: <4D361688.8000408@ieee.org> On 01/-10/-28163 02:59 PM, David Holland wrote: > Hi All, > I hope this makes sense > > I am trying to write a GUI where you click on a button and each time > you click on the button it shows in the entry text how many times you > have clicked. However when I changed an earlier version of the code to > pass a parameter it errors. > > This works :- > > > > from Tkinter import * > > class Application(Frame): > > """GUI App""" > > def __init__(self, master): > > """Initialize the frame.""" > > Frame.__init__(self, master) > > self.grid() > > self.create_widgets() > > > > def create_widgets(self): > > self.inst_lbl=Label(self, text="Click on the button to get instructions") > > self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > > self.pw_lbl=Label(self, text="Password") > > self.submit_bttn=Button(self, text="Submit", command=self.reveal) > > self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > > self.secret_text=Text(self, width=35, height=5, wrap=WORD) > > self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > > self.helpinfo() > > > > def reveal(self): > > Calmexob = Calmex() > > results = Calmexob.getmess() > > self.secret_text.delete(0.0, END) > > self.secret_text.insert(0.0,results) > > > > def helpinfo(self): > > self.secret_text.insert(0.0,"Start") > > > > class Calmex(object): > > > > def __init__(self): > > """Default arg""" > > > > > > def getmess(self): > > mesg="Test" > > return mesg > > > > #main > > root=Tk() > > root.title("Test") > > root.geometry("400x300") > > app=Application(root) > > root.mainloop() > > > > > > But when I changed it to use a number I get an error message. > > Here is the code > > from Tkinter import * > > class Application(Frame): > > """GUI App""" > > def __init__(self, master): > > """Initialize the frame.""" > > Frame.__init__(self, master) > > self.grid() > > x=0 > > self.create_widgets(x) > > > > def create_widgets(self,x): > > self.inst_lbl=Label(self, text="Click on the button to get instructions") > > self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > > self.pw_lbl=Label(self, text="Password") > > x= self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) > > self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > > self.secret_text=Text(self, width=35, height=5, wrap=WORD) > > self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > > self.helpinfo() > > > > def reveal(self, x): > > Calmexob = Calmex(x) > > results = Calmexob.getmess(x) > > self.secret_text.delete(0.0, END) > > self.secret_text.insert(0.0,results) > > x=x+1 > > return x > > > > def helpinfo(self): > > self.secret_text.insert(0.0,"Start") > > > > class Calmex(object): > > > > def __init__(self,x): > > """Default arg""" > > > > > > def getmess(self,x): > > mesg="Test"+str(x) > > return mesg > > > > #main > > root=Tk() > > root.title("Test") > > root.geometry("400x300") > > app=Application(root) > > root.mainloop() > > > > > > > > > > > > > > > > > > > > The error message is > > AttributeError: Application instance has no attribute 'secret_text' > > > > The only change is that I have declared x and changed the function reveal to take and pass x as an arguement. > > > > Thanks in advance. I hope this makes sense. > > > > > > > > > I don't have time to try to understand all the tk stuff. And it sure would have been nice if you showed the whole error message, including the traceback. You didn't even tell us what line it was on. But your problem is that you have an instance of Application without the secret_text attribute, but you're trying to use it. You should get in the habit of initializing all attributes in __init__(). Anyway, it looks like the only places that could get the error are inside the methods reveal() and selfinfo(). If either gets called before create_widget() finishes, you could get this error. The stack trace would show just what combination of method calls is making this happen. DaveA From karim.liateni at free.fr Wed Jan 19 00:53:45 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 19 Jan 2011 00:53:45 +0100 Subject: [Tutor] What is __weakref__ ? In-Reply-To: <4D360AFD.6040208@pearwood.info> References: <4D349B01.1030004@free.fr> <4D34C13A.2060409@pearwood.info> <4D3590CD.5070402@free.fr> <4D360AFD.6040208@pearwood.info> Message-ID: <4D362809.3070408@free.fr> Thanks for the links Steven! Regards Karim On 01/18/2011 10:49 PM, Steven D'Aprano wrote: > Karim wrote: > >> Same thing I don't know what to do with this object weakref :-[ as I >> don't know its meaning. That was my true question in fact; > > > http://mindtrove.info/python-weak-references/ > http://www.doughellmann.com/PyMOTW-ja/weakref/index.html > > From jojo.mwebaze at gmail.com Wed Jan 19 09:55:35 2011 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Wed, 19 Jan 2011 11:55:35 +0300 Subject: [Tutor] Is it possible to tell, from which class an method was inherited from Message-ID: Is it possible to tell, from which class an method was inherited from. take an example below class A: def foo(): pass class B(A): def boo(A): pass class C(B): def coo() pass class D(C): def doo() pass >>> dir (D) ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo'] Is there any method to tell me form which classes boo, coo, foo where inherited from? -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Wed Jan 19 10:53:10 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 19 Jan 2011 09:53:10 +0000 Subject: [Tutor] How to plot graph? In-Reply-To: References: , , , Message-ID: hi all, i installed matplotlib, numpy and scipy. i tried to run attached script to learn how it plot a grph but got error as below: Traceback (most recent call last): File "C:\Python25\myscript\plot\plot1.py", line 3, in from scipy import * File "C:\Python25\Lib\site-packages\scipy\linalg\__init__.py", line 31, in from numpy.testing import NumpyTest ImportError: cannot import name NumpyTest pls advise. thanks From: waynejwerner at gmail.com Date: Tue, 18 Jan 2011 06:14:07 -0600 Subject: Re: [Tutor] How to plot graph? To: tcl76 at hotmail.com CC: tutor at python.org On Tue, Jan 18, 2011 at 4:30 AM, tee chwee liong wrote: hi all, i'm new to python and this is advanced for me. is there a way to plot data with python? i want to plot EyVt, EyHt on the Y-axis and Lane on the X-axis as attached or below. currently i'm using Python2.5 and Win XP. thanks a lot. Take a look at the matplotlib library: http://matplotlib.sourceforge.net/ Especially the gallery page - there are several examples of what you can do. It may not be the easiest thing to start into as a beginner, but it's definitely available. If you're interested in doing a lot of scientific stuff, I'd also recommend using Python(X, Y): http://www.pythonxy.com/ as it bundles most of the tools you'll need (such as matplotlib) into one easy installer. Give it a try and if you get stuck, send us another email with what you've done, what you expect it to do, and what it actually does instead (including the full text of any and all tracebacks). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: plot1.py URL: From kb1pkl at aim.com Wed Jan 19 12:41:28 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 19 Jan 2011 06:41:28 -0500 Subject: [Tutor] Is it possible to tell, from which class an method was inherited from In-Reply-To: References: Message-ID: <4D36CDE8.5070100@aim.com> On 01/19/2011 03:55 AM, Jojo Mwebaze wrote: > Is it possible to tell, from which class an method was inherited from. > take an example below > > |class A: > > def foo(): > pass > class B(A): > > def boo(A): > pass > > class C(B): > def coo() > > pass > class D(C): > > def doo() > pass > >>>> dir (D) > > ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo'] > > | > > Is there any method to tell me form which classes boo, coo, foo where > inherited from? > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Try using the information here: http://stackoverflow.com/questions/1938755/getting-the-superclasses-of-a-python-class >From there, you can use the following (probably sub-prime): def findRootParent(obj, method, prev=None): for parent in obj.__bases__: if hasattr(parent, method): findRootParent(parent, method, parent) print "I'm in %s, it has it" % obj.__name__ else: print "%s first had %s" % (obj.__name__, method) Here's a little test and some output: class A(object): def test1(): pass def test2(): pass class B(A): def test3(): pass class C(B): def test4(): pass findRootParent(C, "test1") Output: A first had test1 I'm in B, it has it I'm in C, it has it That's just me hacking together a solution. I don't know if its the best or if one of the gurus on the list have a better one. It doesn't really work if you have multiple inheritance: class A(object): def test1(): pass class B(object): def test2(): pass class C(A, B): pass findRootParent(C, "test1") findRootParent(C, "test2") Output: A first had test1 I'm in C, it has it C first had test1 C first had test2 B first had test2 I'm in C, it has it Hope it helps, ~Corey From __peter__ at web.de Wed Jan 19 13:58:18 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Jan 2011 13:58:18 +0100 Subject: [Tutor] Is it possible to tell, from which class an method was inherited from References: Message-ID: Jojo Mwebaze wrote: > Is it possible to tell, from which class an method was inherited from. > take an example below > > class A: > def foo(): > pass > class B(A): > def boo(A): > pass > class C(B): > def coo() > pass > class D(C): > def doo() > pass > >>>> dir (D) > ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo'] > > Is there any method to tell me form which classes boo, coo, foo where > inherited from? You can check the classes in method resolution order (mro): import inspect class A: def foo(self): pass def bar(self): pass class B(A): def bar(self): pass class C(B): def baz(self): pass for methodname in dir(C) + ["spam"]: for class_ in inspect.getmro(C): if methodname in class_.__dict__: print "%s.%s()" % (class_.__name__, methodname) break else: print "no attribute named %r found" % methodname From oltarasenko at gmail.com Wed Jan 19 13:59:48 2011 From: oltarasenko at gmail.com (Oleg Oltar) Date: Wed, 19 Jan 2011 14:59:48 +0200 Subject: [Tutor] Decoding from strange symbols Message-ID: Hi, I am trying to decode a string I took from file: file = open ("./Downloads/lamp-post.csv", 'r') data = file.readlines() data[0] '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00 \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00 \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00 \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00 \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00 \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00 \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00 \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00 \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00 \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00 \x002\x000\x001\x000\x00\t\x00A\x00d\x00 \x00s\x00h\x00a\x00r\x00e\x00\t\x00S\x00e\x00a\x00r\x00c\x00h\x00 \x00s\x00h\x00a\x00r\x00e\x00\t\x00E\x00s\x00t\x00i\x00m\x00a\x00t\x00e\x00d\x00 \x00A\x00v\x00g\x00.\x00 \x00C\x00P\x00C\x00\t\x00E\x00x\x00t\x00r\x00a\x00c\x00t\x00e\x00d\x00 \x00F\x00r\x00o\x00m\x00 \x00W\x00e\x00b\x00 \x00P\x00a\x00g\x00e\x00\t\x00L\x00o\x00c\x00a\x00l\x00 \x00M\x00o\x00n\x00t\x00h\x00l\x00y\x00 \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\n' How do I convert this to something human readable? -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Jan 19 14:53:43 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Jan 2011 14:53:43 +0100 Subject: [Tutor] Decoding from strange symbols References: Message-ID: Oleg Oltar wrote: > I am trying to decode a string I took from file: > > file = open ("./Downloads/lamp-post.csv", 'r') > data = file.readlines() > data[0] > > '\xff\xfeK\x00e\x00y\x00w\x00o\x00r\x00d\x00\t\x00C\x00o\x00m\x00p\x00e\x00t\x00i\x00t\x00i\x00o\x00n\x00\t\x00G\x00l\x00o\x00b\x00a\x00l\x00 > How do I convert this to something human readable? If you stare at it long enough you'll see the usual ascii characters interspersed with zero-bytes shown by Python as "\x00". This is an UTF-16 file. Open it with import codecs filename = "./Downloads/lamp-post.csv" with codecs.open(filename, "r", encoding="utf-16") as file: for line in file: print line Note that 'line' will now contain a unicode string instead of a byte string. If you want to write that to a file you have to encode it manually line = u"???" with open("tmp.txt", "w") as f: f.write(line.encode("utf-8")) or use codecs.open() again: with codecs.open("tmp.txt", "w", encoding="utf-8") as f: f.write(line) From steve at pearwood.info Wed Jan 19 15:13:59 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Jan 2011 01:13:59 +1100 Subject: [Tutor] Decoding from strange symbols In-Reply-To: References: Message-ID: <4D36F1A7.4040602@pearwood.info> Oleg Oltar wrote: > Hi, > > I am trying to decode a string I took from file: [...] > How do I convert this to something human readable? In general, you can't unless you know the encoding. A file filled with arbitrary bytes could be anything. However, you can sometimes guess the encoding, either by looking at it and reasoning carefully, as Peter Otten did when he suggested your file was UTF-16, or by statistical analysis, or some other combination of techniques. Guessing encodings is pretty much a black art, so if you need to do this a lot you should use an existing package like this one: http://chardet.feedparser.org/ Once you have the encoding, or at least a guess for the encoding: bytes = open(filename).read() text = bytes.decode(encoding) or use the codecs module, as Peter showed. -- Steven From steve at pearwood.info Wed Jan 19 15:20:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 20 Jan 2011 01:20:53 +1100 Subject: [Tutor] How to plot graph? In-Reply-To: References: , , , Message-ID: <4D36F345.4060909@pearwood.info> tee chwee liong wrote: > hi all, > > i installed matplotlib, numpy and scipy. i tried to run attached script to learn how it plot a grph but got error as below: If you're having problems with numpy and scipy, you will probably get more help from a specialist numpy mailing list. -- Steven From alan.gauld at btinternet.com Wed Jan 19 18:59:40 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Jan 2011 17:59:40 -0000 Subject: [Tutor] Problems passing a parameter in a GUI References: <162770.6452.qm@web25602.mail.ukl.yahoo.com> Message-ID: "David Holland" wrote > This works :- > > def create_widgets(self): > self.submit_bttn=Button(self, text="Submit", > command=self.reveal) > > > But when I changed it to use a number I get an error message. > >def create_widgets(self,x): > x= self.submit_bttn=Button(self, text="Submit", > command=self.reveal(x)) Spot the difference in the commasnd parameter? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 19 19:04:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Jan 2011 18:04:23 -0000 Subject: [Tutor] Decoding from strange symbols References: Message-ID: "Oleg Oltar" wrote > I am trying to decode a string I took from file: > > file = open ("./Downloads/lamp-post.csv", 'r') I assume you know what its supposed to represent? What the columns etc are intended to be? Otherwise it will be a challenge! There is a section here that looks like the months of the year (English) in reverse: \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00 \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00 \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00 \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00 \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00 \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00 \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00 \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00 \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00 \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00 Otherwise its all a bit arbitrary... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 19 19:17:57 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Jan 2011 18:17:57 -0000 Subject: [Tutor] Why super does not work ! References: <4D34B904.5090100@free.fr> <4D34CC2F.1010707@pearwood.info> <4D35AD62.5020904@pearwood.info> Message-ID: "Steven D'Aprano" wrote > I'm sorry, but I don't believe you :/ If it "just works" in Lisp, > why > > does Lisp allow you to override the default linearization? > At 2:00am last night I wrote a long explanatory reposte then discovered my wife's Netbook wouldn'ty let me post it! Now I can't be bothered retyping it all so I'll summarise! :-) MI is harder than SI - always. Lisp makes it as easy as it can get and works well enough that for the past 20+ years its been the stabndartd OOP idiom in Lisp. But OOP is not the most common idiom in the Lisp community so we are not dealing with typical OOP programmers. I used Lisp MI for about 5 years and had no issues that could not be addressed using the standard Lisp tools (redefining the linearization is one such tool.but not one used often) The definition of before/after and around specifiers is the one that is used most.in my experience. Diamonds are usually avoided (you can make one if you work hard at it) but mostly Lisp pulls all parents into a suingle set so there are no duplicate paremts but the order can be a bit "random"! This is less of an issue that it sounds because of the before/after safeguards. So I'm not recommending wholesale use of MI simply saying that it is a valid and convenient tool in languages that expect it (Eiffell is another where I've had success with MI - but sadly less so with the standard library - another tale...) As to my own experience with super - I just can't find cases where it works with MI and, although not recommended, using explicit calls to the superclasses has worked in most cases. Maybe if I was writing production code in Python I'd be less gung ho, but I only use Python for tools and prototyping so it hasn't bitten me so far! :-) Maybe its no coincidence that Smalltalk has always resisted adding MI. Even an experimental branch with MI seems to have died out :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From benderjacob44 at gmail.com Wed Jan 19 22:09:23 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Wed, 19 Jan 2011 16:09:23 -0500 Subject: [Tutor] (no subject) Message-ID: <4D375303.60409@gmail.com> Dear tutors, I'm writing a program that can play Othello. Everything has been going fine, but there is a frequently occurring problem with printing the board with the squares filled in. Here's the code for the board: class board(object): def create_board(self): #Create a virtual board, that will be played on self.board = [] for squares in range(64): self.board.append(" ") self.board_table =\ """ A B C D E F G H 1 |%s|%s|%s|%s|%s|%s|%s|%s| 2 |%s|%s|%s|%s|%s|%s|%s|%s| 3 |%s|%s|%s|%s|%s|%s|%s|%s| 4 |%s|%s|%s|%s|%s|%s|%s|%s| 5 |%s|%s|%s|%s|%s|%s|%s|%s| 6 |%s|%s|%s|%s|%s|%s|%s|%s| 7 |%s|%s|%s|%s|%s|%s|%s|%s| 8 |%s|%s|%s|%s|%s|%s|%s|%s| """ def display_board(self): print self.board_table % self.board v = board() v.create_board() v.display board() I get this error: Traceback (most recent call last): File "C:\Documents and Settings\Owner\My Documents\Dropbox\Shared_With_Chris\Jake's Programs\AI\Othello_Unfinished.py", line 76, in v.display_board() File "C:\Documents and Settings\Owner\My Documents\Dropbox\Shared_With_Chris\Jake's Programs\AI\Othello_Unfinished.py", line 72, in display_board print self.board_table % self.board TypeError: not enough arguments for format string I tried doing: def display_board(self): print self.board_table % self.board[:] But that didn't help either, and I still got the same TypeError. If you could please figure out what's wrong, it would be greatly appreciated. Thanks! From emile at fenx.com Wed Jan 19 22:17:12 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 19 Jan 2011 13:17:12 -0800 Subject: [Tutor] (no subject) In-Reply-To: <4D375303.60409@gmail.com> References: <4D375303.60409@gmail.com> Message-ID: On 1/19/2011 1:09 PM Jacob Bender said... > def display_board(self): > print self.board_table % self.board[:] Self.board is a list, but the formatting substitution needs to be passed a tuple. Try: print self.board_table % tuple(self.board) Emile From duretn at bellsouth.net Wed Jan 19 22:21:22 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Wed, 19 Jan 2011 16:21:22 -0500 Subject: [Tutor] Correct Path for tkinter using python3.1 on Ubuntu Maverick!! Message-ID: <1295472082.8145.16.camel@nevstar> Hello Python Collective, Well, I'm sure this topic came up before on this forum, and I was confident that I mastered it having had to set it up correctly on my Mac systems and linux systems in the path. Here are my findings. I am trying to run this code: #!/usr/bin/env python3.1 from tkinter import label widget = Label( None, text = 'Hello Gui World' ) widget.pack() widget.mainloop() --in order to do several tkinter tutorials that I am following in a book and I keep getting this error: Traceback (most recent call last): File "/home/myhomename/pythonproj/hellogui2.py", line 3, in import messagebox ImportError: No module named messagebox First off, I checked my path, and in having checked several on-line tutorials on how to set up the tkinter module, one of them made mention that the lib-tk folder is no longer available in python3.1 and that this should be the correct path on Linux systems: /usr/lib/python3.1/tkinter , which when I looked inside this directory, I did manage to find the files messagebox.py and messagebox.pyc. I also wen to this link: http://wiki.python.org/moin/TkInter and ran python3.1 in my Terminal: >>>import _tkinter # with underscore, and lowercase 't' >>>import Tkinter # no underscore, uppercase 'T' prior to V3.0; lowercase 't' from v3.0 >>>Tkinter._test() # note underscore in _test. Also, if you are using Python 3.1, try tkinter._test() instead The first line ran ok, but in order to get the second and third line to work I had to change them to( making Tkinter lower case tkinter: >>>import tkinter # no underscore, uppercase 'T' prior to V3.0; lowercase 't' from v3.0 >>>tkinter._test() # note underscore in _test. Also, if you are using Python 3.1, try tkinter._test() instead Is this because my path is still missing some essential module, or does it have to do with the fact that its deprecated in 3.1? Again, I've made sure that my .bashrc file contains export PYTHONPATH = /usr/lib/python3.1/tkinter. Is there anything else that I'm to do? Any help would be greatly appreciated. Best Regards, freesparks From nstinemates at gmail.com Wed Jan 19 18:16:58 2011 From: nstinemates at gmail.com (Nick Stinemates) Date: Wed, 19 Jan 2011 09:16:58 -0800 Subject: [Tutor] OOP question In-Reply-To: References: Message-ID: If you want to test if one outcome is equal to another, you probably want to know if The name of the outcome is the same The odds of the outcome is the same So, you'd implement it like so class Outcome: def __eq__(self, other): if self.name == other.name and self.odds == other.odds: return True return False Make sense? Nick On Wed, Jan 19, 2011 at 9:07 AM, Ben Ganzfried wrote: > yeah I was actually pretty confused about those methods as well. I mean I > get the general idea that we are testing to see if two outcomes are the same > (hence a winning bet)...when you say expand on them, what do you mean > exactly? > > Thanks again, really much appreciated! > > > On Tue, Jan 18, 2011 at 4:31 PM, Nick Stinemates wrote: > >> You may also want to look in to the __eq__ and __ne__ methods. You're just >> re-implementing standard behavior (so redefining them is useless.) You'll >> probably want to expand on them to be more concise. >> >> >> On Tue, Jan 18, 2011 at 10:00 AM, Ben Ganzfried wrote: >> >>> Thanks, Nick! >>> >>> >>> On Tue, Jan 18, 2011 at 12:52 PM, Nick Stinemates >> > wrote: >>> >>>> Updated inline. Check the updated definiton of winAmount. >>>> >>>> Nick >>>> >>>> On Tue, Jan 18, 2011 at 9:25 AM, Ben Ganzfried >>> > wrote: >>>> >>>>> Hey guys, >>>>> >>>>> I'm trying to get a version of Roulette working and I had a quick >>>>> question. Here is my code: >>>>> >>>>> class Outcome: >>>>> >>>>> def __init__(self, name, odds): >>>>> self.name = name >>>>> self.odds = odds >>>>> >>>>> def winAmount(self, amount): >>>>> return self.odds*amount >>>>> >>>>> >>>>> def __eq__(self, other): >>>>> if (self == other): >>>>> return True >>>>> else: >>>>> return False >>>>> >>>>> def __ne__(self, other): >>>>> if (self != other): >>>>> return True >>>>> else: >>>>> return False >>>>> >>>>> def __str__(self): >>>>> return "%s (%d:1)" % ( self.name, self.odds ) >>>>> >>>>> Now whenever I try to call the winAmount method, I get the following >>>>> error: NameError: global name 'odds' is not defined >>>>> >>>>> I'm wondering the following: I had thought that by initializing "odds" >>>>> in the first initialization method that "odds" should then be accessible to >>>>> all the other methods in the class. This does not seem to be the case. So >>>>> what is the ideal fix? On the one hand I still need to initialize "odds", >>>>> right? But if "odds" is within the initialization method, how else can it >>>>> be accessed by the other methods? >>>>> >>>>> Thanks so much! >>>>> >>>>> Ben >>>>> >>>>> _______________________________________________ >>>>> Tutor maillist - Tutor at python.org >>>>> To unsubscribe or change subscription options: >>>>> http://mail.python.org/mailman/listinfo/tutor >>>>> >>>>> >>>> >>> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chester_lab at fltg.net Wed Jan 19 15:50:30 2011 From: chester_lab at fltg.net (FT) Date: Wed, 19 Jan 2011 09:50:30 -0500 Subject: [Tutor] Battery Level Monitoring and Voice Message-ID: <59C05F854F9642F18440F9077FCD5C85@1B1B1L1> Hello everyone, Since I got a simple answer on the Python Win32 web site I decided to post it here for those who would want that information, especially those who can not see. The first 2 lines are all that is needed along with the battery level instances using that object, ( BatteryPercentage = wmi.InstancesOf('win32_battery')) This program uses the computer voices and will list them if the specified one is not found. In this case I used Karen. When the list is displayed you do not need to insert everything in the name, just the obvious part of the name, like Karen. Just make sure you spell it correctly or you will always get the list printed on the screen. this also will sound off every minute because of the sleep amounts I use. It can also be changed to voice the percentage every percent change, just do what you want to do. Bruce #BatteryLevel.py import win32com.client wmi=win32com.client.GetObject('winmgmts:') from random import randint, uniform import msvcrt #INPUT KEYBOARD COMMANDS! import sys import time import pyTTS #VOICE SETUP! tts = pyTTS.Create() purge = pyTTS.tts_purge_before_speak async = pyTTS.tts_async PITCH=0 tts.Volume = 100 tts.Rate = 2 VOICECOUNT = len(tts.GetVoiceNames()) VOICES=[] for v in range( VOICECOUNT): VOICES.append( tts.GetVoiceNames()[v]) def setVoice2Name( name): "SET VOICE BY NAME!" t=-1 for v in range( VOICECOUNT): if name in VOICES[ v]: tts.SetVoiceByName( VOICES[v]) t=v if t==-1: tts.Speak( " %d Voices with %s Name Not Found! " % (VOICECOUNT, name)) print " %d Voices with %s Name Not Found! " % (VOICECOUNT, name) print "Voices:" for v in range( VOICECOUNT): print "%d= %s" % (v, VOICES[ v]) def Speak(text, pitch=999): if pitch==999: pitch=PITCH tts.Speak( " %s" % (pitch, text), async, purge) def SpeakNext(text, pitch=999): if pitch==999: pitch=PITCH tts.Speak( " %s" % (pitch, text), async) def setRate( rate): tts.Rate= rate if __name__ == '__main__': setVoice2Name( "Karen") PITCH=3 setRate( 2) # clear the keyboard buffer while msvcrt.kbhit(): ch = msvcrt.getch() ch=""; ch1=""; sch="" while ch != chr(27) and ch != chr(13): while msvcrt.kbhit(): ch1 = msvcrt.getch() ch = ch1 if ch1 == chr(0) or ch1 == chr(224): ch = msvcrt.getch() sch = ch1+ch #SAVE ANY MULTIKEYS! if ch != chr(27) and ch != chr(13): BatteryPercentage = wmi.InstancesOf('win32_battery') print (" %d Percent battery charge remaining! " % BatteryPercentage[0].EstimatedChargeRemaining) print "Hay! Battery power is getting low! Plug in the power cord:" print "Please Press Enter To Exit This Battery Alert!" SpeakNext(" %d Percent battery charge remaining! " % BatteryPercentage[0].EstimatedChargeRemaining) SpeakNext( "Hay! Battery power is getting low! Plug in the power cord:") SpeakNext( "Please Press Enter To Exit This Battery Alert!") # time.sleep(10) c = 0 while c < 30: if msvcrt.kbhit(): SpeakNext( "Key Was Hit!") c = 100 time.sleep(1) else: time.sleep(2) c += 1 # if msvcrt.kbhit(): # SpeakNext( "Key Was Hit!") # time.sleep(1) # else: # time.sleep(5) SpeakNext( "OK, Goodbye!") time.sleep(2) #RELEASE VOICE INSTANCE FROM MEMORY! del tts sys.exit() From davholla2002 at yahoo.co.uk Wed Jan 19 22:57:00 2011 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 19 Jan 2011 21:57:00 +0000 (GMT) Subject: [Tutor] Problems passing a parameter in a GUI Message-ID: <636258.16490.qm@web25607.mail.ukl.yahoo.com> Dave, Sorry I did not include the traceback but now James Reynolds (thank you very much) has provided a solution I don't need the info any more. Thank you both for your help and time. Traceback (most recent call last): ? File "/home/david/Documents/learnJava2010/v6c.py", line 46, in ??? app=Application(root) ? File "/home/david/Documents/learnJava2010/v6c.py", line 9, in __init__ ??? self.create_widgets(x) ? File "/home/david/Documents/learnJava2010/v6c.py", line 15, in create_widgets ??? x=?? self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) ? File "/home/david/Documents/learnJava2010/v6c.py", line 24, in reveal ??? self.secret_text.delete(0.0, END) AttributeError: Application instance has no attribute 'secret_text' --- On Tue, 18/1/11, Dave Angel wrote: From: Dave Angel Subject: Re: [Tutor] Problems passing a parameter in a GUI To: "David Holland" Cc: tutor at python.org Date: Tuesday, 18 January, 2011, 22:39 On 01/-10/-28163 02:59 PM, David Holland wrote: > Hi All, > I hope this makes sense > > I am trying to write a GUI where you click on a button and each time > you click on the button it shows in the entry text how many times you > have clicked.? However when I changed an earlier version of the code to > pass a parameter it errors. > > This works :- > > > > from Tkinter import * > > class Application(Frame): > >? ? ? """GUI App""" > >? ? ? def __init__(self, master): > >? ? ? ? ? """Initialize the frame.""" > >? ? ? ? ? Frame.__init__(self, master) > >? ? ? ? ? self.grid() > >? ? ? ? ? self.create_widgets() > > > >? ? ? def create_widgets(self): > >? ? ? ? ? self.inst_lbl=Label(self, text="Click on the button to get instructions") > >? ? ? ? ? self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > >? ? ? ? ? self.pw_lbl=Label(self, text="Password") > >? ? ? ? ? self.submit_bttn=Button(self, text="Submit", command=self.reveal) > >? ? ? ? ? self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > >? ? ? ? ? self.secret_text=Text(self, width=35, height=5, wrap=WORD) > >? ? ? ? ? self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > >? ? ? ? ? self.helpinfo() > > > >? ? ? def reveal(self): > >? ? ? ? ? Calmexob = Calmex() > >? ? ? ? ? results = Calmexob.getmess() > >? ? ? ? ? self.secret_text.delete(0.0, END) > >? ? ? ? ? self.secret_text.insert(0.0,results) > > > >? ? ? def helpinfo(self): > >? ? ? ? ? ? ? self.secret_text.insert(0.0,"Start") > > > > class Calmex(object): > > > >? ? ? def __init__(self): > >? ? ? ? ? """Default arg""" > > > > > >? ? ? def getmess(self): > >? ? ? ? ? mesg="Test" > >? ? ? ? ? return mesg > > > > #main > > root=Tk() > > root.title("Test") > > root.geometry("400x300") > > app=Application(root) > > root.mainloop() > > > > > > But when I changed it to use a number I get an error message. > > Here is the code > > from Tkinter import * > > class Application(Frame): > >? ? ? """GUI App""" > >? ? ? def __init__(self, master): > >? ? ? ? ? """Initialize the frame.""" > >? ? ? ? ? Frame.__init__(self, master) > >? ? ? ? ? self.grid() > >? ? ? ? ? x=0 > >? ? ? ? ? self.create_widgets(x) > > > >? ? ? def create_widgets(self,x): > >? ? ? ? ? self.inst_lbl=Label(self, text="Click on the button to get instructions") > >? ? ? ? ? self.inst_lbl.grid(row=0, column=0, columnspan=2, sticky=W) > >? ? ? ? ? self.pw_lbl=Label(self, text="Password") > >? ? ? ? ? x=???self.submit_bttn=Button(self, text="Submit", command=self.reveal(x)) > >? ? ? ? ? self.submit_bttn.grid(row=1, column=1, columnspan=2, sticky=W) > >? ? ? ? ? self.secret_text=Text(self, width=35, height=5, wrap=WORD) > >? ? ? ? ? self.secret_text.grid(row=2, column=1, columnspan=2, sticky=W) > >? ? ? ? ? self.helpinfo() > > > >? ? ? def reveal(self, x): > >? ? ? ? ? Calmexob = Calmex(x) > >? ? ? ? ? results = Calmexob.getmess(x) > >? ? ? ? ? self.secret_text.delete(0.0, END) > >? ? ? ? ? self.secret_text.insert(0.0,results) > >? ? ? ? ? x=x+1 > >? ? ? ? ? return x > > > >? ? ? def helpinfo(self): > >? ? ? ? ? ? ? self.secret_text.insert(0.0,"Start") > > > > class Calmex(object): > > > >? ? ? def __init__(self,x): > >? ? ? ? ? """Default arg""" > > > > > >? ? ? def getmess(self,x): > >? ? ? ? ? mesg="Test"+str(x) > >? ? ? ? ? return mesg > > > > #main > > root=Tk() > > root.title("Test") > > root.geometry("400x300") > > app=Application(root) > > root.mainloop() > > > > > > > > > > > > > > > > > > > > The error message is > > AttributeError: Application instance has no attribute 'secret_text' > > > > The only change is that I have declared x and changed the function???reveal to take and pass x as an arguement. > > > > Thanks in advance.? I hope this makes sense. > > > > > > > > > I don't have time to try to understand all the tk stuff.? And it sure would have been nice if you showed the whole error message, including the traceback.? You didn't even tell us what line it was on. But your problem is that you have an instance of Application without the secret_text attribute, but you're trying to use it.? You should get in the habit of initializing all attributes in __init__().? Anyway, it looks like the only places that could get the error are inside the methods reveal() and selfinfo().? If either gets called before create_widget() finishes, you could get this error. The stack trace would show just what combination of method calls is making this happen. DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From davholla2002 at yahoo.co.uk Wed Jan 19 23:03:19 2011 From: davholla2002 at yahoo.co.uk (David Holland) Date: Wed, 19 Jan 2011 22:03:19 +0000 (GMT) Subject: [Tutor] Tutor Digest, Vol 83, Issue 83 In-Reply-To: Message-ID: <696800.21769.qm@web25603.mail.ukl.yahoo.com> I did understand the difference (it was me who did trying to write the program) however until James Reynolds provided me with the solution I could not think of a better way to do this. Thanks for the help. --- On Wed, 19/1/11, tutor-request at python.org wrote: ------------------------------ Message: 7 Date: Wed, 19 Jan 2011 17:59:40 -0000 From: "Alan Gauld" To: tutor at python.org Subject: Re: [Tutor] Problems passing a parameter in a GUI Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; ??? reply-type=original "David Holland" wrote > This works :- > > def create_widgets(self): >? ? ? self.submit_bttn=Button(self, text="Submit", > command=self.reveal) > > > But when I changed it to use a number I get an error message. > >def create_widgets(self,x): >? ? ? x= self.submit_bttn=Button(self, text="Submit", > command=self.reveal(x)) Spot the difference in the commasnd parameter? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 83, Issue 83 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 20 00:15:46 2011 From: bgailer at gmail.com (bob gailer) Date: Wed, 19 Jan 2011 18:15:46 -0500 Subject: [Tutor] (no subject) In-Reply-To: <4D375303.60409@gmail.com> References: <4D375303.60409@gmail.com> Message-ID: <4D3770A2.7040303@gmail.com> On 1/19/2011 4:09 PM, Jacob Bender wrote: > Dear tutors, > > I'm writing a program that can play Othello. Everything has been > going fine, but there is a frequently occurring problem with printing > the board with the squares filled in. Here's the code for the board: Emile gave you the answer. A couple of other matters: Please always provide a meaningful subject. We track discussions by subject, and can ignore those that fall outside our interest / expertise. Read the documentation before posting. You will find "If /format/ requires a single argument, /values/ may be a single non-tuple object. [4] Otherwise, /values/ must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary)." An easier way to create the list: self.board = [" "]*64 -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From benderjacob44 at gmail.com Thu Jan 20 00:33:20 2011 From: benderjacob44 at gmail.com (Jacob Bender) Date: Wed, 19 Jan 2011 18:33:20 -0500 Subject: [Tutor] Tutor Digest, Vol 83, Issue 84 In-Reply-To: References: Message-ID: <4D3774C0.6070705@gmail.com> On 1/19/2011 4:53 PM, tutor-request at python.org wrote: > Send Tutor mailing list submissions to > tutor at 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 at python.org > > You can reach the person managing the list at > tutor-owner at 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: Decoding from strange symbols (Alan Gauld) > 2. Re: Why super does not work ! (Alan Gauld) > 3. (no subject) (Jacob Bender) > 4. Re: (no subject) (Emile van Sebille) > 5. Correct Path for tkinter using python3.1 on Ubuntu Maverick!! > (Nevins Duret) > 6. Re: OOP question (Nick Stinemates) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Wed, 19 Jan 2011 18:04:23 -0000 > From: "Alan Gauld" > To: tutor at python.org > Subject: Re: [Tutor] Decoding from strange symbols > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Oleg Oltar" wrote >> I am trying to decode a string I took from file: >> >> file = open ("./Downloads/lamp-post.csv", 'r') > I assume you know what its supposed to represent? > What the columns etc are intended to be? > Otherwise it will be a challenge! > > There is a section here that looks like the months of the year > (English) in reverse: > > > \x00S\x00e\x00a\x00r\x00c\x00h\x00e\x00s\x00\t\x00D\x00e\x00c\x00 > \x002\x000\x001\x000\x00\t\x00N\x00o\x00v\x00 > \x002\x000\x001\x000\x00\t\x00O\x00c\x00t\x00 > \x002\x000\x001\x000\x00\t\x00S\x00e\x00p\x00 > \x002\x000\x001\x000\x00\t\x00A\x00u\x00g\x00 > \x002\x000\x001\x000\x00\t\x00J\x00u\x00l\x00 > \x002\x000\x001\x000\x00\t\x00J\x00u\x00n\x00 > \x002\x000\x001\x000\x00\t\x00M\x00a\x00y\x00 > \x002\x000\x001\x000\x00\t\x00A\x00p\x00r\x00 > \x002\x000\x001\x000\x00\t\x00M\x00a\x00r\x00 > \x002\x000\x001\x000\x00\t\x00F\x00e\x00b\x00 > \x002\x000\x001\x000\x00\t\x00J\x00a\x00n\x00 > > Otherwise its all a bit arbitrary... > > HTH, > > Thanks! That did the trick! From tcl76 at hotmail.com Thu Jan 20 04:48:25 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Thu, 20 Jan 2011 03:48:25 +0000 Subject: [Tutor] How to plot graph? In-Reply-To: <4D36F345.4060909@pearwood.info> References: , , , , , , , , <4D36F345.4060909@pearwood.info> Message-ID: actually i just want to plot a simple x and y graph. any suggestion? how about using excel to plot? any sample code that i can follow to: 1) launch excel 2) read x-y from a text file 3) plot graph thanks > Date: Thu, 20 Jan 2011 01:20:53 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] How to plot graph? > > tee chwee liong wrote: > > hi all, > > > > i installed matplotlib, numpy and scipy. i tried to run attached script to learn how it plot a grph but got error as below: > > If you're having problems with numpy and scipy, you will probably get > more help from a specialist numpy mailing list. > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Thu Jan 20 04:54:53 2011 From: smokefloat at gmail.com (David Hutto) Date: Wed, 19 Jan 2011 22:54:53 -0500 Subject: [Tutor] How to plot graph? In-Reply-To: References: <4D36F345.4060909@pearwood.info> Message-ID: actually i just want to plot a simple x and y graph. any suggestion? how about using excel to plot? any sample code that i can follow to: 1) launch excel 2) read x-y from a text file 3) plot graph thanks x,y is simple in many modules(beyond is more computational. What version of python, platform and modules are you using? -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his cotton nardsac, and his Fruit of the Looms? From jojo.mwebaze at gmail.com Thu Jan 20 08:16:58 2011 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Thu, 20 Jan 2011 10:16:58 +0300 Subject: [Tutor] Is it possible to tell, from which class an method was inherited from In-Reply-To: References: Message-ID: Thanks guys for the responses, inspect.classify_class_attrs(klass) does the magic Regards On Wed, Jan 19, 2011 at 3:58 PM, Peter Otten <__peter__ at web.de> wrote: > Jojo Mwebaze wrote: > > > Is it possible to tell, from which class an method was inherited from. > > take an example below > > > > class A: > > def foo(): > > pass > > class B(A): > > def boo(A): > > pass > > class C(B): > > def coo() > > pass > > class D(C): > > def doo() > > pass > > > >>>> dir (D) > > ['__doc__', '__module__', 'boo', 'coo', 'doo', 'foo'] > > > > Is there any method to tell me form which classes boo, coo, foo where > > inherited from? > > You can check the classes in method resolution order (mro): > > > import inspect > > class A: > def foo(self): > pass > def bar(self): > pass > > class B(A): > def bar(self): > pass > > class C(B): > def baz(self): > pass > > for methodname in dir(C) + ["spam"]: > for class_ in inspect.getmro(C): > if methodname in class_.__dict__: > print "%s.%s()" % (class_.__name__, methodname) > break > else: > print "no attribute named %r found" % methodname > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Jan 20 09:43:47 2011 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Jan 2011 09:43:47 +0100 Subject: [Tutor] Is it possible to tell, from which class an method was inherited from References: Message-ID: Jojo Mwebaze wrote: > Thanks guys for the responses, > > inspect.classify_class_attrs(klass) > > does the magic Argh, undocumented functions. How did you find that gem? From wprins at gmail.com Thu Jan 20 12:33:43 2011 From: wprins at gmail.com (Walter Prins) Date: Thu, 20 Jan 2011 11:33:43 +0000 Subject: [Tutor] How to plot graph? In-Reply-To: References: <4D36F345.4060909@pearwood.info> Message-ID: Hi Tee, On 20 January 2011 03:48, tee chwee liong wrote: > actually i just want to plot a simple x and y graph. any suggestion? > how about using excel to plot? any sample code that i can follow to: > 1) launch excel > 2) read x-y from a text file > 3) plot graph > Try this page: http://www.blog.pythonlibrary.org/2010/09/27/wxpython-pyplot-graphs-with-python/ Lots of example there which should circumscribe what you want to do. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Thu Jan 20 20:43:06 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Thu, 20 Jan 2011 11:43:06 -0800 (PST) Subject: [Tutor] Tkinter in classes...why? Message-ID: <235030.90489.qm@web130207.mail.mud.yahoo.com> I have some experience in Tcl\Tk, and so far, Tkinter is striking me as harder to use that Tk in it's "native" environment. I am attempting to re-write a program I originally did in Tcl\Tk in Python. I managed to get a GUI done using just Tkinter, and, after an initial struggle with the Tkinter syntax (and especially the widget "naming" conventions), had no problem getting widgets to display, etc. But, the tutorials I have encountered all mentioned that it is supposed to be a good idea to put one's GUI stuff in a class, then create an instance of the class (which I don't entirely understand, since I thought the whole "class" thing was for stuff that you were gonna have a lot of, like similar records in a database or something, so you could use the class like a factory to spit out little copies of itself. Anyway, when I attempted to convert my non-class based Tkinter code into a class, that's when the problems started. I guess I still don't have a handle on all the "self.this's & self.that's", tho I have created some classes for the aforementioned database entry type stuff and haven't had too much trouble. For starters, it seems like the first thing these class based tutorials do is to start with a frame inside the main Tkinter window? Why? Why not just grid stuff right into the window, instead of making a frame and gridding widgets into that. Is the (self, master) thing in the __init__ section a convention, or is the use of the "master" a requirement? Can you call it something else? What is the purpose of doing an __init__ with a frame after having done __init__ with (self, master)? All this in Tcl\Tk seems to me, in comparison, just dead nuts simple...but Tkinter...seems to have made unnecessarily complicated. Maybe once I understand it, I won't think of it that way, but for now...whatta PITA! From smokefloat at gmail.com Thu Jan 20 20:57:02 2011 From: smokefloat at gmail.com (David Hutto) Date: Thu, 20 Jan 2011 14:57:02 -0500 Subject: [Tutor] Tkinter in classes...why? In-Reply-To: <235030.90489.qm@web130207.mail.mud.yahoo.com> References: <235030.90489.qm@web130207.mail.mud.yahoo.com> Message-ID: On Thu, Jan 20, 2011 at 2:43 PM, Elwin Estle wrote: > I have some experience in Tcl\Tk, and so far, Tkinter is striking me as harder to use that Tk in it's "native" environment. > > I am attempting to re-write a program I originally did in Tcl\Tk in Python. ?I managed to get a GUI done using just Tkinter, and, after an initial struggle with the Tkinter syntax (and especially the widget "naming" conventions), ?had no problem getting widgets to display, etc. > > But, the tutorials I have encountered all mentioned that it is supposed to be a good idea to put one's GUI stuff in a class, then create an instance of the class (which I don't entirely understand, since I thought the whole "class" thing was for stuff that you were gonna have a lot of, like similar records in a database or something, so you could use the class like a factory to spit out little copies of itself. > > Anyway, when I attempted to convert my non-class based Tkinter code into a class, that's when the problems started. ?I guess I still don't have a handle on all the "self.this's & self.that's", tho I have created some classes for the aforementioned database entry type stuff and haven't had too much trouble. > > For starters, it seems like the first thing these class based tutorials do is to start with a frame inside the main Tkinter window? ?Why? ?Why not just grid stuff right into the window, instead of making a frame and gridding widgets into that. > > Is the (self, master) thing in the __init__ section a convention, or is the use of the "master" a requirement? ? Can you call it something else? ?What is the purpose of doing an __init__ with a frame after having done __init__ with (self, master)? > > All this in Tcl\Tk seems to me, in comparison, just dead nuts simple...but Tkinter...seems to have made unnecessarily complicated. ?Maybe once I understand it, I won't think of it that way, but for now...whatta PITA! It's just like any other concept, at first it is a PITA, then it becomes a normal utilization for your projects. Stick to your own platform, and design for it, then expand for others in your portfolio. > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From hacker0100 at hotmail.com Fri Jan 21 04:32:49 2011 From: hacker0100 at hotmail.com (walter weston) Date: Thu, 20 Jan 2011 20:32:49 -0700 Subject: [Tutor] If I use this code will it delete my program fileS? Message-ID: I have a question I know the shutil module deletes directories, If I use this code will it delete all of my program files? import shutil shutil.rmtree('C:\Program Files (x86)') -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Jan 21 04:52:04 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 20 Jan 2011 21:52:04 -0600 Subject: [Tutor] If I use this code will it delete my program fileS? In-Reply-To: References: Message-ID: On Thu, Jan 20, 2011 at 9:32 PM, walter weston wrote: > I have a question I know the shutil module deletes directories, If I use > this code will it delete all of my program files? > > import shutil > shutil.rmtree('C:\Program Files (x86)') > Assuming you have the proper permissions, yes. An easy and safe(ish) way to test this would be to create a directory and populate it with subdirectories and files, then try calling rmtree() on that directory. Of course it's also safer to use forward slashes in your directory. For instance, if you had rmtree('C:\test'), it will try to remove the directory that has a tab character in it. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From liam at steelsky.co.nz Fri Jan 21 06:30:04 2011 From: liam at steelsky.co.nz (Liam Clarke-Hutchinson) Date: Fri, 21 Jan 2011 18:30:04 +1300 Subject: [Tutor] Tkinter in classes...why? In-Reply-To: References: <235030.90489.qm@web130207.mail.mud.yahoo.com> Message-ID: Your signature is obscenely large David. > But, the tutorials I have encountered all mentioned that it is supposed to be a good idea to put one's GUI stuff in a class, then create an instance of the class (which I don't entirely understand, since I thought the whole "class" thing was for stuff that you were gonna have a lot of, like similar records in a database or something, so you could use the class like a factory to spit out little copies of itself. You're creating an instance of a class, with all the state of that instance relevant to only that instance. Consider an instance of a class to be a convenient way of handling variable scope, I guess. Coming from Tcl to Python will have some significant differences, I'm sure, but Python's OOP is far more likely to be aligned to mainstream coding than Tk... give me a second to google Tcl to determine if it has OO paradigms... ...okay, sorta does. > All this in Tcl\Tk seems to me, in comparison, just dead nuts simple...but Tkinter...seems to have made unnecessarily complicated. Maybe once I understand it, I won't think of it that way, but for now...whatta PITA! Tcl is not Python. Fair enough that you recoil at what you consider to be unnecessary complexity, but yeah, Tcl is is not Python. I've heard good things about Tcl, but I also know that none of my programming peers use it. Perhaps try another Python GUI library like wxPython, or pyGTK or pyQT etc. That way, they might be different enough that you can escape comparisons to Tcl. But hey, sometimes, a language just doesn't fit your way of working. If Tcl suits you better, then stick with Tcl. Regards, Liam Clarke On Fri, Jan 21, 2011 at 8:57 AM, David Hutto wrote: > On Thu, Jan 20, 2011 at 2:43 PM, Elwin Estle > wrote: > > I have some experience in Tcl\Tk, and so far, Tkinter is striking me as > harder to use that Tk in it's "native" environment. > > > > I am attempting to re-write a program I originally did in Tcl\Tk in > Python. I managed to get a GUI done using just Tkinter, and, after an > initial struggle with the Tkinter syntax (and especially the widget "naming" > conventions), had no problem getting widgets to display, etc. > > > > But, the tutorials I have encountered all mentioned that it is supposed > to be a good idea to put one's GUI stuff in a class, then create an instance > of the class (which I don't entirely understand, since I thought the whole > "class" thing was for stuff that you were gonna have a lot of, like similar > records in a database or something, so you could use the class like a > factory to spit out little copies of itself. > > > > Anyway, when I attempted to convert my non-class based Tkinter code into > a class, that's when the problems started. I guess I still don't have a > handle on all the "self.this's & self.that's", tho I have created some > classes for the aforementioned database entry type stuff and haven't had too > much trouble. > > > > For starters, it seems like the first thing these class based tutorials > do is to start with a frame inside the main Tkinter window? Why? Why not > just grid stuff right into the window, instead of making a frame and > gridding widgets into that. > > > > Is the (self, master) thing in the __init__ section a convention, or is > the use of the "master" a requirement? Can you call it something else? > What is the purpose of doing an __init__ with a frame after having done > __init__ with (self, master)? > > > > All this in Tcl\Tk seems to me, in comparison, just dead nuts > simple...but Tkinter...seems to have made unnecessarily complicated. Maybe > once I understand it, I won't think of it that way, but for now...whatta > PITA! > > It's just like any other concept, at first it is a PITA, then it > becomes a normal utilization for your projects. Stick to your own > platform, and design for it, then expand for others in your portfolio. > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- > The lawyer in me says argue...even if you're wrong. The scientist in > me... says shut up, listen, and then argue. But the lawyer won on > appeal, so now I have to argue due to a court order. > > Furthermore, if you could be a scientific celebrity, would you want > einstein sitting around with you on saturday morning, while you're > sitting in your undies, watching Underdog?...Or better yet, would > Einstein want you to violate his Underdog time? > > Can you imagine Einstein sitting around in his underware? Thinking > about the relativity between his pubic nardsac, and his Fruit of the > Looms, while knocking a few Dorito's crumbs off his inner brilliant > white thighs, and hailing E = mc**2, and licking the orangy, > delicious, Doritoey crust that layered his genetically rippled > fingertips? > > But then again, J. Edgar Hoover would want his pantyhose intertwined > within the equation. > > However, I digress, momentarily. > > But Einstein gave freely, for humanity, not for gain, other than > personal freedom. > > An equation that benefited all, and yet gain is a personal product. > > Also, if you can answer it, is gravity anymore than interplanetary static > cling? > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Fri Jan 21 06:56:19 2011 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 20 Jan 2011 23:56:19 -0600 Subject: [Tutor] not understanding a recursion example Message-ID: I am not understanding the following code (I did not write it). It demonstrates walking a tree-like data structure using recursion. It does run and produces reasonable output. I particularly do not understand the "traverse.level" statements. Can anyone give me an idea how this is working and the principles? I would like understand recursive calls in Python better as I have not used the technique previously. Thanks, Bill data = {'count': 2, 'text': '1', 'kids': [{'count': 3, 'text': '1.1', 'kids': [{'count': 1, 'text': '1.1.1', 'kids': [{'count':0, 'text': '1.1.1.1', 'kids': []}]}, {'count': 0, 'text': '1.1.2', 'kids': [{'count':0, 'text': '1.1.1.2', 'kids': [{'count':0, 'text': '1.1.1.1.1', 'kids': []}]}]}, {'count': 0, 'text': '1.1.3', 'kids': []}]}, {'count': 0, 'text': '1.2', 'kids': []}]} def traverse(data): print(' ' * traverse.level + data['text']) for kid in data['kids']: traverse.level += 1 traverse(kid) traverse.level -= 1 if __name__ == '__main__': traverse.level = 1 traverse(data) -------------- next part -------------- An HTML attachment was scrubbed... URL: From arunkumar413 at gmail.com Fri Jan 21 10:10:16 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Fri, 21 Jan 2011 14:40:16 +0530 Subject: [Tutor] Importing packages Message-ID: Hi, I'm trying to program with gdata (http://code.google.com/p/gdata-python-client/) using python library.I'm having problem in writing import statements. The source directory content is like this: atom(folder): this folder contains some files with the .py extension gdata (folder):this folder contains some folders and as well as some files with the .py extension. Also each of the folders contain a __init__.py file. I want to use the classes and functions of the gdata and its inner folders' classes and functions. please tell me how write the import statements -- Thank you Arun Kumar http://clicknscroll.blogspot.com From __peter__ at web.de Fri Jan 21 10:43:35 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Jan 2011 10:43:35 +0100 Subject: [Tutor] not understanding a recursion example References: Message-ID: Bill Allen wrote: > I am not understanding the following code (I did not write it). It > demonstrates walking a tree-like data structure using recursion. It does > run and produces reasonable output. I particularly do not understand the > "traverse.level" statements. Can anyone give me an idea how this is > working > and the principles? I would like understand recursive calls in Python > better as I have not used the technique previously. > def traverse(data): > print(' ' * traverse.level + data['text']) > for kid in data['kids']: > traverse.level += 1 > traverse(kid) > traverse.level -= 1 > > if __name__ == '__main__': > traverse.level = 1 > traverse(data) Functions are objects in python; you can tuck arbitrary attributes onto them, and the above uses a function attribute instead of a global variable. A more standard way to write the above would be def traverse(data): global level print(' ' * level + data['text']) for kid in data['kids']: level += 1 traverse(kid) level -= 1 if __name__ == '__main__': level = 1 traverse(data) What it does: * call traverse with the outermost dictionary * print the data["text"] value indented by the current global level. * iterate over the data["kids"] list of dictionaries * for each entry in that list - increment indentation level - invoke traverse which will print the data["text"] value. (Remember that traverse was called with the current value of kid, so in terms of the outer traverse() the inner traverse() is printing kid["text"]) Process the kid's kids in the same way. - decrement the indentation level However using global variables is generally a bad practice. It is easy to leave them in an inconsistent state, and if you are using multiple threads (i. e. invoke traverse() a second time while the first call hasn't finished) you'll end up with a big mess. I would therefore write the traverse function as def traverse(data, level): print(' ' * level + data['text']) for kid in data['kids']: traverse(kid, level+1) if __name__ == "__main__": traverse(data, 1) which I think may also be easier to understand. Peter From pacificmorrowind at gmail.com Fri Jan 21 10:58:04 2011 From: pacificmorrowind at gmail.com (Pacific Morrowind) Date: Fri, 21 Jan 2011 01:58:04 -0800 Subject: [Tutor] Importing packages In-Reply-To: References: Message-ID: <4D3958AC.3000204@gmail.com> Hi; On 21/01/2011 1:10 AM, arun kumar wrote: > Hi, > > I'm trying to program with gdata > (http://code.google.com/p/gdata-python-client/) using python > library.I'm having problem in writing import statements. > > The source directory content is like this: > > atom(folder): this folder contains some files with the .py extension > gdata (folder):this folder contains some folders and as well as some > files with the .py extension. Also each of the folders contain a > __init__.py file. > > I want to use the classes and functions of the gdata and its inner > folders' classes and functions. > > please tell me how write the import statements Without knowing the exact names/format of those folders can't be 100% exact but you'd want to say something along the lines of import gdata.example.funky to import the module gdata/example/funky.py or import gdata.example2 to import the package gdata/example2 (__init__.py) - just a quick method to say the same thing as import gdata.example2.__init__ basically and logically is clear that that is the base fuctions/info etc. for that package (example2). Pacific From tcl76 at hotmail.com Fri Jan 21 11:17:12 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 21 Jan 2011 10:17:12 +0000 Subject: [Tutor] How to plot graph? In-Reply-To: References: , , , , , , <4D36F345.4060909@pearwood.info>, , Message-ID: hi, i'm using python 2.5 and windows xp. my sample data is as below. i intend to plot EyVt and EyHt on the Y-axis and Lane as the X-axis. Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 55 0 1 2 10 35 0 1 3 25 35 0 1 4 35 25 0 1 5 10 20 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s thanks > Date: Wed, 19 Jan 2011 22:54:53 -0500 > Subject: Re: [Tutor] How to plot graph? > From: smokefloat at gmail.com > To: tcl76 at hotmail.com > CC: steve at pearwood.info; tutor at python.org > > actually i just want to plot a simple x and y graph. any suggestion? > how about using excel to plot? any sample code that i can follow to: > 1) launch excel > 2) read x-y from a text file > 3) plot graph > > thanks > > x,y is simple in many modules(beyond is more computational. What > version of python, platform and modules are you using? > > > -- > The lawyer in me says argue...even if you're wrong. The scientist in > me... says shut up, listen, and then argue. But the lawyer won on > appeal, so now I have to argue due to a court order. > > Furthermore, if you could be a scientific celebrity, would you want > einstein sitting around with you on saturday morning, while you're > sitting in your undies, watching Underdog?...Or better yet, would > Einstein want you to violate his Underdog time? > > Can you imagine Einstein sitting around in his underware? Thinking > about the relativity between his cotton nardsac, and his Fruit of the > Looms? -------------- next part -------------- An HTML attachment was scrubbed... URL: From arunkumar413 at gmail.com Fri Jan 21 11:31:25 2011 From: arunkumar413 at gmail.com (arun kumar) Date: Fri, 21 Jan 2011 16:01:25 +0530 Subject: [Tutor] Importing packages In-Reply-To: <4D3958AC.3000204@gmail.com> References: <4D3958AC.3000204@gmail.com> Message-ID: hi, I am not understanding what you are saying. I included those modules in the sys.path. i want to know how to write the import statement for the modules and packages. I downloaded the gdata client library and extracted it. It contained a scr directory which contained two directories: 1)atom 2)gdata gdata again has some 31 directories and some .py files.These 31 directories contains files with .py extension. Where as the atom directory no further dirrectories. It contained only files with .py extension I want to write the import statementt for the files in gdata directory and also for the files in the 31 directories of the gdata. On 1/21/11, Pacific Morrowind wrote: > Hi; > > On 21/01/2011 1:10 AM, arun kumar wrote: >> Hi, >> >> I'm trying to program with gdata >> (http://code.google.com/p/gdata-python-client/) using python >> library.I'm having problem in writing import statements. >> >> The source directory content is like this: >> >> atom(folder): this folder contains some files with the .py extension >> gdata (folder):this folder contains some folders and as well as some >> files with the .py extension. Also each of the folders contain a >> __init__.py file. >> >> I want to use the classes and functions of the gdata and its inner >> folders' classes and functions. >> >> please tell me how write the import statements > Without knowing the exact names/format of those folders can't be 100% > exact but you'd want to say something along the lines of > > import gdata.example.funky > to import the module gdata/example/funky.py > or > import gdata.example2 > to import the package gdata/example2 (__init__.py) - just a quick method > to say the same thing as import gdata.example2.__init__ basically and > logically is clear that that is the base fuctions/info etc. for that > package (example2). > Pacific > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Thank you Arun Kumar http://clicknscroll.blogspot.com From wallenpb at gmail.com Fri Jan 21 16:15:09 2011 From: wallenpb at gmail.com (Bill Allen) Date: Fri, 21 Jan 2011 09:15:09 -0600 Subject: [Tutor] not understanding a recursion example In-Reply-To: References: Message-ID: Peter, Thank you very much for the explanation. I understand this much better now. You are correct, the implementation you show is easier for me to understand. --Bill On Fri, Jan 21, 2011 at 03:43, Peter Otten <__peter__ at web.de> wrote: > Bill Allen wrote: > > > I am not understanding the following code (I did not write it). It > > demonstrates walking a tree-like data structure using recursion. It does > > run and produces reasonable output. I particularly do not understand the > > "traverse.level" statements. Can anyone give me an idea how this is > > working > > and the principles? I would like understand recursive calls in Python > > better as I have not used the technique previously. > > > def traverse(data): > > print(' ' * traverse.level + data['text']) > > for kid in data['kids']: > > traverse.level += 1 > > traverse(kid) > > traverse.level -= 1 > > > > if __name__ == '__main__': > > traverse.level = 1 > > traverse(data) > > > Functions are objects in python; you can tuck arbitrary attributes onto > them, and the above uses a function attribute instead of a global variable. > A more standard way to write the above would be > > def traverse(data): > global level > print(' ' * level + data['text']) > for kid in data['kids']: > level += 1 > traverse(kid) > level -= 1 > > if __name__ == '__main__': > level = 1 > traverse(data) > > What it does: > * call traverse with the outermost dictionary > * print the data["text"] value indented by the current global level. > * iterate over the data["kids"] list of dictionaries > * for each entry in that list > - increment indentation level > - invoke traverse which will print the data["text"] value. > (Remember that traverse was called with the current value of kid, so > in terms of the outer traverse() the inner traverse() is printing > kid["text"]) Process the kid's kids in the same way. > - decrement the indentation level > > However using global variables is generally a bad practice. > It is easy to leave them in an inconsistent state, and if you are using > multiple threads (i. e. invoke traverse() a second time while the first > call > hasn't finished) you'll end up with a big mess. > > I would therefore write the traverse function as > > def traverse(data, level): > print(' ' * level + data['text']) > for kid in data['kids']: > traverse(kid, level+1) > > if __name__ == "__main__": > traverse(data, 1) > > which I think may also be easier to understand. > > Peter > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Fri Jan 21 16:40:42 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 21 Jan 2011 10:40:42 -0500 Subject: [Tutor] Importing packages In-Reply-To: References: Message-ID: On Fri, Jan 21, 2011 at 4:10 AM, arun kumar wrote: > Hi, > > I'm trying to program with gdata > (http://code.google.com/p/gdata-python-client/) using python > library.I'm having problem in writing import statements. Have you read the Getting Started document linked from their wiki? Particularly, there's a section on the right way to install the library, then some example of it's use (including the import statements) here: http://code.google.com/apis/gdata/articles/python_client_lib.html#library You haven't said what you tried or what error messages you've gotten, so if those docs don't help, you'll have to give us more information. Particularly: what version of python are you running? What Operating System? How have you manipulated your sys.path, where did you install the gdata libraries, and what is the folder structure there? You may also find the part of the python tutorial about modules and packages useful in figuring out what's going on: http://docs.python.org/tutorial/modules.html -- Jerry From badouglas at gmail.com Fri Jan 21 21:57:44 2011 From: badouglas at gmail.com (bruce) Date: Fri, 21 Jan 2011 12:57:44 -0800 Subject: [Tutor] list of tutors for python Message-ID: Hi guys. Please don't slam me!! I'm working on a project, looking for a pretty good number of pythonistas. Trying to find resources that I should look to to find them, and thought I would try here for suggestions. Any comments would be appreciated. Thanks From emile at fenx.com Fri Jan 21 23:12:59 2011 From: emile at fenx.com (Emile van Sebille) Date: Fri, 21 Jan 2011 14:12:59 -0800 Subject: [Tutor] list of tutors for python In-Reply-To: References: Message-ID: On 1/21/2011 12:57 PM bruce said... > Hi guys. > > Please don't slam me!! I'm working on a project, looking for a pretty > good number of pythonistas. Trying to find resources that I should > look to to find them, and thought I would try here for suggestions. > > Any comments would be appreciated. > You're looking for what exactly? Emile From steve at pearwood.info Sat Jan 22 00:20:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 22 Jan 2011 10:20:52 +1100 Subject: [Tutor] list of tutors for python In-Reply-To: References: Message-ID: <4D3A14D4.803@pearwood.info> bruce wrote: > Hi guys. > > Please don't slam me!! I'm working on a project, looking for a pretty > good number of pythonistas. Trying to find resources that I should > look to to find them, and thought I would try here for suggestions. I'm sorry, I don't understand what your question is. If you're looking for Python resources where people can go and get advice, this mailing list is one. The "official" mailing lists run by python.org can be found here: http://www.python.org/community/lists/ http://mail.python.org/mailman/listinfo It includes this mailing list, as well as python-list at python.org which is also available on Usenet as comp.lang.python. You can also look at Reddit and StackOverflow: http://reddit.com/r/python/ http://stackoverflow.com/questions/tagged/python There are probably many other places on the internet -- google is your friend. If you are looking for a list of *people*, there is no such list. -- Steven From brian.sheely at pmaclabs.com Fri Jan 21 19:17:27 2011 From: brian.sheely at pmaclabs.com (brian.sheely at pmaclabs.com) Date: Fri, 21 Jan 2011 11:17:27 -0700 Subject: [Tutor] unable to build python-2.7.1 Message-ID: <20110121111727.165f2fbea8b407e77dba2faab819c48c.b940a020ba.wbe@email06.secureserver.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 22 02:16:21 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 01:16:21 -0000 Subject: [Tutor] Tkinter in classes...why? References: <235030.90489.qm@web130207.mail.mud.yahoo.com> Message-ID: Elwin Estle" wrote >I have some experience in Tcl\Tk, and so far, > Tkinter is striking me as harder to use that Tk > in it's "native" environment. They are actually very similar although Tkinter is a little more verbose. Remember that Tk uses objects too, its just that they are less visible. When you create Tk widgets you define them using a tree of objects rooted at '.' But there are good reasons to use OOP in building GUIs regardless of the Framework - and even many Tcl/Tk programmers use tools like [incr Tcl] to build OOP GUIs using Tk... > But, the tutorials I have encountered all mentioned that it is > supposed to be a good idea to put one's GUI stuff in a class, > then create an instance of the class (which I don't entirely > understand, since I thought the whole "class" thing was for > stuff that you were gonna have a lot of, Not necessarily a lot of but things you may want to reuse. And Guis are full of things you can reuse like Forms, Dialogs, composite widgets etc. By packaging them as a class based on a Frame its as easy to reuse them as just adding a new Frame to your app. And you bring in all the entries, radio buttons ,labels etc that you need for free. As well as the event handlers for the class. (This is also the main reason you should try to keep app logic out of your GUI event handlers!) > use the class like a factory to spit out little copies of itself. Yep, lots of nreuase of login widgets, file editing widgets etc etc. Much easier to reuse than writing GUI functions in Tk and trying to import them into another project. Also, visually its an easy mapping to make in your head to see a widget or panel on screen and associate it with the class code behind it. GUI widgets are conceptually objects so we might as well make them software objects too. > I still don't have a handle on all the "self.this's & self.that's", Yeah OOOP does take a little getting used too. But you had to get used to TK's arcane naming tree too, once mastered its all pretty logical. > Why not just grid stuff right into the window, instead of > making a frame and gridding widgets into that. Because a Frame is a container that allows you to reuse that whole panel. packing(or gridding if you prefer) loses you the reuseability. > Is the (self, master) thing in the __init__ section a convention, Its the Tkinter equivalent of using '.' to start your naming tree in Tk. The master is passed to a hideen attribute inside the widget which maintains the links up the tree. Tk just does that explicitly via the name. > or is the use of the "master" a requirement? > Can you call it something else? You can call it whatever you like in most cases - its a bit like self in a class definition. You can change it if you want but I don't recommend it - you will confuse anyone reading the code (including, possibly yourself!) but I have seen "parent" used in some programs. > What is the purpose of doing an __init__ with a frame > after having done __init__ with (self, master)? The self,master is usually to the superclass. The rest of init is about the current object. If that makes no sense you need to go back to the OOP primers because its no different in Tkinter than elsewhere in that regard. > All this in Tcl\Tk seems to me, in comparison, just dead > nuts simple...but Tkinter...seems to have made unnecessarily > complicated. You can write Tkinter code exactly like Tk but you lose the reuse and logical organisation advantages that OOP brings. But Tkinter works just fine without OOP. But using OOP with Tkinter will make the jump to other, more powerful, GUI frameworks later, much, much easier because they all use OOP, almost without exception (unless you count raw Win32!). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 22 02:24:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 01:24:07 -0000 Subject: [Tutor] list of tutors for python References: Message-ID: "bruce" wrote > Please don't slam me!! I'm working on a project, looking for a > pretty > good number of pythonistas. Trying to find resources that I should > look to to find them, and thought I would try here for suggestions. OK, This list is not a recruiting forum for Python tutors. It is a mailing list where people(specifically Pythonic newbies) post questions about Python and get answers. As such it won't help you find recruits for your project, but it may answer a lot of the questions for which you want to recruit those experts... In effect you get the entire membership of the list for free. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From waynejwerner at gmail.com Sat Jan 22 05:08:09 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 21 Jan 2011 22:08:09 -0600 Subject: [Tutor] unable to build python-2.7.1 In-Reply-To: <20110121111727.165f2fbea8b407e77dba2faab819c48c.b940a020ba.wbe@email06.secureserver.net> References: <20110121111727.165f2fbea8b407e77dba2faab819c48c.b940a020ba.wbe@email06.secureserver.net> Message-ID: On Fri, Jan 21, 2011 at 12:17 PM, wrote: > I would have thought that building python-2.7.1 would be pretty > straightforward - even on an SGI Altix. There were no issues when I ran > configure. However, running make results in the following compile error: > > Objects/floatobject.c(2603): remark #810: conversion from "int" to > "unsigned char" may lose significant bits > sign = (*p >> 7) & 1; > ^ > (0): internal error: backend signals > compilation aborted for Objects/floatobject.c (code 4) > make: *** [Objects/floatobject.o] Error 4 > > The compiler instructions were: > > icc -pthread -c -fno-strict-aliasing -Olimit 1500 -g -O2 -DNDEBUG -g > -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include > -DPy_BUILD_CORE -o Objects/floatobject.o Objects/floatobject.c > > Does anyone have any ideas what the problem might be? Thanks in advance. > This mailing list is really targeted at the python programming language, not so much building python. You may get better results somewhere like stackoverflow. However, if I had to guess, the problem is likely in the code that is converting an int to an unsigned char - icc is probably set to die on the warning. However, I'm not familiar enough with C code or the compiler flags to tell you how to fix/ignore it. Good luck, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From jigenbakuda at yahoo.com Sat Jan 22 17:56:43 2011 From: jigenbakuda at yahoo.com (michael scott) Date: Sat, 22 Jan 2011 08:56:43 -0800 (PST) Subject: [Tutor] Exercise suggestions Message-ID: <704586.24112.qm@web130210.mail.mud.yahoo.com> I am new to programming, I intend to get an entry level job programming next year (or a little bit longer). I am switching fields and not going to college, but kinda "self teaching" myself through various methods. I currently understand concepts in programming in python up to classes (like I understand how to make objects, I understand inheritance, etc...), and I have experimented with building guis in Tkinter, but I'm finding that I understand concepts, but have no real way to implement them. So now my problem emerges... can anyone give me suggestions of exercises I should do to help improve my knowledge of what I can "actually" do with the concepts I have. My main goal is to get to the point where I can assist in fixing bugs in open source programs (I'll be learning C++ in a couple months as well), but when I look at bugs / source code of larger programs, I am just so blown away at how little I understand. So I need to find a way to bridge the gap between my current level and the level needed to contribute to open source programs. A lofty goal I understand, but it is my goal. And I am very dedicated to reaching it. Anyways, given my situation, do you good people have any suggestions for me. I don't need a person walking me through it, a simple, "build a program that asks a user to give you a name and create permutations of it" is great. Of course that example is elementary, but that is the gist of the responses I'm looking for. I just have no idea of what kind of programs to build, my ignorance is holding me back in my opinion. Any response is welcomed, but I do ask if you are critical of me, please offer a method for me to improve the deficiency / deficiencies I have. Thank you so much for reading my inquiry :) What is it about you... that intrigues me so? -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Jan 22 19:12:58 2011 From: emile at fenx.com (Emile van Sebille) Date: Sat, 22 Jan 2011 10:12:58 -0800 Subject: [Tutor] unable to build python-2.7.1 In-Reply-To: <20110121111727.165f2fbea8b407e77dba2faab819c48c.b940a020ba.wbe@email06.secureserver.net> References: <20110121111727.165f2fbea8b407e77dba2faab819c48c.b940a020ba.wbe@email06.secureserver.net> Message-ID: On 1/21/2011 10:17 AM brian.sheely at pmaclabs.com said... > I would have thought that building python-2.7.1 would be pretty straightforward > - even on an SGI Altix. There were no issues when I ran configure. However, > running make results in the following compile error: You should ask this on the porting Python mailing list... http://www.google.com/url?sa=D&q=http://mail.python.org/mailman/listinfo/python-porting Emile > > Objects/floatobject.c(2603): remark #810: conversion from "int" to "unsigned > char" may lose significant bits > sign = (*p>> 7)& 1; > ^ > (0): internal error: backend signals > compilation aborted for Objects/floatobject.c (code 4) > make: *** [Objects/floatobject.o] Error 4 > > The compiler instructions were: > > icc -pthread -c -fno-strict-aliasing -Olimit 1500 -g -O2 -DNDEBUG -g -O3 -Wall > -Wstrict-prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -o > Objects/floatobject.o Objects/floatobject.c > > Does anyone have any ideas what the problem might be? Thanks in advance. > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From kb1pkl at aim.com Sat Jan 22 21:02:56 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 22 Jan 2011 15:02:56 -0500 Subject: [Tutor] Exercise suggestions In-Reply-To: <704586.24112.qm@web130210.mail.mud.yahoo.com> References: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: <4D3B37F0.1020408@aim.com> On 01/22/2011 11:56 AM, michael scott wrote: > I am new to programming, I intend to get an entry level job programming > next year (or a little bit longer). I am switching fields and not going > to college, but kinda "self teaching" myself through various methods. I > currently understand concepts in programming in python up to classes > (like I understand how to make objects, I understand inheritance, > etc...), and I have experimented with building guis in Tkinter, but I'm > finding that I understand concepts, but have no real way to implement them. > > So now my problem emerges... can anyone give me suggestions of exercises > I should do to help improve my knowledge of what I can "actually" do > with the concepts I have. > > My main goal is to get to the point where I can assist in fixing bugs in > open source programs (I'll be learning C++ in a couple months as well), > but when I look at bugs / source code of larger programs, I am just so > blown away at how little I understand. So I need to find a way to bridge > the gap between my current level and the level needed to contribute to > open source programs. A lofty goal I understand, but it is my goal. And > I am very dedicated to reaching it. > > Anyways, given my situation, do you good people have any suggestions for > me. I don't need a person walking me through it, a simple, "build a > program that asks a user to give you a name and create permutations of > it" is great. Of course that example is elementary, but that is the gist > of the responses I'm looking for. I just have no idea of what kind of > programs to build, my ignorance is holding me back in my opinion. > > Any response is welcomed, but I do ask if you are critical of me, please > offer a method for me to improve the deficiency / deficiencies I have. > Thank you so much for reading my inquiry :) When I felt I was ready to start doing some work, I got involved in an open source project. It's definitely an experience! Try going through http://freshmeat.net/ and remake a few things. Can't really recommend anything else, fresh out of ideas too ;-) ~Corey From smokefloat at gmail.com Sat Jan 22 21:09:05 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 22 Jan 2011 15:09:05 -0500 Subject: [Tutor] Exercise suggestions In-Reply-To: <4D3B37F0.1020408@aim.com> References: <704586.24112.qm@web130210.mail.mud.yahoo.com> <4D3B37F0.1020408@aim.com> Message-ID: On Sat, Jan 22, 2011 at 3:02 PM, Corey Richardson wrote: > On 01/22/2011 11:56 AM, michael scott wrote: >> >> I am new to programming, I intend to get an entry level job programming >> next year (or a little bit longer). I am switching fields and not going >> to college, but kinda "self teaching" myself through various methods. I >> currently understand concepts in programming in python up to classes >> (like I understand how to make objects, I understand inheritance, >> etc...), and I have experimented with building guis in Tkinter, but I'm >> finding that I understand concepts, but have no real way to implement >> them. >> >> So now my problem emerges... can anyone give me suggestions of exercises >> I should do to help improve my knowledge of what I can "actually" do >> with the concepts I have. >> >> My main goal is to get to the point where I can assist in fixing bugs in >> open source programs (I'll be learning C++ in a couple months as well), >> but when I look at bugs / source code of larger programs, I am just so >> blown away at how little I understand. So I need to find a way to bridge >> the gap between my current level and the level needed to contribute to >> open source programs. A lofty goal I understand, but it is my goal. And >> I am very dedicated to reaching it. >> >> Anyways, given my situation, do you good people have any suggestions for >> me. I don't need a person walking me through it, a simple, "build a >> program that asks a user to give you a name and create permutations of >> it" is great. Of course that example is elementary, but that is the gist >> of the responses I'm looking for. I just have no idea of what kind of >> programs to build, my ignorance is holding me back in my opinion. >> >> Any response is welcomed, but I do ask if you are critical of me, please >> offer a method for me to improve the deficiency / deficiencies I have. >> Thank you so much for reading my inquiry :) > > When I felt I was ready to start doing some work, I got involved in an open > source project. It's definitely an experience! Try going through > http://freshmeat.net/ Isn't that for those that aren't given real apprenticeship?:) and remake a few things. Can't really recommend > anything else, fresh out of ideas too ;-) Remix IS evolution. So ideas are really irrelevant. > > ~Corey > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From smokefloat at gmail.com Sat Jan 22 21:03:10 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 22 Jan 2011 15:03:10 -0500 Subject: [Tutor] Telephone app Message-ID: This is just a reach question. What modules would i want to use if i wanted to just send the signal, and receive the signal, other than maybe, signal. In other words please tone.dumb it down, and show a pseudo example. -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From amonroe at columbus.rr.com Sat Jan 22 21:12:51 2011 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 22 Jan 2011 15:12:51 -0500 Subject: [Tutor] Exercise suggestions In-Reply-To: <704586.24112.qm@web130210.mail.mud.yahoo.com> References: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: <190670215048.20110122151251@columbus.rr.com> > I just have no idea of what kind of programs to build, Some of the stock answers for this question are: http://projecteuler.net/ http://www.pythonchallenge.com/ I usually suggest porting one of the old games in: http://www.atariarchives.org/basicgames/ Alan From wprins at gmail.com Sat Jan 22 21:25:51 2011 From: wprins at gmail.com (Walter Prins) Date: Sat, 22 Jan 2011 20:25:51 +0000 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: Hi David, On 22 January 2011 20:03, David Hutto wrote: > This is just a reach question. What modules would i want to use if i > wanted to just send the signal, and receive the signal, other than > maybe, signal. In other words please tone.dumb it down, and show a > pseudo example. > I've read your question several times and don't really understand what you're asking? What signal are you trying to send and receive? From the subject I must guess you want to interact with the phone somehow, but I'm not exactly sure what you're asking. (You're right though, that the "signal" module has nothing to do with telephones.) On Windows, the standard way to interact with telephony systems is via the TAPI interfaces ( http://msdn.microsoft.com/en-us/library/ms734273%28v=vs.85%29.aspx) , which I guess should be directly usable in Python via at least PyWin32 or some other means. It's also possible that a Python specific wrapper exists, although a quick google hasn't turned up anything obvious. Hope that helps... Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Sat Jan 22 21:31:38 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 22 Jan 2011 15:31:38 -0500 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: No, its just wondering whether it works like the USB, with two data pins, and -+, I know how the original works, but interpreting through computer language is a little disabling. From smokefloat at gmail.com Sat Jan 22 21:33:43 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 22 Jan 2011 15:33:43 -0500 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: I'm getting ahead and behind my self here. I'm going from electrician to programmer. So I'm tring to construct the 'flow through' and the functional flow through. From kb1pkl at aim.com Sat Jan 22 22:17:10 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Sat, 22 Jan 2011 16:17:10 -0500 Subject: [Tutor] Exercise suggestions In-Reply-To: References: <704586.24112.qm@web130210.mail.mud.yahoo.com> <4D3B37F0.1020408@aim.com> Message-ID: <4D3B4956.5040507@aim.com> On 01/22/2011 03:09 PM, David Hutto wrote: >> When I felt I was ready to start doing some work, I got involved in an open >> source project. It's definitely an experience! Try going through >> http://freshmeat.net/ > > Isn't that for those that aren't given real apprenticeship?:) > Programming is my hobby, not my profession. Also given the fact that I've yet to graduate high school, OS was the way to go for me. ~Corey From chrysalis_reborn at yahoo.com Sat Jan 22 22:52:21 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Sat, 22 Jan 2011 13:52:21 -0800 (PST) Subject: [Tutor] Exercise suggestions In-Reply-To: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: <33082.40466.qm@web130208.mail.mud.yahoo.com> Well, I'm a noob myself, so perhaps take what I say with a grain or three of salt.? On the other hand, I have sort of the opposite problem, lots of ideas, but not the time nor skill to make them happen. Do you even necessarily have to complete a project?? Sometimes just making an attempt can teach you things. How about an archiving assistant, that makes a list of files to be fed into an archiver such as zip, etc.? I seem to remember that Python (is it supposed to be capitalized?? Official logo is in lower case), has modules to access zip or bzip or somesuch.? Sure, there are tons of these sorts of apps already, but so what?? Maybe you can make one that is better. Find some text files to parse.? I have found a use for this where I work.? The company used to have these old dedicated green screen "dumb terminals" used to access a database.? They upgraded to pc's with an emulator program for the old green screen.? In my job I have to do audits of various information that is still stored in that database, which meana a lot of manual data entry.? I found that the emulator we were using has a low level scripting engine built in.? I was able to use that to feed it a list of part numbers, and then capture the raw screens of data to a large text file...which I then had to parse. I wrote a program in Tcl that would let the user select from several lists of part numbers, then it would write a custom script for the emulator and then call the emulator with that script.? The emulator would do it's thing and spit out text file and then call my parser, a separate program, that would then step through the screens and extract the information I was after.? It could do 600 part numbers in about 20 minutes, a task that would have taken me hours to do manually. At one point I needed to extract some information from some raw vCard files.? Same thing, load a text file and step through it and extract what I needed.? Next step is to get this information into an SQLite database. Such projects teach string handling, regular expressions, etc., plus it trains you to look for patterns in text that you can feed to your regex. Simple games.? Do a text adventure.? Do an ascii art adventure game using the Tkinter text widget.? Do some other sort of adventure game and use the canvas widget, instead. Do a tetris clone.? Do a "same game" clone.? Do an icebreaker clone.? Do a python based version of Santa Paravia, http://www.santaparavia.com/Home.aspx Make a simple MUD using python's networking capabilities. Here's another work related project I did (but never finished), again in Tcl, but I am in the process of re-writing it in python, hopefully using OOP: I run a CMM (Coordinate Measuring Machine).?? We have a rather kludgy process for submitting work orders for parts to be measured on the machine, using something called Maximo (an IBM product...interesting, isn't it...how they tend to make crappy products and have "BM" in their name...coincidence?? I think not.)? Maximo is ugly an ugly lookin' slow, cryptic web app.? I think java is involved in it somewhere...which seems to be the case with a lot of ugly, slow web-apps. Anyway, I decided to create a dedicated application to do the same thing.? The machine operators would put in a part number, their ID number, a quantity, and a part serial number, if any.? My app would find the part name, validate the info, and generate a time stamped "work order".? That was as far as I got, but the idea was that I could then "sign off" on this work order and the application would track the amount of time between when the operator submitted the part for measurement on the CMM to the time I was done with it, with a sort of sub category that listed how long it took for the CMM to actually measure the part.? Then this information would be made available in a searchable format that my boss could then use to track usage of the CMM, how often parts were being submitted, etc. Further work related stuff.?? We had some documents in Excel format, these were used to print hard copies that the operators would write information on as they checked the various parts off the machining stations (gage readings and such).? I hate, hate, hate, having to deal with these "checksheets"; making new ones for the operators, filing them, etc.? I thought, what if I could make this process simpler? Phase one:? All the Excel files are "printed" to pdf.? I wrote a program that would glob the filenames of these pdf files from a certain directory, sort them by the property number of the machining station associated with a given part, then generate an HTML web page with a list of the checksheets for that machine.?? An operator (or me) can just pick their machine on the web page, then scroll through a list of part numbers, and choose the one they want.? The pdf opens in Internet Explorer, and they can print them off.? No more digging for the original master copy in a three ring binder.? No more auditing to make sure that the master in the binder is up to date, since the pdf is made directly from the original Excel master...which is my boss's responsibility ;-). Phase two:? Still partially vaporware.? I export the original Excel file to .csv format.? I have a Tcl based parser? (hey, I am only just switching to python here, okay?) that loads one of these files, and parses it into XML format.? The idea is to take these XML files and use them in some sort of web app to make an HTML form based version that the operators can just fill out.? These will be searchable and otherwise data-massageable...right now, the operators fill 'em out and we file them until there is a problem.? The engineers would also be able access the info to see if there are any trends with features on parts that are going out of spec, part runs vs. tool wear, etc. Here's another idea.? Imagine that you are the owner of some sort of restaurant.? Write yourself a Point of Sale app for your restaurant.? I've always thought it would be neat to walk into say, a pizza place and use some sort of kiosk with drag and drop virtual pizza ingredients.? You design your pizza, it sends the order to the kitchen, you pay, and then go sit down until someone brings your order.??? This could work for a fast food place, or whatever. Further restaurant idea, more complicated.? I had this one years ago, but the computer hardware back then wasn't up to it...at least the hardware I could afford, anyway.? This is a simulation game of sorts.?? The user designs a restaurant from the ground up, chooses the physical layout of the dining room, kitchen, etc.? Designs a menu.? Designates where the food for creating that menu is stored.? Hires servers, a chef, prep cooks, etc., then fires up the virtual restaurant.? From here they get to see how the layout of their kitchen and dining room works.? Are people getting in each other's way in the kitchen or the dining room?? Is your kitchen able to keep up?? Do you have enough staff?? Are the dishes being washed fast enough?? Are you buying enough ingredients to make sure that you don't run out of food?? Or have too much stock on hand and you are losing some to spoilage?? Are you managing costs and making a profit??? What about unexpected events, like equipment breakdowns, or a sudden influx of customers on a night you expected things to be a bit slow?? What if you get a surprise visit from the health inspector?? What if a customer gets food poisoning and sues you?? What if an employee is injured at work?? (slips, falls, cuts, etc.)? What if a rival restaurant offers your chef more money? (and just thinking about this, the whole idea above could also be applied to a factory, which is all a restaurant is, really, a factory that produces edible consumables, rather than durable goods). What about a facebook app?? I think you can do those in python. There are all sorts of scenarios in the above for one to analyze and create code to simulate, etc. Enough of my blathering.?? Basically....find something, a problem, an imaginary idea like a game, and then figure out how to apply programming solutions to that problem. --- On Sat, 1/22/11, michael scott wrote: From: michael scott Subject: [Tutor] Exercise suggestions To: tutor at python.org Date: Saturday, January 22, 2011, 11:56 AM I am new to programming, I intend to get an entry level job programming next year (or a little bit longer). I am switching fields and not going to college, but kinda "self teaching" myself through various methods. I currently understand concepts in programming in python up to classes (like I understand how to make objects, I understand inheritance, etc...), and I have experimented with building guis in Tkinter,? but I'm finding that I understand concepts, but have no real way to implement them. So now my problem emerges... can anyone give me suggestions of exercises I should do to help improve? my knowledge of what I can "actually" do with the concepts I have. My main goal is to get to the point where I can assist in fixing bugs in open source programs (I'll be learning C++ in a couple months as well), but when I look at bugs / source code of larger programs, I am just so blown away at how little I understand. So I need to find a way to bridge the gap between my current level and the level needed to contribute to open source programs. A lofty goal I understand, but it is my goal. And I am very dedicated to reaching it. Anyways, given my situation, do you good people have any suggestions for me. I don't need a person walking me through it, a simple, "build a program that asks a user to give you a name and create permutations of it" is great. Of course that example is elementary, but that is the gist of the responses I'm looking for. I just have no idea of what kind of programs to build, my ignorance is holding me back in my opinion. Any response is welcomed, but I do ask if you are critical of me, please offer a method for me to improve the deficiency / deficiencies? I have. Thank you so much for reading my inquiry :) ?What is it about you... that intrigues me so? -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Sat Jan 22 23:06:24 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Sat, 22 Jan 2011 14:06:24 -0800 Subject: [Tutor] Exercise suggestions In-Reply-To: <33082.40466.qm@web130208.mail.mud.yahoo.com> References: <33082.40466.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D3B54E0.9010806@iandouglas.com> For me, the quickest way to jump into a programming language was seeing a current open source project and say "I wish it did this too, or that instead ..." and implement it myself. Not only do you learn about the project itself, and pick up some tips and tricks along the way, you then also have a way to tell the original author about something you could contribute if others are interested. So, it's not just working on something to make it "better", you do it to make it "personal" to your own needs instead. On 01/22/2011 01:52 PM, Elwin Estle wrote: > Sure, there are tons of these sorts of apps already, but so what? > Maybe you can make one that is better. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Sat Jan 22 23:00:27 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Sat, 22 Jan 2011 14:00:27 -0800 (PST) Subject: [Tutor] python wallpapers Message-ID: <434832.26930.qm@web130204.mail.mud.yahoo.com> I dabble in Blender 3d. Just for the heck of it, I made some desktop wallpapers using the python logo.? Enjoy or not, as suits your fancy. http://thepythonnoob.blogspot.com/2011/01/some-3d-python-wallpapers.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Sat Jan 22 23:35:36 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Sat, 22 Jan 2011 14:35:36 -0800 (PST) Subject: [Tutor] Exercise suggestions In-Reply-To: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: <752903.76931.qm@web130208.mail.mud.yahoo.com> Okay, here's another one.? I started this geez...30 years ago?? On a Texas Instruments 99/4A computer.? I've never gotten around to doing anything further with the idea. It was a game called "Piledriver".? The idea was that in a distant future, energy demands had become so great that there were all these competing energy companies running nuclear reactors to generate power.? The reactors were run by human brains hardwired into the control systems, i.e. "Atomic Pile", or "Piledrivers"? (hey, I was 19 when I thought of this, okay?) The player is, of course, one of these "piledrivers".? The idea was that they started with a basic nuclear generator set up, providing power to a certain area of a city, at a certain cost.? They had to take the profits from their efforts and build an "energy empire".? They had to deal with things like installing and maintaining transmission lines, additional power generating capability, etc.? They had to fund day to day expenses, pay for security forces, which served several purposes, to keep any "unauthorized persons" from stealing their fuel either for competitors or perhaps for terrorists wanting to build bombs, etc., or environmentalists wanting to shut down your evil, earth threatening facility... The security forces also act to prevent any other industrial espionage from competitors, terrorists, or over zealous environmental groups. Also funded were your own espionage agents to do the same to competitors, infiltrate militant environmental groups, get blackmail material on politicians that could help/hurt your business, etc? There would be? R & D specialists who would periodically introduce new technologies to increase the efficiency or safety of the nuclear generators. (I had this sort of random name generator I made for the scientists creations, that would spit out things like "Your R & D department have created the hypertronic whatchamacallit, which increases your reactor efficiency by .02%", or somesuch. You had to control the rate you charged customers for your energy.? Too much and they might switch to a competitor.? Too little and you couldn't afford to pay your security guys, PR department (advertising...or there to put a "spin" on things in case there was some sort of industrial "incident" at your facility), or R&D department.? You paid for advertising, public service stuff and other PR to keep the environmentalists of your back. You could also do things like fund lobbyists or bribe politicians to get preferential treatment from the government. Bad things could happen, like faulty equipment creating an "incident", or perhaps a competitor manages to infiltrate a mole into your R&D, PR, or Security forces.? You might end up with a horde of angry environmentalists at your gates, complete with TV crews, etc, and have to deal with that (causing energy subscribers to leave for competitors, or government fines, etc.) My original idea also allowed for some hands on stuff.? There would be these little maintenance bots that you'd "drive" around the facility, looking for things like faulty equipment, or sabotage by competitors or terrorists...or even environmentalists. ...anyway, you get the idea.? Perhaps a lame idea in the context of today's 3D graphical games,? but if properly implemented...maybe it would be fun. --- On Sat, 1/22/11, michael scott wrote: From: michael scott Subject: [Tutor] Exercise suggestions To: tutor at python.org Date: Saturday, January 22, 2011, 11:56 AM I am new to programming, I intend to get an entry level job programming next year (or a little bit longer). I am switching fields and not going to college, but kinda "self teaching" myself through various methods. I currently understand concepts in programming in python up to classes (like I understand how to make objects, I understand inheritance, etc...), and I have experimented with building guis in Tkinter,? but I'm finding that I understand concepts, but have no real way to implement them. So now my problem emerges... can anyone give me suggestions of exercises I should do to help improve? my knowledge of what I can "actually" do with the concepts I have. My main goal is to get to the point where I can assist in fixing bugs in open source programs (I'll be learning C++ in a couple months as well), but when I look at bugs / source code of larger programs, I am just so blown away at how little I understand. So I need to find a way to bridge the gap between my current level and the level needed to contribute to open source programs. A lofty goal I understand, but it is my goal. And I am very dedicated to reaching it. Anyways, given my situation, do you good people have any suggestions for me. I don't need a person walking me through it, a simple, "build a program that asks a user to give you a name and create permutations of it" is great. Of course that example is elementary, but that is the gist of the responses I'm looking for. I just have no idea of what kind of programs to build, my ignorance is holding me back in my opinion. Any response is welcomed, but I do ask if you are critical of me, please offer a method for me to improve the deficiency / deficiencies? I have. Thank you so much for reading my inquiry :) ?What is it about you... that intrigues me so? -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Sat Jan 22 23:55:19 2011 From: wescpy at gmail.com (wesley chun) Date: Sat, 22 Jan 2011 14:55:19 -0800 Subject: [Tutor] Exercise suggestions In-Reply-To: <704586.24112.qm@web130210.mail.mud.yahoo.com> References: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: > [...] I'm finding that I > understand concepts, but have no real way to implement them. > > So now my problem emerges... can anyone give me suggestions of exercises I > should do to help improve? my knowledge of what I can "actually" do with the > concepts I have. michael, first of all, welcome to Python! a couple of suggestions... 1) the best thing to do is to "scratch an itch" now that you know how to code. what is an app that would really benefit you on a daily (or weekly) basis? it can be anything. for me, i've created small apps to: a) validate the syntax of a Python script, b) create PowerPoint files on the fly based on a plain text file (because i didn't want to edit slides in PowerPoint anymore), etc. 2) if you happen to have my book, i put in numerous exercises at the end of every chapter to complement the reading and to enforce that you did pick up on the material within that and previous chapters. i've gotten good feedback from readers who say that they were really useful in hammering home the concepts. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 ? ? http://corepython.com wesley.chun : wescpy-gmail.com : @wescpy python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sat Jan 22 23:05:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 22:05:28 -0000 Subject: [Tutor] Telephone app References: Message-ID: "David Hutto" wrote > This is just a reach question. What modules would i want to use if i > wanted to just send the signal, and receive the signal, other than > maybe, signal. In other words please tone.dumb it down, and show a > pseudo example. We need a lot more info. How are you interfacing and to what? Are you talking about SIP? Or is it a TAPI app? Are you interfacing to a real handset or building a softphone? What are you using for a server or switch? The one thing you probably don't want to use is signal.... There are modules to support SIP. I don't know of any TAPI ones but I suspect they will exist. If not you can use the native Windows APIs (MSTAPI.DLL I think) or the Java API vias a bridge or from Jython. But thats a prettty wide ask. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 22 23:11:54 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 22:11:54 -0000 Subject: [Tutor] Telephone app References: Message-ID: "David Hutto" wrote > No, its just wondering whether it works like the USB, with two data > pins, and -+, I know how the original works, but interpreting > through > computer language is a little disabling. The original what? What works like USB? A traditional analog line works with a 2 wire signal to the central switch with a 3 wire signal between stations. All controlled by hardware analog signalling. If you move to digital telephony (non VoIP) then you get into a plethory of different signalling protocols all controlled by the ITU. Which protocol applies depends on the manufacturer of the switch, the country you are in etc. ISDN is defined in a standard of its own. VoIP has a whole different set of protocols, the most common on PCs is SIP. If you just want to control an analog phoneline then the esiest way is to use a modem and communicate with it via the Hayes command set over the serial port. And whatever you do remember that the core of all telecomms work is a reliable state machine. All telecomms protocols are stateful to some degree. But for now its just not clear what you are trying to do. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 22 23:14:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 22:14:08 -0000 Subject: [Tutor] Telephone app References: Message-ID: "David Hutto" wrote > I'm getting ahead and behind my self here. I'm going from > electrician > to programmer. So I'm tring to construct the 'flow through' and the > functional flow through. Can you step back a bit and explain what it is you are trying to accomplish? "flow through" and "functional flow through" are meaningless terms in telecomms - at least so far as I am aware (after my 35 years in telecomms engineering...) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Jan 22 23:24:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 22 Jan 2011 22:24:08 -0000 Subject: [Tutor] Exercise suggestions References: <704586.24112.qm@web130210.mail.mud.yahoo.com> Message-ID: "michael scott" wrote > don't need a person walking me through it, a simple, "build a > program that asks > a user to give you a name and create permutations of it" is great. > Of course > that example is elementary, but that is the gist of the responses > I'm looking > for. So have you done it yet? And then added a GUI? Or generated a group of random letters and let the user guess the longest word they can make up using those letters - and compare the result that the computer found based on a dictionary of valid words? Then add a second user so it becomes a competition with the computer validating the two results and declaring a winner. > I just have no idea of what kind of programs to build, my ignorance > is > holding me back in my opinion. Your suggestion was a good start then use imagination on how to improve it. Then go looking for things you do manually on your computer (or in a notebook) and automate them. You need experience and the more relevant and real your programmes are the better. The one problem with Opensource projects compasred to professional/commercial coding is that there is nearly always a dearth of design documentation. Moost commercial software shops will produce architecure and design documentation that helps you find your way aropund a project. There are probably exceptions (Linux is one which has several books written about the design) but thats my experience of Opensource code. You just have to wade in and start reading. Playing with a debugger and grepping for likely strings in functions is a good starting point - and asking questions on the devel mailing lists too. > Any response is welcomed, but I do ask if you are critical of me Your aspirations are good but remember that most professional programmers are college or universitry trained. Its not an easy job to market to crack without professional qualifications. You need a lot of experience to evidence your competence. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Jan 23 00:36:21 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Jan 2011 10:36:21 +1100 Subject: [Tutor] Exercise suggestions In-Reply-To: <33082.40466.qm@web130208.mail.mud.yahoo.com> References: <33082.40466.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D3B69F5.1090602@pearwood.info> Elwin Estle wrote: > I seem to remember that Python (is it supposed to be capitalized? Official logo is in lower case) The official logo of Apple doesn't even have an "A" in it, but we don't spell the company "pple" :) By long-standing convention and practice, the programming language is spelled with an initial capital ("Python"), and the executable command on computers is spelled in lowercase ("python"). Go to http://www.python.org/ and you will see the language is always referred to as Python rather than python. -- Steven From tcl76 at hotmail.com Sun Jan 23 01:38:10 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 23 Jan 2011 00:38:10 +0000 Subject: [Tutor] Help on RE Message-ID: hi, i have a set of data and using re to extract it into array. however i only get positive value, how to extract the whole value including the -ve sign? For eg: Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 55 0 1 2 10 35 0 1 3 25 35 0 1 4 35 25 0 1 5 10 -1 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s When i run my code, i get 1 instead of -1 in the last line. here is my code. pls advise. i'm using Python 2.5 and Win XP. tq ##code### import re file = open("C:/Python25/myscript/plot/sampledata.txt", "r") x1 = [] y1 = [] y2 = [] for line in file: numbers = re.findall("\d+", line) print numbers -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Sun Jan 23 01:53:49 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 23 Jan 2011 00:53:49 +0000 Subject: [Tutor] Help on RE In-Reply-To: References: , Message-ID: thanks it works!! :) > Date: Sat, 22 Jan 2011 19:51:35 -0500 > Subject: Re: [Tutor] Help on RE > From: japhy at pearachute.com > To: tcl76 at hotmail.com > CC: tutor at python.org > > it's a bug in your regex - you want something like "-?\d+" > > - japhy > > On Sat, Jan 22, 2011 at 7:38 PM, tee chwee liong wrote: > > hi, > > > > i have a set of data and using re to extract it into array. however i only > > get positive value, how to extract the whole value including the -ve sign? > > For eg: > > > > Platform: PC > > Tempt : 25 > > TAP0 :0 > > TAP1 :1 > > +++++++++++++++++++++++++++++++++++++++++++++ > > Port Chnl Lane EyVt EyHt > > +++++++++++++++++++++++++++++++++++++++++++++ > > 0 1 1 75 55 > > 0 1 2 10 35 > > 0 1 3 25 35 > > 0 1 4 35 25 > > 0 1 5 10 -1 > > +++++++++++++++++++++++++++++++++++++++++++++ > > Time: 20s > > > > When i run my code, i get 1 instead of -1 in the last line. here is my code. > > pls advise. i'm using Python 2.5 and Win XP. tq > > ##code### > > import re > > file = open("C:/Python25/myscript/plot/sampledata.txt", "r") > > x1 = [] > > y1 = [] > > y2 = [] > > for line in file: > > numbers = re.findall("\d+", line) > > print numbers > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Sun Jan 23 02:01:26 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 23 Jan 2011 01:01:26 +0000 Subject: [Tutor] Help on RE In-Reply-To: <20110123005537.GA19098@dragon.alchemy.com> References: , <20110123005537.GA19098@dragon.alchemy.com> Message-ID: thanks for making me understand more on re. re is a confusing topic as i'm starting on python. > Date: Sat, 22 Jan 2011 16:55:37 -0800 > From: steve at alchemy.com > To: tcl76 at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] Help on RE > > On Sun, Jan 23, 2011 at 12:38:10AM +0000, tee chwee liong wrote: > > i have a set of data and using re to extract it into array. however i only get positive value, how to extract the whole value including the -ve sign? > > numbers = re.findall("\d+", line) > > The \d matches a digit character. \d+ matches one or more digit characters. > Nothing in your regex matches a sign character. You might want something like > [-+]\d+ > which would require either a - or + followed by digits. If you want the sign > to be optional, maybe this would work: > [-+]?\d+ > > > > > -- > Steve Willoughby | Using billion-dollar satellites > steve at alchemy.com | to hunt for Tupperware. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Sun Jan 23 01:55:37 2011 From: steve at alchemy.com (Steve Willoughby) Date: Sat, 22 Jan 2011 16:55:37 -0800 Subject: [Tutor] Help on RE In-Reply-To: References: Message-ID: <20110123005537.GA19098@dragon.alchemy.com> On Sun, Jan 23, 2011 at 12:38:10AM +0000, tee chwee liong wrote: > i have a set of data and using re to extract it into array. however i only get positive value, how to extract the whole value including the -ve sign? > numbers = re.findall("\d+", line) The \d matches a digit character. \d+ matches one or more digit characters. Nothing in your regex matches a sign character. You might want something like [-+]\d+ which would require either a - or + followed by digits. If you want the sign to be optional, maybe this would work: [-+]?\d+ -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From steve at pearwood.info Sun Jan 23 04:10:35 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 23 Jan 2011 14:10:35 +1100 Subject: [Tutor] Help on RE In-Reply-To: References: , <20110123005537.GA19098@dragon.alchemy.com> Message-ID: <4D3B9C2B.7070004@pearwood.info> tee chwee liong wrote: > thanks for making me understand more on re. re is a confusing topic as i'm starting on python. I quote the great Jamie Zawinski, a world-class programmer and hacker: Some people, when confronted with a problem, think 'I know, I'll use regular expressions." Now they have two problems. Zawinski doesn't mean that you should never use regexes. But they should be used only when necessary, for problems that are difficult enough to require a dedicated domain-specific language for solving search problems. Because that's what regexes are: they're a programming language for text searching. They're not a full-featured programming language like Python (technically, they are not Turing Complete) but nevertheless they are a programming language. A programming language with a complicated, obscure, hideously ugly syntax (and people complain about Forth!). Even the creator of Perl, Larry Wall, has complained about regex syntax and gives 19 serious faults with regular expressions: http://dev.perl.org/perl6/doc/design/apo/A05.html Most people turn to regexes much too quickly, using them to solve problems that are either too small to need regexes, or too large. Using regexes for solving your problem is like using a chainsaw for peeling an orange. Your data is very simple, and doesn't need regexes. It looks like this: Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 55 0 1 2 10 35 0 1 3 25 35 0 1 4 35 25 0 1 5 10 -1 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s The part you care about is the table of numbers, each line looks like this: 0 1 5 10 -1 The easiest way to parse this line is this: numbers = [int(word) for word in line.split()] All you need then is a way of telling whether you have a line in the table, or a header. That's easy -- just catch the exception and ignore it. template = "Port=%d, Channel=%d, Lane=%d, EyVT=%d, EyHT=%d" for line in lines: try: numbers = [int(word) for word in line.split()] except ValueError: continue print(template % tuple(numbers)) Too easy. Adding regexes just makes it slow, fragile, and difficult. My advice is, any time you think you might need regexes, you probably don't. -- Steven From tcl76 at hotmail.com Sun Jan 23 04:31:40 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Sun, 23 Jan 2011 03:31:40 +0000 Subject: [Tutor] Help on RE In-Reply-To: <4D3B9C2B.7070004@pearwood.info> References: , , <20110123005537.GA19098@dragon.alchemy.com>, , <4D3B9C2B.7070004@pearwood.info> Message-ID: elegant. :) simple yet elegant. > Date: Sun, 23 Jan 2011 14:10:35 +1100 > From: steve at pearwood.info > To: tutor at python.org > Subject: Re: [Tutor] Help on RE > > tee chwee liong wrote: > > thanks for making me understand more on re. re is a confusing topic as i'm starting on python. > > I quote the great Jamie Zawinski, a world-class programmer and hacker: > > Some people, when confronted with a problem, think 'I know, I'll > use regular expressions." Now they have two problems. > > > Zawinski doesn't mean that you should never use regexes. But they should > be used only when necessary, for problems that are difficult enough to > require a dedicated domain-specific language for solving search problems. > > Because that's what regexes are: they're a programming language for text > searching. They're not a full-featured programming language like Python > (technically, they are not Turing Complete) but nevertheless they are a > programming language. A programming language with a complicated, > obscure, hideously ugly syntax (and people complain about Forth!). Even > the creator of Perl, Larry Wall, has complained about regex syntax and > gives 19 serious faults with regular expressions: > > http://dev.perl.org/perl6/doc/design/apo/A05.html > > Most people turn to regexes much too quickly, using them to solve > problems that are either too small to need regexes, or too large. Using > regexes for solving your problem is like using a chainsaw for peeling an > orange. > > Your data is very simple, and doesn't need regexes. It looks like this: > > > Platform: PC > Tempt : 25 > TAP0 :0 > TAP1 :1 > +++++++++++++++++++++++++++++++++++++++++++++ > Port Chnl Lane EyVt EyHt > +++++++++++++++++++++++++++++++++++++++++++++ > 0 1 1 75 55 > 0 1 2 10 35 > 0 1 3 25 35 > 0 1 4 35 25 > 0 1 5 10 -1 > +++++++++++++++++++++++++++++++++++++++++++++ > Time: 20s > > > The part you care about is the table of numbers, each line looks like this: > > 0 1 5 10 -1 > > The easiest way to parse this line is this: > > numbers = [int(word) for word in line.split()] > > All you need then is a way of telling whether you have a line in the > table, or a header. That's easy -- just catch the exception and ignore it. > > template = "Port=%d, Channel=%d, Lane=%d, EyVT=%d, EyHT=%d" > for line in lines: > try: > numbers = [int(word) for word in line.split()] > except ValueError: > continue > print(template % tuple(numbers)) > > > Too easy. Adding regexes just makes it slow, fragile, and difficult. > > > My advice is, any time you think you might need regexes, you probably don't. > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From badouglas at gmail.com Sun Jan 23 07:16:03 2011 From: badouglas at gmail.com (bruce) Date: Sat, 22 Jan 2011 22:16:03 -0800 Subject: [Tutor] multi-threaded/parallel processing - local tutor Message-ID: Hi. I'm working on a project that uses python to spawn/create multiple threads, to run parallel processes to fetch data from websites. I'm looking to (if possible) go over this in person with someone in the San Fran area. Lunch/beer/oj can be on me!! It's a little too complex to try to describe here, and pasting the code/apps wouldn't do any good without an associated conversation. So, if you're in the Bay area, and you're up to some in person tutoring, let me know. Thanks guys for this list!! From shantanoo at gmail.com Sun Jan 23 08:40:37 2011 From: shantanoo at gmail.com (=?utf-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Sun, 23 Jan 2011 13:10:37 +0530 Subject: [Tutor] multi-threaded/parallel processing - local tutor In-Reply-To: References: Message-ID: <3C32FD97-0827-4839-938A-A0E8ECAD0A72@gmail.com> You may find following useful. 2.6+ --- http://docs.python.org/library/multiprocessing.html 3.x --- http://docs.python.org/dev/library/multiprocessing.html On 23-Jan-2011, at 11:46 AM, bruce wrote: > Hi. > > I'm working on a project that uses python to spawn/create multiple > threads, to run parallel processes to fetch data from websites. I'm > looking to (if possible) go over this in person with someone in the > San Fran area. Lunch/beer/oj can be on me!! > > It's a little too complex to try to describe here, and pasting the > code/apps wouldn't do any good without an associated conversation. > > So, if you're in the Bay area, and you're up to some in person > tutoring, let me know. > > Thanks guys for this list!! > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From japhy at pearachute.com Sun Jan 23 01:51:35 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Sat, 22 Jan 2011 19:51:35 -0500 Subject: [Tutor] Help on RE In-Reply-To: References: Message-ID: it's a bug in your regex - you want something like "-?\d+" - japhy On Sat, Jan 22, 2011 at 7:38 PM, tee chwee liong wrote: > hi, > > i have a set of data and using re to extract it into array. however i only > get positive value, how to extract the whole value including the -ve sign? > For eg: > > Platform: PC > Tempt?: 25 > TAP0?:0 > TAP1?:1 > +++++++++++++++++++++++++++++++++++++++++++++ > Port?Chnl?Lane?EyVt?EyHt > +++++++++++++++++++++++++++++++++++++++++++++ > 0? 1? 1? 75 ?55 > 0? 1? 2? 10?35 > 0? 1? 3? 25?35 > 0? 1? 4? 35?25 > 0? 1? 5? 10?-1 > +++++++++++++++++++++++++++++++++++++++++++++ > Time: 20s > > When i run my code, i get 1 instead of -1 in the last line. here is my code. > pls advise. i'm using Python 2.5 and Win XP. tq > ##code### > import re > file = open("C:/Python25/myscript/plot/sampledata.txt", "r") > x1 = [] > y1 = [] > y2 = [] > for line in file: > ??? numbers = re.findall("\d+", line) > ??? print numbers > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From fomcl at yahoo.com Sun Jan 23 10:33:32 2011 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 23 Jan 2011 01:33:32 -0800 (PST) Subject: [Tutor] Help on RE In-Reply-To: <4D3B9C2B.7070004@pearwood.info> References: , <20110123005537.GA19098@dragon.alchemy.com> <4D3B9C2B.7070004@pearwood.info> Message-ID: <435065.82426.qm@web110714.mail.gq1.yahoo.com> http://imgs.xkcd.com/comics/regular_expressions.png ;-) Cheers!! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ________________________________ From: Steven D'Aprano To: tutor at python.org Sent: Sun, January 23, 2011 4:10:35 AM Subject: Re: [Tutor] Help on RE tee chwee liong wrote: > thanks for making me understand more on re. re is a confusing topic as i'm >starting on python. > I quote the great Jamie Zawinski, a world-class programmer and hacker: Some people, when confronted with a problem, think 'I know, I'll use regular expressions." Now they have two problems. Zawinski doesn't mean that you should never use regexes. But they should be used only when necessary, for problems that are difficult enough to require a dedicated domain-specific language for solving search problems. Because that's what regexes are: they're a programming language for text searching. They're not a full-featured programming language like Python (technically, they are not Turing Complete) but nevertheless they are a programming language. A programming language with a complicated, obscure, hideously ugly syntax (and people complain about Forth!). Even the creator of Perl, Larry Wall, has complained about regex syntax and gives 19 serious faults with regular expressions: http://dev.perl.org/perl6/doc/design/apo/A05.html Most people turn to regexes much too quickly, using them to solve problems that are either too small to need regexes, or too large. Using regexes for solving your problem is like using a chainsaw for peeling an orange. Your data is very simple, and doesn't need regexes. It looks like this: Platform: PC Tempt : 25 TAP0 :0 TAP1 :1 +++++++++++++++++++++++++++++++++++++++++++++ Port Chnl Lane EyVt EyHt +++++++++++++++++++++++++++++++++++++++++++++ 0 1 1 75 55 0 1 2 10 35 0 1 3 25 35 0 1 4 35 25 0 1 5 10 -1 +++++++++++++++++++++++++++++++++++++++++++++ Time: 20s The part you care about is the table of numbers, each line looks like this: 0 1 5 10 -1 The easiest way to parse this line is this: numbers = [int(word) for word in line.split()] All you need then is a way of telling whether you have a line in the table, or a header. That's easy -- just catch the exception and ignore it. template = "Port=%d, Channel=%d, Lane=%d, EyVT=%d, EyHT=%d" for line in lines: try: numbers = [int(word) for word in line.split()] except ValueError: continue print(template % tuple(numbers)) Too easy. Adding regexes just makes it slow, fragile, and difficult. My advice is, any time you think you might need regexes, you probably don't. -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sun Jan 23 13:09:46 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 23 Jan 2011 04:09:46 -0800 Subject: [Tutor] What is a semantic error? Message-ID: Here are 3 examples of syntax errors: >>> print('and) Traceback (most recent call last): File "", line 1, in Syntax Error: print('and): , line 112 >>> if 3 > 2 ... print(3) ... Traceback (most recent call last): File "", line 1, in Syntax Error: if 3 > 2: , line 19 >>> if 34 345: ... print(34) ... Traceback (most recent call last): File "", line 1, in Syntax Error: if 34 345:: , line 19 >>> But could someone give me a clearcut example of a semantic error? And a definition that delineates semantic errors from syntax errors. I googled this one up, http://ubuntuforums.org/showthread.php?t=527855, where the guy uses '&' where he should have used 'and'. That's clearcut, but is it really a semantic error? If he had used, say, '!' where he used '&' (which it seems has meaning in that context), that would be a syntax error, right? >>> if 3 == 3 & 4 > 3: ... print("Duh") ... >>> >>> if 3 == 3 ! 4 > 3: ... print("Doh!") ... Traceback (most recent call last): File "", line 1, in Syntax Error: if 3 == 3 ! 4 > 3:: , line 111 >>> Is a semantic error one that Python doesn't see as an error -- no error is raised; whereas syntax errors aren't errors unless Python sees them as "Syntax Error"s? Thanks, Dick Moores From hugo.yoshi at gmail.com Sun Jan 23 13:41:55 2011 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 23 Jan 2011 13:41:55 +0100 Subject: [Tutor] What is a semantic error? In-Reply-To: References: Message-ID: On Sun, Jan 23, 2011 at 1:09 PM, Richard D. Moores wrote: > > Is a semantic error one that Python doesn't see as an error -- no > error is raised; whereas syntax errors aren't errors unless Python > sees them as "Syntax Error"s? > Pretty much this. A semantic error is also called a logic error. A program with a semantic error will not crash or terminate abnormally, but it will not produce the output that you want. Semantic errors are much harder to catch than syntax errors, because programs with semantic errors are still valid programs in the language. A syntax error makes the program invalid, which means the computer can easily identify it. It's up to you to identify semantic errors. HTH, Hugo From waynejwerner at gmail.com Sun Jan 23 13:44:16 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Sun, 23 Jan 2011 06:44:16 -0600 Subject: [Tutor] What is a semantic error? In-Reply-To: References: Message-ID: On Sun, Jan 23, 2011 at 6:09 AM, Richard D. Moores wrote: > Is a semantic error one that Python doesn't see as an error -- no > error is raised; whereas syntax errors aren't errors unless Python > sees them as "Syntax Error"s? > > Yes: http://en.wikipedia.org/wiki/Semantic_error Here is a semantic error: total = 0 for x in xrange(1,11): total = x # Sums up x The actual intent was to use += for total. Another example # Sums up numbers 1-10 inclusive total = 0 for x in xrange(1,10): total += x Of course (x)range doesn't include the end index, so in both cases the program would compile and execute, but neither would give the programmers intended result. HTH -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Jan 23 15:08:14 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 24 Jan 2011 01:08:14 +1100 Subject: [Tutor] What is a semantic error? In-Reply-To: References: Message-ID: <4D3C364E.90905@pearwood.info> Richard D. Moores wrote: > But could someone give me a clearcut example of a semantic error? And > a definition that delineates semantic errors from syntax errors. "Semantics" relates to the *meaning* of words, sentences or programs. In common English, we might say this sentence has a few grammatical errors, but the semantics are clear: "I getted the milk out off the fridge and putted them into me coffee." On the other hand, these sentences are grammatically fine but semantically ambiguous: "Children make nutritious snacks." "The thief was sentenced to six months in the violin case." "Cocaine users are turning to ice." "Police shoot man with crossbow." "The building workers are refusing to work after fatal accidents." and of course the classic example of a grammatically valid sentence with no semantic meaning: "Colourless green ideas sleep furiously." Often you can guess the meaning of such ambiguous sentences from domain specific knowledge. We know that eating children is generally frowned upon, and so we reject the interpretation of the snacks being made *from* the children rather than *by* the children. Other times it is much harder to resolve the ambiguity: "The English history teacher marked the test paper." Did she, or he, teach English history, or was she English and a history teacher? Bringing it back to programming in general, and Python specifically, we don't talk about "grammar errors" but "syntax errors" instead. The two are, more or less, analogous. In principle you could design a compiler to try guessing what you probably meant when faced with syntax errors: x, y = alist[1;3] probably is a typo of ; instead of : but such cases are far too rare to be worth worrying about, and in any case, "Do what I mean" (DWIM) tools are risky and rarely do what you mean. http://www.catb.org/~esr/jargon/html/D/DWIM.html A *semantic* error would be something like this: x, y = alist[1:2] when what you actually needed was alist[1:3]. Or: mylist = mylist.sort() (did you really want mylist to be set to None? I don't think so.) It's rare that the compiler can tell what you want, as opposed to what you asked for, with any accuracy. How could the compiler tell that when you wrote: x = math.tan(1.25) you actually wanted math.atan instead? Or should that be math.tan(1.25*pi)? Or something else? -- Steven From alan.gauld at btinternet.com Sun Jan 23 17:43:18 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 23 Jan 2011 16:43:18 -0000 Subject: [Tutor] What is a semantic error? References: <4D3C364E.90905@pearwood.info> Message-ID: "Steven D'Aprano" wrote > are, more or less, analogous. In principle you could design a > compiler to try guessing what you probably meant when faced with > syntax errors: And in fact there are several such compilers for languages like C. The Digital Equipment VAX VMS had an IDE with such a compiler called LSE (Language Sensitive Environment) which could detect and correct many common C syntax errors such as missing semi-colons or using = instead of == etc. It was of course not perfect because there are many such xcases where its imp[ossibler to be certain if its a mistake or a deliberate but unusual construct. But it got it right 9 times out of 10... Languages like ADA and Pascal with much tighter syntax rules are even easier to correct. Open languages like Lisp and Forth are more limited in their opportunities. The LSE tool could be set to automatically correct or present a list of potential corrections which the user then stepped through at the end selecting the corrections required. LSE was quite expensive (about $30,000 for a server license I think, compared to $2000 for the vanilla C compiler) but it saved a lot of time on our project. Automatically detecting/correcting semantic errors is sadly not possible. (I have seen one compiler - for CORAL I think it was?) which attempted to do so, but it could only spit out a list of possible errors with what it thought were the probability of error. And it was wrong at least as often as it was right... Alan G. From badouglas at gmail.com Sun Jan 23 18:38:00 2011 From: badouglas at gmail.com (bruce) Date: Sun, 23 Jan 2011 09:38:00 -0800 Subject: [Tutor] multi-threaded/parallel processing - local tutor In-Reply-To: <3C32FD97-0827-4839-938A-A0E8ECAD0A72@gmail.com> References: <3C32FD97-0827-4839-938A-A0E8ECAD0A72@gmail.com> Message-ID: not looking for docs.. already have code. looking to actually talk to someone in the san fran/bay area for an in person talk/tutor session. thanks 2011/1/22 ????? : > You may find following useful. > > 2.6+ --- http://docs.python.org/library/multiprocessing.html > 3.x --- http://docs.python.org/dev/library/multiprocessing.html > > > On 23-Jan-2011, at 11:46 AM, bruce wrote: > >> Hi. >> >> I'm working on a project that uses python to spawn/create multiple >> threads, to run parallel processes to fetch data from websites. I'm >> looking to (if possible) go over this in person with someone in the >> San Fran area. Lunch/beer/oj can be on me!! >> >> It's a little too complex to try to describe here, and pasting the >> code/apps wouldn't do any good without an associated conversation. >> >> So, if you're in the Bay area, and you're up to some in person >> tutoring, let me know. >> >> Thanks guys for this list!! >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > From rdmoores at gmail.com Sun Jan 23 20:24:27 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 23 Jan 2011 11:24:27 -0800 Subject: [Tutor] What is a semantic error? In-Reply-To: References: Message-ID: Thanks, Tutors, for the excellent replies. I think I've got it now. Dick From bermanrl at cfl.rr.com Sun Jan 23 17:56:14 2011 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 23 Jan 2011 11:56:14 -0500 Subject: [Tutor] PDF to TXT Message-ID: <1295801774.1653.11.camel@bermanrl-desktop> Hi, I am trying to convert .pdf files to .txt files. The script I am using below is mostly taken from research done on Google and it appears to be the one outline most consistently favored (http://code.activestate.com/recipes/577095-convert-pdf-to-plain-text/). I am using Win 7, Python 2.7.1. My code: #pdf2txt.py import sys import pyPdf import os def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + " \n" # Collapse whitespace # content = u" ".join(content.replace(u"\xa0", u" ").strip().split()) return content def main(): pdf = sys.argv[1] filedir,filename = os.path.split(pdf) nameonly = os.path.splitext(filename) newname = nameonly[0] + ".txt" outtxt = os.path.join(filedir,newname) f = open(outtxt,'w') f.write(getPDFContent(pdf)) f.close() main() exit() ============================================================================================================== The program runs for a while and then dies while in one of the pypdf functions. The trace is below. Any insight into how to resolve this situation will be most appreciated. Thank you, Robert ======================================================================================================================= The trace I get is: decimal.InvalidOperation: Invalid literal for Decimal: '.' File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 28, in main() File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 25, in main f.write(getPDFContent(pdf)) File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 13, in getPDFContent content += pdf.getPage(i).extractText() + " \n" File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1381, in extractText content = ContentStream(content, self.pdf) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1464, in __init__ self.__parseContentStream(stream) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1503, in __parseContentStream operands.append(readObject(stream, None)) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 87, in readObject return NumberObject.readFromStream(stream) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 234, in readFromStream return FloatObject(name) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 207, in __new__ return decimal.Decimal.__new__(cls, str(value), context) File "C:\Python27\Lib\decimal.py", line 548, in __new__ "Invalid literal for Decimal: %r" % value) File "C:\Python27\Lib\decimal.py", line 3844, in _raise_error raise error(explanation) From smokefloat at gmail.com Sun Jan 23 22:04:31 2011 From: smokefloat at gmail.com (David Hutto) Date: Sun, 23 Jan 2011 16:04:31 -0500 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: > Can you step back a bit and explain what it is you are trying to > accomplish? "flow through" and "functional flow through" are meaningless > terms in telecomms - at least so far as I am aware (after my 35 years in > telecomms engineering...) It's two fold. First is the obvious of conducting a call/receiving the caller id info. The second is to send directly to the phone, and transmit the caller id data. By flow through, I mean that the phone has one of 2 states(on the hook, off the hook), and three sub states(on the hook/off the hook in use/off the hook not in use). On the actual phone we pick up the receiver, or press the button on the cordless to receive, but the line is always connected, meaning it stops at the phone(terminal). I pick up the receiver, and transmit a series of specific tones which indicate the area code, trunk number and extension(if I remember this correctly, it's been a while since I studied the phone itself). So I have to receive the signal that the phone is ringing(then I'm assuming it sends the caller id info in between rings in some form)/or transmit a series of tones to them to connect. So I think my main question is what modules might be relevant to doing this? And should I be thinking of it any differently than a USB port which has 4 pins two data(+-), and two dc current(+-)? From wprins at gmail.com Sun Jan 23 22:33:33 2011 From: wprins at gmail.com (Walter Prins) Date: Sun, 23 Jan 2011 21:33:33 +0000 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: On 23 January 2011 21:04, David Hutto wrote: > So I have to receive the signal that the phone is ringing(then I'm > assuming it sends the caller id info in between rings in some form)/or > transmit a series of tones to them to connect. > > So I think my main question is what modules might be relevant to doing > this? And should I be thinking of it any differently than a USB port > which has 4 pins two data(+-), and two dc current(+-)? > > I think you're thinking too low level, as alluded to by Alan this type of stuff is done via a voice-modem that you can directly control (via serial port) and get signals from e.g. using its command set. A common standard for about 3 decades has been the Hayes command set: http://en.wikipedia.org/wiki/Hayes_command_set As for control from Python - given that the modem would be present as a serial (COM port) device in the system, I'd have thought that (at worst) you'd be looking to use PySerial to interact with the modem. There may also be more targetted wrappers specifically wrapping modems (don't know, haven't looked). And as mentioned before, you can probably also use the more abstract interface provided by the operating system (TAPI stuff). And yes, USB is quite different from the POTS (Plain Old Telephone System). Forget any ideas that they're anywhere the same thing. Hope that helps. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 23 23:41:39 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 23 Jan 2011 17:41:39 -0500 Subject: [Tutor] Telephone app In-Reply-To: References: Message-ID: <4D3CAEA3.60503@gmail.com> On 1/23/2011 4:04 PM, David Hutto wrote: Warning - do NOT connect a telco landline to a USB port. The line voltage when "on hook" is around 50 V and rises over 100 when ringing. That will certainly fry the port. There are expansion cards and other devices designed to connect to the landline and to a phone. They also process caller id and send touch tone signals. I've tried to follow your explanation. It is too vague for me to make sense of. I guess you want to take the line that comes to you from your local telco, stick something computer-wise between it and an ordinary analog phone, so the computer can receive and process the caller id from an incoming call, and also ensure that the caller id appears on the phone itself, and use the computer to dial numbers (NOT known as caller id). Correct so far? > It's two fold. First is the obvious of conducting a call/receiving the > caller id info. May be obvious to you, but not to me! To support your query please provide some kind of wiring diagram and define "conducting a call". > The second is to send directly to the phone, and transmit the caller id data. Again this is not very precise or clear. What do you want to send to the pone? > By flow through, I mean that the phone has one of 2 states(on the > hook, off the hook) I'm OK with that. > off the hook in use/off the hook not in use). That is not clear. > On the actual phone we pick up the receiver, or press the button on > the cordless to receive, but the line is always connected, meaning it > stops at the phone(terminal). I pick up the receiver, and transmit a > series of specific tones which indicate the area code, trunk number > and extension(if I remember this correctly, it's been a while since I > studied the phone itself). > > So I have to receive the signal that the phone is ringing(then I'm > assuming it sends the caller id info in between rings in some form)/or > transmit a series of tones to them to connect. Huh? > So I think my main question is what modules might be relevant to doing > this? As someone mentioned earlier - TAPI is your friend. > And should I be thinking of it any differently than a USB port > which has 4 pins two data(+-), and two dc current(+-)? As I warned above, YES. -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Mon Jan 24 00:28:05 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 24 Jan 2011 10:28:05 +1100 Subject: [Tutor] Telephone app In-Reply-To: <4D3CAEA3.60503@gmail.com> References: <4D3CAEA3.60503@gmail.com> Message-ID: <4D3CB985.3000006@pearwood.info> bob gailer wrote: > On 1/23/2011 4:04 PM, David Hutto wrote: [...] > I guess you want to take the line that comes to you from your local > telco, stick something computer-wise between it and an ordinary analog > phone, so the computer can receive and process the caller id from an > incoming call, and also ensure that the caller id appears on the phone > itself, and use the computer to dial numbers (NOT known as caller id). Folks, this question has nothing to do with Python and is off-topic for this list. Can you all take it off-list please? There are probably communities on the Internet or Usenet that are interested in low-level telecommunications protocols and devices. We don't go there to talk about Python, please don't stay here talking about their areas of expertise. Thank you. -- Steven From alan.gauld at btinternet.com Mon Jan 24 01:05:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Jan 2011 00:05:14 -0000 Subject: [Tutor] Telephone app References: <4D3CAEA3.60503@gmail.com> <4D3CB985.3000006@pearwood.info> Message-ID: "Steven D'Aprano" wrote > Folks, this question has nothing to do with Python and is off-topic > for this list. Can you all take it off-list please? To be fair David is intending doing this with Python. However he is so far off-base with how he thinks it would work that he probably does need to go research the technology options a bit more before coming back and discussing his preferred options. > There are probably communities on the Internet or Usenet that are > interested in low-level telecommunications protocols and devices. Indeed and they would be a good starying point for adcvvice on how to proceed. Once a techniocal solutoon uis selected we can get back to how to build it in Python. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 24 01:10:02 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Jan 2011 00:10:02 -0000 Subject: [Tutor] Telephone app References: Message-ID: "David Hutto" wrote > By flow through, I mean that the phone has one of 2 states(on the > hook, off the hook), and three sub states(on the hook/off the hook > in > use/off the hook not in use). Umm, no. Much more than that. > On the actual phone we pick up the receiver, or press the button on > the cordless to receive, but the line is always connected, meaning > it > stops at the phone(terminal). I pick up the receiver, and transmit a > series of specific tones which indicate the area code, trunk number > and extension(if I remember this correctly, it's been a while since > I > studied the phone itself). You are describing an anlalog phone but with a greatly oversimplified model. (no dialtone/busy tone/party-line detection etc) You need to do a lot more research into how analog phones work and you will need some hardware to interface to it - weither a dedicated CTI card or a modem. > So I think my main question is what modules might be relevant to > doing > this? And should I be thinking of it any differently than a USB port > which has 4 pins two data(+-), and two dc current(+-)? USB is a digital serial bus, phones are analog. They are not at all alike (quite apart from the voltage issues Bob mentioned). -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From microcore at yahoo.com.cn Mon Jan 24 01:39:45 2011 From: microcore at yahoo.com.cn (Hongbao Chen) Date: Mon, 24 Jan 2011 08:39:45 +0800 Subject: [Tutor] PDF to TXT In-Reply-To: References: Message-ID: Check the python scripts and find the cause of the raise of exception. Good luck. Cheers -----Original Message----- From: tutor-bounces+microcore=yahoo.com.cn at python.org [mailto:tutor-bounces+microcore=yahoo.com.cn at python.org] On Behalf Of tutor-request at python.org Sent: Monday, January 24, 2011 7:33 AM To: tutor at python.org Subject: Tutor Digest, Vol 83, Issue 100 Send Tutor mailing list submissions to tutor at 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 at python.org You can reach the person managing the list at tutor-owner at 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: What is a semantic error? (Richard D. Moores) 2. PDF to TXT (Robert Berman) 3. Re: Telephone app (David Hutto) 4. Re: Telephone app (Walter Prins) 5. Re: Telephone app (bob gailer) 6. Re: Telephone app (Steven D'Aprano) ---------------------------------------------------------------------- Message: 1 Date: Sun, 23 Jan 2011 11:24:27 -0800 From: "Richard D. Moores" To: Tutor List Subject: Re: [Tutor] What is a semantic error? Message-ID: Content-Type: text/plain; charset=UTF-8 Thanks, Tutors, for the excellent replies. I think I've got it now. Dick ------------------------------ Message: 2 Date: Sun, 23 Jan 2011 11:56:14 -0500 From: Robert Berman To: Tutor at python.org Subject: [Tutor] PDF to TXT Message-ID: <1295801774.1653.11.camel at bermanrl-desktop> Content-Type: text/plain; charset="UTF-8" Hi, I am trying to convert .pdf files to .txt files. The script I am using below is mostly taken from research done on Google and it appears to be the one outline most consistently favored (http://code.activestate.com/recipes/577095-convert-pdf-to-plain-text/). I am using Win 7, Python 2.7.1. My code: #pdf2txt.py import sys import pyPdf import os def getPDFContent(path): content = "" # Load PDF into pyPDF pdf = pyPdf.PdfFileReader(file(path, "rb")) # Iterate pages for i in range(0, pdf.getNumPages()): # Extract text from page and add to content content += pdf.getPage(i).extractText() + " \n" # Collapse whitespace # content = u" ".join(content.replace(u"\xa0", u" ").strip().split()) return content def main(): pdf = sys.argv[1] filedir,filename = os.path.split(pdf) nameonly = os.path.splitext(filename) newname = nameonly[0] + ".txt" outtxt = os.path.join(filedir,newname) f = open(outtxt,'w') f.write(getPDFContent(pdf)) f.close() main() exit() ============================================================================ ================================== The program runs for a while and then dies while in one of the pypdf functions. The trace is below. Any insight into how to resolve this situation will be most appreciated. Thank you, Robert ============================================================================ =========================================== The trace I get is: decimal.InvalidOperation: Invalid literal for Decimal: '.' File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 28, in main() File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 25, in main f.write(getPDFContent(pdf)) File "C:\Users\bermanrl\Projects\ScriptSearch\testdir\pdf2txt.py", line 13, in getPDFContent content += pdf.getPage(i).extractText() + " \n" File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1381, in extractText content = ContentStream(content, self.pdf) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1464, in __init__ self.__parseContentStream(stream) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \pdf.py", line 1503, in __parseContentStream operands.append(readObject(stream, None)) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 87, in readObject return NumberObject.readFromStream(stream) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 234, in readFromStream return FloatObject(name) File "C:\Python27\Lib\site-packages\pyPdf-1.13-py2.7-win32.egg\pyPdf \generic.py", line 207, in __new__ return decimal.Decimal.__new__(cls, str(value), context) File "C:\Python27\Lib\decimal.py", line 548, in __new__ "Invalid literal for Decimal: %r" % value) File "C:\Python27\Lib\decimal.py", line 3844, in _raise_error raise error(explanation) ------------------------------ Message: 3 Date: Sun, 23 Jan 2011 16:04:31 -0500 From: David Hutto To: Alan Gauld Cc: tutor at python.org Subject: Re: [Tutor] Telephone app Message-ID: Content-Type: text/plain; charset=ISO-8859-1 > Can you step back a bit and explain what it is you are trying to > accomplish? "flow through" and "functional flow through" are meaningless > terms in telecomms - at least so far as I am aware (after my 35 years in > telecomms engineering...) It's two fold. First is the obvious of conducting a call/receiving the caller id info. The second is to send directly to the phone, and transmit the caller id data. By flow through, I mean that the phone has one of 2 states(on the hook, off the hook), and three sub states(on the hook/off the hook in use/off the hook not in use). On the actual phone we pick up the receiver, or press the button on the cordless to receive, but the line is always connected, meaning it stops at the phone(terminal). I pick up the receiver, and transmit a series of specific tones which indicate the area code, trunk number and extension(if I remember this correctly, it's been a while since I studied the phone itself). So I have to receive the signal that the phone is ringing(then I'm assuming it sends the caller id info in between rings in some form)/or transmit a series of tones to them to connect. So I think my main question is what modules might be relevant to doing this? And should I be thinking of it any differently than a USB port which has 4 pins two data(+-), and two dc current(+-)? ------------------------------ Message: 4 Date: Sun, 23 Jan 2011 21:33:33 +0000 From: Walter Prins To: David Hutto Cc: Alan Gauld , tutor at python.org Subject: Re: [Tutor] Telephone app Message-ID: Content-Type: text/plain; charset="iso-8859-1" On 23 January 2011 21:04, David Hutto wrote: > So I have to receive the signal that the phone is ringing(then I'm > assuming it sends the caller id info in between rings in some form)/or > transmit a series of tones to them to connect. > > So I think my main question is what modules might be relevant to doing > this? And should I be thinking of it any differently than a USB port > which has 4 pins two data(+-), and two dc current(+-)? > > I think you're thinking too low level, as alluded to by Alan this type of stuff is done via a voice-modem that you can directly control (via serial port) and get signals from e.g. using its command set. A common standard for about 3 decades has been the Hayes command set: http://en.wikipedia.org/wiki/Hayes_command_set As for control from Python - given that the modem would be present as a serial (COM port) device in the system, I'd have thought that (at worst) you'd be looking to use PySerial to interact with the modem. There may also be more targetted wrappers specifically wrapping modems (don't know, haven't looked). And as mentioned before, you can probably also use the more abstract interface provided by the operating system (TAPI stuff). And yes, USB is quite different from the POTS (Plain Old Telephone System). Forget any ideas that they're anywhere the same thing. Hope that helps. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Sun, 23 Jan 2011 17:41:39 -0500 From: bob gailer To: David Hutto Cc: tutor at python.org Subject: Re: [Tutor] Telephone app Message-ID: <4D3CAEA3.60503 at gmail.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 1/23/2011 4:04 PM, David Hutto wrote: Warning - do NOT connect a telco landline to a USB port. The line voltage when "on hook" is around 50 V and rises over 100 when ringing. That will certainly fry the port. There are expansion cards and other devices designed to connect to the landline and to a phone. They also process caller id and send touch tone signals. I've tried to follow your explanation. It is too vague for me to make sense of. I guess you want to take the line that comes to you from your local telco, stick something computer-wise between it and an ordinary analog phone, so the computer can receive and process the caller id from an incoming call, and also ensure that the caller id appears on the phone itself, and use the computer to dial numbers (NOT known as caller id). Correct so far? > It's two fold. First is the obvious of conducting a call/receiving the > caller id info. May be obvious to you, but not to me! To support your query please provide some kind of wiring diagram and define "conducting a call". > The second is to send directly to the phone, and transmit the caller id data. Again this is not very precise or clear. What do you want to send to the pone? > By flow through, I mean that the phone has one of 2 states(on the > hook, off the hook) I'm OK with that. > off the hook in use/off the hook not in use). That is not clear. > On the actual phone we pick up the receiver, or press the button on > the cordless to receive, but the line is always connected, meaning it > stops at the phone(terminal). I pick up the receiver, and transmit a > series of specific tones which indicate the area code, trunk number > and extension(if I remember this correctly, it's been a while since I > studied the phone itself). > > So I have to receive the signal that the phone is ringing(then I'm > assuming it sends the caller id info in between rings in some form)/or > transmit a series of tones to them to connect. Huh? > So I think my main question is what modules might be relevant to doing > this? As someone mentioned earlier - TAPI is your friend. > And should I be thinking of it any differently than a USB port > which has 4 pins two data(+-), and two dc current(+-)? As I warned above, YES. -- Bob Gailer 919-636-4239 Chapel Hill NC ------------------------------ Message: 6 Date: Mon, 24 Jan 2011 10:28:05 +1100 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] Telephone app Message-ID: <4D3CB985.3000006 at pearwood.info> Content-Type: text/plain; charset=ISO-8859-1; format=flowed bob gailer wrote: > On 1/23/2011 4:04 PM, David Hutto wrote: [...] > I guess you want to take the line that comes to you from your local > telco, stick something computer-wise between it and an ordinary analog > phone, so the computer can receive and process the caller id from an > incoming call, and also ensure that the caller id appears on the phone > itself, and use the computer to dial numbers (NOT known as caller id). Folks, this question has nothing to do with Python and is off-topic for this list. Can you all take it off-list please? There are probably communities on the Internet or Usenet that are interested in low-level telecommunications protocols and devices. We don't go there to talk about Python, please don't stay here talking about their areas of expertise. Thank you. -- Steven ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 83, Issue 100 ************************************** __________________________________________________ ????????????????????????????? http://cn.mail.yahoo.com From saxontrack at hotmail.com Mon Jan 24 10:28:24 2011 From: saxontrack at hotmail.com (saxon piggott) Date: Mon, 24 Jan 2011 09:28:24 +0000 Subject: [Tutor] ArcGis 10 support materials for Python In-Reply-To: References: Message-ID: Hello, I was wondering if there is any information anywhere on the use of Python scripts (How to..) for ESRIs ArcGIS 10? or alternatively, if ESRI press or perhaps some other publisher has released a book that details obect oriented programming (presumably with Python scripting) for ArcGIS 10? A simialr book exists for VBA for ArcGIS 9 called Getting To Know ArcObjects released by Robert Burke for ESRI. However I cannot find a dedicated Python text or site for ArcGIS 9 or 10 anywhere. Its a bit of a problem as ArcGIS is phasing out VBA which is no longer available in version 10. Any help locating a relevent publication would be greatly appreciated as I can find very little information for this on the Esri site. Best regards, Saxon Piggott -------------- next part -------------- An HTML attachment was scrubbed... URL: From CMSA at gmx.de Mon Jan 24 13:46:24 2011 From: CMSA at gmx.de (CS) Date: Mon, 24 Jan 2011 13:46:24 +0100 Subject: [Tutor] Weave - how to find the compiler on windows Message-ID: <20110124124624.33130@gmx.net> Hello! I want to use weave.biltz(), but it doesn?t find the compiler. I installed minGW on windows in the path C:\MinGW\bin (so no spaces here) and added it to the path variable (and it works on the command line). I already installed python and scipy. Okay, now the question : How do I tell scipy where the compiler is?! Every time I call weave.blitz() it returns "The 'gcc' compiler was not found" In the documentation it is written that the compiler used for building python is used for weave too. But I just installed python by an .exe - file... Thanks! From vceder at gmail.com Mon Jan 24 14:33:51 2011 From: vceder at gmail.com (Vern Ceder) Date: Mon, 24 Jan 2011 08:33:51 -0500 Subject: [Tutor] ArcGis 10 support materials for Python In-Reply-To: References: Message-ID: I do know that ArgGIS and Python are used together a fair amount, but I'm not aware of a book. I'm assuming that you've already checked out pages like this? http://gisweb.apsu.edu/blogs/arcgis-10-and-python Cheers, Vern On Mon, Jan 24, 2011 at 4:28 AM, saxon piggott wrote: > Hello, > > I was wondering if there is any information anywhere on the use of Python > scripts (How to..) for ESRIs ArcGIS 10? or alternatively, if ESRI press or > perhaps some other publisher has released a book that details obect oriented > programming (presumably with Python scripting) for ArcGIS 10? > > A simialr book exists for VBA for ArcGIS 9 called Getting To Know ArcObjects > released by Robert Burke for ESRI. However I cannot find a?dedicated Python > text or site for ArcGIS 9 or 10 anywhere.? Its a bit of a problem as ArcGIS > is phasing out VBA which is no longer available in version 10. > > Any help locating a relevent publication would be greatly appreciated as I > can find very little information for this on the Esri site. > > Best regards, > Saxon Piggott > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vern Ceder vceder at gmail.com, vceder at dogsinmotion.com The Quick Python Book, 2nd Ed - http://bit.ly/bRsWDW From bsdwiz at gmail.com Mon Jan 24 18:25:53 2011 From: bsdwiz at gmail.com (bsdwiz at gmail.com) Date: Mon, 24 Jan 2011 11:25:53 -0600 Subject: [Tutor] Help listing directory timestamps and deleting directories Message-ID: Hi, hoping for some help here. I've been trying to write a python script (complete newb) and have spent several days trying to get this right with no success. I am trying to list timestamps in a directory and if they are older than x amount of days delete the directories. It seems that in my for loop it is only evaluating the last timestamp of the last directory and using that timestamp to make the deletion decision. I realize that this script isn't going to delete the directories with evaluate as true but I haven't been able to get that far yet... ###########start script############## ###Modules### import os import time ###Global Variables### curr_t = time.time() days = 2629743 #2629743 is 30 days in epoch time. directory=os.path.join("/home", "userid", "python") for r,d,f in os.walk(directory): for dir in d: timestamp = os.path.getmtime(os.path.join(r,dir)) ## It seems that the below "if" statement is only comparing the timestamp of the last directory that this variable lists. print timestamp if curr_t - days < timestamp: #### I am expecting this statement to compare each timestamp of the "directory" variable and print out if it should be deleted or not. print "Your file will be deleted" else: print "File will NOT be deleted..." #######################end of script############################# Thank you for your time! -------------- next part -------------- An HTML attachment was scrubbed... URL: From vince at vinces.ca Mon Jan 24 20:02:53 2011 From: vince at vinces.ca (Vince Spicer) Date: Mon, 24 Jan 2011 13:02:53 -0600 Subject: [Tutor] Help listing directory timestamps and deleting directories In-Reply-To: References: Message-ID: On Mon, Jan 24, 2011 at 11:25 AM, bsdwiz at gmail.com wrote: > Hi, hoping for some help here. I've been trying to write a python script > (complete newb) and have spent several days trying to get this right with no > success. > > I am trying to list timestamps in a directory and if they are older than x > amount of days delete the directories. It seems that in my for loop it is > only evaluating the last timestamp of the last directory and using that > timestamp to make the deletion decision. I realize that this script isn't > going to delete the directories with evaluate as true but I haven't been > able to get that far yet... > > > > ###########start script############## > ###Modules### > > import os > import time > > ###Global Variables### > > curr_t = time.time() > > days = 2629743 #2629743 is 30 days in epoch time. > > directory=os.path.join("/home", "userid", "python") > > > for r,d,f in os.walk(directory): > for dir in d: > timestamp = os.path.getmtime(os.path.join(r,dir)) ## It seems that > the below "if" statement is only comparing the timestamp of the last > directory that this variable lists. > print timestamp > if curr_t - days < timestamp: #### I am expecting > this statement to compare each timestamp of the "directory" variable and > print out if it should be deleted or not. > print "Your file will be deleted" > > else: > print "File will NOT be deleted..." > > > #######################end of script############################# > > > > Thank you for your time! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > First off, I would recommend using dates and not times, this can help make things clearer when dealing with dates, also the dateutil module can make date math a lot simpler (easy_install dateutil) from datetime import datetime from dateutil.relativedelta import relativedelta remove_after = datetime.now() - relativedelta(days=31) # exactly 1 month prior to today check_dir = "/path/to/whatever" for r,d,f in os.walk(check_dir): for dir in d: loc = os.path.join(r,dir) last_modified = datetime.fromtimestamp(os.path.getmtime(loc)) if last_modifed < remove_after: print "delete old directory", loc else: print "keep recently modified", loc Hope this helps, Vince Spicer Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: From japhy at pearachute.com Mon Jan 24 20:23:49 2011 From: japhy at pearachute.com (Japhy Bartlett) Date: Mon, 24 Jan 2011 14:23:49 -0500 Subject: [Tutor] Help listing directory timestamps and deleting directories In-Reply-To: References: Message-ID: I would check that os.path.join(r,dir) is giving you the directory you think it is. - japhy On Mon, Jan 24, 2011 at 12:25 PM, bsdwiz at gmail.com wrote: > Hi, hoping for some help here. I've been trying to write a python script > (complete newb) and have spent several days trying to get this right with no > success. > > I am trying to list timestamps in a directory and if they are older than x > amount of days delete the directories. It seems that in my for loop it is > only evaluating the last timestamp of the last directory and using that > timestamp to make the deletion decision. I realize that this script isn't > going to delete the directories with evaluate as true but I haven't been > able to get that far yet... > > > > ###########start script############## > ###Modules### > > import os > import time > > ###Global Variables### > > curr_t = time.time() > > days = 2629743 #2629743 is 30 days in epoch time. > > directory=os.path.join("/home", "userid", "python") > > > for r,d,f in os.walk(directory): > ??? for dir in d: > ??????? timestamp = os.path.getmtime(os.path.join(r,dir)) ## It seems that > the below "if" statement is only comparing the timestamp of the last > directory that this variable lists. > ??????? print timestamp > ??????? if curr_t - days < timestamp:????????????????? #### I am expecting > this statement to compare each timestamp of the "directory" variable and > print out if it should be deleted or not. > ??????????? print "Your file will be deleted" > > ??????? else: > ??????????? print "File will NOT be deleted..." > > > #######################end of script############################# > > > > Thank you for your time! > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From karim.liateni at free.fr Mon Jan 24 23:30:57 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 24 Jan 2011 23:30:57 +0100 Subject: [Tutor] Help listing directory timestamps and deleting directories In-Reply-To: References: Message-ID: <4D3DFDA1.4010403@free.fr> Hello, Also working w/o external module just the standard one: *>>> import datetime >>> remove_after = datetime.datetime.now() - datetime.timedelta(days=31) >>> remove_after datetime.datetime(2010, 12, 24, 23, 21, 10, 11315) * Regards Karim On 01/24/2011 08:02 PM, Vince Spicer wrote: > > > On Mon, Jan 24, 2011 at 11:25 AM, bsdwiz at gmail.com > > > wrote: > > Hi, hoping for some help here. I've been trying to write a python > script (complete newb) and have spent several days trying to get > this right with no success. > > I am trying to list timestamps in a directory and if they are > older than x amount of days delete the directories. It seems that > in my for loop it is only evaluating the last timestamp of the > last directory and using that timestamp to make the deletion > decision. I realize that this script isn't going to delete the > directories with evaluate as true but I haven't been able to get > that far yet... > > > > ###########start script############## > ###Modules### > > import os > import time > > ###Global Variables### > > curr_t = time.time() > > days = 2629743 #2629743 is 30 days in epoch time. > > directory=os.path.join("/home", "userid", "python") > > > for r,d,f in os.walk(directory): > for dir in d: > timestamp = os.path.getmtime(os.path.join(r,dir)) ## It > seems that the below "if" statement is only comparing the > timestamp of the last directory that this variable lists. > print timestamp > if curr_t - days < timestamp: #### I am > expecting this statement to compare each timestamp of the > "directory" variable and print out if it should be deleted or not. > print "Your file will be deleted" > > else: > print "File will NOT be deleted..." > > > #######################end of script############################# > > > > Thank you for your time! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > First off, I would recommend using dates and not times, this can help > make things clearer > when dealing with dates, also the dateutil module can make date math a > lot simpler (easy_install dateutil) > > > from datetime import datetime > from dateutil.relativedelta import relativedelta > > remove_after = datetime.now() - relativedelta(days=31) # exactly 1 > month prior to today > check_dir = "/path/to/whatever" > > for r,d,f in os.walk(check_dir): > for dir in d: > loc = os.path.join(r,dir) > last_modified = datetime.fromtimestamp(os.path.getmtime(loc)) > if last_modifed < remove_after: > print "delete old directory", loc > else: > print "keep recently modified", loc > > > > Hope this helps, > > Vince Spicer > Developer > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Tue Jan 25 06:56:47 2011 From: wallenpb at gmail.com (Bill Allen) Date: Mon, 24 Jan 2011 23:56:47 -0600 Subject: [Tutor] Not understanding a bit of code behavior Message-ID: This is a bit embarrassing, but I have crafted a bit of code that does EXACTLY what I what, but I am now a bit baffled as to precisely why. I have written a function to do a bit of webscraping by following links for a project at work. If I leave the code as is, it behaves like it is recursively passing through the data tree- which is what I want. However, if I change it only slightly, it makes only one pass through the top level data. What I do not understand is why is ever behaves as if it is recursive as the function is only called once. If I comment out_list=[] and let out_list-=part_list be used the following parses through the whole tree of data as if recursive. If I use out_list=[] and comment out_list=part_list, it only processes to top level of the data tree. The function is called only once as: Exploded_BOM_List = get_BOM(first_num) in which I pass it a single part number to start with. The webscraping bit goes to a particular webpage about that part where it then picks up more part numbers and repeats the process. So can anyone help me understand why this actually works? Certainly no complaints here about it, but I would like to better understand why changes the behavior so profoundly. All the print statements are just to I could follow out the data flow while working on this. By following the data flow, I am finding that part_list is actually having values added to it during the time the function is running. Problem is, I don't see clearly why that should be so. def get_BOM(part_list): x=re.compile('part='+'.*?'+'>') BOM_List = [] # out_list = [] out_list = part_list print("called get_BOM") pass_num = 0 for part_num in part_list: mypath = "http://xxx.xxx.xxx.xxx/cgi-bin/search/part-url.cgi?part=" + part_num mylines = urllib.urlopen(mypath).readlines() print("pass number ", pass_num) print(mypath) print("PL:",part_list) for item in mylines: if "http://" in item: if "part=" in item: xstring=str(x.findall(item)).strip('"[\'part=>\']"') BOM_List.append(xstring) print("BL:",BOM_List) for bom_item in BOM_List: if bom_item not in out_list: out_list.append(bom_item) print("OL:",out_list) pass_num += 1 return(out_list) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Tue Jan 25 07:05:42 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 25 Jan 2011 00:05:42 -0600 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: By the way, my guess as to why this is working for me the way it does is that the statement out_list = part_list is actually linking these two objects, making them one. My intention had been to just assign values from one to the other, but I think I have done far more than that. In this case, if that is true, then it has worked out well for me, giving me a feedback loop through the data. However, I can see that it could also be a pitfall if this behavior is not clearly understood. Am I right? Am I way off base? Either way, I could use some elaboration about it. --Bill On Mon, Jan 24, 2011 at 23:56, Bill Allen wrote: > This is a bit embarrassing, but I have crafted a bit of code that does > EXACTLY what I what, but I am now a bit baffled as to precisely why. I have > written a function to do a bit of webscraping by following links for a > project at work. If I leave the code as is, it behaves like it is > recursively passing through the data tree- which is what I want. However, > if I change it only slightly, it makes only one pass through the top level > data. What I do not understand is why is ever behaves as if it is recursive > as the function is only called once. > > If I comment out_list=[] and let out_list-=part_list be used the following > parses through the whole tree of data as if recursive. If I use out_list=[] > and comment out_list=part_list, it only processes to top level of the data > tree. > > The function is called only once as: Exploded_BOM_List = > get_BOM(first_num) in which I pass it a single part number to start with. > The webscraping bit goes to a particular webpage about that part where it > then picks up more part numbers and repeats the process. > > So can anyone help me understand why this actually works? Certainly no > complaints here about it, but I would like to better understand why changes > the behavior so profoundly. All the print statements are just to I could > follow out the data flow while working on this. By following the data flow, > I am finding that part_list is actually having values added to it during the > time the function is running. Problem is, I don't see clearly why that > should be so. > > def get_BOM(part_list): > x=re.compile('part='+'.*?'+'>') > BOM_List = [] > > # out_list = [] > out_list = part_list > print("called get_BOM") > pass_num = 0 > for part_num in part_list: > mypath = "http://xxx.xxx.xxx.xxx/cgi-bin/search/part-url.cgi?part=" > + part_num > mylines = urllib.urlopen(mypath).readlines() > print("pass number ", pass_num) > print(mypath) > print("PL:",part_list) > for item in mylines: > if "http://" in item: > if "part=" in item: > xstring=str(x.findall(item)).strip('"[\'part=>\']"') > BOM_List.append(xstring) > print("BL:",BOM_List) > for bom_item in BOM_List: > if bom_item not in out_list: > out_list.append(bom_item) > print("OL:",out_list) > pass_num += 1 > return(out_list) > > > > > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Tue Jan 25 07:37:31 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 25 Jan 2011 00:37:31 -0600 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: Ok, I have definately verified this to myself. The following works perfectly and is a little easier to understand. In this version, I am plainly modifying my parts_list iterator thus producing the effect of an iterator that is growing over the course of the operation of the code. So, I am convinced that I had previously assigned part_list to out_list by reference, not value as I mistaken thought when I first wrote the code, which explains it. It was a silly mistake born from still being new in Python and thinking in terms of another language I know that typically assigns by value instead. It had no occurred to me initially that it was possible to modify an iterator in this way. I do not think most languages would allow this. Question, is it possible to copy values from one object to another in such a way as they are not just references one to the other? Sorry about asking questions and then answering them. Things began to become more clear with each question I asked. def get_BOM(part_list): x=re.compile('part='+'.*?'+'>') BOM_List = [] pass_num = 0 for part_num in part_list: mypath = "http://172.25.8.13/cgi-bin/search/part-url.cgi?part=" + part_num mylines = urllib.urlopen(mypath).readlines() for item in mylines: if "http://" in item: if "part=" in item: xstring=str(x.findall(item)).strip('"[\'part=>\']"') BOM_List.append(xstring) for bom_item in BOM_List: if bom_item not in part_list: part_list.append(bom_item) pass_num += 1 return(part_list) On Tue, Jan 25, 2011 at 00:05, Bill Allen wrote: > By the way, my guess as to why this is working for me the way it does is > that the statement > > out_list = part_list > > is actually linking these two objects, making them one. My intention had > been to just assign values from one to the other, but I think I have done > far more than that. In this case, if that is true, then it has worked out > well for me, giving me a feedback loop through the data. However, I can see > that it could also be a pitfall if this behavior is not clearly understood. > Am I right? Am I way off base? Either way, I could use some elaboration > about it. > > > --Bill > > > > > > > On Mon, Jan 24, 2011 at 23:56, Bill Allen wrote: > >> This is a bit embarrassing, but I have crafted a bit of code that does >> EXACTLY what I what, but I am now a bit baffled as to precisely why. I have >> written a function to do a bit of webscraping by following links for a >> project at work. If I leave the code as is, it behaves like it is >> recursively passing through the data tree- which is what I want. However, >> if I change it only slightly, it makes only one pass through the top level >> data. What I do not understand is why is ever behaves as if it is recursive >> as the function is only called once. >> >> If I comment out_list=[] and let out_list-=part_list be used the following >> parses through the whole tree of data as if recursive. If I use out_list=[] >> and comment out_list=part_list, it only processes to top level of the data >> tree. >> >> The function is called only once as: Exploded_BOM_List = >> get_BOM(first_num) in which I pass it a single part number to start with. >> The webscraping bit goes to a particular webpage about that part where it >> then picks up more part numbers and repeats the process. >> >> So can anyone help me understand why this actually works? Certainly no >> complaints here about it, but I would like to better understand why changes >> the behavior so profoundly. All the print statements are just to I could >> follow out the data flow while working on this. By following the data flow, >> I am finding that part_list is actually having values added to it during the >> time the function is running. Problem is, I don't see clearly why that >> should be so. >> >> def get_BOM(part_list): >> x=re.compile('part='+'.*?'+'>') >> BOM_List = [] >> >> # out_list = [] >> out_list = part_list >> print("called get_BOM") >> pass_num = 0 >> for part_num in part_list: >> mypath = " >> http://xxx.xxx.xxx.xxx/cgi-bin/search/part-url.cgi?part=" + part_num >> mylines = urllib.urlopen(mypath).readlines() >> print("pass number ", pass_num) >> print(mypath) >> print("PL:",part_list) >> for item in mylines: >> if "http://" in item: >> if "part=" in item: >> xstring=str(x.findall(item)).strip('"[\'part=>\']"') >> BOM_List.append(xstring) >> print("BL:",BOM_List) >> for bom_item in BOM_List: >> if bom_item not in out_list: >> out_list.append(bom_item) >> print("OL:",out_list) >> pass_num += 1 >> return(out_list) >> >> >> >> >> >> >> >> >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 25 08:42:52 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 25 Jan 2011 07:42:52 -0000 Subject: [Tutor] Not understanding a bit of code behavior References: Message-ID: "Bill Allen" wrote > I am convinced that I had previously assigned part_list to out_list > by > reference, not value as I mistaken thought when I first wrote the > code, In Python variables are names which refer to objects. So your assignment made both names refer to the same object. > Question, is it possible to copy values from one object to another > in such a > way as they are not just references one to the other? If you want to copy a list the usual way is to create a new copy using slicing: newList = oldList[:] You can also use the deepcopy module if the list is multi level. > Sorry about asking questions and then answering them. Things began > to > become more clear with each question I asked. Thats often the way :-) The act of articulating the problem forces you to think about it differently. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokefloat at gmail.com Tue Jan 25 08:54:22 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 25 Jan 2011 02:54:22 -0500 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: On Tue, Jan 25, 2011 at 2:42 AM, Alan Gauld wrote: > > "Bill Allen" wrote > >> I am convinced that I had previously assigned part_list to out_list by >> reference, not value as I mistaken thought when I first wrote the code, > > In Python variables are names which refer to objects. > So your assignment made both names refer to the same object. > >> Question, is it possible to copy values from one object to another in such >> a >> way as they are not just references one to the other? > > If you want to copy a list the usual way is to create a new copy > using slicing: > > newList = oldList[:] > > You can also use the deepcopy module if the list is multi level. > >> Sorry about asking questions and then answering them. ?Things began to >> become more clear with each question I asked. > > Thats often the way :-) > The act of articulating the problem forces you to think about it > differently.RTFM, before ask the list. No that they aren't helpful here, but try on your own(and don't start off topic questions) > > HTH > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From waynejwerner at gmail.com Tue Jan 25 13:38:27 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Tue, 25 Jan 2011 06:38:27 -0600 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: On Tue, Jan 25, 2011 at 1:42 AM, Alan Gauld wrote: > > "Bill Allen" wrote > > Thats often the way :-) > The act of articulating the problem forces you to think about it > differently. > Also called "Rubber Duck Debugging" http://en.wikipedia.org/wiki/Rubber_duck_debugging I've used it myself several times - usually in writing my message to the list (or on Stackoverflow.com) I end out answering my own darn question before I've finished typing it! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Jan 25 14:45:40 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 00:45:40 +1100 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: <4D3ED404.1000201@pearwood.info> Bill Allen wrote: > Ok, I have definately verified this to myself. The following works > perfectly and is a little easier to understand. In this version, I am > plainly modifying my parts_list iterator thus producing the effect of an > iterator that is growing over the course of the operation of the code. So, > I am convinced that I had previously assigned part_list to out_list by > reference, not value as I mistaken thought when I first wrote the code, I believe you're working under a misunderstanding there. Python is neither by reference nor value, if I've understood what you mean by that. (Normally people talk about "by reference" when discussing calling functions, not assignment, so I may have misunderstood you.) After executing the line `out_list = part_list`, *both* of these statements are *incorrect*: "out_list is a copy of part_list" +++ WRONG +++ "out_list and part_list are the same variable (out_list is an alias for part_list)" +++ ALSO WRONG +++ In a nutshell, Python uses the *name binding* assignment model. When you do this: part_list = [1, 2] Python creates a *name* "part_list" and binds it to the *object* [1, 2]. Then when you do this: out_list = part_list the name "out_list" is created and bound to the same object as part_list. This means that out_list and part_list are two names for the same object, but this is not a permanent state of affairs -- they happen to be bound to the same object now, but you can re-bind one without changing the other. A month or so ago, somebody raised a similar question about pass by reference and pass by value. If you will excuse me blowing my own trumpet, I think my response then may be useful for you now: http://www.mail-archive.com/tutor%40python.org/msg46612.html To use a copy of part_list, you need to explicitly copy it. For lists, the easiest way is with a slice: out_list = part_list[:] You can also use the copy module, and functions copy.copy and copy.deepcopy, to copy other objects. > which explains it. It was a silly mistake born from still being new in > Python and thinking in terms of another language I know that typically > assigns by value instead. It had no occurred to me initially that it was > possible to modify an iterator in this way. I do not think most languages > would allow this. My understanding is that this behaviour -- multiple names for one object -- is standard semantics for most modern languages, including Perl, Ruby, Java, and many others. -- Steven From wallenpb at gmail.com Tue Jan 25 15:57:45 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 25 Jan 2011 08:57:45 -0600 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: <4D3ED404.1000201@pearwood.info> References: <4D3ED404.1000201@pearwood.info> Message-ID: Steven, Thanks! That is quite helpful to know the nuts and bolts of how that works. --Bill On Tue, Jan 25, 2011 at 07:45, Steven D'Aprano wrote: > Bill Allen wrote: > >> Ok, I have definately verified this to myself. The following works >> perfectly and is a little easier to understand. In this version, I am >> plainly modifying my parts_list iterator thus producing the effect of an >> iterator that is growing over the course of the operation of the code. >> So, >> I am convinced that I had previously assigned part_list to out_list by >> reference, not value as I mistaken thought when I first wrote the code, >> > > I believe you're working under a misunderstanding there. Python is neither > by reference nor value, if I've understood what you mean by that. (Normally > people talk about "by reference" when discussing calling functions, not > assignment, so I may have misunderstood you.) > > After executing the line `out_list = part_list`, *both* of these statements > are *incorrect*: > > "out_list is a copy of part_list" +++ WRONG +++ > "out_list and part_list are the same variable (out_list is an alias for > part_list)" +++ ALSO WRONG +++ > > In a nutshell, Python uses the *name binding* assignment model. When you do > this: > > part_list = [1, 2] > > Python creates a *name* "part_list" and binds it to the *object* [1, 2]. > Then when you do this: > > out_list = part_list > > the name "out_list" is created and bound to the same object as part_list. > This means that out_list and part_list are two names for the same object, > but this is not a permanent state of affairs -- they happen to be bound to > the same object now, but you can re-bind one without changing the other. > > A month or so ago, somebody raised a similar question about pass by > reference and pass by value. If you will excuse me blowing my own trumpet, I > think my response then may be useful for you now: > > http://www.mail-archive.com/tutor%40python.org/msg46612.html > > To use a copy of part_list, you need to explicitly copy it. For lists, the > easiest way is with a slice: > > out_list = part_list[:] > > You can also use the copy module, and functions copy.copy and > copy.deepcopy, to copy other objects. > > > > which explains it. It was a silly mistake born from still being new in >> Python and thinking in terms of another language I know that typically >> assigns by value instead. It had no occurred to me initially that it was >> possible to modify an iterator in this way. I do not think most languages >> would allow this. >> > > My understanding is that this behaviour -- multiple names for one object -- > is standard semantics for most modern languages, including Perl, Ruby, Java, > and many others. > > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Tue Jan 25 16:02:49 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 25 Jan 2011 09:02:49 -0600 Subject: [Tutor] Not understanding a bit of code behavior In-Reply-To: References: Message-ID: That's exactly right! Never heard it called that before, but that is basically what happened. I appreciate the help. --Bill On Tue, Jan 25, 2011 at 06:38, Wayne Werner wrote: > On Tue, Jan 25, 2011 at 1:42 AM, Alan Gauld wrote: > >> >> "Bill Allen" wrote >> >> Thats often the way :-) >> The act of articulating the problem forces you to think about it >> differently. >> > > Also called "Rubber Duck Debugging" > http://en.wikipedia.org/wiki/Rubber_duck_debugging > > I've used it myself > several times - usually in writing my message to the list (or on > Stackoverflow.com) I end out answering my own darn question before I've > finished typing it! > > -Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hacker0100 at hotmail.com Tue Jan 25 18:25:36 2011 From: hacker0100 at hotmail.com (walter weston) Date: Tue, 25 Jan 2011 10:25:36 -0700 Subject: [Tutor] ideas for a simple program In-Reply-To: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: can I have some good ideas for simple programs, I have come to realize the hardest part of programming is not having a project to do and having to think of one haha -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Tue Jan 25 18:45:03 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Tue, 25 Jan 2011 09:45:03 -0800 Subject: [Tutor] ideas for a simple program In-Reply-To: References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: <4D3F0C1F.5020901@iandouglas.com> With an Email address like "hacker0100", your best bet might be to do what we told another user just a few days ago: Find an open-source project, and try to add a new feature to it, or fix a bug in it. That way you learn about the language, the project, and could get your name out there as a contributor if your changes are accepted by the original author. On 01/25/2011 09:25 AM, walter weston wrote: > > can I have some good ideas for simple programs, I have come to realize > the hardest part of programming is not having a project to do and > having to think of one haha > -------------- next part -------------- An HTML attachment was scrubbed... URL: From swiftone at swiftone.org Tue Jan 25 18:47:31 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 25 Jan 2011 12:47:31 -0500 Subject: [Tutor] ideas for a simple program In-Reply-To: References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: On Tue, Jan 25, 2011 at 12:25 PM, walter weston wrote: > can I have some good ideas for simple programs, I have come to realize the > hardest part of programming is not having a project to do and having to > think of one haha There are two ways to approach this: 1) Think of something that you'd like to have, personally, and start work on it. Here you'll have a real passion and benefit. 2) Tackle something that everyone does. Here you'll have a lot of examples and people will likely quickly understand your goals. For #1 I can't help, though I recommend the attempt, but for #2 I recommend small games. A blackjack game or a computer that can play tic-tac-toe with you are great ways to work on a well-defined problem that won't take forever. Once you feel sufficiently confident, helping on an open source project as others suggest is a great way. -- Brett Ritter / SwiftOne swiftone at swiftone.org From wallenpb at gmail.com Tue Jan 25 19:36:55 2011 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 25 Jan 2011 12:36:55 -0600 Subject: [Tutor] ideas for a simple program In-Reply-To: References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: For a simple programming project that probably has just enough complexity to be interesting, google for Conway's Game of Life. You'll find an algorithm to use. --Bill On Tue, Jan 25, 2011 at 11:25, walter weston wrote: > > can I have some good ideas for simple programs, I have come to realize the > hardest part of programming is not having a project to do and having to > think of one haha > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 25 21:41:24 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 21:41:24 +0100 Subject: [Tutor] The trap of the year Message-ID: <4D3F3574.3040802@free.fr> Hello All, Just to share on rageous bug I encounter where 2 lists which "should" to be different (same id) because hold by different instances of the same class are not in fact DIFFERENT, see below: >>> class Device(): ... def __init__(self, parameters=[]): ... self.parameters = parameters ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> a.param() 140559202956568 >>> b.param() 140559202956568 When I discovered that I was puzzled because at the prompt: >>> a = [] >>> b = [] >>> id(a) 140559202956496 >>> id(b) 140559202957000 I am not really understanding why my init in the class made it refers to the same list object. What is the difference with 2nd example directly at the prompt? By the way, this one is ok: >>> class Device(): ... def __init__(self,parameters=None): ... self.parameters = None ... self.parameters = [] ... def param(self): ... print(id(self.parameters)) ... >>> a=Device() >>> b=Device() >>> b.param() 140559202956496 >>> a.param() 140559202956568 Karim From izzaddin.ruhulessin at gmail.com Tue Jan 25 22:07:33 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Tue, 25 Jan 2011 22:07:33 +0100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F3574.3040802@free.fr> References: <4D3F3574.3040802@free.fr> Message-ID: I think it has something to do with the physical id of the object 2011/1/25 Karim > > Hello All, > > Just to share on rageous bug I encounter where 2 lists which "should" to be > different (same id) because hold by different instances of the same class > are not in fact DIFFERENT, see below: > > >>> class Device(): > ... def __init__(self, parameters=[]): > ... self.parameters = parameters > ... def param(self): > ... print(id(self.parameters)) > ... > >>> a=Device() > >>> b=Device() > >>> a.param() > 140559202956568 > >>> b.param() > 140559202956568 > > When I discovered that I was puzzled because at the prompt: > > >>> a = [] > >>> b = [] > >>> id(a) > 140559202956496 > >>> id(b) > 140559202957000 > > I am not really understanding why my init in the class made it refers to > the same list object. > What is the difference with 2nd example directly at the prompt? > > By the way, this one is ok: > > >>> class Device(): > ... def __init__(self,parameters=None): > ... self.parameters = None > ... self.parameters = [] > ... def param(self): > ... print(id(self.parameters)) > ... > >>> a=Device() > >>> b=Device() > >>> b.param() > 140559202956496 > >>> a.param() > 140559202956568 > > Karim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From malaclypse2 at gmail.com Tue Jan 25 22:12:11 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 25 Jan 2011 16:12:11 -0500 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F3574.3040802@free.fr> References: <4D3F3574.3040802@free.fr> Message-ID: On Tue, Jan 25, 2011 at 3:41 PM, Karim wrote: > I am not really understanding why my init in the class made it refers to > the same list object. > What is the difference with 2nd example directly at the prompt? > See http://effbot.org/zone/default-values.htm -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Tue Jan 25 22:08:08 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Tue, 25 Jan 2011 22:08:08 +0100 Subject: [Tutor] The trap of the year In-Reply-To: References: <4D3F3574.3040802@free.fr> Message-ID: Or the internal memory id or whatever it's called. 2011/1/25 Izz ad-Din Ruhulessin > I think it has something to do with the physical id of the object > > 2011/1/25 Karim > > >> Hello All, >> >> Just to share on rageous bug I encounter where 2 lists which "should" to >> be different (same id) because hold by different instances of the same class >> are not in fact DIFFERENT, see below: >> >> >>> class Device(): >> ... def __init__(self, parameters=[]): >> ... self.parameters = parameters >> ... def param(self): >> ... print(id(self.parameters)) >> ... >> >>> a=Device() >> >>> b=Device() >> >>> a.param() >> 140559202956568 >> >>> b.param() >> 140559202956568 >> >> When I discovered that I was puzzled because at the prompt: >> >> >>> a = [] >> >>> b = [] >> >>> id(a) >> 140559202956496 >> >>> id(b) >> 140559202957000 >> >> I am not really understanding why my init in the class made it refers to >> the same list object. >> What is the difference with 2nd example directly at the prompt? >> >> By the way, this one is ok: >> >> >>> class Device(): >> ... def __init__(self,parameters=None): >> ... self.parameters = None >> ... self.parameters = [] >> ... def param(self): >> ... print(id(self.parameters)) >> ... >> >>> a=Device() >> >>> b=Device() >> >>> b.param() >> 140559202956496 >> >>> a.param() >> 140559202956568 >> >> Karim >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 25 22:16:59 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 22:16:59 +0100 Subject: [Tutor] The trap of the year In-Reply-To: References: <4D3F3574.3040802@free.fr> Message-ID: <4D3F3DCB.6040407@free.fr> If I understand a little bit what happen in: def __init__(self, parameters=[]): [...] The list argument is built before instance creation and indeed constructor execution. So this is the same list instance of constructor parameter for all new instance creation. For me it was a bad surprise! I never see warning about this fact in any books before. Regards Karim On 01/25/2011 10:08 PM, Izz ad-Din Ruhulessin wrote: > Or the internal memory id or whatever it's called. > > 2011/1/25 Izz ad-Din Ruhulessin > > > I think it has something to do with the physical id of the object > > 2011/1/25 Karim > > > > Hello All, > > Just to share on rageous bug I encounter where 2 lists which > "should" to be different (same id) because hold by different > instances of the same class are not in fact DIFFERENT, see below: > > >>> class Device(): > ... def __init__(self, parameters=[]): > ... self.parameters = parameters > ... def param(self): > ... print(id(self.parameters)) > ... > >>> a=Device() > >>> b=Device() > >>> a.param() > 140559202956568 > >>> b.param() > 140559202956568 > > When I discovered that I was puzzled because at the prompt: > > >>> a = [] > >>> b = [] > >>> id(a) > 140559202956496 > >>> id(b) > 140559202957000 > > I am not really understanding why my init in the class made it > refers to the same list object. > What is the difference with 2nd example directly at the prompt? > > By the way, this one is ok: > > >>> class Device(): > ... def __init__(self,parameters=None): > ... self.parameters = None > ... self.parameters = [] > ... def param(self): > ... print(id(self.parameters)) > ... > >>> a=Device() > >>> b=Device() > >>> b.param() > 140559202956496 > >>> a.param() > 140559202956568 > > Karim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Jan 25 22:20:59 2011 From: bgailer at gmail.com (bob gailer) Date: Tue, 25 Jan 2011 16:20:59 -0500 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F3574.3040802@free.fr> References: <4D3F3574.3040802@free.fr> Message-ID: <4D3F3EBB.5060405@gmail.com> On 1/25/2011 3:41 PM, Karim wrote: > > Hello All, > > Just to share on rageous bug I encounter where 2 lists which "should" > to be different (same id) because hold by different instances of the > same class are not in fact DIFFERENT, see below: > > >>> class Device(): > ... def __init__(self, parameters=[]): > ... self.parameters = parameters > ... def param(self): > ... print(id(self.parameters)) > ... > >>> a=Device() > >>> b=Device() > >>> a.param() > 140559202956568 > >>> b.param() > 140559202956568 > This is not a bug. It is intentional behavior which is documented in the Python Language Reference. Under 7.6 Function definitions you will find: *Default parameter values are evaluated when the function definition is executed.* This means that the expression is evaluated once, when the function is defined, and that that same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.: -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 25 22:28:12 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 22:28:12 +0100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F3EBB.5060405@gmail.com> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> Message-ID: <4D3F406C.3070003@free.fr> Hello Bob, I know this fact for function but in this case this is not a function but a constructor method of a class. The impact is not the same because all instance share the same argument parameter.This a kind of singleton argument :-) . I believed that the constructor will create each time a new argument init. Regards Karim On 01/25/2011 10:20 PM, bob gailer wrote: > *values are evaluated when th* -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Tue Jan 25 22:29:10 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 22:29:10 +0100 Subject: [Tutor] The trap of the year In-Reply-To: References: <4D3F3574.3040802@free.fr> Message-ID: <4D3F40A6.8020301@free.fr> On 01/25/2011 10:12 PM, Jerry Hill wrote: > On Tue, Jan 25, 2011 at 3:41 PM, Karim > wrote: > > I am not really understanding why my init in the class made it > refers to the same list object. > What is the difference with 2nd example directly at the prompt? > > > See http://effbot.org/zone/default-values.htm > > -- > Jerry > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Thanks for the link jerry! Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From wynnstinson at rocketmail.com Tue Jan 25 22:31:07 2011 From: wynnstinson at rocketmail.com (W S) Date: Tue, 25 Jan 2011 13:31:07 -0800 (PST) Subject: [Tutor] placing widgets Message-ID: <312659.84240.qm@web120906.mail.ne1.yahoo.com> hi, i have written some Tk/Python code to do a few simple tasks, and am having trouble with my combobox placement on the frame. is there a way to more explicitly place it other than: This method does not give a lot of control xx=apply(OptionMenu,(self,TCase)+tuple(TestCase)) xx.grid(row=1, sticky=E+W) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdeltoro1973 at gmail.com Tue Jan 25 22:52:56 2011 From: jdeltoro1973 at gmail.com (Juan Jose Del Toro) Date: Tue, 25 Jan 2011 15:52:56 -0600 Subject: [Tutor] extracting text from word files (.doc, .docx) and pdf Message-ID: Dear List; I am looking for a way to extract parts of a text from word (.doc,.docx) files as well as pdf; the idea is to walk through the whole directory tree and populate a csv file with an excerpt from each file. For PDF I found PyPdf ave found nothing to read doc, docx -- ?Saludos! / Greetings! Juan Jos? Del Toro M. jdeltoro1973 at gmail.com Guadalajara, Jalisco MEXICO -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Tue Jan 25 22:57:59 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 16:57:59 -0500 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F406C.3070003@free.fr> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> Message-ID: <4D3F4767.2060606@aim.com> On 01/25/2011 04:28 PM, Karim wrote: > > Hello Bob, > > I know this fact for function but in this case this is not a function > but a constructor method of a class. To be pedantic, a method _is_ a function, just under the umbrella of a class, with it's parent object being passed to it. ~Corey > The impact is not the same because all instance share the same argument > parameter.This a kind > of singleton argument :-) . I believed that the constructor will create > each time a new argument init. > > > Regards > Karim > From kb1pkl at aim.com Tue Jan 25 23:01:39 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 17:01:39 -0500 Subject: [Tutor] placing widgets In-Reply-To: <312659.84240.qm@web120906.mail.ne1.yahoo.com> References: <312659.84240.qm@web120906.mail.ne1.yahoo.com> Message-ID: <4D3F4843.3040705@aim.com> On 01/25/2011 04:31 PM, W S wrote: > hi, i have written some Tk/Python code to do a few simple tasks, and am having > trouble with my combobox placement on the frame. is there a way to more > explicitly place it other than: This method does not give a lot of control > xx=apply(OptionMenu,(self,TCase)+tuple(TestCase)) > xx.grid(row=1, sticky=E+W) You can use place (http://effbot.org/tkinterbook/place.htm). Never had the occasion to use it, but you may find it useful. ~Corey From wprins at gmail.com Tue Jan 25 23:13:26 2011 From: wprins at gmail.com (Walter Prins) Date: Tue, 25 Jan 2011 22:13:26 +0000 Subject: [Tutor] extracting text from word files (.doc, .docx) and pdf In-Reply-To: References: Message-ID: On 25 January 2011 21:52, Juan Jose Del Toro wrote: > Dear List; > > I am looking for a way to extract parts of a text from word (.doc,.docx) > files as well as pdf; the idea is to walk through the whole directory tree > and populate a csv file with an excerpt from each file. > For PDF I found PyPdf ave found nothing to read > doc, docx > http://www.google.com/search?q=python+read+ms+word+file&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a which returns this: http://stackoverflow.com/questions/125222/extracting-text-from-ms-word-files-in-python Additionally -- docx are, IIRC, zipped XML, so you could probably just uncompress it and scan the XML directly... Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Tue Jan 25 23:21:13 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 17:21:13 -0500 Subject: [Tutor] extracting text from word files (.doc, .docx) and pdf In-Reply-To: References: Message-ID: <4D3F4CD9.6040607@aim.com> On 01/25/2011 04:52 PM, Juan Jose Del Toro wrote: > Dear List; > > I am looking for a way to extract parts of a text from word (.doc,.docx) > files as well as pdf; the idea is to walk through the whole directory tree > and populate a csv file with an excerpt from each file. > For PDF I found PyPdf ave found nothing to read > doc, docx > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor A docx file is a compressed XML file (or groups of files). I don't know if there is a python module for it, but you could probably whip up your own. I know 7z on Windows will extract a .docx (probably anything can if you point to it, not sure). From there you'll need to explore the structure and how Microsoft decided to use XML. ElementTree would probably be useful here. Not sure about a doc file, a simple dd of a doc file shows some garbage (probably useful for formatting ;-) as well as the text. I found http://code.activestate.com/recipes/279003-converting-word-documents-to-text/ . From karim.liateni at free.fr Tue Jan 25 23:25:02 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 23:25:02 +0100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F4767.2060606@aim.com> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> <4D3F4767.2060606@aim.com> Message-ID: <4D3F4DBE.30905@free.fr> Yes you're right. But the class and instance thing made me believe the context would be different. Error of judgment. Regards Karim On 01/25/2011 10:57 PM, Corey Richardson wrote: > On 01/25/2011 04:28 PM, Karim wrote: >> Hello Bob, >> >> I know this fact for function but in this case this is not a function >> but a constructor method of a class. > To be pedantic, a method _is_ a function, just under the umbrella of a > class, with it's parent object being passed to it. > ~Corey > >> The impact is not the same because all instance share the same argument >> parameter.This a kind >> of singleton argument :-) . I believed that the constructor will create >> each time a new argument init. >> >> >> Regards >> Karim >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From karim.liateni at free.fr Tue Jan 25 23:28:17 2011 From: karim.liateni at free.fr (Karim) Date: Tue, 25 Jan 2011 23:28:17 +0100 Subject: [Tutor] placing widgets In-Reply-To: <312659.84240.qm@web120906.mail.ne1.yahoo.com> References: <312659.84240.qm@web120906.mail.ne1.yahoo.com> Message-ID: <4D3F4E81.9050606@free.fr> On 01/25/2011 10:31 PM, W S wrote: > hi, i have written some Tk/Python code to do a few simple tasks, and > am having trouble with my combobox placement on the frame. is there a > way to more explicitly place it other than: This method does not give > a lot of control > xx=apply(OptionMenu,(self,TCase)+tuple(TestCase)) > xx.grid(row=1, sticky=E+W) > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor with grid you have row and column attribute. Plus you can create several Frames and place your widget in it if you want more specific placements. Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Wed Jan 26 00:00:06 2011 From: smokefloat at gmail.com (David Hutto) Date: Tue, 25 Jan 2011 18:00:06 -0500 Subject: [Tutor] placing widgets In-Reply-To: <4D3F4E81.9050606@free.fr> References: <312659.84240.qm@web120906.mail.ne1.yahoo.com> <4D3F4E81.9050606@free.fr> Message-ID: Note when you answer yourself, it shows initiative and responsiveness to the situation you're trying to comprehend. -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From chrysalis_reborn at yahoo.com Wed Jan 26 00:26:51 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Tue, 25 Jan 2011 15:26:51 -0800 (PST) Subject: [Tutor] class question Message-ID: <859352.36127.qm@web130208.mail.mud.yahoo.com> Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes?? Seems to me like the one large class would be clearer in some ways.? I have something I am trying to do that have somewhere in the neighborhood of 20 attributes that all relate together, however there are sort of "clumps" of attributes that have a sub-relationship to each other and I wondered if they should be their own class, but I am not sure, assuming that is a good idea, how these smaller classes might work together.? I have only the foggiest notion of inheritance and I'd kind of like to stay away from that aspect of things until I get a better grasp of individual classes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Jan 26 00:33:34 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 10:33:34 +1100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F3574.3040802@free.fr> References: <4D3F3574.3040802@free.fr> Message-ID: <4D3F5DCE.2030008@pearwood.info> Karim wrote: > > Hello All, > > Just to share on rageous bug I encounter where 2 lists which "should" to > be different (same id) because hold by different instances of the same > class are not in fact DIFFERENT, see below: I think you are confused. If the two lists have the same ID, they should be the same, not different. > >>> class Device(): > ... def __init__(self, parameters=[]): > ... self.parameters = parameters This creates a list ONCE, when the method is created, and then uses that same list over and over again. Consider this: >>> import time >>> now = time.ctime() >>> now 'Wed Jan 26 10:05:31 2011' >>> def test(t=now): ... print(t) ... >>> test() Wed Jan 26 10:05:31 2011 >>> time.sleep(60); test() Wed Jan 26 10:05:31 2011 Are you surprised that time.ctime() only gets called *once*? I hope not -- I would expect that you consider this example obvious and not surprising. How about this instead? >>> def test2(t=time.ctime()): ... print(t) ... >>> test2() Wed Jan 26 10:09:10 2011 >>> time.sleep(60); test2() Wed Jan 26 10:09:10 2011 I hope that this also will not be surprising. time.ctime() is called once, when the function is created, and the result used as often as needed. It is no different when the default value is a list like []. The list is created once, and used each time the function is called. > When I discovered that I was puzzled because at the prompt: > > >>> a = [] > >>> b = [] > >>> id(a) > 140559202956496 > >>> id(b) > 140559202957000 But this test is completely different. You create TWO lists, not one. A better test would be: >>> a = [] >>> b = a >>> id(a), id(b) (3083146668, 3083146668) > I am not really understanding why my init in the class made it refers to > the same list object. Because it only creates one list, when the method is defined, not each time the method is called. Only the *inside* of the method is executed each time the method is called, not the method definition. If you want something to be executed each time the method is called, you have to put it in the body of the method: >>> def test3(t=None): ... if t is None: t = time.ctime() ... print(t) ... >>> test3() Wed Jan 26 10:18:33 2011 >>> time.sleep(60); test3() Wed Jan 26 10:19:37 2011 -- Steven From steve at pearwood.info Wed Jan 26 00:39:24 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 10:39:24 +1100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F406C.3070003@free.fr> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> Message-ID: <4D3F5F2C.2040304@pearwood.info> Karim wrote: > > Hello Bob, > > I know this fact for function but in this case this is not a function > but a constructor method of a class. Methods *are* functions. (Technically, they are lightweight wrappers around functions.) They are treated exactly the same by Python. The "constructor method" __init__ is treated not special. You can easily see this by printing the function from *inside* the class, before it gets wrapped by the class machinery: >>> class Test: # From Python 3, Python 2 may be a bit different. ... def __init__(myname, arg=[]): ... pass ... print(__init__) ... print(__init__.__defaults__) ... ([],) And there you can clearly see the list used as a default value. It is a little bit harder from outside, because the function is wrapped in a method-wrapper, but not that hard: >>> instance = Test() >>> instance.__init__.__func__ >>> instance.__init__.__func__.__defaults__ ([],) -- Steven From steve at pearwood.info Wed Jan 26 00:49:32 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 10:49:32 +1100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F4767.2060606@aim.com> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> <4D3F4767.2060606@aim.com> Message-ID: <4D3F618C.8060301@pearwood.info> Corey Richardson wrote: > To be pedantic, a method _is_ a function, just under the umbrella of a > class, with it's parent object being passed to it. To be even more pedantic, a method object is a wrapper (technically, a descriptor) around a function object. It's also slightly different between Python 2 and Python 3. Python 2 has bound and unbound method wrappers, depending on whether you call class.method or instance.method, but Python 3 gets rid of unbound methods and just returns the function object when you call class.method. And of course, there are also "class methods" and "static methods", as well as custom-built method types. Descriptors are fundamental to Python, but they're for advanced users. You can treat methods as just functions, except that they automatically get the first argument (usually called "self") automatically supplied. -- Steven From emile at fenx.com Wed Jan 26 00:59:38 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Jan 2011 15:59:38 -0800 Subject: [Tutor] extracting text from word files (.doc, .docx) and pdf In-Reply-To: References: Message-ID: On 1/25/2011 1:52 PM Juan Jose Del Toro said... > Dear List; > > I am looking for a way to extract parts of a text from word (.doc,.docx) I recently did a project extracting data from word documents and used antiword (http://www.winfield.demon.nl/) then used it like this: def setContent(self): self.content = [ ii.strip().replace("??","") for ii in commands.getoutput('/usr/local/bin/antiword "%s"' % doc).split("\n") if ii ] Emile From linux4n6 at gmail.com Tue Jan 25 20:46:12 2011 From: linux4n6 at gmail.com (It't me) Date: Tue, 25 Jan 2011 20:46:12 +0100 Subject: [Tutor] sorted question Message-ID: Hi all, I'm learning Python with Google's Python class Ik have a question about the following code: ================================= def sort(var): return var[-1] #returns the last character of var def sort_last(): tup = [(1, 3), (3, 2), (2, 1)] print(sorted(tup, key=sort)) sort_last() ================================== I uderstand everything except (var) value. I understand that key=sort calls the sort function. But where comes the var value from? Does sort automatic pass the value from tup to (var) because (var) is nowhere defined. Thanks, Martin -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Wed Jan 26 01:22:32 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 19:22:32 -0500 Subject: [Tutor] class question In-Reply-To: <859352.36127.qm@web130208.mail.mud.yahoo.com> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D3F6948.50900@aim.com> On 01/25/2011 06:26 PM, Elwin Estle wrote: > Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes? Seems to me like the one large class would be clearer in some ways. I have something I am trying to do that have somewhere in the neighborhood of 20 attributes that all relate together, however there are sort of "clumps" of attributes that have a sub-relationship to each other and I wondered if they should be their own class, but I am not sure, assuming that is a good idea, how these smaller classes might work together. I have only the foggiest notion of inheritance and I'd kind of like to stay away from that aspect of things until I get a better grasp of individual classes. > If you're just learning, go ahead and make a 'do it all' class. Don't do it later in your growth as a programmer though. Inheritance works like this: class Parent: def __init__(self): print "Parent initialised" class Child(Parent): pass The parenthesis set the superclass or parent class. If you now do: c = Child() You should see "Parent initialised" printed to the terminal. It makes all the 'parents' methods available to it. You can think of it as copying all the code from the parent class into the child class. You can overwrite the methods too: class Animal: def speak(self): print self.noise class Pig(Animal): def __init__(self): self.noise = "Oink!" pig = Pig() pig.speak() Hope it helped, ~Corey From marc.tompkins at gmail.com Wed Jan 26 01:28:05 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Jan 2011 16:28:05 -0800 Subject: [Tutor] class question In-Reply-To: <859352.36127.qm@web130208.mail.mud.yahoo.com> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: On Tue, Jan 25, 2011 at 3:26 PM, Elwin Estle wrote: > > Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes?? Seems to me like the one large class would be clearer in some ways.? I have something I am trying to do that have somewhere in the neighborhood of 20 attributes that all relate together, however there are sort of "clumps" of attributes that have a sub-relationship to each other and I wondered if they should be their own class, but I am not sure, assuming that is a good idea, how these smaller classes might work together.? I have only the foggiest notion of inheritance and I'd kind of like to stay away from that aspect of things until I get a better grasp of individual classes. > For me, the question of one big class/multiple smaller classes comes down to reusability. If you find yourself writing the same code over and over again (or cutting/pasting big blocks of code), you should probably break up your classes. -- www.fsrtechnologies.com From alan.gauld at btinternet.com Wed Jan 26 01:30:05 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 00:30:05 -0000 Subject: [Tutor] The trap of the year References: <4D3F3574.3040802@free.fr> <4D3F3DCB.6040407@free.fr> Message-ID: "Karim" wrote > If I understand a little bit what happen in: > > def __init__(self, parameters=[]): > [...] > > The list argument is built before instance creation and indeed > constructor execution. > So this is the same list instance of constructor parameter for all > new > instance creation. Yes that is a feature of Pythons default argument mechanism. It has been discussed many times on this list and in the docs. As you discovered the best way to avoid it is use None as the default then create a new list inside the function if it is None. > I never see warning about this fact in any books before. Its quite commonly warned against but until you get bitten the significance just passes you by! I bet if you look out for it now you'll see it often ebnough! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Wed Jan 26 01:37:13 2011 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 25 Jan 2011 16:37:13 -0800 Subject: [Tutor] sorted question In-Reply-To: References: Message-ID: On Tue, Jan 25, 2011 at 11:46 AM, It't me wrote: > Hi all, > > I'm learning Python with Google's Python class > > Ik have a question about the following code: > ================================= > def sort(var): > ?return var[-1]? #returns the last character of var > > def sort_last(): > ? tup = [(1, 3), (3, 2), (2, 1)] > ? print(sorted(tup, key=sort)) > > sort_last() > ================================== > > I uderstand everything except (var) value. > I understand that key=sort calls the sort function. > But where comes the var value from? > Does sort automatic pass the value from tup to (var) > > because (var) is nowhere defined. > > Thanks, > > Martin Could you post the URL to that class? 'Cause I don't see it either, from what you've posted. If that's all there is, something is profoundly wrong. -- www.fsrtechnologies.com From alan.gauld at btinternet.com Wed Jan 26 01:39:16 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 00:39:16 -0000 Subject: [Tutor] placing widgets References: <312659.84240.qm@web120906.mail.ne1.yahoo.com> Message-ID: "W S" wrote > trouble with my combobox placement on the frame. is there a way to > more > explicitly place it other than: This method does not give a lot of > control > xx=apply(OptionMenu,(self,TCase)+tuple(TestCase)) > xx.grid(row=1, sticky=E+W) There are basically 3 layout managers in Tk. pack() is the simplest and gives the programmer least control but generally yields a usable GUI even if the user messes around with fonts and sizing etc. grid() is next easiest since it represents the window as a table into whose cells you insert the widgets. This gives more control but can lead to strange results on resizing. place() is the one that many beginners think is easiest because it uses actual coordinates. It allows very precise positioning provided the user doesn't resize the window or change font sizes Most Tk programmers use grid() and pack(), often a combination. I tend to use pack at the top kevel to create a set of Frames. Then inside the Frames I use either pack or grid as appropriate for the layout I want. That provides flexibility plus adaptability to user changes. All of the managers have a slew of options that can be used to fine tune the spacing, directional bias, etc. RTFM for details. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 01:42:08 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 00:42:08 -0000 Subject: [Tutor] extracting text from word files (.doc, .docx) and pdf References: Message-ID: "Juan Jose Del Toro" wrote > I am looking for a way to extract parts of a text from word > (.doc,.docx) > files as well as pdf; In addition to the suggestions already given you can use COM to drive Word itself if you have Word on the PC in which you are running the code. If not there are ways to drive OpenOffice too although I've never used them... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 01:50:55 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 00:50:55 -0000 Subject: [Tutor] class question References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: "Elwin Estle" wrote > Is it better to have one large sort of "do it all" class, > or break the larger class up into smaller classes? Usually the latter. But remember that classes model objects. Objects usually have a direct relationship to some kind of "real world" entity - even if its an abstract conceptual entity. So if the attributes and behaviours are all exhibited by the thing you are modelling then they should maybe stay together. But uasually the big thing can be modelled as a composition of smaller things... > Seems to me like the one large class would be clearer > in some ways. Very rarely is a big lump of code clearer than several small single purpose lumps of code. And big lumps of code are nearly always harder to reuse - one of the other reasons to create classes... > I have something I am trying to do that have somewhere > in the neighborhood of 20 attributes that all relate together, > however there are sort of "clumps" of attributes that have > a sub-relationship to each other Without specifics we can't be sure. But it sounds like you have a composite structure. OTOH 20 attributes is not enormous - 200 would be, but not 20. But even 20 is enough to challenge. > I have only the foggiest notion of inheritance It doesn't sound like inheritance is an issue here. It sounds like we are talking about composition. But without specific details we can't be sure. Remember that the thing that defines a class should be its operations not its data. Do these smaller "clumps of attributes" have common behaviour associated with them? The data should only be there to support the operations. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Jan 26 01:51:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 11:51:36 +1100 Subject: [Tutor] ideas for a simple program In-Reply-To: <4D3F0C1F.5020901@iandouglas.com> References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> <4D3F0C1F.5020901@iandouglas.com> Message-ID: <4D3F7018.1080007@pearwood.info> ian douglas wrote: > With an Email address like "hacker0100", your best bet might be to do > what we told another user just a few days ago: Ha ha, it's funny how different people interpret email addresses differently. *I* look at an email address "hacker0100" and think "wannabe". No offense Walter. > Find an open-source project, and try to add a new feature to it, or fix > a bug in it. That way you learn about the language, the project, and > could get your name out there as a contributor if your changes are > accepted by the original author. If you're contributing to open source projects for the credit, or to become famous, you're probably going to be disappointed. However, if you contribute bug reports or tests to this project, I can promise that the project owner will give you credit in the next release :) http://code.google.com/p/pycalcstats/ -- Steven From emile at fenx.com Wed Jan 26 01:53:07 2011 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Jan 2011 16:53:07 -0800 Subject: [Tutor] sorted question In-Reply-To: References: Message-ID: On 1/25/2011 11:46 AM It't me said... > Hi all, > > I'm learning Python with Google's Python class > > Ik have a question about the following code: > ================================= > def sort(var): > return var[-1] #returns the last character of var Nit: it'll be a character if passed in a string of characters. If you pass in a tuple or list, it'll be the last thing in the list. > > def sort_last(): > tup = [(1, 3), (3, 2), (2, 1)] > print(sorted(tup, key=sort)) > > sort_last() > ================================== > > I uderstand everything except (var) value. > I understand that key=sort calls the sort function. > But where comes the var value from? > Does sort automatic pass the value from tup to (var) > > because (var) is nowhere defined. in the line def sort(var): var becomes in effect a placeholder for whatever value is passed to the function. in the line print(sorted(tup, key=sort)) sort is being passed into sorted, and looking into the python documentation for sorted we find two things. sorted(iterable[, cmp[, key[, reverse]]])? Return a new sorted list from the items in iterable. 1) that sorted expects the first paramater to be iterable. And a bit further we find... key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly). Aahh... there it is -- each element of the iterable will be passed into the function named by key to determine the comparison key. Now, applies to your code this means that for each pair in [(1, 3), (3, 2), (2, 1)] sorted will comare the result of your sort function when passed that pair, and your sort function returns the last element in that pair. HTH, Emile From karim.liateni at free.fr Wed Jan 26 02:12:51 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 02:12:51 +0100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F5F2C.2040304@pearwood.info> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> <4D3F5F2C.2040304@pearwood.info> Message-ID: <4D3F7513.1050409@free.fr> Thanks for the tip Steven. Regards Karim On 01/26/2011 12:39 AM, Steven D'Aprano wrote: > Karim wrote: >> >> Hello Bob, >> >> I know this fact for function but in this case this is not a function >> but a constructor method of a class. > > Methods *are* functions. (Technically, they are lightweight wrappers > around functions.) They are treated exactly the same by Python. The > "constructor method" __init__ is treated not special. You can easily > see this by printing the function from *inside* the class, before it > gets wrapped by the class machinery: > > >>> class Test: # From Python 3, Python 2 may be a bit different. > ... def __init__(myname, arg=[]): > ... pass > ... print(__init__) > ... print(__init__.__defaults__) > ... > > ([],) > > And there you can clearly see the list used as a default value. > > It is a little bit harder from outside, because the function is > wrapped in a method-wrapper, but not that hard: > > >>> instance = Test() > >>> instance.__init__.__func__ > > >>> instance.__init__.__func__.__defaults__ > ([],) > > > > From karim.liateni at free.fr Wed Jan 26 02:17:19 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 02:17:19 +0100 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F5DCE.2030008@pearwood.info> References: <4D3F3574.3040802@free.fr> <4D3F5DCE.2030008@pearwood.info> Message-ID: <4D3F761F.9060108@free.fr> After one 2 months of python intensive development. I made this init defaults error in my db classes constructors... Shame on me :-[ Steven ! Your example shows me obvious. Regards Karim On 01/26/2011 12:33 AM, Steven D'Aprano wrote: > Karim wrote: >> >> Hello All, >> >> Just to share on rageous bug I encounter where 2 lists which "should" >> to be different (same id) because hold by different instances of the >> same class are not in fact DIFFERENT, see below: > > I think you are confused. If the two lists have the same ID, they > should be the same, not different. > > >> >>> class Device(): >> ... def __init__(self, parameters=[]): >> ... self.parameters = parameters > > This creates a list ONCE, when the method is created, and then uses > that same list over and over again. > > Consider this: > > >>> import time > >>> now = time.ctime() > >>> now > 'Wed Jan 26 10:05:31 2011' > >>> def test(t=now): > ... print(t) > ... > >>> test() > Wed Jan 26 10:05:31 2011 > >>> time.sleep(60); test() > Wed Jan 26 10:05:31 2011 > > > Are you surprised that time.ctime() only gets called *once*? I hope > not -- I would expect that you consider this example obvious and not > surprising. > > How about this instead? > > >>> def test2(t=time.ctime()): > ... print(t) > ... > >>> test2() > Wed Jan 26 10:09:10 2011 > >>> time.sleep(60); test2() > Wed Jan 26 10:09:10 2011 > > > I hope that this also will not be surprising. time.ctime() is called > once, when the function is created, and the result used as often as > needed. > > It is no different when the default value is a list like []. The list > is created once, and used each time the function is called. > > > > When I discovered that I was puzzled because at the prompt: >> >> >>> a = [] >> >>> b = [] >> >>> id(a) >> 140559202956496 >> >>> id(b) >> 140559202957000 > > But this test is completely different. You create TWO lists, not one. > A better test would be: > > >>> a = [] > >>> b = a > >>> id(a), id(b) > (3083146668, 3083146668) > > >> I am not really understanding why my init in the class made it refers >> to the same list object. > > Because it only creates one list, when the method is defined, not each > time the method is called. > > Only the *inside* of the method is executed each time the method is > called, not the method definition. If you want something to be > executed each time the method is called, you have to put it in the > body of the method: > > > >>> def test3(t=None): > ... if t is None: t = time.ctime() > ... print(t) > ... > >>> test3() > Wed Jan 26 10:18:33 2011 > >>> time.sleep(60); test3() > Wed Jan 26 10:19:37 2011 > > > From karim.liateni at free.fr Wed Jan 26 02:21:21 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 02:21:21 +0100 Subject: [Tutor] The trap of the year In-Reply-To: References: <4D3F3574.3040802@free.fr> <4D3F3DCB.6040407@free.fr> Message-ID: <4D3F7711.8090500@free.fr> Sorry Alan, When I read your tutorial I was probably blind... :-D I am going to re-read it. Regards Karim On 01/26/2011 01:30 AM, Alan Gauld wrote: > > "Karim" wrote > >> If I understand a little bit what happen in: >> >> def __init__(self, parameters=[]): >> [...] >> >> The list argument is built before instance creation and indeed >> constructor execution. >> So this is the same list instance of constructor parameter for all new >> instance creation. > > Yes that is a feature of Pythons default argument mechanism. > It has been discussed many times on this list and in the docs. > As you discovered the best way to avoid it is use None as the > default then create a new list inside the function if it is None. > >> I never see warning about this fact in any books before. > > Its quite commonly warned against but until you get bitten > the significance just passes you by! I bet if you look out for > it now you'll see it often ebnough! > > HTH, > > From karim.liateni at free.fr Wed Jan 26 02:30:10 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 02:30:10 +0100 Subject: [Tutor] class question In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D3F7922.4020409@free.fr> Hello, Design Patterns is the key for code reuse and problem solving. Indeed you have to separate your objects (classes) to use it. The god class is like a script with only one function: not very flexible and easy to debug. Program towards interface that means you have to use inheritance. Try to determine the objects you need for your problem and next step is how arrange it together (relational). Regards Karim On 01/26/2011 01:28 AM, Marc Tompkins wrote: > On Tue, Jan 25, 2011 at 3:26 PM, Elwin Estle wrote: >> Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes? Seems to me like the one large class would be clearer in some ways. I have something I am trying to do that have somewhere in the neighborhood of 20 attributes that all relate together, however there are sort of "clumps" of attributes that have a sub-relationship to each other and I wondered if they should be their own class, but I am not sure, assuming that is a good idea, how these smaller classes might work together. I have only the foggiest notion of inheritance and I'd kind of like to stay away from that aspect of things until I get a better grasp of individual classes. >> > For me, the question of one big class/multiple smaller classes comes > down to reusability. > If you find yourself writing the same code over and over again (or > cutting/pasting big blocks of code), you should probably break up your > classes. > > -- > www.fsrtechnologies.com > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Wed Jan 26 02:46:38 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 12:46:38 +1100 Subject: [Tutor] class question In-Reply-To: <859352.36127.qm@web130208.mail.mud.yahoo.com> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D3F7CFE.6010104@pearwood.info> Elwin Estle wrote: > Is it better to have one large sort of "do it all" class, or break > the larger class up into smaller classes? Yes. Or no. It's impossible to answer that question definitively without knowing more about what "it all" is. But I can give some general advice: * Python isn't Java. Don't feel that you must use classes. If your problem is better solved using a procedural or functional approach, go right ahead and use it. Classes aren't compulsory. * The standard model which you should use it: verbs -> functions or methods nouns -> classes or attributes You should be able to answer the question "What *thing* does your class represent?". (The answer can be an abstract thing, but it should be a thing.) If you can't answer that question, then you shouldn't use a class. You should solve the problem using stand-alone functions. * Think about "is-a" and "has-a" relationships: - if x is a Foo, then use a class Foo and make x an instance of Foo - if x has a Foo, then give x an attribute x.foo which is a Foo * Classes should represent a *single* well-defined thing. That might be a compound thing, or a collection of things -- the class represents the entire collection. If the thing is made of parts, each part could be represented by an attribute. This is okay: class Coffee: def __init__(self): self.style = 'white' self.milk = 'full cream' self.sugars = 1 self.size = 'regular' class Pie: def __init__(self): self.kind = 'cherry' self.slices = 1 self.with_cream = False class SpecialOfTheDay: def __init__(self): self.drink = Coffee() self.snack = Pie() But don't design a class like this: class CoffeeAndPie: def __init__(self): self.style = 'white' self.milk = 'full cream' self.sugars = 1 self.size = 'regular' self.kind = 'cherry' self.slices = 1 self.with_cream = False One slice of coffee? Oh really? * Classes should be more general rather than too specific. But don't go crazy and make it so abstract that you run out of air to breathe, and nobody can understand what the hell the class is for: http://www.joelonsoftware.com/articles/fog0000000018.html * Coupling is usually bad. Aim to reduce coupling, unless you have a good reason for wanting strongly coupled systems. What's coupling? A key and a lock are *highly* coupled: only one key will fit the lock, and no other key will do the job. But, say, a knife and a steak are loosely coupled. Any sharp knife will cut a steak. Sure, some knives are better than others, but at a pitch, you could even use a blunt butter-knife and a lot of effort. Another example: your clothes iron and ironing board have very loose coupling. You can use any iron on any board, and it will be just fine. But the memory cards in your computer are moderately coupled with the motherboard: only some memory cards will fit. You can't use a 1980 64K memory card in a 2011 motherboard. But provided the memory will fit, it doesn't matter which card you use. * One way to reduce coupling is with the Law of Demeter: if you want your dog to walk, don't talk to your dog's legs. You will only confuse the dog and it won't get anywhere. http://en.wikipedia.org/wiki/Law_of_Demeter Hope this helps. -- Steven From steve at pearwood.info Wed Jan 26 02:50:07 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 12:50:07 +1100 Subject: [Tutor] class question In-Reply-To: <4D3F6948.50900@aim.com> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <4D3F6948.50900@aim.com> Message-ID: <4D3F7DCF.3070203@pearwood.info> Corey Richardson wrote: > On 01/25/2011 06:26 PM, Elwin Estle wrote: >> Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes? > If you're just learning, go ahead and make a 'do it all' class. Don't do > it later in your growth as a programmer though. Learn bad habits first, then spend years trying to break them! *wink* -- Steven From vearasilp at gmail.com Wed Jan 26 03:50:05 2011 From: vearasilp at gmail.com (Kann Vearasilp) Date: Wed, 26 Jan 2011 09:50:05 +0700 Subject: [Tutor] To learn multithreading in Python Message-ID: Dear all, I want to learn about threading, multithreading, and parallel programming. I have never done this kind of programming before. Would python be a good kick-starting? Do you have any suggestions for tutorials, books? Kann -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Wed Jan 26 04:14:02 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 22:14:02 -0500 Subject: [Tutor] class question In-Reply-To: <4D3F7DCF.3070203@pearwood.info> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <4D3F6948.50900@aim.com> <4D3F7DCF.3070203@pearwood.info> Message-ID: <4D3F917A.1010100@aim.com> On 01/25/2011 08:50 PM, Steven D'Aprano wrote: > Corey Richardson wrote: >> On 01/25/2011 06:26 PM, Elwin Estle wrote: >>> Is it better to have one large sort of "do it all" class, or break >>> the larger class up into smaller classes? > >> If you're just learning, go ahead and make a 'do it all' class. Don't do >> it later in your growth as a programmer though. > > Learn bad habits first, then spend years trying to break them! > > *wink* Hey, gotta learn the concepts first, right? ;-) I remember my first "substantial" program, hangman! Quite a mess. Excerpt: def getlist3(self): list3 = [] for i in range(5): list3.append(self.gameWord[i]) self.list3 = list3 I don't even remember what list3 is. I have a whole function for a list comprehension! self.list3 = [char for (idx, char) in enumerate(gameWord) if gameWord.index(char, idx) < 5] (list3 happened to be the hint characters given, remembered while doing) Just proof that it doesn't have to take years, it could take months. From steve at pearwood.info Wed Jan 26 04:18:53 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 14:18:53 +1100 Subject: [Tutor] ideas for a simple program In-Reply-To: References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: <4D3F929D.5050901@pearwood.info> walter weston wrote: > > can I have some good ideas for simple programs, What are you interested in? Find something you like to do, and write a program to help you do it. Interested in maths? Write a program to generate prime numbers, or to search for amicable numbers. Look at Project Euler, although (in my opinion) the puzzles there are quite hard and require a lot of maths know-how. Write a number guessing game. Or Hangman or Battleship. Try the Python Challenge: http://www.pythonchallenge.com/ More puzzle sites here, written in other languages but you can solve them in Python if you like: http://sixrevisions.com/resources/10-puzzle-websites-to-sharpen-your-programming-skills/ Unfortunately, most of them seem to be aimed at people who aren't newbies. I think the world needs a good set of programming puzzles for beginners. Write a program that asks the user to enter a word, then counts how many vowels and consonants are in the word. Write a program to check the spelling of a word. (Easy.) Write one that makes suggestions for mis-spelled words. (Harder.) Write a program that asks the user to type a message, and then converts it to Pig Latin. If you don't know what Pig Latin is, google for it :) Write a program that asks the user for a list of numbers, separated by spaces or commas, and then calculated the total and the average. A program that prints the time. Or how many days left until your birthday, or Christmas. A program that counts how many palindrome numbers there are between two other numbers. (A palindrome number is one like 12321, or 473374.) A program that sings (well, prints) the "There were ten in the bed" song. If you don't know it, it is a children's song. You start off by holding up ten fingers, or you can use actual children. You don't have to start with ten. Then you sing: There were ten in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were nine in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were eight in the bed, and the little one said, ... Well you get the idea. Eventually you've left with only the little one left, and the song ends: There was one in a bed, and the little one said Good night! Or the 99 bottles of beer song. Google for it. Or a program to find anagrams. Write a program to find a random image on the Internet and display it in a window. This might be a little advanced for a beginner. Or a program to find a random image on your hard drive, and display it in a window, Write a program to simulate rolling dice, and print a histogram of the results. Write a program that tests how random a sequence of supposed coin tosses are. If I say that I tossed a coin 20 times and got HTHTHTHHTTHTTHHTHTHT how likely is it that I'm lying? -- Steven From swiftone at swiftone.org Wed Jan 26 05:03:05 2011 From: swiftone at swiftone.org (Brett Ritter) Date: Tue, 25 Jan 2011 23:03:05 -0500 Subject: [Tutor] ideas for a simple program In-Reply-To: <4D3F929D.5050901@pearwood.info> References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> <4D3F929D.5050901@pearwood.info> Message-ID: On Tue, Jan 25, 2011 at 10:18 PM, Steven D'Aprano wrote: > Or a program to find anagrams. A great exercise in learning how different string operations perform is to search a text file for the largest palindrome string. I recall running one on the Constitution where a good program could do it in seconds and a bad program would take hours (if it didn't run out of memory first). -- Brett Ritter / SwiftOne swiftone at swiftone.org From kb1pkl at aim.com Wed Jan 26 05:33:58 2011 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 25 Jan 2011 23:33:58 -0500 Subject: [Tutor] The trap of the year In-Reply-To: <4D3F618C.8060301@pearwood.info> References: <4D3F3574.3040802@free.fr> <4D3F3EBB.5060405@gmail.com> <4D3F406C.3070003@free.fr> <4D3F4767.2060606@aim.com> <4D3F618C.8060301@pearwood.info> Message-ID: <4D3FA436.1000909@aim.com> On 01/25/2011 06:49 PM, Steven D'Aprano wrote: > Corey Richardson wrote: > >> To be pedantic, a method _is_ a function, just under the umbrella of a >> class, with it's parent object being passed to it. > > To be even more pedantic, a method object is a wrapper (technically, a > descriptor) around a function object. It's also slightly different > between Python 2 and Python 3. Python 2 has bound and unbound method > wrappers, depending on whether you call class.method or instance.method, > but Python 3 gets rid of unbound methods and just returns the function > object when you call class.method. > > And of course, there are also "class methods" and "static methods", as > well as custom-built method types. > > Descriptors are fundamental to Python, but they're for advanced users. > You can treat methods as just functions, except that they automatically > get the first argument (usually called "self") automatically supplied. > > Learning something every day, thank you Steven. ~Corey From steve at pearwood.info Wed Jan 26 05:36:48 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 15:36:48 +1100 Subject: [Tutor] ideas for a simple program In-Reply-To: References: <1316926545.177259.1295971489355.JavaMail.ubuntu@domU-12-31-38-06-C0-11> Message-ID: <4D3FA4E0.4090506@pearwood.info> walter weston wrote: > > can I have some good ideas for simple programs Some more ideas... Take a built-in Python command, and try to duplicate it in pure Python. E.g.: # Untested. def my_len(obj): # Like Python's len() function, only slower. try: return obj.__len__() except AttributeError: n = 0 try: while True: x = obj[n] n += 1 except IndexError: return n Take a shell command from your operating system, and try to re-write it in Python. Or write a useful or fun utility in Python, e.g. I have a Python script that runs every night scanning my procmail logs for spam which is deleted, it copies the subject line and sender, deletes vowels from them, and emails the list to me. Go to the Python Cookbook and look for bugs or improvements in people's recipes. Or come up with your own. http://code.activestate.com/recipes/langs/python/ Go to the Python bug tracker, and try to fix some of the bugs. Or write tests for them. Or documentation. http://bugs.python.org/ -- Steven From steve at pearwood.info Wed Jan 26 05:55:51 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 26 Jan 2011 15:55:51 +1100 Subject: [Tutor] sorted question In-Reply-To: References: Message-ID: <4D3FA957.9070807@pearwood.info> It't me wrote: > Hi all, > > I'm learning Python with Google's Python class > > Ik have a question about the following code: > ================================= > def sort(var): > return var[-1] #returns the last character of var Why is the function called "sort" when it doesn't sort? Why not call it "run" or "cook" or "pink" or "xhg6gf2jgf"? Function names *must* tell you what they do, or at least give you a hint. Misleading names like "sort" for something that doesn't sort is very bad. Even a name like "xhg6gf2jgf" would be better than a name that lies about what it does. > def sort_last(): > tup = [(1, 3), (3, 2), (2, 1)] > print(sorted(tup, key=sort)) > > sort_last() > ================================== > > I uderstand everything except (var) value. > I understand that key=sort calls the sort function. Do you mean the sort function you wrote, or the built-in list sort method? I'll assume you mean the sort function you wrote. > But where comes the var value from? > Does sort automatic pass the value from tup to (var) No. sorted() passes the values to the key function "sort". "sort" *receives* those values, it doesn't go and get them. When you write a function with an argument, the argument isn't defined until you call it: def add_one(x): return x + 1 x is a local variable of the function, but is not yet defined. But when you call the function: add_one(42) x is set to 42. In your "sort" function, the local variable is called "var". Calling sorted(tup, key=sort) with tup = [(1, 3), (3, 2), (2, 1)] results in the sorted() function calling your key function "sort" with each of the items in turn: * build a new list by calling the "sort" function with (1,3), then (3,2), then (2, 1) * sort a copy of the original list according to the values in the new list * return the sorted copy -- Steven From ian.douglas at iandouglas.com Wed Jan 26 08:46:43 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Tue, 25 Jan 2011 23:46:43 -0800 Subject: [Tutor] Having a problem with markdown Message-ID: <4D3FD163.9070404@iandouglas.com> Hey all, I followed a tutorial on creating a very simple wiki in Python, which worked fine until the example where the instructor wanted to render the output through markdown.markdown() Here's the view code: from agwiki.wiki.models import Page from django.shortcuts import render_to_response from django.http import HttpResponseRedirect import markdown def view_page(request, page_name): try: page = Page.objects.get(pk=page_name) except Page.DoesNotExist: return render_to_response("create.html", {"page_name":page_name}) content = page.content return render_to_response("view.html",{"page_name":page_name,"content":markdown.markdown(content)}) The problem I'm having is that the output in a browser is outputing HTML markers as < and > instead of < and > so the browser literally shows "

hello world

". If I leave the line as it originally was: return render_to_response("view.html",{"page_name":page_name,"content":content}) It just prints "hello world" as saved in the database. I'm just not sure where to start looking for a solution here, and would appreciate any pointers. -------------- next part -------------- An HTML attachment was scrubbed... URL: From i.eat.brainzzz at gmail.com Wed Jan 26 03:51:28 2011 From: i.eat.brainzzz at gmail.com (Casey Key) Date: Tue, 25 Jan 2011 19:51:28 -0700 Subject: [Tutor] Shuts down when asking user for info Message-ID: Please help , run the script and see that once you press enter after entering name it just shuts it down, help. -------------- next part -------------- print("\tWelcome to Casey's magical python code!") print("\tWritten by no other than Casey Key!") print("\nWe will begin by getting some information,mmmkay?") name = input("what is your name") Print("your name is",name) input("\n\nPress the enter key to exit.") From alan.gauld at btinternet.com Wed Jan 26 11:16:02 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 26 Jan 2011 10:16:02 +0000 (GMT) Subject: [Tutor] The trap of the year In-Reply-To: <4D3F7711.8090500@free.fr> References: <4D3F3574.3040802@free.fr> <4D3F3DCB.6040407@free.fr> <4D3F7711.8090500@free.fr> Message-ID: <894842.4471.qm@web86706.mail.ird.yahoo.com> > When I read your tutorial I was probably blind... :-D > I am going to re-read it. Actually I don't think I discuss it. I only mention default arguments very briefly because they are not a standard programming feature. My tutor tries to teach general programming not Python specifics so it doesn't do much more than mention default args. (But maybe I should add a warning about this gotcha, it does catch a lot of folks iout...) Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From tcl76 at hotmail.com Wed Jan 26 11:24:45 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Wed, 26 Jan 2011 10:24:45 +0000 Subject: [Tutor] Shuts down when asking user for info In-Reply-To: References: Message-ID: maybe you can use raw_input? Date: Tue, 25 Jan 2011 19:51:28 -0700 From: i.eat.brainzzz at gmail.com To: tutor at python.org Subject: [Tutor] Shuts down when asking user for info Please help , run the script and see that once you press enter after entering name it just shuts it down, help. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 26 12:08:07 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 11:08:07 -0000 Subject: [Tutor] class question References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <4D3F7922.4020409@free.fr> Message-ID: "Karim" wrote > Program towards interface that means you have to use inheritance. Just to be picky, you can program by interface without using inheritance. Inheritance is only needed to implement interfaces in languages like C++. In Python (and other dynamically bound OOP languages) you can use polymorphism without inheritance. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 12:13:59 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 11:13:59 -0000 Subject: [Tutor] Shuts down when asking user for info References: Message-ID: "Casey Key" wrote > Please help , run the script and see that once you press enter after > entering name it just shuts it down, help. > -------------- print("\tWelcome to Casey's magical python code!") print("\tWritten by no other than Casey Key!") print("\nWe will begin by getting some information,mmmkay?") name = input("what is your name") Print("your name is",name) >----------------- Python is case sensitive, print starts with a lowercase P. However that should have generated an error. How did you run the program? If you ran it from an IDE or from the command prompt you would have seen the error. I suspect you are just double clicking in a file manager? Doing that the window will close before you can read it. Always test your code by running from a prompt so that you see all output, including errors. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 12:09:35 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 11:09:35 -0000 Subject: [Tutor] Shuts down when asking user for info References: Message-ID: "tee chwee liong" wrote > maybe you can use raw_input? It looks like the OP is using Python 3 so input() is the correct function. Alan G. From karim.liateni at free.fr Wed Jan 26 12:19:43 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 12:19:43 +0100 Subject: [Tutor] class question In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <4D3F7922.4020409@free.fr> Message-ID: <4D40034F.4080902@free.fr> Sure, but I come from java world and 1 inheritance is allowed but we can implement multiple interfaces. I like to use Abstract classes in Python then inherit and implement abstract method like in java (at least that's all I remember from Java experience). Indeed I was too direct everybody has the same style. Regards Karim On 01/26/2011 12:08 PM, Alan Gauld wrote: > > "Karim" wrote > >> Program towards interface that means you have to use inheritance. > > Just to be picky, you can program by interface without using > inheritance. Inheritance is only needed to implement interfaces in > languages like C++. In Python (and other dynamically bound OOP > languages) you can use polymorphism without inheritance. > From karim.liateni at free.fr Wed Jan 26 12:25:19 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 12:25:19 +0100 Subject: [Tutor] class question In-Reply-To: <4D3F7CFE.6010104@pearwood.info> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <4D3F7CFE.6010104@pearwood.info> Message-ID: <4D40049F.5050600@free.fr> I know the the law of Murphy. But this one is a must-have.:-) Regards Karim > * One way to reduce coupling is with the Law of Demeter: if you want > your dog to walk, don't talk to your dog's legs. You will only confuse > the dog and it won't get anywhere. > > http://en.wikipedia.org/wiki/Law_of_Demeter > > > > Hope this helps. > > > From chrysalis_reborn at yahoo.com Wed Jan 26 13:45:18 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Wed, 26 Jan 2011 04:45:18 -0800 (PST) Subject: [Tutor] class question Message-ID: <229841.16130.qm@web130204.mail.mud.yahoo.com> Elwin Estle wrote: > Is it better to have one large sort of "do it all" class, or break > the larger class up into smaller classes? Yes. Or no. It's impossible to answer that question definitively without knowing more about what "it all" is. But I can give some general advice: * Python isn't Java. Don't feel that you must use classes. If your problem is better solved using a procedural or functional approach, go right ahead and use it. Classes aren't compulsory. * The standard model which you should use it: ? verbs -> functions or methods ? nouns -> classes or attributes ? You should be able to answer the question "What *thing* does ? your class represent?". (The answer can be an abstract thing, ? but it should be a thing.) ? If you can't answer that question, then you shouldn't use a ? class. You should solve the problem using stand-alone functions. * Think about "is-a" and "has-a" relationships: ================================================================== The class in question, does, in fact, deal with a thing.? The problem is, the "thing" is highly mutable.?? The "is-a" and the "has-a" changes. Here is the scenario: A raw casting comes into a factory.? It is listed as such.? When machined, this part number changes to a different part number.?? The raw casting has no "quality related" stuff, but the machined casting does, and it can have more than one "quality related" thing. ...because, the raw casting may go through multiple operations to get to it's final state.? It may get machined on a lathe, then be transferred to a CNC machining station where a bolt circle may be drilled and tapped into it.? Each of those operations on separate machines will have a different set of quality checks associated with it. ...or it might be a part that goes from a raw casting to a sort of "mini-assembly" such as a rocker lever (if you know what that is), so we have raw casting = one part number, then it gets a bushing pressed into it = another part number, then it gets a threaded insert = another part number, but it is still the same thing, and each one of those steps may have some sort of quality check involved. Lets complicate things even further.? One raw casting may be machined into multiple part numbers.? Perhaps the only thing that changes is the location of a single hole.? But again, each one of those part numbers may go through multiple machining operations on different machines, with different quality checks.? This is done through something called a "tabbed" blueprint, wherein there is a master number, but there are "tabs" indicating that if you changes such and such feature, then the part number isn't the master number, but the tabbed number. So, in essence, there's a sort of "network" of "is-a" and "has-a" information. My idea was to, instead of having just a single "part" class, to have a sort of "component aggregate" class, which would cover not only single parts, but assemblies of parts.? So, even if a part was as simple as a raw casting that is just machined into a finished part and that's it, it would still be treated as a sort of assembly, with the raw casting being a component of the finished part number, if that makes sense. So there's all this information associated with a given part.? I am thinking it has a sort of tree structure.? I am just wondering if some of the branches of the tree should be separate classes that are then tied into the "trunk" of the master class, or if the whole thing should be a tree into and of itself. ...and yeah, I know, it's kind of a complex problem for a newbie to be thinking about. -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Wed Jan 26 15:35:27 2011 From: oberoc at gmail.com (Tino Dai) Date: Wed, 26 Jan 2011 09:35:27 -0500 Subject: [Tutor] class question In-Reply-To: <229841.16130.qm@web130204.mail.mud.yahoo.com> References: <229841.16130.qm@web130204.mail.mud.yahoo.com> Message-ID: > > > A raw casting comes into a factory. It is listed as such. When machined, > this part number changes to a different part number. The raw casting has > no "quality related" stuff, but the machined casting does, and it can have > more than one "quality related" thing. > > ...because, the raw casting may go through multiple operations to get to > it's final state. It may get machined on a lathe, then be transferred to a > CNC machining station where a bolt circle may be drilled and tapped into > it. Each of those operations on separate machines will have a different set > of quality checks associated with it. > > ...or it might be a part that goes from a raw casting to a sort of > "mini-assembly" such as a rocker lever (if you know what that is), so we > have raw casting = one part number, then it gets a bushing pressed into it = > another part number, then it gets a threaded insert = another part number, > but it is still the same thing, and each one of those steps may have some > sort of quality check involved. > > Lets complicate things even further. One raw casting may be machined into > multiple part numbers. Perhaps the only thing that changes is the location > of a single hole. But again, each one of those part numbers may go through > multiple machining operations on different machines, with different quality > checks. This is done through something called a "tabbed" blueprint, wherein > there is a master number, but there are "tabs" indicating that if you > changes such and such feature, then the part number isn't the master number, > but the tabbed number. > > So, in essence, there's a sort of "network" of "is-a" and "has-a" > information. > > My idea was to, instead of having just a single "part" class, to have a > sort of "component aggregate" class, which would cover not only single > parts, but assemblies of parts. So, even if a part was as simple as a raw > casting that is just machined into a finished part and that's it, it would > still be treated as a sort of assembly, with the raw casting being a > component of the finished part number, if that makes sense. > > So there's all this information associated with a given part. I am > thinking it has a sort of tree structure. I am just wondering if some of > the branches of the tree should be separate classes that are then tied into > the "trunk" of the master class, or if the whole thing should be a tree into > and of itself. > > ...and yeah, I know, it's kind of a complex problem for a newbie to be > thinking about. > > > > Here is my two-cents. This code is untested. Import statements haven't been included, there could be syntax errors, etc etc etc. What I did was switching off the part_number attribute in the Thing class. For the functions that "do stuff" to the thing instance, I appended a part-number (assuming new part number = master number + doing stuff number). The quality functions will check for that part number before proceeding with the checks. class Thing: # single part class def __init__(self,part_number='12345'): # 12345 is a default part number self.part_number=part_number def routeThing(thing): try: thing.part_number.append('-someRoutingPartNumber') exception AttributeError (e): e.printStackTrace() print "Router was not applied to thing" def checkQualityRoute1(thing): if hasattrib(thing,part_number) && (thing.part_number.find('-someRoutingPartNumber'): else: print "Thing has not be routed yet" def checkQualityRoute2(thing): if hasattrib(thing,part_number) && (thing.part_number.find('-someRoutingPartNumber'): else: print "Thing has not be routed yet" .... continue for all of the functions that you might need HTH, -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From izzaddin.ruhulessin at gmail.com Wed Jan 26 15:41:33 2011 From: izzaddin.ruhulessin at gmail.com (Izz ad-Din Ruhulessin) Date: Wed, 26 Jan 2011 15:41:33 +0100 Subject: [Tutor] class question In-Reply-To: References: <229841.16130.qm@web130204.mail.mud.yahoo.com> Message-ID: class Raw ---> class Processor ---> class Final 2011/1/26 Tino Dai > > >> >> A raw casting comes into a factory. It is listed as such. When machined, >> this part number changes to a different part number. The raw casting has >> no "quality related" stuff, but the machined casting does, and it can have >> more than one "quality related" thing. >> >> ...because, the raw casting may go through multiple operations to get to >> it's final state. It may get machined on a lathe, then be transferred to a >> CNC machining station where a bolt circle may be drilled and tapped into >> it. Each of those operations on separate machines will have a different set >> of quality checks associated with it. >> >> ...or it might be a part that goes from a raw casting to a sort of >> "mini-assembly" such as a rocker lever (if you know what that is), so we >> have raw casting = one part number, then it gets a bushing pressed into it = >> another part number, then it gets a threaded insert = another part number, >> but it is still the same thing, and each one of those steps may have some >> sort of quality check involved. >> >> Lets complicate things even further. One raw casting may be machined into >> multiple part numbers. Perhaps the only thing that changes is the location >> of a single hole. But again, each one of those part numbers may go through >> multiple machining operations on different machines, with different quality >> checks. This is done through something called a "tabbed" blueprint, wherein >> there is a master number, but there are "tabs" indicating that if you >> changes such and such feature, then the part number isn't the master number, >> but the tabbed number. >> >> So, in essence, there's a sort of "network" of "is-a" and "has-a" >> information. >> >> My idea was to, instead of having just a single "part" class, to have a >> sort of "component aggregate" class, which would cover not only single >> parts, but assemblies of parts. So, even if a part was as simple as a raw >> casting that is just machined into a finished part and that's it, it would >> still be treated as a sort of assembly, with the raw casting being a >> component of the finished part number, if that makes sense. >> >> So there's all this information associated with a given part. I am >> thinking it has a sort of tree structure. I am just wondering if some of >> the branches of the tree should be separate classes that are then tied into >> the "trunk" of the master class, or if the whole thing should be a tree into >> and of itself. >> >> ...and yeah, I know, it's kind of a complex problem for a newbie to be >> thinking about. >> >> >> >> > Here is my two-cents. This code is untested. Import statements haven't been > included, there could be syntax errors, etc etc etc. What I did > was switching off the part_number attribute in the Thing class. For the > functions that "do stuff" to the thing instance, I appended a part-number > (assuming new part number = master number + doing stuff number). The quality > functions will check for that part number before proceeding with the checks. > > > class Thing: # single part class > def __init__(self,part_number='12345'): # 12345 is a default > part number > self.part_number=part_number > > def routeThing(thing): > try: > thing.part_number.append('-someRoutingPartNumber') > > exception AttributeError (e): > e.printStackTrace() > print "Router was not applied to thing" > > def checkQualityRoute1(thing): > if hasattrib(thing,part_number) && > (thing.part_number.find('-someRoutingPartNumber'): > > else: > print "Thing has not be routed yet" > > def checkQualityRoute2(thing): > if hasattrib(thing,part_number) && > (thing.part_number.find('-someRoutingPartNumber'): > > else: > print "Thing has not be routed yet" > > .... continue for all of the functions that you might need > > HTH, > -Tino > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oberoc at gmail.com Wed Jan 26 15:47:04 2011 From: oberoc at gmail.com (Tino Dai) Date: Wed, 26 Jan 2011 09:47:04 -0500 Subject: [Tutor] Having a problem with markdown In-Reply-To: <4D3FD163.9070404@iandouglas.com> References: <4D3FD163.9070404@iandouglas.com> Message-ID: On Wed, Jan 26, 2011 at 2:46 AM, ian douglas wrote: > Hey all, > > I followed a tutorial on creating a very simple wiki in Python, which > worked fine until the example where the instructor wanted to render the > output through markdown.markdown() > > Here's the view code: > > from agwiki.wiki.models import Page > from django.shortcuts import render_to_response > from django.http import HttpResponseRedirect > import markdown > > def view_page(request, page_name): > try: > page = Page.objects.get(pk=page_name) > except Page.DoesNotExist: > return render_to_response("create.html", {"page_name":page_name}) > content = page.content > return > render_to_response("view.html",{"page_name":page_name,"content":markdown.markdown(content)}) > > The problem I'm having is that the output in a browser is outputing HTML > markers as < and > instead of < and > so the browser literally shows > "

hello world

". If I leave the line as it originally was: > > return > render_to_response("view.html",{"page_name":page_name,"content":content}) > > It just prints "hello world" as saved in the database. I'm just not sure > where to start looking for a solution here, and would appreciate any > pointers. > > > Two thing: - This sounds like homework. - This is a python mailing list, not a django mailing list Where I would start would be to investigate what the markdown class does. In addition I would read over the django documentation to see why django is doing that. It's in the django documentation, I hit that issue not too long ago. HTH, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Wed Jan 26 16:11:43 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Wed, 26 Jan 2011 07:11:43 -0800 Subject: [Tutor] Having a problem with markdown In-Reply-To: References: <4D3FD163.9070404@iandouglas.com> Message-ID: Thanks Tino, It's certainly not homework, I'm learning Python after being in the Perl/PHP world for well over a decade. Trying to teach this old dog some new tricks. On Jan 26, 2011 6:47 AM, "Tino Dai" wrote: > On Wed, Jan 26, 2011 at 2:46 AM, ian douglas wrote: > >> Hey all, >> >> I followed a tutorial on creating a very simple wiki in Python, which >> worked fine until the example where the instructor wanted to render the >> output through markdown.markdown() >> >> Here's the view code: >> >> from agwiki.wiki.models import Page >> from django.shortcuts import render_to_response >> from django.http import HttpResponseRedirect >> import markdown >> >> def view_page(request, page_name): >> try: >> page = Page.objects.get(pk=page_name) >> except Page.DoesNotExist: >> return render_to_response("create.html", {"page_name":page_name}) >> content = page.content >> return >> render_to_response("view.html",{"page_name":page_name,"content":markdown.markdown(content)}) >> >> The problem I'm having is that the output in a browser is outputing HTML >> markers as < and > instead of < and > so the browser literally shows >> "

hello world

". If I leave the line as it originally was: >> >> return >> render_to_response("view.html",{"page_name":page_name,"content":content}) >> >> It just prints "hello world" as saved in the database. I'm just not sure >> where to start looking for a solution here, and would appreciate any >> pointers. >> >> >> Two thing: > - This sounds like homework. > - This is a python mailing list, not a django mailing list > > Where I would start would be to investigate what the markdown class does. In > addition I would read over the django documentation to see why django is > doing that. It's in the django documentation, I hit that issue not too long > ago. > > HTH, > Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Jan 26 18:10:35 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 18:10:35 +0100 Subject: [Tutor] Print to std output with color Message-ID: <4D40558B.7050701@free.fr> Hello all, Is there a simple way to print with color to stdout like the unix/linux example below: *print( '^[[1;31mThis is a warning!^[[0m' ) where <=> ^[ *I see thing with curses module. But is there an more simple object in other module to do the trick? Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From brightstaar385 at yahoo.com Wed Jan 26 18:15:31 2011 From: brightstaar385 at yahoo.com (shaheryar ali) Date: Wed, 26 Jan 2011 09:15:31 -0800 (PST) Subject: [Tutor] Is it possible to make a circle of 1 hour In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> Message-ID: <984820.5887.qm@web110114.mail.gq1.yahoo.com> Hi every body, I was wondering, Is it possible to generate a circle on Google maps using python, such that distance in the created circle could be travel in 1 hour. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Wed Jan 26 18:21:02 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Wed, 26 Jan 2011 09:21:02 -0800 (PST) Subject: [Tutor] tkinter, create widgets during runtime? Message-ID: <860525.59728.qm@web130208.mail.mud.yahoo.com> With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code.? i.e., something like: for {set i 0} {$i <= 5} {incr i} { ??? label .myLabel_$i -text "this is label myLabel_$i" ??? pack .myLabel_$i } ...which will generate five labels from "myLabel_0" to "myLabel_5". Useful if you need a varying number of widgets, or a series of "incremental" widgets. Is there a way to do something like this in Tkinter?? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above? -------------- next part -------------- An HTML attachment was scrubbed... URL: From echowit at aol.com Wed Jan 26 18:35:17 2011 From: echowit at aol.com (echowit at aol.com) Date: Wed, 26 Jan 2011 12:35:17 -0500 (EST) Subject: [Tutor] Tutor Digest, Vol 83, Issue 115 In-Reply-To: References: Message-ID: <8CD8B968844F75D-1020-235F@webmail-m048.sysops.aol.com> I not offering a program design answer. I don't have a clue as to your operation, but I've been there as far as QA software, CNC programs and Quality record keeping. My thought is that instead of starting with the casting, think of the BOM on the final ass'y/configuration print and work backwards. Hint, I wish I'd have had Python's Dictionary & Tuple when I was active. -----Original Message----- From: tutor-request To: tutor Sent: Wed, Jan 26, 2011 6:55 am Subject: Tutor Digest, Vol 83, Issue 115 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor r, via email, send a message with subject or body 'help' to tutor-request at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific han "Re: Contents of Tutor digest..." oday's Topics: 1. Re: class question (Alan Gauld) 2. Re: Shuts down when asking user for info (Alan Gauld) 3. Re: Shuts down when asking user for info (Alan Gauld) 4. Re: class question (Karim) 5. Re: class question (Karim) 6. Re: class question (Elwin Estle) --------------------------------------------------------------------- Message: 1 ate: Wed, 26 Jan 2011 11:08:07 -0000 rom: "Alan Gauld" o: tutor at python.org ubject: Re: [Tutor] class question essage-ID: ontent-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=response Karim" wrote > Program towards interface that means you have to use inheritance. Just to be picky, you can program by interface without using nheritance. Inheritance is only needed to implement interfaces n languages like C++. In Python (and other dynamically ound OOP languages) you can use polymorphism without nheritance. -- lan Gauld uthor of the Learn to Program web site ttp://www.alan-g.me.uk/ ----------------------------- Message: 2 ate: Wed, 26 Jan 2011 11:13:59 -0000 rom: "Alan Gauld" o: tutor at python.org ubject: Re: [Tutor] Shuts down when asking user for info essage-ID: ontent-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Casey Key" wrote > Please help , run the script and see that once you press enter after entering name it just shuts it down, help. > -------------- rint("\tWelcome to Casey's magical python code!") rint("\tWritten by no other than Casey Key!") rint("\nWe will begin by getting some information,mmmkay?") ame = input("what is your name") rint("your name is",name) ----------------- Python is case sensitive, print starts with a lowercase P. However that should have generated an error. ow did you run the program? If you ran it from an IDE or rom the command prompt you would have seen the error. suspect you are just double clicking in a file manager? oing that the window will close before you can read it. lways test your code by running from a prompt so that ou see all output, including errors. lan Gauld uthor of the Learn To Program website ttp://www.alan-g.me.uk/ ----------------------------- Message: 3 ate: Wed, 26 Jan 2011 11:09:35 -0000 rom: "Alan Gauld" o: tutor at python.org ubject: Re: [Tutor] Shuts down when asking user for info essage-ID: ontent-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original tee chwee liong" wrote > maybe you can use raw_input? It looks like the OP is using Python 3 so input() is the correct unction. lan G. ----------------------------- Message: 4 ate: Wed, 26 Jan 2011 12:19:43 +0100 rom: Karim o: tutor at python.org ubject: Re: [Tutor] class question essage-ID: <4D40034F.4080902 at free.fr> ontent-Type: text/plain; charset=ISO-8859-1; format=flowed ure, but I come from java world and 1 inheritance is allowed but we can mplement multiple interfaces. like to use Abstract classes in Python then inherit and implement bstract method like in java (at least hat's all I remember from Java experience). ndeed I was too direct everybody has the same style. Regards arim On 01/26/2011 12:08 PM, Alan Gauld wrote: "Karim" wrote > Program towards interface that means you have to use inheritance. Just to be picky, you can program by interface without using inheritance. Inheritance is only needed to implement interfaces in languages like C++. In Python (and other dynamically bound OOP languages) you can use polymorphism without inheritance. ------------------------------ Message: 5 ate: Wed, 26 Jan 2011 12:25:19 +0100 rom: Karim o: Steven D'Aprano c: tutor at python.org ubject: Re: [Tutor] class question essage-ID: <4D40049F.5050600 at free.fr> ontent-Type: text/plain; charset=ISO-8859-1; format=flowed know the the law of Murphy. ut this one is a must-have.:-) Regards arim > * One way to reduce coupling is with the Law of Demeter: if you want your dog to walk, don't talk to your dog's legs. You will only confuse the dog and it won't get anywhere. http://en.wikipedia.org/wiki/Law_of_Demeter Hope this helps. ------------------------------ Message: 6 ate: Wed, 26 Jan 2011 04:45:18 -0800 (PST) rom: Elwin Estle o: tutor at python.org, Steven D'Aprano ubject: Re: [Tutor] class question essage-ID: <229841.16130.qm at web130204.mail.mud.yahoo.com> ontent-Type: text/plain; charset="iso-8859-1" Elwin Estle wrote: > Is it better to have one large sort of "do it all" class, or break the larger class up into smaller classes? Yes. Or no. It's impossible to answer that question definitively without knowing more about hat "it all" is. But I can give some general advice: * Python isn't Java. Don't feel that you must use classes. If your problem is etter solved using a procedural or functional approach, go right ahead and use t. Classes aren't compulsory. * The standard model which you should use it: ? verbs -> functions or methods nouns -> classes or attributes ? You should be able to answer the question "What *thing* does your class represent?". (The answer can be an abstract thing, but it should be a thing.) ? If you can't answer that question, then you shouldn't use a class. You should solve the problem using stand-alone functions. * Think about "is-a" and "has-a" relationships: ================================================================= The class in question, does, in fact, deal with a thing.? The problem is, the thing" is highly mutable.?? The "is-a" and the "has-a" changes. Here is the scenario: A raw casting comes into a factory.? It is listed as such.? When machined, this art number changes to a different part number.?? The raw casting has no quality related" stuff, but the machined casting does, and it can have more han one "quality related" thing. ...because, the raw casting may go through multiple operations to get to it's inal state.? It may get machined on a lathe, then be transferred to a CNC achining station where a bolt circle may be drilled and tapped into it.? Each f those operations on separate machines will have a different set of quality hecks associated with it. ...or it might be a part that goes from a raw casting to a sort of mini-assembly" such as a rocker lever (if you know what that is), so we have aw casting = one part number, then it gets a bushing pressed into it = another art number, then it gets a threaded insert = another part number, but it is till the same thing, and each one of those steps may have some sort of quality heck involved. Lets complicate things even further.? One raw casting may be machined into ultiple part numbers.? Perhaps the only thing that changes is the location of a ingle hole.? But again, each one of those part numbers may go through multiple achining operations on different machines, with different quality checks.? This s done through something called a "tabbed" blueprint, wherein there is a master umber, but there are "tabs" indicating that if you changes such and such eature, then the part number isn't the master number, but the tabbed number. So, in essence, there's a sort of "network" of "is-a" and "has-a" information. My idea was to, instead of having just a single "part" class, to have a sort of component aggregate" class, which would cover not only single parts, but ssemblies of parts.? So, even if a part was as simple as a raw casting that is ust machined into a finished part and that's it, it would still be treated as a ort of assembly, with the raw casting being a component of the finished part umber, if that makes sense. So there's all this information associated with a given part.? I am thinking it as a sort of tree structure.? I am just wondering if some of the branches of he tree should be separate classes that are then tied into the "trunk" of the aster class, or if the whole thing should be a tree into and of itself. ...and yeah, I know, it's kind of a complex problem for a newbie to be thinking bout. ------------- next part -------------- n HTML attachment was scrubbed... RL: ------------------------------ _______________________________________________ utor maillist - Tutor at python.org ttp://mail.python.org/mailman/listinfo/tutor nd of Tutor Digest, Vol 83, Issue 115 ************************************* -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 26 18:44:36 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 17:44:36 -0000 Subject: [Tutor] class question References: <859352.36127.qm@web130208.mail.mud.yahoo.com><4D3F7922.4020409@free.fr> <4D40034F.4080902@free.fr> Message-ID: "Karim" wrote > Sure, but I come from java world and 1 inheritance is allowed but we > can implement multiple interfaces. > I like to use Abstract classes in Python then inherit and implement > abstract method like in java (at least Sure and that is the normal way of doing it. Not least because you can inherit non abstract methods too! But there is a danger of forgetting that inheritance is not the *only* way. Thats all I was pointing out, inheritance is the norm but not essential. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 18:47:23 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 17:47:23 -0000 Subject: [Tutor] Is it possible to make a circle of 1 hour References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <984820.5887.qm@web110114.mail.gq1.yahoo.com> Message-ID: "shaheryar ali" wrote > I was wondering, Is it possible to generate a circle on Google maps > using > python, such that distance in the created circle could be travel in > 1 hour. Technically it would be possible I'm sure. The trick is determining how big the circle should be. How are you travelling? On foot across country? On foot by road? On bike? By car? By private plane/helicoptor? By fighter jet? And does it take account of rush hour in cities etc? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sirgnip at gmail.com Wed Jan 26 19:10:33 2011 From: sirgnip at gmail.com (Scott Nelson) Date: Wed, 26 Jan 2011 12:10:33 -0600 Subject: [Tutor] Print to std output with color In-Reply-To: <4D40558B.7050701@free.fr> References: <4D40558B.7050701@free.fr> Message-ID: Curses is one way to go. Another is to use the PyWin32 module discussed in this thread: http://thread.gmane.org/gmane.comp.python.tutor/58450/focus=58454 Basically, here's a snippet of code that can get you started. This requires that you have the PyWin32 module installed (already installed by default if you use ActiveState's Python distribution for Windows). Using PyWin32 isn't for the faint of heart, but it does work. import win32console handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) print 'blue text' On Wed, Jan 26, 2011 at 11:10 AM, Karim wrote: > > Hello all, > > Is there a simple way to print with color to stdout like the unix/linux > example below: > > *print( '^[[1;31mThis is a warning!^[[0m' ) > > where <=> ^[ > > *I see thing with curses module. But is there an more simple object in > other module to do the trick? > Kind of *decorate_output( mode=WARNING, 'This is a warning!')* > > Regards > Karim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 26 19:10:28 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 18:10:28 -0000 Subject: [Tutor] class question References: <229841.16130.qm@web130204.mail.mud.yahoo.com> Message-ID: "Elwin Estle" wrote > The class in question, does, in fact, deal with a thing. > The problem is, the "thing" is highly mutable. You can mutate objects, that is not a problem. But you need to be sure you need to. Is this really a series of different types of casting or a single Workpiece going through a sequence of Actions each Action having a set of quality data associated? If so it may be that you have a single Workpiece class and a relatively small heirarchy of Actions. > A raw casting comes into a factory. It is listed as such. > When machined, this part number changes to a > different part number. The raw casting has no > "quality related" stuff, but the machined casting does, Is it the casting or the machining that has the quality related data? ie Is it casting specific or operation specific? > ...because, the raw casting may go through multiple > operations to get to it's final state. Do you know in advance what these operations will be? Can you assign a WorkPlan to the Workpiece? Each step of the plan having an associated Action? > Each of those operations on separate machines will > have a different set of quality checks associated with it. So here we clearly say it is the Action that has the data associated... > ...or it might be a part that goes from a raw casting to > a sort of "mini-assembly" such as a rocker lever ... > but it is still the same thing, and each one of those > steps may have some sort of quality check involved. So a workpice can consist of other WorkPieces. And again tyhe Actions associated have quality data > Lets complicate things even further. One raw casting > may be machined into multiple part numbers. Is that true? Or is it one type of casting? Each instance of casting will surely onmly go through one specific set of actions? If we treat them all as generic workpieces then the Actions are different but the workpiece concept remains constant? Or, are we saying that a single original workpiece can be cut into several distinct workpieces? Again thats not necessarily a problem, objects can clone themselves and have the clones diverge thereafter. > Perhaps the only thing that changes is the location > of a single hole. But again, each one of those part > numbers may go through multiple machining operations > on different machines, with different quality checks. > This is done through something called a "tabbed" > blueprint, wherein there is a master number, but there > are "tabs" indicating that if you changes such and > such feature, then the part number isn't the master > number, but the tabbed number. I'm not sure I follow that bit. > So, in essence, there's a sort of "network" of "is-a" > and "has-a" information. I see a lot of "has-a" but very little "is-a" at this stage. In fact I don't see any "is-a" yet, althopugh I can see where some might emerge in the future. > have a sort of "component aggregate" class, which > would cover not only single parts, but assemblies I think that will be essential. > if a part was as simple as a raw casting that is > just machined into a finished part and that's it, > it would still be treated as a sort of assembly, One of the key features of assemblies is that they should scale down to a single item just as easily as up to many parts. > So there's all this information associated with a > given part. I am thinking it has a sort of tree structure. I think there probably is and you should look into the composite pattern to build that. > I am just wondering if some of the branches of > the tree should be separate classes Probably, but not so many different classes as you currently suspect. > ...and yeah, I know, it's kind of a complex problem > for a newbie to be thinking about. Yes, very challenging. This is one of the kinds of problem where the best solution is probably not be the first one you think of. But you won't know that till after you try building it! My proposal is only a guess based on a quick review of your description and no local domain knowledge... You may also find it useful to think through the state model for your castings/workpieces. That may help to constrain the number of Actions/operations required. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From benjamin.kircher at gmail.com Wed Jan 26 19:10:44 2011 From: benjamin.kircher at gmail.com (Benjamin Kircher) Date: Wed, 26 Jan 2011 19:10:44 +0100 Subject: [Tutor] Having a problem with markdown In-Reply-To: References: <4D3FD163.9070404@iandouglas.com> Message-ID: On Jan 26, 2011, at 4:11 PM, ian douglas wrote: > Thanks Tino, > > It's certainly not homework, I'm learning Python after being in the Perl/PHP world for well over a decade. Trying to teach this old dog some new tricks. > > On Jan 26, 2011 6:47 AM, "Tino Dai" wrote: > > On Wed, Jan 26, 2011 at 2:46 AM, ian douglas wrote: > > > >> Hey all, > >> > >> I followed a tutorial on creating a very simple wiki in Python, which > >> worked fine until the example where the instructor wanted to render the > >> output through markdown.markdown() > >> > >> Here's the view code: > >> > >> from agwiki.wiki.models import Page > >> from django.shortcuts import render_to_response > >> from django.http import HttpResponseRedirect > >> import markdown > >> > >> def view_page(request, page_name): > >> try: > >> page = Page.objects.get(pk=page_name) > >> except Page.DoesNotExist: > >> return render_to_response("create.html", {"page_name":page_name}) > >> content = page.content > >> return > >> render_to_response("view.html",{"page_name":page_name,"content":markdown.markdown(content)}) > >> > >> The problem I'm having is that the output in a browser is outputing HTML > >> markers as < and > instead of < and > so the browser literally shows > >> "

hello world

". If I leave the line as it originally was: > >> > >> return > >> render_to_response("view.html",{"page_name":page_name,"content":content}) > >> > >> It just prints "hello world" as saved in the database. I'm just not sure > >> where to start looking for a solution here, and would appreciate any > >> pointers. > >> > >> > >> Two thing: > > - This sounds like homework. > > - This is a python mailing list, not a django mailing list > > > > Where I would start would be to investigate what the markdown class does. In > > addition I would read over the django documentation to see why django is > > doing that. It's in the django documentation, I hit that issue not too long > > ago. > > > > HTH, > > Tino > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Hi Ian. Well, I did that very same tutorial a few months ago and ran into the same issue. It's not an issue with markdown but a feature called auto-escaping. The tutorial is quite old (but nonetheless good), so back in that day auto-escaping wasn't the default in Django. Now it is. However, you might want consult the Django docs about auto-escaping http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#autoescape ;) -- Benjamin From alan.gauld at btinternet.com Wed Jan 26 19:24:42 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 18:24:42 -0000 Subject: [Tutor] Print to std output with color References: <4D40558B.7050701@free.fr> Message-ID: "Karim" wrote > Is there a simple way to print with color to stdout like the > unix/linux > example below: > > *print( '^[[1;31mThis is a warning!^[[0m' ) Not generically since stdout is a data stream which may not be printed (it could be spoken for example - how does the synthesiser interpret colour?) and the terminal may have a colour scheme that makes your output invisible! Also different terminals have different capabilities, many do not support colour but do support bold/italic/underline etc. Thats why curses exists, it does a best endeavours attempt at rendering what you want but reverts to defaults for cases where it is not supported. but even curses is not able to work with all terminals - for example line oriented terminals/teletypes. > *I see thing with curses module. But is there an more simple object > in > other module to do the trick? > Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ There are some attempts at providing easier terminal control functions. The effbot did one I seem to recall.... http://effbot.org/zone/console-handbook.htm That might suffice for you? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Jan 26 19:27:56 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 26 Jan 2011 18:27:56 -0000 Subject: [Tutor] Print to std output with color References: <4D40558B.7050701@free.fr> Message-ID: "Karim" wrote > Is there a simple way to print with color to stdout like the > unix/linux > example below: > > *print( '^[[1;31mThis is a warning!^[[0m' ) I should have said the effbot solution (and WConio) are only for Windows. On Linux I think you are pretty well stuck with curses. I did find a simplified curses library here: http://nadiana.com/python-curses-terminal-controller HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From izzaddin.ruhulessin at gmail.com Wed Jan 26 19:37:45 2011 From: izzaddin.ruhulessin at gmail.com (C.Y. Ruhulessin) Date: Wed, 26 Jan 2011 19:37:45 +0100 Subject: [Tutor] Is it possible to make a circle of 1 hour In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <984820.5887.qm@web110114.mail.gq1.yahoo.com> Message-ID: Do time machines count to? 2011/1/26 Alan Gauld > > "shaheryar ali" wrote > > > I was wondering, Is it possible to generate a circle on Google maps using >> python, such that distance in the created circle could be travel in 1 >> hour. >> > > Technically it would be possible I'm sure. The trick is determining how > big the circle should be. How are you travelling? On foot across country? > On foot by road? On bike? By car? By private plane/helicoptor? > By fighter jet? > > And does it take account of rush hour in cities etc? > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Jan 26 20:03:24 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 26 Jan 2011 10:03:24 -0900 Subject: [Tutor] Class Docs - how much is too much? Message-ID: <20110126190324.GA1827@johnsons-web.com> FYI: I'm currently using version 2.6.5 I've developed a module which necessitates a very large amount of documentation. At this point all of the documentation is in the class docstring. I'm thinking that perhaps I should pare down the docstring and deliver specific documentation topics with object methods. Example: ## Instantiation examples o.intialize() ## configuration code to copy and paste into file o.configuration() ## Internal processes o.internals() ## ... etc. ## Docstring would include instructions for implementing such ## methods. :) Perhaps there is a PEP for this and a link to such a PEP would suffice. thanks -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From brightstaar385 at yahoo.com Wed Jan 26 20:13:19 2011 From: brightstaar385 at yahoo.com (shaheryar ali) Date: Wed, 26 Jan 2011 11:13:19 -0800 (PST) Subject: [Tutor] Is it possible to make a circle of 1 hour In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <984820.5887.qm@web110114.mail.gq1.yahoo.com> Message-ID: <140645.72484.qm@web110102.mail.gq1.yahoo.com> Alan, Well its gonna be by foot (walk) and it could be any place, road, city center, countryside, preferably you can say a leisure. but how to proceed with it, any Idea? I have made some logic for it but I am more Interested to know what other ideas could be, one more thing every time a random route is generated Thanks for the reply tho BR Ali ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wed, January 26, 2011 7:47:23 PM Subject: Re: [Tutor] Is it possible to make a circle of 1 hour "shaheryar ali" wrote > I was wondering, Is it possible to generate a circle on Google maps using > python, such that distance in the created circle could be travel in 1 hour. Technically it would be possible I'm sure. The trick is determining how big the circle should be. How are you travelling? On foot across country? On foot by road? On bike? By car? By private plane/helicoptor? By fighter jet? And does it take account of rush hour in cities etc? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Wed Jan 26 20:14:09 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Wed, 26 Jan 2011 11:14:09 -0800 Subject: [Tutor] Having a problem with markdown In-Reply-To: References: <4D3FD163.9070404@iandouglas.com> Message-ID: <4D407281.9030805@iandouglas.com> Thanks, Benjamin, I figured it was a version issue, I'm just so new to Python that I didn't know where to look. Sorry for polluting the list with Django questions, I thought it was an underlying Python issue, not the framework. -id On 01/26/2011 10:10 AM, Benjamin Kircher wrote: > > Hi Ian. > > Well, I did that very same tutorial a few months ago and ran into the same issue. It's not an issue with markdown but a feature called auto-escaping. The tutorial is quite old (but nonetheless good), so back in that day auto-escaping wasn't the default in Django. Now it is. > > However, you might want consult the Django docs about auto-escaping > http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#autoescape > > ;) > > -- > Benjamin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Wed Jan 26 20:31:58 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 26 Jan 2011 19:31:58 +0000 Subject: [Tutor] Print to std output with color In-Reply-To: References: <4D40558B.7050701@free.fr> Message-ID: <4D4076AE.4060201@timgolden.me.uk> On 26/01/2011 6:10 PM, Scott Nelson wrote: > Curses is one way to go. Another is to use the PyWin32 module discussed in > this thread: > > http://thread.gmane.org/gmane.comp.python.tutor/58450/focus=58454 > > Basically, here's a snippet of code that can get you started. This requires > that you have the PyWin32 module installed (already installed by default if > you use ActiveState's Python distribution for Windows). Using PyWin32 isn't > for the faint of heart, but it does work. > > import win32console > handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) > handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) > print 'blue text' Or use something which does it for you already: colorama -- http://tartley.com/?p=1062 TJG From karim.liateni at free.fr Wed Jan 26 20:37:47 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 20:37:47 +0100 Subject: [Tutor] Print to std output with color In-Reply-To: References: <4D40558B.7050701@free.fr> Message-ID: <4D40780B.1010904@free.fr> Thanks a lot Scott for the tip! Regards Karim On 01/26/2011 07:10 PM, Scott Nelson wrote: > Curses is one way to go. Another is to use the PyWin32 module > discussed in this thread: > http://thread.gmane.org/gmane.comp.python.tutor/58450/focus=58454 > Basically, here's a snippet of code that can get you started. This > requires that you have the PyWin32 module installed (already installed > by default if you use ActiveState's Python distribution for Windows). > Using PyWin32 isn't for the faint of heart, but it does work. > import win32console > handle = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) > handle.SetConsoleTextAttribute(win32console.FOREGROUND_BLUE) > print 'blue text' > > On Wed, Jan 26, 2011 at 11:10 AM, Karim > wrote: > > > Hello all, > > Is there a simple way to print with color to stdout like the > unix/linux example below: > > *print( '^[[1;31mThis is a warning!^[[0m' ) > > where <=> ^[ > > *I see thing with curses module. But is there an more simple > object in other module to do the trick? > Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ > > Regards > Karim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Jan 26 20:41:09 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 20:41:09 +0100 Subject: [Tutor] Print to std output with color In-Reply-To: References: <4D40558B.7050701@free.fr> Message-ID: <4D4078D5.5000507@free.fr> Thanks Alan! I will go there have a look. Regards Karim On 01/26/2011 07:24 PM, Alan Gauld wrote: > > "Karim" wrote > >> Is there a simple way to print with color to stdout like the unix/linux >> example below: >> >> *print( '^[[1;31mThis is a warning!^[[0m' ) > > Not generically since stdout is a data stream which may not be > printed (it could be spoken for example - how does the synthesiser > interpret colour?) and the terminal may have a colour scheme that > makes your output invisible! > > Also different terminals have different capabilities, many do > not support colour but do support bold/italic/underline etc. > Thats why curses exists, it does a best endeavours attempt > at rendering what you want but reverts to defaults for cases > where it is not supported. but even curses is not able to work > with all terminals - for example line oriented terminals/teletypes. > >> *I see thing with curses module. But is there an more simple object in >> other module to do the trick? >> Kind of _/decorate_output( mode=WARNING, *'This is a warning!')*/_ > > There are some attempts at providing easier terminal control > functions. The effbot did one I seem to recall.... > > http://effbot.org/zone/console-handbook.htm > > That might suffice for you? > > From sirgnip at gmail.com Wed Jan 26 20:43:44 2011 From: sirgnip at gmail.com (Scott Nelson) Date: Wed, 26 Jan 2011 13:43:44 -0600 Subject: [Tutor] Print to std output with color In-Reply-To: References: <4D40558B.7050701@free.fr> Message-ID: > > Curses is one way to go. Another is to use the PyWin32 module discussed in > this thread: > I just realized I was assuming you were on Windows. If you are on another OS, the code I posted will obviously not work for you as it is specific to Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Jan 26 20:48:36 2011 From: karim.liateni at free.fr (Karim) Date: Wed, 26 Jan 2011 20:48:36 +0100 Subject: [Tutor] Print to std output with color In-Reply-To: References: <4D40558B.7050701@free.fr> Message-ID: <4D407A94.7090407@free.fr> That's what I figured out at effbot website. Thanks for the additional link Alan! Regards Karim On 01/26/2011 07:27 PM, Alan Gauld wrote: > > "Karim" wrote > >> Is there a simple way to print with color to stdout like the unix/linux >> example below: >> >> *print( '^[[1;31mThis is a warning!^[[0m' ) > > I should have said the effbot solution (and WConio) are only for > Windows. On Linux I think you are pretty well stuck with curses. > I did find a simplified curses library here: > > http://nadiana.com/python-curses-terminal-controller > > HTH, > From chrysalis_reborn at yahoo.com Wed Jan 26 21:00:24 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Wed, 26 Jan 2011 12:00:24 -0800 (PST) Subject: [Tutor] class question Message-ID: <450586.51181.qm@web130207.mail.mud.yahoo.com> --- On Wed, 1/26/11, Alan Gauld wrote: From: Alan Gauld Subject: Re: [Tutor] class question To: tutor at python.org Date: Wednesday, January 26, 2011, 1:10 PM >>Is this really a series of different types of casting or a single Workpiece going through a sequence of Actions >>each Action having a set of quality data associated? >>If so it may be that you have a single Workpiece class and a relatively small heirarchy of Actions. No, there are multiple castings, anywhere from smallish parts you can hold in the palm of your hand, up to engine blocks weighing nearly 2 tons. >>Is it the casting or the machining that has the quality related data? ie Is it casting specific or operation specific? The casting can have quality data associated with it, tho rarely. If there is a machining issue that can be traced back to defective castings, then yes (but we don't really have any process in place for this, normally that sort of thing is the casting supplier's problem). Normally, tho, it is the machining that has the associated quality data., i.e., measure a 2.500 machined bore with a +/- .001 tolerance, using such and such gage, giving some result (like 2.503, for example), measured on such and such date by such and such machine operator. Various bits like this will be associated with a given machining operation. Sometimes machining operations are all done on a single machine, sometimes they span multiple machines. >>Do you know in advance what these operations will be? Can you assign a WorkPlan to the Workpiece? Each step of the plan having an associated Action? I would say yes. However, and this ties in with something you ask further down, sometimes that plan may sort of "overlap" For example, say we have a raw casting, 3402963R, that when machined, becomes part # 3402963. But that same raw casting may also be machined into another part number # 3332965, simply by adding or omitting hole or some other feature. So, I suppose one could have separate plans for each finished part number, in which case there might be some duplication of things for each plan. > Each of those operations on separate machines will have a different set of quality checks associated with it. So here we clearly say it is the Action that has the data associated... > ...or it might be a part that goes from a raw casting to a sort of "mini-assembly" such as a rocker lever ... > but it is still the same thing, and each one of those steps may have some sort of quality check involved. So a workpice can consist of other WorkPieces. And again tyhe Actions associated have quality data >>> Lets complicate things even further. One raw casting may be machined into multiple part numbers. >>Is that true? Or is it one type of casting? >>Each instance of casting will surely onmly go through one specific set of actions? If we treat them all as generic >>workpieces then the Actions are different but the workpiece concept remains constant? >>Or, are we saying that a single original workpiece can be cut into several distinct workpieces? Again thats not >>necessarily a problem, objects can clone themselves and have the clones diverge thereafter. Yes, that is the case, as described above. >>> This is done through something called a "tabbed" blueprint, wherein there is a master number, but there are "tabs" indicating that if you changes such and such feature, then the part number isn't the master number, but the tabbed number. >>I'm not sure I follow that bit. Say you have a master part, # 3245671, this is sort of a "primary machined number". On the blueprint for this part, there will be certain features that don't have any dimensional information, but instead have a callout of some kind, i.e., "Hole D", or somesuch. At the top of the blueprint is a "tab block" that is a table of "alternate part numbers", vs these "named features". Each of these part numbers will have differing information as to the nature of "Hole D". Perhaps the size of "Hole D" differs from one part number to the next, or perhaps it is omitted all together. It goes along wth the "one casting makes multiple part numbers" thing described above. In and of itself, this perhaps may not seem that complicated...but the blueprints aren't filed under the the actual part number for a given tabbed part, but under the master number. So...you may have part 3458760, but the blueprint for it is filed under 3245671, so you have to go hunt up that blueprint, then hunt up the information on it that describes the actual part in question. All this ties in to your quality control documentation. You have to make sure that when you check a hole diameter, you are checking the correct one as per the tabbed print. Why not have separate prints for each part number? This was originally a convenience/cost saving thing, I suspect. Back in the days when blueprints were hand drawn, having someone do a separate print for all the part numbers on a tabbed print would have been expensive, and also introduced the potential for human error. The blueprints in question are all scanned to pdf, but there are thousands of them, and paying someone to go in and somehow modify them for multiple parts would be a lot of work. >>> So, in essence, there's a sort of "network" of "is-a" and "has-a" information. >I see a lot of "has-a" but very little "is-a" at this stage. In fact I don't see any "is-a" yet, althopugh I can see where some might emerge in the future. I see what you mean. They are all "parts" and a part might have "parts", but they are still all parts. >>You may also find it useful to think through the state model for your castings/workpieces. That may help to constrain the number of Actions/operations required. ummm...what's a "state model"? I have kind of an idea, but ...I will do a google and see what pops up. Thanks! From emile at fenx.com Wed Jan 26 21:38:30 2011 From: emile at fenx.com (Emile van Sebille) Date: Wed, 26 Jan 2011 12:38:30 -0800 Subject: [Tutor] Class Docs - how much is too much? In-Reply-To: <20110126190324.GA1827@johnsons-web.com> References: <20110126190324.GA1827@johnsons-web.com> Message-ID: On 1/26/2011 11:03 AM Tim Johnson said... > FYI: I'm currently using version 2.6.5 > > I've developed a module which necessitates a very large amount of > documentation. At this point all of the documentation is in the > class docstring. I'm thinking that perhaps I should pare down the > docstring and deliver specific documentation topics with object > methods. Example: > ## Instantiation examples > o.intialize() > ## configuration code to copy and paste into file > o.configuration() > ## Internal processes > o.internals() > ## ... etc. > ## Docstring would include instructions for implementing such > ## methods. > > :) Perhaps there is a PEP for this and a link to such a PEP would > suffice. Yep -- google python pep docstring and you get http://www.python.org/dev/peps/pep-0257/ Emile From brightstaar385 at yahoo.com Wed Jan 26 22:03:38 2011 From: brightstaar385 at yahoo.com (shaheryar ali) Date: Wed, 26 Jan 2011 13:03:38 -0800 (PST) Subject: [Tutor] Is it possible to make a circle of 1 hour In-Reply-To: References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <984820.5887.qm@web110114.mail.gq1.yahoo.com> Message-ID: <641750.44768.qm@web110102.mail.gq1.yahoo.com> No, ________________________________ From: C.Y. Ruhulessin To: Alan Gauld Cc: tutor at python.org Sent: Wed, January 26, 2011 8:37:45 PM Subject: Re: [Tutor] Is it possible to make a circle of 1 hour Do time machines count to? 2011/1/26 Alan Gauld >"shaheryar ali" wrote > > > >I was wondering, Is it possible to generate a circle on Google maps using >>python, such that distance in the created circle could be travel in 1 hour. >> Technically it would be possible I'm sure. The trick is determining how >big the circle should be. How are you travelling? On foot across country? >On foot by road? On bike? By car? By private plane/helicoptor? >By fighter jet? > >And does it take account of rush hour in cities etc? > >HTH, > > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.alan-g.me.uk/ > > >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Wed Jan 26 22:46:08 2011 From: tim at johnsons-web.com (Tim Johnson) Date: Wed, 26 Jan 2011 12:46:08 -0900 Subject: [Tutor] Class Docs - how much is too much? In-Reply-To: References: <20110126190324.GA1827@johnsons-web.com> Message-ID: <20110126214608.GA2742@johnsons-web.com> * Emile van Sebille [110126 12:30]: > On 1/26/2011 11:03 AM Tim Johnson said... >> >> I've developed a module which necessitates a very large amount of >> documentation. At this point all of the documentation is in the >> class docstring. I'm thinking that perhaps I should pare down the >> docstring and deliver specific documentation topics with object <<...>> >> :) Perhaps there is a PEP for this and a link to such a PEP would >> suffice. > > Yep -- google python pep docstring and you get > > http://www.python.org/dev/peps/pep-0257/ Thank you. That's all I need. -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com From steve at pearwood.info Wed Jan 26 22:48:52 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 27 Jan 2011 08:48:52 +1100 Subject: [Tutor] class question In-Reply-To: <450586.51181.qm@web130207.mail.mud.yahoo.com> References: <450586.51181.qm@web130207.mail.mud.yahoo.com> Message-ID: <4D4096C4.9020602@pearwood.info> Elwin Estle wrote: > --- On Wed, 1/26/11, Alan Gauld wrote: > > From: Alan Gauld > Subject: Re: [Tutor] class question > To: tutor at python.org > Date: Wednesday, January 26, 2011, 1:10 PM >>> Is this really a series of different types of casting or a single Workpiece going through a sequence of Actions >>> each Action having a set of quality data associated? > >>> If so it may be that you have a single Workpiece class and a relatively small heirarchy of Actions. > > No, there are multiple castings, anywhere from smallish parts you can hold in the palm of your hand, up to engine blocks weighing nearly 2 tons. Then each such casting has its own set of actions and chain of classes. There is a process that goes from egg to chick to hen to KFC Chicken Nuggets, but you wouldn't write a single class to model all of those things. You would write a separate class for each distinct stage of the process, and write a process that replaces each data item with the next one in the series. I think you are focused too heavily on the fact that it's the same lump of metal all the way through the pipeline. That's the least important part of the design -- you can do that with a simple record: class Lump: def __init__(self, id, kind): self.id = id self.obj = kind() lumps = [ Lump(1, EngineBlockCasting), Lump(2, EngineBlockCasting), Lump(3, WidgetCasting), Lump(4, MiniCasting), ... ] and then later on: lumps[1].obj = EngineBlockWithHolesDrilled() Although of course you will write functions or methods to move from one class to another, e.g. drill_holes(lumps, 1), rather than do it all by hand. -- Steven From alan.gauld at btinternet.com Thu Jan 27 00:24:45 2011 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 26 Jan 2011 23:24:45 +0000 (GMT) Subject: [Tutor] class question In-Reply-To: <450586.51181.qm@web130207.mail.mud.yahoo.com> References: <450586.51181.qm@web130207.mail.mud.yahoo.com> Message-ID: <983437.87865.qm@web86703.mail.ird.yahoo.com> > >>I'm not sure I follow that bit. > > Say you have a master part, # 3245671, this is sort of a "primary machined >number". > > On the blueprint for this part, there will be certain features that don't have >any dimensional > > information, but instead have a callout of some kind, i.e., "Hole D", or >somesuch. > > At the top of the blueprint is a "tab block" that is a table of "alternate >part numbers", > Ah OK, Yes I've seen that used in produccing similar but different printed circuit boards (my background is in electronics not foundry work) > This was originally a convenience/cost saving thing, I suspect. Almost certainly, and it makes it much easier to add new variants since only the tab values need changing. What it means for you is that you need in parallel to your main app a mechanism for managing the identities through these differeing ID values. Effectively a lookup table and mechanism for tracing designs from raw pattern to finished item. > >>You may also find it useful to think through the state model for your > castings/workpieces. That may help to constrain the number of >Actions/operations required. > > ummm...what's a "state model"? It defines what operations can be done on your objects at any given time depending on the "state" of the object. As a simple example a light can be switched on when it is off and off when it is on, but it cannot be switched off if it is already off. In your can you will have a sequence of operations with dependencies between them such that certain operations can only be done after others have completed. Others cannot be done after others have been done. State models can be table driven which makes them highly configurable so that a single object can be loaded by multiple state models and effectively act like different object types without having to change the code. HTH, Alan G. From alan.gauld at btinternet.com Thu Jan 27 02:32:31 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 27 Jan 2011 01:32:31 -0000 Subject: [Tutor] Is it possible to make a circle of 1 hour References: <859352.36127.qm@web130208.mail.mud.yahoo.com><984820.5887.qm@web110114.mail.gq1.yahoo.com> <140645.72484.qm@web110102.mail.gq1.yahoo.com> Message-ID: "shaheryar ali" wrote > Well its gonna be by foot (walk) and it could be any place, road, > city center, > countryside, preferably you can say a leisure. OK, so if we limit it to on foot by any means then the circle would be about 3 miles (5km) in radius. > but how to proceed with it, any Idea? I don;t know the Google maps API but it sounds like you just need to figure out how to determine the current scale then draw a circle representing a 3 mile radius. > more Interested to know what other ideas could be, one more thing > every time a > random route is generated Not sure what ypu mean by that last bit. Alan G. From mehgcap at gmail.com Thu Jan 27 05:01:20 2011 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 26 Jan 2011 23:01:20 -0500 Subject: [Tutor] get xml for parsing? Message-ID: Hi all, How would I go about getting the xml from a website through the site's api? The url does not end in .xml since the xml is generated based on the parameters in the url. For example: https://api.website.com/user/me/count/10?api_key=MY_KEY would return ten results (the count parameter) as xml. How do I actually get this xml into my program? TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From stefan_ml at behnel.de Thu Jan 27 06:39:59 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Jan 2011 06:39:59 +0100 Subject: [Tutor] get xml for parsing? In-Reply-To: References: Message-ID: Alex Hall, 27.01.2011 05:01: > How would I go about getting the xml from a website through the site's > api? The url does not end in .xml since the xml is generated based on > the parameters in the url. For example: > https://api.website.com/user/me/count/10?api_key=MY_KEY > would return ten results (the count parameter) as xml. How do I > actually get this xml into my program? TIA. The filename extension doesn't matter. If you know it's XML that you get back, you can use ElementTree (in the xml.etree package) or lxml (external package) to read it. Use the urllib2 package in the standard library to request the XML page, then pass the result into the XML parser (parse()). Stefan From chrysalis_reborn at yahoo.com Thu Jan 27 13:15:37 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Thu, 27 Jan 2011 04:15:37 -0800 (PST) Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <860525.59728.qm@web130208.mail.mud.yahoo.com> Message-ID: <939669.84109.qm@web130222.mail.mud.yahoo.com> >From the lack of replies...I am guessing that this can't be done.? Tho I just realized I had a typo in part of it. The line that reads: "Is there a way to do something like this in Tkinter?? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above?" ...should have said, "Or am I correct in guessing tat if it IS possible, it is probably more..." --- On Wed, 1/26/11, Elwin Estle wrote: From: Elwin Estle Subject: [Tutor] tkinter, create widgets during runtime? To: tutor at python.org Date: Wednesday, January 26, 2011, 12:21 PM With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code.? i.e., something like: for {set i 0} {$i <= 5} {incr i} { ??? label .myLabel_$i -text "this is label myLabel_$i" ??? pack .myLabel_$i } ...which will generate five labels from "myLabel_0" to "myLabel_5". Useful if you need a varying number of widgets, or a series of "incremental" widgets. Is there a way to do something like this in Tkinter?? Or am I correct in guessing that if it is not possible, it is probably more complicated than the above? -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Jan 27 14:39:17 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 27 Jan 2011 08:39:17 -0500 Subject: [Tutor] get xml for parsing? In-Reply-To: References: Message-ID: On 1/27/11, Stefan Behnel wrote: > Alex Hall, 27.01.2011 05:01: >> How would I go about getting the xml from a website through the site's >> api? The url does not end in .xml since the xml is generated based on >> the parameters in the url. For example: >> https://api.website.com/user/me/count/10?api_key=MY_KEY >> would return ten results (the count parameter) as xml. How do I >> actually get this xml into my program? TIA. > > The filename extension doesn't matter. If you know it's XML that you get > back, you can use ElementTree (in the xml.etree package) or lxml (external > package) to read it. Use the urllib2 package in the standard library to > request the XML page, then pass the result into the XML parser (parse()). Okay, thanks! > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From karim.liateni at free.fr Thu Jan 27 14:59:56 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 27 Jan 2011 14:59:56 +0100 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <939669.84109.qm@web130222.mail.mud.yahoo.com> References: <939669.84109.qm@web130222.mail.mud.yahoo.com> Message-ID: <4D417A5C.5030006@free.fr> I never did that but this is python! You can create anything you want at runtime! Make a factory method in you gui class which inherit from Frame or whatever container code below is testing: >>> from Tkinter import * >>> class gui(Frame): ... def __init__(self, master=None): ... Frame.__init__(self, master) ... self.pack() ... def createLabels(self): ... labels = [] ... for i in range(4): ... labelName = "myLabel_{0}".format(i) ... labels.append(Label(master=self, text="this is label " + labelName)) ... for label in labels: ... label.pack() ... >>> a=gui() >>> a.createLabels() self is the instance of your inherited Frame or else container. Regards Karim On 01/27/2011 01:15 PM, Elwin Estle wrote: > From the lack of replies...I am guessing that this can't be done. Tho > I just realized I had a typo in part of it. > > The line that reads: > "Is there a way to do something like this in Tkinter? Or am I correct > in guessing that if it is not possible, it is probably more > complicated than the above?" > > ...should have said, "Or am I correct in guessing tat if it IS > possible, it is probably more..." > > --- On *Wed, 1/26/11, Elwin Estle //* wrote: > > > From: Elwin Estle > Subject: [Tutor] tkinter, create widgets during runtime? > To: tutor at python.org > Date: Wednesday, January 26, 2011, 12:21 PM > > With Tcl/Tk, you can generate widgets "on the fly" during program > execution, without having to explicitly create them in your code. > i.e., something like: > > for {set i 0} {$i <= 5} {incr i} { > label .myLabel_$i -text "this is label myLabel_$i" > pack .myLabel_$i > } > > ...which will generate five labels from "myLabel_0" to "myLabel_5". > > Useful if you need a varying number of widgets, or a series of > "incremental" widgets. > > Is there a way to do something like this in Tkinter? Or am I > correct in guessing that if it is not possible, it is probably > more complicated than the above? > > > > > > -----Inline Attachment Follows----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Thu Jan 27 15:17:50 2011 From: python at bdurham.com (python at bdurham.com) Date: Thu, 27 Jan 2011 09:17:50 -0500 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <939669.84109.qm@web130222.mail.mud.yahoo.com> References: <939669.84109.qm@web130222.mail.mud.yahoo.com> Message-ID: <1296137870.26134.1417531649@webmail.messagingengine.com> Elwin, There is a dedicated Python Tkinter mailing list called tkinter-discuss. I would post your question to this mailing list - I've found them very helpful. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Jan 27 16:54:33 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 27 Jan 2011 09:54:33 -0600 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <860525.59728.qm@web130208.mail.mud.yahoo.com> References: <860525.59728.qm@web130208.mail.mud.yahoo.com> Message-ID: On Wed, Jan 26, 2011 at 11:21 AM, Elwin Estle wrote: > With Tcl/Tk, you can generate widgets "on the fly" during program > execution, without having to explicitly create them in your code. i.e., > something like: > > for {set i 0} {$i <= 5} {incr i} { > label .myLabel_$i -text "this is label myLabel_$i" > pack .myLabel_$i } > for x in xrange(5): Label(root, text="This is label %d" %x).pack() will generate the labels. You can't put the variable names in the local namespace without some tricksy methods. You could, however, have a dict labels and just do labels[x] = Label(root, text="blah") labels[x].pack() HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jan 27 16:08:22 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 27 Jan 2011 10:08:22 -0500 Subject: [Tutor] Facebook Message-ID: Dear Tutors, I'm using the Facebook API. How do you get an access token? The documentations at http://developers.facebook.com/docs/api, but I can't figure out an easy way to do it. Sincerely, Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Thu Jan 27 17:19:17 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 27 Jan 2011 17:19:17 +0100 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: References: <860525.59728.qm@web130208.mail.mud.yahoo.com> Message-ID: <4D419B05.90908@free.fr> Hello Wayne, I provided a complete example see the mail above, pretty similar to yours. Regards Karim On 01/27/2011 04:54 PM, Wayne Werner wrote: > > On Wed, Jan 26, 2011 at 11:21 AM, Elwin Estle > > wrote: > > With Tcl/Tk, you can generate widgets "on the fly" during program > execution, without having to explicitly create them in your code. > i.e., something like: > > for {set i 0} {$i <= 5} {incr i} { > label .myLabel_$i -text "this is label myLabel_$i" > pack .myLabel_$i > > } > > > for x in xrange(5): > Label(root, text="This is label %d" %x).pack() > > will generate the labels. You can't put the variable names in the > local namespace without some tricksy methods. You could, however, have > a dict labels and just do > > labels[x] = Label(root, text="blah") > labels[x].pack() > > HTH, > Wayne > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Jan 27 17:43:58 2011 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 27 Jan 2011 10:43:58 -0600 Subject: [Tutor] Facebook In-Reply-To: References: Message-ID: <139079F5-8F31-4777-A159-4D828429186A@gmail.com> And what have you tried? What libs are you using? Which part is confusing you? ----------------------------- Sent from a mobile device. Apologies for brevity and top-posting. ----------------------------- On Jan 27, 2011, at 9:08 AM, Christopher King wrote: > Dear Tutors, > I'm using the Facebook API. How do you get an access token? The documentations at http://developers.facebook.com/docs/api, but I can't figure out an easy way to do it. > > Sincerely, > Chris > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Thu Jan 27 18:06:13 2011 From: g.nius.ck at gmail.com (Christopher King) Date: Thu, 27 Jan 2011 12:06:13 -0500 Subject: [Tutor] Facebook In-Reply-To: <139079F5-8F31-4777-A159-4D828429186A@gmail.com> References: <139079F5-8F31-4777-A159-4D828429186A@gmail.com> Message-ID: Well actually I got it working now. I used the library from https://github.com/facebook/python-sdk/. It said you had to create an app, which I didn't want to do. That is, to get the access token. An access token is what gives me the right to look at peoples profile. What I found, was an app already made, in which I can edit the html to have it request any permission I want it to, and then give me the access token for my own programs. Its let's you save the code in a permalink. He is my code: http://fbrell.com/saved/6b455533f5f2c124cdc74a635d09cbd4. It will not work by itself, so you must slightly edit it. Where it says, put permissions here, type what permissions you want the token to have, separated by commas, and click run code. Then click the button. A list of request-able permissions are here: http://developers.facebook.com/docs/authentication/permissions/. I've tested it, and its cool. I posted to my wall from facebook! On Thu, Jan 27, 2011 at 11:43 AM, Luke Paireepinart wrote: > And what have you tried? What libs are you using? Which part is confusing > you? > > ----------------------------- > Sent from a mobile device. Apologies for brevity and top-posting. > ----------------------------- > > On Jan 27, 2011, at 9:08 AM, Christopher King wrote: > > Dear Tutors, > I'm using the Facebook API. How do you get an access token? The > documentations at > http://developers.facebook.com/docs/api, but I can't figure out an easy > way to do it. > > Sincerely, > Chris > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Jan 27 20:42:41 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jan 2011 06:42:41 +1100 Subject: [Tutor] Facebook In-Reply-To: <139079F5-8F31-4777-A159-4D828429186A@gmail.com> References: <139079F5-8F31-4777-A159-4D828429186A@gmail.com> Message-ID: <4D41CAB1.1020204@pearwood.info> Luke Paireepinart wrote: > And what have you tried? What libs are you using? Which part is confusing you? Surely it is the part Christopher says... getting an access token? I wonder whether he has read this? http://developers.facebook.com/docs/authentication/?_fb_noscript=1 (which is the first link that comes up when googling for "facebook api access token"). > On Jan 27, 2011, at 9:08 AM, Christopher King wrote: > >> Dear Tutors, >> I'm using the Facebook API. How do you get an access token? The documentations at http://developers.facebook.com/docs/api, but I can't figure out an easy way to do it. -- Steven From karim.liateni at free.fr Thu Jan 27 20:46:41 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 27 Jan 2011 20:46:41 +0100 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <4D417A5C.5030006@free.fr> References: <939669.84109.qm@web130222.mail.mud.yahoo.com> <4D417A5C.5030006@free.fr> Message-ID: <4D41CBA1.7030904@free.fr> Sorry, I forgot to update continuously the Frame: >>> app.mainloop() Karim On 01/27/2011 02:59 PM, Karim wrote: > > I never did that but this is python! > You can create anything you want at runtime! > Make a factory method in you gui class which inherit from Frame or > whatever container code below is testing: > > >>> from Tkinter import * > >>> class gui(Frame): > ... def __init__(self, master=None): > ... Frame.__init__(self, master) > ... self.pack() > ... def createLabels(self): > ... labels = [] > ... for i in range(4): > ... labelName = "myLabel_{0}".format(i) > ... labels.append(Label(master=self, text="this is label > " + labelName)) > ... for label in labels: > ... label.pack() > ... > >>> a=gui() > >>> a.createLabels() > > > self is the instance of your inherited Frame or else container. > > Regards > Karim > > > On 01/27/2011 01:15 PM, Elwin Estle wrote: >> From the lack of replies...I am guessing that this can't be done. >> Tho I just realized I had a typo in part of it. >> >> The line that reads: >> "Is there a way to do something like this in Tkinter? Or am I >> correct in guessing that if it is not possible, it is probably more >> complicated than the above?" >> >> ...should have said, "Or am I correct in guessing tat if it IS >> possible, it is probably more..." >> >> --- On *Wed, 1/26/11, Elwin Estle //* wrote: >> >> >> From: Elwin Estle >> Subject: [Tutor] tkinter, create widgets during runtime? >> To: tutor at python.org >> Date: Wednesday, January 26, 2011, 12:21 PM >> >> With Tcl/Tk, you can generate widgets "on the fly" during program >> execution, without having to explicitly create them in your >> code. i.e., something like: >> >> for {set i 0} {$i <= 5} {incr i} { >> label .myLabel_$i -text "this is label myLabel_$i" >> pack .myLabel_$i >> } >> >> ...which will generate five labels from "myLabel_0" to "myLabel_5". >> >> Useful if you need a varying number of widgets, or a series of >> "incremental" widgets. >> >> Is there a way to do something like this in Tkinter? Or am I >> correct in guessing that if it is not possible, it is probably >> more complicated than the above? >> >> >> >> >> >> -----Inline Attachment Follows----- >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Thu Jan 27 20:47:02 2011 From: karim.liateni at free.fr (Karim) Date: Thu, 27 Jan 2011 20:47:02 +0100 Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: <4D417A5C.5030006@free.fr> References: <939669.84109.qm@web130222.mail.mud.yahoo.com> <4D417A5C.5030006@free.fr> Message-ID: <4D41CBB6.7020907@free.fr> Sorry, I forgot to update continuously the Frame: >>> a.mainloop() Karim On 01/27/2011 02:59 PM, Karim wrote: > > I never did that but this is python! > You can create anything you want at runtime! > Make a factory method in you gui class which inherit from Frame or > whatever container code below is testing: > > >>> from Tkinter import * > >>> class gui(Frame): > ... def __init__(self, master=None): > ... Frame.__init__(self, master) > ... self.pack() > ... def createLabels(self): > ... labels = [] > ... for i in range(4): > ... labelName = "myLabel_{0}".format(i) > ... labels.append(Label(master=self, text="this is label > " + labelName)) > ... for label in labels: > ... label.pack() > ... > >>> a=gui() > >>> a.createLabels() > > > self is the instance of your inherited Frame or else container. > > Regards > Karim > > > On 01/27/2011 01:15 PM, Elwin Estle wrote: >> From the lack of replies...I am guessing that this can't be done. >> Tho I just realized I had a typo in part of it. >> >> The line that reads: >> "Is there a way to do something like this in Tkinter? Or am I >> correct in guessing that if it is not possible, it is probably more >> complicated than the above?" >> >> ...should have said, "Or am I correct in guessing tat if it IS >> possible, it is probably more..." >> >> --- On *Wed, 1/26/11, Elwin Estle //* wrote: >> >> >> From: Elwin Estle >> Subject: [Tutor] tkinter, create widgets during runtime? >> To: tutor at python.org >> Date: Wednesday, January 26, 2011, 12:21 PM >> >> With Tcl/Tk, you can generate widgets "on the fly" during program >> execution, without having to explicitly create them in your >> code. i.e., something like: >> >> for {set i 0} {$i <= 5} {incr i} { >> label .myLabel_$i -text "this is label myLabel_$i" >> pack .myLabel_$i >> } >> >> ...which will generate five labels from "myLabel_0" to "myLabel_5". >> >> Useful if you need a varying number of widgets, or a series of >> "incremental" widgets. >> >> Is there a way to do something like this in Tkinter? Or am I >> correct in guessing that if it is not possible, it is probably >> more complicated than the above? >> >> >> >> >> >> -----Inline Attachment Follows----- >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Jan 27 23:23:15 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 27 Jan 2011 17:23:15 -0500 Subject: [Tutor] small ElementTree problem Message-ID: Hi all, I am using, and very much enjoying, the ElementTree library. However, I have hit a problem. Say I have something along the lines of: Message from Service 1.0 1 result 1 2 result 2 In my ResultSet class, I parse this to get the text of elements like message or version. Then, I use root.findall("list/result") and iterate over the result, passing to a second function which parses the passed-in elements into Result objects. For example: all=root.findall("list/result") for i in all: self.mylist.append(Obj().parse(i)) In Obj.parse(), the element passed in is treated like this: def parse(data): root=data.getroot() self.id=root.find("id").text self.name=root.find("name).text Printing the results of the above through Obj.id or Obj.name gives me odd behavior: print Obj.id :> None What is going on? Does the root change when I call find()? Why would an Element object get used when I clearly say to use the text of the found element? TIA. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From chrysalis_reborn at yahoo.com Thu Jan 27 23:39:40 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Thu, 27 Jan 2011 14:39:40 -0800 (PST) Subject: [Tutor] tkinter, create widgets during runtime? In-Reply-To: Message-ID: <157090.81543.qm@web130207.mail.mud.yahoo.com> Thanks!? That was just what I was looking for. --- On Thu, 1/27/11, Wayne Werner wrote: From: Wayne Werner Subject: Re: [Tutor] tkinter, create widgets during runtime? To: "Elwin Estle" Cc: tutor at python.org Date: Thursday, January 27, 2011, 10:54 AM On Wed, Jan 26, 2011 at 11:21 AM, Elwin Estle wrote: With Tcl/Tk, you can generate widgets "on the fly" during program execution, without having to explicitly create them in your code.? i.e., something like: for {set i 0} {$i <= 5} {incr i} { ??? label .myLabel_$i -text "this is label myLabel_$i" ??? pack .myLabel_$i? } for x in xrange(5):?? ?Label(root, text="This is label %d" %x).pack() will generate the labels. You can't put the variable names in the local namespace without some tricksy methods. You could, however, have a dict labels and just do labels[x] = Label(root, text="blah")labels[x].pack() HTH,Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Jan 27 23:46:32 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 27 Jan 2011 17:46:32 -0500 Subject: [Tutor] ascii codec cannot encode character Message-ID: Hello again: I have never seen this message before. I am pulling xml from a site's api and printing it, testing the wrapper I am writing for the api. I have never seen this error until just now, in the twelfth result of my search: UnicodeEncodeError: 'ASCII' codec can't encode character u'\u2019' in position 42: ordinal not in range(128) I tried making the strings Unicode by saying something like self.title=unicode(data.find("title").text) but the same error appeared. I found the manual chapter on this, but I am not sure I want to ignore since I do not know what this character (or others) might mean in the string. I am not clear on what 'replace' will do. Any suggestions? -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From karim.liateni at free.fr Fri Jan 28 00:12:38 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 28 Jan 2011 00:12:38 +0100 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: <4D41FBE6.6070405@free.fr> id is a tag so it is a OBJECT Element with attributes accessible by dictionnary x.attrib[key] and x.text for tag content text. canonical string representation of your Element object: Obj.id :> composite pattern. For result use iterator as below (not tested but should be ok): *_/#Parsing:/_ doc = ElementTree() doc.parse(xmlFile)* *_/#iteration over tag element:/_ ids = [] names =[] for result in doc.iter('result'): idElem = result.find('id') *** nameElem = result.find('name')** * ids.append(idElem.text) names.append(nameElement.text) final = zip(ids, names) * You are not obliged to provide the full XPATH. Etree search for you. Regards Karim On 01/27/2011 11:23 PM, Alex Hall wrote: > Hi all, > I am using, and very much enjoying, the ElementTree library. However, > I have hit a problem. Say I have something along the lines of: > > > Message from Service > 1.0 > > > 1 > result 1 > > > 2 > result 2 > > > > > In my ResultSet class, I parse this to get the text of elements like > message or version. Then, I use root.findall("list/result") and > iterate over the result, passing to a second function which parses the > passed-in elements into Result objects. For example: > > all=root.findall("list/result") > for i in all: > self.mylist.append(Obj().parse(i)) > > In Obj.parse(), the element passed in is treated like this: > > def parse(data): > root=data.getroot() > self.id=root.find("id").text > self.name=root.find("name).text > > Printing the results of the above through Obj.id or Obj.name gives me > odd behavior: > print Obj.id :> print self.id :> None > > What is going on? Does the root change when I call find()? Why would > an Element object get used when I clearly say to use the text of the > found element? TIA. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jan 28 00:23:40 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 27 Jan 2011 18:23:40 -0500 Subject: [Tutor] small ElementTree problem In-Reply-To: <4D41FBE6.6070405@free.fr> References: <4D41FBE6.6070405@free.fr> Message-ID: Thanks, I think I have it working. On 1/27/11, Karim wrote: > > id is a tag so it is a OBJECT Element with attributes accessible by > dictionnary x.attrib[key] and x.text for tag content text. > > canonical string representation of your Element object: Obj.id :> 'result' at [mem addr] > And root is also an Element but the parent of id and name childs => > composite pattern. > For result use iterator as below (not tested but should be ok): > > *_/#Parsing:/_ > > doc = ElementTree() > doc.parse(xmlFile)* > > *_/#iteration over tag element:/_ > > ids = [] > names =[] > for result in doc.iter('result'): > idElem = result.find('id') > *** nameElem = result.find('name')** > * ids.append(idElem.text) > names.append(nameElement.text) > > final = zip(ids, names) > * > > You are not obliged to provide the full XPATH. Etree search for you. > > Regards > Karim > > On 01/27/2011 11:23 PM, Alex Hall wrote: >> Hi all, >> I am using, and very much enjoying, the ElementTree library. However, >> I have hit a problem. Say I have something along the lines of: >> >> >> Message from Service >> 1.0 >> >> >> 1 >> result 1 >> >> >> 2 >> result 2 >> >> >> >> >> In my ResultSet class, I parse this to get the text of elements like >> message or version. Then, I use root.findall("list/result") and >> iterate over the result, passing to a second function which parses the >> passed-in elements into Result objects. For example: >> >> all=root.findall("list/result") >> for i in all: >> self.mylist.append(Obj().parse(i)) >> >> In Obj.parse(), the element passed in is treated like this: >> >> def parse(data): >> root=data.getroot() >> self.id=root.find("id").text >> self.name=root.find("name).text >> >> Printing the results of the above through Obj.id or Obj.name gives me >> odd behavior: >> print Obj.id :> > print self.id :> None >> >> What is going on? Does the root change when I call find()? Why would >> an Element object get used when I clearly say to use the text of the >> found element? TIA. >> > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Fri Jan 28 03:25:36 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 28 Jan 2011 13:25:36 +1100 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: References: Message-ID: <4D422920.2050606@pearwood.info> Alex Hall wrote: > Hello again: > I have never seen this message before. I am pulling xml from a site's > api and printing it, testing the wrapper I am writing for the api. I > have never seen this error until just now, in the twelfth result of my > search: > UnicodeEncodeError: 'ASCII' codec can't encode character u'\u2019' in > position 42: ordinal not in range(128) > > I tried making the strings Unicode by saying something like > self.title=unicode(data.find("title").text) > but the same error appeared. I found the manual chapter on this, but I > am not sure I want to ignore since I do not know what this character > (or others) might mean in the string. I am not clear on what 'replace' > will do. Any suggestions? Short version ============= You need to decode the bytes you get from the XML into unicode characters. You would do this using something like: unicode(data.find("title").text, encoding='utf-8') If that doesn't work, change utf-8 to another encoding. If the XML file tells you what the encoding should be, use that. Alternatively, you could say: unicode(data.find("title").text, errors='replace') to substitute a "missing character" glyph for any undecodable bytes in the XML stream, or unicode(data.find("title").text, errors='ignore') to just ignore them. Long version ============ You can't just say "turn these bytes into unicode" and expect it to magically work. Remember, in Python 2, so-called "strings" are actually strings of *bytes*, not characters. If you're a native English speaker, you've probably never needed to care about the distinction, but it is real. When you have a string "spam", what that *really* is is a sequence of bytes 73 70 61 6D (in hexadecimal). By convention, Python uses the ASCII encoding map bytes to characters (e.g. hex 73 <=> "s"). That's not the only choice, but it has been the conventional choice for so long that people have forgotten that there are any other choices. The problem with ASCII is that it only knows how to deal with 128 different bytes, and about 30 of those are invisible control characters. The other 128 bytes don't mean anything in ASCII, and you can run into problems trying to deal with them as text. There are hundreds of thousands of useful characters in the world, and only 128 ASCII ones. Prior to Unicode, people would choose their own preferred set of 256 useful characters, and semi-arbitrarily assign them to each of the 256 different bytes. Consequently there was a plethora of ad hoc encodings where a byte like (say) xC4 might represent (say) '?' on Windows computers used in northern and western Europe '?' on computers in Greece '?' on Macintosh computers in Western Europe '?' on Macintoshes in Eastern Europe and so forth. As you can imagine, exchanging files from one machine to another was a nightmare. This is where Unicode comes in -- in theory, there is a Unicode character for every useful character in any language anywhere, including mathematical symbols, dingbats, ancient dead languages, pictograms, and more. BUT files on disk, and in memory, are in bytes, not characters. You need some way to convert a character string into bytes, and back again. There are many different ways of doing so, depending on whether you care about making it as fast as possible, or as efficient as possible, or compatible with some pre-Unicode character set. And this is where the idea of encodings come in. You can see a list of supported encodings here: http://docs.python.org/library/codecs.html#standard-encodings So the idea is, when you have a stream of bytes (say, from reading from a disk), you have to *decode* those bytes into Unicode text, and to write that text back again, you have to *encode* it to bytes. Now, Python tries to be very conservative: if you don't specify an encoding, it assumes you want ASCII, the lowest common denominator encoding that keeps English speakers happy. Lucky us. Until we have to deal with one or more bytes which can't be decoded into ASCII: >>> "\xC4".decode('ascii') Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128) Python isn't going to guess what character you want byte C4 to represent. We've already seen there are at least four different choices. You have to tell it which one you mean: >>> print unicode("\xC4", encoding='macroman') ? Must-read article: http://www.joelonsoftware.com/articles/Unicode.html -- Steven From mehgcap at gmail.com Fri Jan 28 04:02:25 2011 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 27 Jan 2011 22:02:25 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: <4D422920.2050606@pearwood.info> References: <4D422920.2050606@pearwood.info> Message-ID: On 1/27/11, Steven D'Aprano wrote: > Alex Hall wrote: >> Hello again: >> I have never seen this message before. I am pulling xml from a site's >> api and printing it, testing the wrapper I am writing for the api. I >> have never seen this error until just now, in the twelfth result of my >> search: >> UnicodeEncodeError: 'ASCII' codec can't encode character u'\u2019' in >> position 42: ordinal not in range(128) >> >> I tried making the strings Unicode by saying something like >> self.title=unicode(data.find("title").text) >> but the same error appeared. I found the manual chapter on this, but I >> am not sure I want to ignore since I do not know what this character >> (or others) might mean in the string. I am not clear on what 'replace' >> will do. Any suggestions? > > Short version > ============= > > You need to decode the bytes you get from the XML into unicode > characters. You would do this using something like: > > unicode(data.find("title").text, encoding='utf-8') > > If that doesn't work, change utf-8 to another encoding. If the XML file > tells you what the encoding should be, use that. > > Alternatively, you could say: > > unicode(data.find("title").text, errors='replace') > > to substitute a "missing character" glyph for any undecodable bytes in > the XML stream, or > > unicode(data.find("title").text, errors='ignore') > > to just ignore them. I tried both of those and got a different error. I have since fixed it so I no longer have the exact text, but it was something about not supporting convertion from unicode. I finally ended up doing this: self.title=data.find("title").text.encode("utf-8") and it seems happy enough, though I get odd characters above 128. I suppose it is better than a traceback, and I suspect I just have the wrong character set. Still, I found it very odd that unicode(string, errors='replace') threw an exception. > > > Long version > ============ > > You can't just say "turn these bytes into unicode" and expect it to > magically work. Remember, in Python 2, so-called "strings" are actually > strings of *bytes*, not characters. If you're a native English speaker, > you've probably never needed to care about the distinction, but it is real. > > When you have a string "spam", what that *really* is is a sequence of > bytes 73 70 61 6D (in hexadecimal). By convention, Python uses the ASCII > encoding map bytes to characters (e.g. hex 73 <=> "s"). That's not the > only choice, but it has been the conventional choice for so long that > people have forgotten that there are any other choices. > > The problem with ASCII is that it only knows how to deal with 128 > different bytes, and about 30 of those are invisible control characters. > The other 128 bytes don't mean anything in ASCII, and you can run into > problems trying to deal with them as text. > > There are hundreds of thousands of useful characters in the world, and > only 128 ASCII ones. Prior to Unicode, people would choose their own > preferred set of 256 useful characters, and semi-arbitrarily assign them > to each of the 256 different bytes. Consequently there was a plethora of > ad hoc encodings where a byte like (say) xC4 might represent (say) > > '?' on Windows computers used in northern and western Europe > '?' on computers in Greece > '?' on Macintosh computers in Western Europe > '?' on Macintoshes in Eastern Europe > > and so forth. As you can imagine, exchanging files from one machine to > another was a nightmare. This is where Unicode comes in -- in theory, > there is a Unicode character for every useful character in any language > anywhere, including mathematical symbols, dingbats, ancient dead > languages, pictograms, and more. > > BUT files on disk, and in memory, are in bytes, not characters. You need > some way to convert a character string into bytes, and back again. There > are many different ways of doing so, depending on whether you care about > making it as fast as possible, or as efficient as possible, or > compatible with some pre-Unicode character set. And this is where the > idea of encodings come in. You can see a list of supported encodings here: > > http://docs.python.org/library/codecs.html#standard-encodings > > So the idea is, when you have a stream of bytes (say, from reading from > a disk), you have to *decode* those bytes into Unicode text, and to > write that text back again, you have to *encode* it to bytes. > > Now, Python tries to be very conservative: if you don't specify an > encoding, it assumes you want ASCII, the lowest common denominator > encoding that keeps English speakers happy. Lucky us. Until we have to > deal with one or more bytes which can't be decoded into ASCII: > > >>> "\xC4".decode('ascii') > Traceback (most recent call last): > File "", line 1, in > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: > ordinal not in range(128) > > Python isn't going to guess what character you want byte C4 to > represent. We've already seen there are at least four different choices. > You have to tell it which one you mean: > > >>> print unicode("\xC4", encoding='macroman') > ? > > > Must-read article: > http://www.joelonsoftware.com/articles/Unicode.html A very interesting explanation! Thanks. > > > > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From stefan_ml at behnel.de Fri Jan 28 07:11:12 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Jan 2011 07:11:12 +0100 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: Hi, since you said that you have it working already, here are just a few comments on your code. Alex Hall, 27.01.2011 23:23: > all=root.findall("list/result") > for i in all: > self.mylist.append(Obj().parse(i)) It's uncommon to use "i" for anything but integer loop variables. And 'all' is not a very telling name either. I'd use something like "all_results" and "result_element" instead. > In Obj.parse(), the element passed in is treated like this: > > def parse(data): > root=data.getroot() I don't understand this. You already have an Element here according to your code above. Why do you try to call getroot() on it? Again, "data" is not very telling. Giving it a better name will help you here. > self.id=root.find("id").text > self.name=root.find("name).text There's a findtext() method on Elements for this purpose. > Printing the results of the above through Obj.id or Obj.name gives me > odd behavior: > print Obj.id :> print self.id :> None "Obj.id" is a class attribute. "self.id" is an instance attribute. Different things. > Does the root change when I call find()? No. > Why would > an Element object get used when I clearly say to use the text of the > found element? I don't think the code snippets you showed us above are enough to answer this. Stefan From ben.ganzfried at gmail.com Fri Jan 28 03:03:24 2011 From: ben.ganzfried at gmail.com (Ben Ganzfried) Date: Thu, 27 Jan 2011 21:03:24 -0500 Subject: [Tutor] Project Idea Message-ID: Hey guys, Would it be feasible for a beginner to write a script that could connect with: https://chrome.google.com/extensions/detail/laankejkbhbdhmipfmgcngdelahlfoji ? More specifically, I am interested in writing a script such that the user would have to enter a short password (say 6 random letters) and only then could they access the Internet. (Also, it looks like stayfocusd only works for google chrome...i'd love for my script to apply to all other internet browsers that may be installed on a computer as well). If so, I would love to hear any tips or advice for getting started that you could suggest. Thanks a bunch, Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Fri Jan 28 09:43:26 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Jan 2011 03:43:26 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: References: Message-ID: <4D4281AE.6020408@ieee.org> On 01/-10/-28163 02:59 PM, Alex Hall wrote: > Hello again: > I have never seen this message before. I am pulling xml from a site's > api and printing it, testing the wrapper I am writing for the api. I > have never seen this error until just now, in the twelfth result of my > search: > UnicodeEncodeError: 'ASCII' codec can't encode character u'\u2019' in > position 42: ordinal not in range(128) > > I tried making the strings Unicode by saying something like > self.title=unicode(data.find("title").text) > but the same error appeared. I found the manual chapter on this, but I > am not sure I want to ignore since I do not know what this character > (or others) might mean in the string. I am not clear on what 'replace' > will do. Any suggestions? > You don't show any of your code, nor the complete error message. But I can try to correct one confusion on your part. Encoding is converting from unicode to ascii. So manually converting to unicode isn't going to help. The question is what part of your code is doing an implicit conversion to ascii, and how can you change that to either leave things in unicode, or do an explicit encode to some other character set (utf8, or ...) Also, you should be specifying your environment (python version, OS) in such a query, as the rules are substantially different in version 3.x DaveA From __peter__ at web.de Fri Jan 28 09:43:55 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2011 09:43:55 +0100 Subject: [Tutor] ascii codec cannot encode character References: Message-ID: Alex Hall wrote: > Hello again: > I have never seen this message before. I am pulling xml from a site's > api and printing it, testing the wrapper I am writing for the api. I > have never seen this error until just now, in the twelfth result of my > search: > UnicodeEncodeError: 'ASCII' codec can't encode character u'\u2019' in > position 42: ordinal not in range(128) > > I tried making the strings Unicode by saying something like > self.title=unicode(data.find("title").text) > but the same error appeared. I found the manual chapter on this, but I > am not sure I want to ignore since I do not know what this character > (or others) might mean in the string. I am not clear on what 'replace' > will do. Any suggestions? You get a UnicodeEncodeError if you print a unicode string containing non- ascii characters, and Python cannot determine the target's encoding: $ cat tmp.py # -*- coding: utf-8 -*- print u'???' $ python tmp.py ??? $ python tmp.py > tmp.txt Traceback (most recent call last): File "tmp.py", line 2, in print u'???' UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) The error occurs because by default Python 2 tries to convert unicode into bytes using the ascii codec. One approach to tackle this is to check sys.stdout's encoding, and if it's unknown (None) wrap it into a codecs.Writer that can handle all characters that may occur. UTF-8 is usually a good choice, but other codecs are possible. $ cat tmp2.py # -*- coding: utf-8 -*- import sys if sys.stdout.encoding is None: import codecs Writer = codecs.getwriter("utf-8") sys.stdout = Writer(sys.stdout) print u'???' $ python tmp2.py ??? $ python tmp2.py > tmp.txt $ cat tmp.txt ??? From davea at ieee.org Fri Jan 28 10:56:38 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Jan 2011 04:56:38 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: References: <4D422920.2050606@pearwood.info> Message-ID: <4D4292D6.9070401@ieee.org> On 01/-10/-28163 02:59 PM, Alex Hall wrote: > > I tried both of those and got a different error. I have since fixed it > so I no longer have the exact text, but it was something about not > supporting convertion from unicode. I finally ended up doing this: > self.title?ta.find("title").text.encode("utf-8") > and it seems happy enough, though I get odd characters above 128. I > suppose it is better than a traceback, and I suspect I just have the > wrong character set. Still, I found it very odd that unicode(string, > errors=eplace') threw an exception. >> Well as I said before it would certainly have helped if you had quoted the entire error in the first place. That includes the stack trace. But now that it's gone, you could answer some of the other questions. How are you using this self.title value? It's apparently a byte string, and you say it displays incorrectly. But what device are you sending it to? Your console on Windows, or your messagebox on wxPython? Or where? DaveA From mehgcap at gmail.com Fri Jan 28 14:02:49 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 08:02:49 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: <4D4292D6.9070401@ieee.org> References: <4D422920.2050606@pearwood.info> <4D4292D6.9070401@ieee.org> Message-ID: On 1/28/11, Dave Angel wrote: > On 01/-10/-28163 02:59 PM, Alex Hall wrote: >> >> I tried both of those and got a different error. I have since fixed it >> so I no longer have the exact text, but it was something about not >> supporting convertion from unicode. I finally ended up doing this: >> self.title?ta.find("title").text.encode("utf-8") >> and it seems happy enough, though I get odd characters above 128. I >> suppose it is better than a traceback, and I suspect I just have the >> wrong character set. Still, I found it very odd that unicode(string, >> errors=eplace') threw an exception. >>> > > Well as I said before it would certainly have helped if you had quoted > the entire error in the first place. That includes the stack trace. > > But now that it's gone, you could answer some of the other questions. > > How are you using this self.title value? It's apparently a byte > string, and you say it displays incorrectly. But what device are you > sending it to? Your console on Windows, or your messagebox on wxPython? > Or where? For the moment it will be a Win7x64 console or a .txt file on the same machine (this is py2.7, but 2.6 is also installed). Eventually, as this is an api wrapper, it will go to wx for me, and probably other gui libraries if anyone else feels like using it. > > DaveA > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From mehgcap at gmail.com Fri Jan 28 14:09:53 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 08:09:53 -0500 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: On 1/28/11, Stefan Behnel wrote: > Hi, > > since you said that you have it working already, here are just a few > comments on your code. > > Alex Hall, 27.01.2011 23:23: >> all=root.findall("list/result") >> for i in all: >> self.mylist.append(Obj().parse(i)) > > It's uncommon to use "i" for anything but integer loop variables. And 'all' > is not a very telling name either. I'd use something like "all_results" and > "result_element" instead. True. The names in my program are different as I wrote this example from scratch to avoid the extra code that would not make sense without the whole file, but you make a good point. > > >> In Obj.parse(), the element passed in is treated like this: >> >> def parse(data): >> root=data.getroot() > > I don't understand this. You already have an Element here according to your > code above. Why do you try to call getroot() on it? Again, "data" is not > very telling. Giving it a better name will help you here. Right, I have since changed this. It would not work either way, so I thought that maybe using the same root logic on an element that I had used on the original xml would help. Obviously, it did not. :) > > >> self.id=root.find("id").text >> self.name=root.find("name).text > > There's a findtext() method on Elements for this purpose. I thought that was used to search for the text of an element? I want to get the text, whatever it may be, not search for it. Or am I misunderstanding the function? > > >> Printing the results of the above through Obj.id or Obj.name gives me >> odd behavior: >> print Obj.id :> > print self.id :> None > > "Obj.id" is a class attribute. "self.id" is an instance attribute. > Different things. True, and that was a typing mistake on my part. This error has since been fixed, however; it was something odd in the method that calls this one. Once that was fixed, things started working (more or less) as expected. > > >> Does the root change when I call find()? > > No. Didn't think so, but I thought I would confirm since it was the only explanation that seemed to make sense. Again, though, the problem seems to have been in the calling function. > > >> Why would >> an Element object get used when I clearly say to use the text of the >> found element? > > I don't think the code snippets you showed us above are enough to answer > this. Exactly, as the problem was in the calling function. Thanks for looking through it! > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From stefan_ml at behnel.de Fri Jan 28 14:16:20 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Jan 2011 14:16:20 +0100 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: Alex Hall, 28.01.2011 14:09: > On 1/28/11, Stefan Behnel wrote: >> Alex Hall, 27.01.2011 23:23: >>> self.id=root.find("id").text >>> self.name=root.find("name).text >> >> There's a findtext() method on Elements for this purpose. >> > I thought that was used to search for the text of an element? I want > to get the text, whatever it may be, not search for it. Or am I > misunderstanding the function? What do you think 'find()' does? Use the Source, Luke. ;) Stefan From mehgcap at gmail.com Fri Jan 28 14:25:50 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 08:25:50 -0500 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: On 1/28/11, Stefan Behnel wrote: > Alex Hall, 28.01.2011 14:09: >> On 1/28/11, Stefan Behnel wrote: >>> Alex Hall, 27.01.2011 23:23: >>>> self.id=root.find("id").text >>>> self.name=root.find("name).text >>> >>> There's a findtext() method on Elements for this purpose. >>> >> I thought that was used to search for the text of an element? I want >> to get the text, whatever it may be, not search for it. Or am I >> misunderstanding the function? > > What do you think 'find()' does? Use the Source, Luke. ;) Here is what I am thinking: element.find("tagname"): returns an element with the tag name, the first element with that name to be found. You can then use the usual properties and methods on this element. element.findtext("text"): returns the first element found that has a value of "text". Take this example: some text Now you get the root, then call: root.find("a") #returns the "a" element root.findtext("some text") #also returns the "a" element > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From stefan_ml at behnel.de Fri Jan 28 14:32:02 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Jan 2011 14:32:02 +0100 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: Alex Hall, 28.01.2011 14:25: > On 1/28/11, Stefan Behnel wrote: >> Alex Hall, 28.01.2011 14:09: >>> On 1/28/11, Stefan Behnel wrote: >>>> Alex Hall, 27.01.2011 23:23: >>>>> self.id=root.find("id").text >>>>> self.name=root.find("name).text >>>> >>>> There's a findtext() method on Elements for this purpose. >>>> >>> I thought that was used to search for the text of an element? I want >>> to get the text, whatever it may be, not search for it. Or am I >>> misunderstanding the function? >> >> What do you think 'find()' does? Use the Source, Luke. ;) > Here is what I am thinking: > element.find("tagname"): returns an element with the tag name, the > first element with that name to be found. You can then use the usual > properties and methods on this element. > element.findtext("text"): returns the first element found that has a > value of "text". Take this example: > > some text > > Now you get the root, then call: > root.find("a") #returns the "a" element > root.findtext("some text") #also returns the "a" element Ah, ok, then you should read the documentation: http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext findtext() does what find() does, except that it returns the text value of the Element instead of the Element itself. It basically spells out to "find text of element matching(path)". Stefan From bgailer at gmail.com Fri Jan 28 15:42:14 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 28 Jan 2011 09:42:14 -0500 Subject: [Tutor] Is it possible to make a circle of 1 hour In-Reply-To: <984820.5887.qm@web110114.mail.gq1.yahoo.com> References: <859352.36127.qm@web130208.mail.mud.yahoo.com> <984820.5887.qm@web110114.mail.gq1.yahoo.com> Message-ID: <4D42D5C6.1030208@gmail.com> In future please start a new thread instead of hijacking an existing one. We track things by thread, and I almost missed your question! -- Bob Gailer 919-636-4239 Chapel Hill NC From waynejwerner at gmail.com Fri Jan 28 15:52:25 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 28 Jan 2011 08:52:25 -0600 Subject: [Tutor] Project Idea In-Reply-To: References: Message-ID: On Thu, Jan 27, 2011 at 8:03 PM, Ben Ganzfried wrote: > Hey guys, > > Would it be feasible for a beginner to write a script that could connect > with: > https://chrome.google.com/extensions/detail/laankejkbhbdhmipfmgcngdelahlfoji > ? More specifically, I am interested in writing a script such that the user > would have to enter a short password (say 6 random letters) and only then > could they access the Internet. (Also, it looks like stayfocusd only works > for google chrome...i'd love for my script to apply to all other internet > browsers that may be installed on a computer as well). > > If so, I would love to hear any tips or advice for getting started that you > could suggest. > Well, it would be fairly trivial to write program launchers that work in a similar fashion. If you are using linux it would also be fairly trivial to write wrappers around shell commands that actually *do* connect to the 'net, at least if you're familiar with those commands. Depending on how much of a beginner you consider yourself to be, and what level of sophistication you want, this may or may not be the ideal beginner project. But luckily you have the tutor list where we're more than happy to give you pointers in the right direction if you get stuck or explain things you may not understand yet, especially once you've shown some initiative! Good luck! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Fri Jan 28 16:09:20 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 28 Jan 2011 15:09:20 +0000 Subject: [Tutor] What does ^ and | mean? Message-ID: hi, i'm confuse on how does ^ and | mean. When i tried |, i thought it is addition but 4|4 also give 4? >>> 4|2 6 >>> 4|1 5 >>> 4|3 7 >>> 4|4 4 When i tried ^, looks like subtraction but 2^4 gives 6? >>> 2^3 1 >>> 2^2 0 >>> 2^4 6 Pls help to clear my confusion. thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Fri Jan 28 16:16:17 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 10:16:17 -0500 Subject: [Tutor] What does ^ and | mean? In-Reply-To: References: Message-ID: Not sure about caret (^), but I believe | is binary or. 4|2 is 100 | 010 = 110, and 110 in decimal is 6. 4|4= 100|100 is 100 or 4. The caret might be binary and, but I am not sure. On 1/28/11, tee chwee liong wrote: > > hi, > > i'm confuse on how does ^ and | mean. When i tried |, i thought it is > addition but 4|4 also give 4? >>>> 4|2 > 6 >>>> 4|1 > 5 >>>> 4|3 > 7 >>>> 4|4 > 4 > > When i tried ^, looks like subtraction but 2^4 gives 6? > > >>>> 2^3 > 1 >>>> 2^2 > 0 >>>> 2^4 > 6 > > Pls help to clear my confusion. thanks. > > > > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From waynejwerner at gmail.com Fri Jan 28 16:17:36 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 28 Jan 2011 09:17:36 -0600 Subject: [Tutor] What does ^ and | mean? In-Reply-To: References: Message-ID: On Fri, Jan 28, 2011 at 9:09 AM, tee chwee liong wrote: > hi, > > i'm confuse on how does ^ and | mean. When i tried |, i thought it is > addition but 4|4 also give 4? > They're called bitwise operators: http://wiki.python.org/moin/BitwiseOperators + is the addition operator: 4 + 2 == 6 4 + 4 == 8 | is the bitwise OR > >>> 4|2 > 6 > >>> 4|1 > 5 > >>> 4|3 > 7 > >>> 4|4 > 4 > > When i tried ^, looks like subtraction but 2^4 gives 6? > ^ is the bitwise XOR - is subtraction > > >>> 2^3 > 1 > >>> 2^2 > 0 > >>> 2^4^ is the XOR operator > 6 > > Pls help to clear my confusion. thanks. > For more information about bitwise operations, wikipedia is your friend! http://en.wikipedia.org/wiki/Bitwise_operation HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From tcl76 at hotmail.com Fri Jan 28 16:20:04 2011 From: tcl76 at hotmail.com (tee chwee liong) Date: Fri, 28 Jan 2011 15:20:04 +0000 Subject: [Tutor] What does ^ and | mean? In-Reply-To: References: , Message-ID: thanks for showing the path.. :) From: waynejwerner at gmail.com Date: Fri, 28 Jan 2011 09:17:36 -0600 Subject: Re: [Tutor] What does ^ and | mean? To: tcl76 at hotmail.com CC: tutor at python.org On Fri, Jan 28, 2011 at 9:09 AM, tee chwee liong wrote: hi, i'm confuse on how does ^ and | mean. When i tried |, i thought it is addition but 4|4 also give 4? They're called bitwise operators: http://wiki.python.org/moin/BitwiseOperators + is the addition operator: 4 + 2 == 6 4 + 4 == 8 | is the bitwise OR >>> 4|2 6 >>> 4|1 5 >>> 4|3 7 >>> 4|4 4 When i tried ^, looks like subtraction but 2^4 gives 6? ^ is the bitwise XOR - is subtraction >>> 2^3 1 >>> 2^2 0 >>> 2^4^ is the XOR operator 6 Pls help to clear my confusion. thanks. For more information about bitwise operations, wikipedia is your friend! http://en.wikipedia.org/wiki/Bitwise_operation HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From duretn at bellsouth.net Fri Jan 28 16:22:16 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Fri, 28 Jan 2011 10:22:16 -0500 Subject: [Tutor] Wrapping my head around global variables!! Message-ID: <4D42DF28.4010504@bellsouth.net> Hello Python collective, I am trying to wrap my head around what exactly is causing me not to get any output or error message in the following code: > #!/usr/bin/env python3.1 > > import random > > def main(): > > def chosen_letter(): > > chosen_letter = Consonant() > chosen_letter = Vowel() > > return chosen_letter > > Consonant = random.choice( [B, C, D, F, G, H, J, K, L, M, N, P, Q, > R, S, T, V, W, X, Z] ) > Vowel = random.choice( [A, E, I, O, U, Y] ) > print("Choose a letter"( Consonant, Vowel )) > print("You randomly chose"( Consonant, Vowel )) > > if Consonant == ( "B C D F G H J K L M N P Q R S T V W X Z" ): > print("You randomly chose a Consonant") > else: > print("You randomly chose a Vowel") > > if Consonant: > gameStatus = "CONTINUE" > elif Vowel == A or Vowel == E or Vowel == I or Vowel == O or Vowel > == U or Vowel == Y: > gameStatus = "FINISHED ALL VOWELS" > > if gameStatus == "FINISHED ALL VOWELS": > print("FINISHED DISPLAYING ALL VOWELS") > else: > print("LOOKING FOR MORE VOWELS") > > if __name__ == "__main__": main() > All this code is intended to do is to have a user, in this case my 4 year old, choose letters of the alphabet until all vowels are specified. For whatever reason I'm neither getting an error message nor am I obtaining any messages in the output console. Any help on this would be greatly appreciated. I eventually want to make this into a gui in order to introduce young kids to programming, by having the letters print out to screen as the user makes choices based on vowels and consonants. Again, thank you for any help and expertise. Best Regards, freesparks From __peter__ at web.de Fri Jan 28 17:21:18 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2011 17:21:18 +0100 Subject: [Tutor] Wrapping my head around global variables!! References: <4D42DF28.4010504@bellsouth.net> Message-ID: Nevins Duret wrote: > Hello Python collective, > > I am trying to wrap my head around what exactly is causing me > not to get any output or error message in the following code: > >> #!/usr/bin/env python3.1 >> >> import random >> >> def main(): >> >> def chosen_letter(): >> >> chosen_letter = Consonant() >> chosen_letter = Vowel() >> >> return chosen_letter Hint: what function are you leaving with the above return statement? I won't spoil you the fun of tackling the other problems with your code, one at a time. Come back here for those you can't handle yourself. >> if __name__ == "__main__": main() From chrysalis_reborn at yahoo.com Fri Jan 28 20:15:29 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Fri, 28 Jan 2011 11:15:29 -0800 (PST) Subject: [Tutor] Wrapping my head around global variables!! In-Reply-To: <4D42DF28.4010504@bellsouth.net> Message-ID: <426534.62913.qm@web130202.mail.mud.yahoo.com> I don't consider myself qualified to answer your question...but just in looking at your program and the description of what it is supposed to do, I'm a bit confused. So let me get this straight...the user is supposed to choose a letter, and the program is supposed to tell them if it is a vowel or a consonant? ...and keep looping through until they have chosen all the vowels? ...am I understanding this correctly? If so, why use the random function at all? Or is the program supposed to randomly choose a letter and the user specifies whether it is a consonant or a vowel? In either case I don't see anywhere in the code where you actually have the user type anything. But then, like I say, I am no python expert, by any means. --- On Fri, 1/28/11, Nevins Duret wrote: > From: Nevins Duret > Subject: [Tutor] Wrapping my head around global variables!! > To: tutor at python.org > Date: Friday, January 28, 2011, 10:22 AM > Hello Python collective, > > ? ? ? ? I am trying to wrap my head > around what exactly is causing me not to get any output or > error message in the following code: > > > #!/usr/bin/env python3.1 > > > > import random > > > > def main(): > > > >? ???def chosen_letter(): > > > >? ? ? ???chosen_letter = > Consonant() > >? ? ? ???chosen_letter = > Vowel() > > > >? ???return chosen_letter > > > >? ???Consonant = random.choice( [B, > C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z] ) > >? ???Vowel = random.choice( [A, E, > I, O, U, Y] ) > >? ???print("Choose a letter"( > Consonant, Vowel )) > >? ???print("You randomly chose"( > Consonant, Vowel )) > > > >? ???if Consonant == ( "B C D F G H > J K L M N P Q R S T V W X Z" ): > >? ? ? ???print("You > randomly chose a Consonant") > >? ???else: > >? ? ? ???print("You > randomly chose a Vowel") > > > >? ???if Consonant: > >? ? ? ? ? > ???gameStatus = "CONTINUE" > >? ???elif Vowel == A or Vowel == E > or Vowel == I or Vowel == O or Vowel == U or Vowel == Y: > >? ? ? ? ? > ???gameStatus = "FINISHED ALL VOWELS" > > > >? ???if gameStatus == "FINISHED ALL > VOWELS": > >? ? ? ???print("FINISHED > DISPLAYING ALL VOWELS") > >? ???else: > >? ? ? ???print("LOOKING > FOR MORE VOWELS") > > > > if __name__ == "__main__": main() > > > All this code is intended to do is to have a user, in this > case my 4 year old, choose letters of the alphabet until all > vowels are specified.? For whatever reason I'm neither > getting an error message nor am I obtaining any messages in > the output console.? Any help on this would be greatly > appreciated.? I eventually want to make this into a gui > in order to introduce young kids to programming, by having > the letters print out to screen as the user makes choices > based on vowels and consonants.? Again, thank you for > any help and expertise. > > Best Regards, > > freesparks > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From davea at ieee.org Fri Jan 28 20:33:58 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Jan 2011 14:33:58 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: References: <4D422920.2050606@pearwood.info> <4D4292D6.9070401@ieee.org> Message-ID: <4D431A26.5010801@ieee.org> On 01/28/2011 08:02 AM, Alex Hall wrote: > On 1/28/11, Dave Angel wrote: >> On 01/-10/-28163 02:59 PM, Alex Hall wrote: >>> >>> I tried both of those and got a different error. I have since fixed it >>> so I no longer have the exact text, but it was something about not >>> supporting convertion from unicode. I finally ended up doing this: >>> self.title?ta.find("title").text.encode("utf-8") >>> and it seems happy enough, though I get odd characters above 128. I >>> suppose it is better than a traceback, and I suspect I just have the >>> wrong character set. Still, I found it very odd that unicode(string, >>> errors=eplace') threw an exception. >>>> >> >> Well as I said before it would certainly have helped if you had quoted >> the entire error in the first place. That includes the stack trace. >> >> But now that it's gone, you could answer some of the other questions. >> >> How are you using this self.title value? It's apparently a byte >> string, and you say it displays incorrectly. But what device are you >> sending it to? Your console on Windows, or your messagebox on wxPython? >> Or where? > For the moment it will be a Win7x64 console or a .txt file on the same > machine (this is py2.7, but 2.6 is also installed). Eventually, as > this is an api wrapper, it will go to wx for me, and probably other > gui libraries if anyone else feels like using it. >> >> DaveA >> > > So clearly, the Win7x26 console on your machine doesn't support utf-8. As Peter said, you could inspect sys.stdout (that's what print uses) to see what encoding it specifies. Note that if you may be sending the data to various places, that may have different support, you probably don't want to encode it till it's know where it's going. So you might leave self.title as unicode, but when you actually print it, encode it in the print statement. And when you write it to a file, you encode it separately, and maybe differently. And when you use it in wx, you pick a third way. Does anybody know what encodings the Win7x64 console can be made to support? And how to tell what it's configured for, for a given country? DaveA From davea at ieee.org Fri Jan 28 21:01:24 2011 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Jan 2011 15:01:24 -0500 Subject: [Tutor] Wrapping my head around global variables!! In-Reply-To: <4D42DF28.4010504@bellsouth.net> References: <4D42DF28.4010504@bellsouth.net> Message-ID: <4D432094.10406@ieee.org> On 01/-10/-28163 02:59 PM, Nevins Duret wrote: > Hello Python collective, > > I am trying to wrap my head around what exactly is causing me not to get > any output or error message in the following code: > >> #!/usr/bin/env python3.1 >> >> import random >> >> def main(): >> >> def chosen_letter(): >> >> chosen_letter = Consonant() >> chosen_letter = Vowel() >> >> return chosen_letter >> >> Consonant = random.choice( [B, C, D, F, G, H, J, K, L, M, N, P, Q, R, >> S, T, V, W, X, Z] ) >> Vowel = random.choice( [A, E, I, O, U, Y] ) >> print("Choose a letter"( Consonant, Vowel )) >> print("You randomly chose"( Consonant, Vowel )) >> >> if Consonant == ( "B C D F G H J K L M N P Q R S T V W X Z" ): >> print("You randomly chose a Consonant") >> else: >> print("You randomly chose a Vowel") >> >> if Consonant: >> gameStatus = "CONTINUE" >> elif Vowel == A or Vowel == E or Vowel == I or Vowel == O or Vowel == >> U or Vowel == Y: >> gameStatus = "FINISHED ALL VOWELS" >> >> if gameStatus == "FINISHED ALL VOWELS": >> print("FINISHED DISPLAYING ALL VOWELS") >> else: >> print("LOOKING FOR MORE VOWELS") >> >> if __name__ == "__main__": main() >> > All this code is intended to do is to have a user, in this case my 4 > year old, choose letters of the alphabet until all vowels are specified. > For whatever reason I'm neither getting an error message nor am I > obtaining any messages in the output console. Any help on this would be > greatly appreciated. I eventually want to make this into a gui in order > to introduce young kids to programming, by having the letters print out > to screen as the user makes choices based on vowels and consonants. > Again, thank you for any help and expertise. > > Best Regards, > > freesparks > Not too clear what you're up to here. The first problem is that your main() function returned before it did anything useful. That's because you didn't indent the return statement of the nested chosen_letter() function to match the rest of the body. Since it was indented like the body of main(), the rest of main() was ignored. Having said that, you have a pile of problems in this code. Not a good idea to name local variables the same as the function name. This isn't BASIC. And you assign two different values to the same name. And you call two functions, Consonant() and Vowel(), when the only other symbols by those names are probably character strings. You call random.choice with a list made up of undefined symbols. You'll need to put quotes around each of "B", "C", etc. You compare Consonant to a string, when you probably meant to check if it was in the string. Consider using the "in" operator And it looks like you meant to have a loop inside main(), since your last print is "LOOKING FOR MORE VOWELS" HTH, DaveA From bgailer at gmail.com Fri Jan 28 21:12:53 2011 From: bgailer at gmail.com (bob gailer) Date: Fri, 28 Jan 2011 15:12:53 -0500 Subject: [Tutor] Wrapping my head around global variables!! In-Reply-To: <4D42DF28.4010504@bellsouth.net> References: <4D42DF28.4010504@bellsouth.net> Message-ID: <4D432345.4060808@gmail.com> On 1/28/2011 10:22 AM, Nevins Duret wrote: > Hello Python collective, > > I am trying to wrap my head around what exactly is causing me > not to get any output or error message in the following code: There are so many problems with this program it is hard to know where to begin. Have you successfully run any other Python programs? What operating system are you using? What do you do to run the program? Why no output? Simple. Here are the steps the program executes start import random def main(): if __name__ == "__main__": main() return chosen_letter end Please study the program till you understand what is happening. Then figure out what to change. > >> #!/usr/bin/env python3.1 >> >> import random >> >> def main(): >> >> def chosen_letter(): >> >> chosen_letter = Consonant() >> chosen_letter = Vowel() >> >> return chosen_letter >> >> Consonant = random.choice( [B, C, D, F, G, H, J, K, L, M, N, P, >> Q, R, S, T, V, W, X, Z] ) >> Vowel = random.choice( [A, E, I, O, U, Y] ) >> print("Choose a letter"( Consonant, Vowel )) >> print("You randomly chose"( Consonant, Vowel )) >> >> if Consonant == ( "B C D F G H J K L M N P Q R S T V W X Z" ): >> print("You randomly chose a Consonant") >> else: >> print("You randomly chose a Vowel") >> >> if Consonant: >> gameStatus = "CONTINUE" >> elif Vowel == A or Vowel == E or Vowel == I or Vowel == O or >> Vowel == U or Vowel == Y: >> gameStatus = "FINISHED ALL VOWELS" >> >> if gameStatus == "FINISHED ALL VOWELS": >> print("FINISHED DISPLAYING ALL VOWELS") >> else: >> print("LOOKING FOR MORE VOWELS") >> >> if __name__ == "__main__": main() >> > All this code is intended to do is to have a user, in this case my 4 > year old, choose letters of the alphabet until all vowels are > specified. For whatever reason I'm neither getting an error message > nor am I obtaining any messages in the output console. Any help on > this would be greatly appreciated. I eventually want to make this > into a gui in order to introduce young kids to programming, by having > the letters print out to screen as the user makes choices based on > vowels and consonants. Again, thank you for any help and expertise. > > Best Regards, > > freesparks > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Fri Jan 28 22:23:55 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 16:23:55 -0500 Subject: [Tutor] ascii codec cannot encode character In-Reply-To: <4D431A26.5010801@ieee.org> References: <4D422920.2050606@pearwood.info> <4D4292D6.9070401@ieee.org> <4D431A26.5010801@ieee.org> Message-ID: On 1/28/11, Dave Angel wrote: > On 01/28/2011 08:02 AM, Alex Hall wrote: >> On 1/28/11, Dave Angel wrote: >>> On 01/-10/-28163 02:59 PM, Alex Hall wrote: >>>> >>>> I tried both of those and got a different error. I have since fixed it >>>> so I no longer have the exact text, but it was something about not >>>> supporting convertion from unicode. I finally ended up doing this: >>>> self.title?ta.find("title").text.encode("utf-8") >>>> and it seems happy enough, though I get odd characters above 128. I >>>> suppose it is better than a traceback, and I suspect I just have the >>>> wrong character set. Still, I found it very odd that unicode(string, >>>> errors=eplace') threw an exception. >>>>> >>> >>> Well as I said before it would certainly have helped if you had quoted >>> the entire error in the first place. That includes the stack trace. >>> >>> But now that it's gone, you could answer some of the other questions. >>> >>> How are you using this self.title value? It's apparently a byte >>> string, and you say it displays incorrectly. But what device are you >>> sending it to? Your console on Windows, or your messagebox on wxPython? >>> Or where? >> For the moment it will be a Win7x64 console or a .txt file on the same >> machine (this is py2.7, but 2.6 is also installed). Eventually, as >> this is an api wrapper, it will go to wx for me, and probably other >> gui libraries if anyone else feels like using it. >>> >>> DaveA >>> >> >> > So clearly, the Win7x26 console on your machine doesn't support utf-8. > As Peter said, you could inspect sys.stdout (that's what print uses) to > see what encoding it specifies. > > Note that if you may be sending the data to various places, that may > have different support, you probably don't want to encode it till it's > know where it's going. So you might leave self.title as unicode, but > when you actually print it, encode it in the print statement. And when > you write it to a file, you encode it separately, and maybe differently. > And when you use it in wx, you pick a third way. A great point. I have never had to deal with non-ascii before, so never even thought about all this. > > Does anybody know what encodings the Win7x64 console can be made to > support? And how to tell what it's configured for, for a given country? > > DaveA > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From karim.liateni at free.fr Fri Jan 28 22:54:50 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 28 Jan 2011 22:54:50 +0100 Subject: [Tutor] Accessing a secured webpage Message-ID: <4D433B2A.4000306@free.fr> Hello, I want to create a client to access a webpage. But when I access it interactively there is a dialog box which ask for login and password. I want to access it in batch via python but I could only found a basic example: ||#||!/bin/env|| ||python| |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| |import| urllib2 reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) xhtmldata|=| reponse.|read|() |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) | I want to provide login and password via python code. The web adress is like http://website.com:8081/ddts/ddts_main. If you have link it is welcome! Regards Karim -------------- next part -------------- An HTML attachment was scrubbed... URL: From vince at vinces.ca Fri Jan 28 23:05:41 2011 From: vince at vinces.ca (Vince Spicer) Date: Fri, 28 Jan 2011 16:05:41 -0600 Subject: [Tutor] Accessing a secured webpage In-Reply-To: <4D433B2A.4000306@free.fr> References: <4D433B2A.4000306@free.fr> Message-ID: You may want to look at httplib2 http://code.google.com/p/httplib2/ This great module makes auth very simple Vince On Fri, Jan 28, 2011 at 3:54 PM, Karim wrote: > > Hello, > > I want to create a client to access a webpage. But when I access it > interactively there is a dialog box > which ask for login and password. > I want to access it in batch via python but I could only found a basic > example: > > #!/bin/env python# -*- coding: utf-8 -*- > import urllib2 > reponse = urllib2.urlopen('http://www.kernel.org/') > xhtmldata = reponse.read()for num,ligne in enumerate(xhtmldata.splitlines()) : > print "%04d - %s"%(num,ligne) > > I want to provide login and password via python code. The web adress is > like http://website.com:8081/ddts/ddts_main. > If you have link it is welcome! > > Regards > Karim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Vince Spicer Developer -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.douglas at iandouglas.com Fri Jan 28 23:15:52 2011 From: ian.douglas at iandouglas.com (ian douglas) Date: Fri, 28 Jan 2011 14:15:52 -0800 Subject: [Tutor] Accessing a secured webpage In-Reply-To: <4D433B2A.4000306@free.fr> References: <4D433B2A.4000306@free.fr> Message-ID: <4D434018.8050203@iandouglas.com> If it's HTTP basic_auth, you could try this method too: http://username:password at domain.com/page.html On 01/28/2011 01:54 PM, Karim wrote: > > Hello, > > I want to create a client to access a webpage. But when I access it > interactively there is a dialog box > which ask for login and password. > I want to access it in batch via python but I could only found a basic > example: > ||#||!/bin/env|| ||python| > |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| > > |import| urllib2 > reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) > xhtmldata|=| reponse.|read|() > |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : > |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) > | > I want to provide login and password via python code. The web adress > is like http://website.com:8081/ddts/ddts_main. > If you have link it is welcome! > > Regards > Karim > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Jan 28 23:28:46 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 28 Jan 2011 23:28:46 +0100 Subject: [Tutor] Accessing a secured webpage In-Reply-To: References: <4D433B2A.4000306@free.fr> Message-ID: <4D43431E.7050103@free.fr> Vince I saw your answer on the related subject fron October 2010 : *Re: [Tutor] Requesting restricted URL (further authentication requested)*. Thanks Karim On 01/28/2011 11:05 PM, Vince Spicer wrote: > You may want to look at httplib2 > > http://code.google.com/p/httplib2/ > > This great module makes auth very simple > > Vince > > On Fri, Jan 28, 2011 at 3:54 PM, Karim > wrote: > > > Hello, > > I want to create a client to access a webpage. But when I access > it interactively there is a dialog box > which ask for login and password. > I want to access it in batch via python but I could only found a > basic example: > > ||#||!/bin/env|| ||python| > |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| > > |import| urllib2 > reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) > xhtmldata|=| reponse.|read|() > |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : > |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) > | > > I want to provide login and password via python code. The web > adress is like http://website.com:8081/ddts/ddts_main. > If you have link it is welcome! > > Regards > Karim > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Vince Spicer > Developer > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Fri Jan 28 23:33:08 2011 From: karim.liateni at free.fr (Karim) Date: Fri, 28 Jan 2011 23:33:08 +0100 Subject: [Tutor] Accessing a secured webpage In-Reply-To: <4D434018.8050203@iandouglas.com> References: <4D433B2A.4000306@free.fr> <4D434018.8050203@iandouglas.com> Message-ID: <4D434424.4070300@free.fr> Thanks Ian! This is a simple one! I found this other way said more flexible, I must check it too: *import urllib class myURLOpener(urllib.FancyURLopener): def setpasswd(self, user, passwd): self.__user = user self.__passwd = passwd def prompt_user_passwd(self, host, realm): return self.__user, self.__passwd urlopener = myURLOpener() urlopener.setpasswd("mulder", "trustno1")* Basically, we must subclass **urllib.FancyURLopener** and override **prompt_user_passwd(). **Regards Karim ** ** On 01/28/2011 11:15 PM, ian douglas wrote: > If it's HTTP basic_auth, you could try this method too: > > http://username:password at domain.com/page.html > > > On 01/28/2011 01:54 PM, Karim wrote: >> >> Hello, >> >> I want to create a client to access a webpage. But when I access it >> interactively there is a dialog box >> which ask for login and password. >> I want to access it in batch via python but I could only found a >> basic example: >> ||#||!/bin/env|| ||python| >> |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| >> >> |import| urllib2 >> reponse|=| urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) >> xhtmldata|=| reponse.|read|() >> |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : >> |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) >> | >> I want to provide login and password via python code. The web adress >> is like http://website.com:8081/ddts/ddts_main. >> If you have link it is welcome! >> >> Regards >> Karim >> >> >> _______________________________________________ >> Tutor maillist -Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sat Jan 29 01:14:01 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 19:14:01 -0500 Subject: [Tutor] getting binary file from website with custom header Message-ID: Hello, I am continuing to work on that api wrapper... I never realized how little I know about urllib/urllib2! The idea of downloading from the api is pretty easy: give it a url and a password and it gives you the book. Here is a quote from the api documentation: In addition the MD5 hash of the end user password must be passed in the request via a "X-password" HTTP header. Here is what I am doing. I use hashlib.md5(password).hexdigest() to get the md5 of the password. "base" is just the base url, and "destination" is just a local path. If it matters, this is an https url. user=urllib.quote(user) #user is an email address, so make it useable in a url req=urllib2.Request(base+"download/for/"+user+"/content/"+str(id), None, {"X-password":password}) try: book=urllib2.urlopen(req) local=open(destination+str(id), "w") #name the file local.write(book.read()) #save the blob to the local file local.close() except urllib2.HTTPError, e: print "HTTP error "+str(e.code) except urllib2.URLError, e: print "URL error: "+e.reason I keep getting an error 403, which the api defines as a bad login attempt. I am sure my password is right, though, so while I investigate, I thought I would check that I am not only going about this http header thing right but also getting the binary object right. I am following an example I found pretty closely. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From mehgcap at gmail.com Sat Jan 29 01:18:02 2011 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 28 Jan 2011 19:18:02 -0500 Subject: [Tutor] small ElementTree problem In-Reply-To: References: Message-ID: On 1/28/11, Stefan Behnel wrote: > Alex Hall, 28.01.2011 14:25: >> On 1/28/11, Stefan Behnel wrote: >>> Alex Hall, 28.01.2011 14:09: >>>> On 1/28/11, Stefan Behnel wrote: >>>>> Alex Hall, 27.01.2011 23:23: >>>>>> self.id=root.find("id").text >>>>>> self.name=root.find("name).text >>>>> >>>>> There's a findtext() method on Elements for this purpose. >>>>> >>>> I thought that was used to search for the text of an element? I want >>>> to get the text, whatever it may be, not search for it. Or am I >>>> misunderstanding the function? >>> >>> What do you think 'find()' does? Use the Source, Luke. ;) >> Here is what I am thinking: >> element.find("tagname"): returns an element with the tag name, the >> first element with that name to be found. You can then use the usual >> properties and methods on this element. >> element.findtext("text"): returns the first element found that has a >> value of "text". Take this example: >> >> some text >> >> Now you get the root, then call: >> root.find("a") #returns the "a" element >> root.findtext("some text") #also returns the "a" element > > Ah, ok, then you should read the documentation: > > http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext I had been reading documentation, but not that page. Thanks. > > findtext() does what find() does, except that it returns the text value of > the Element instead of the Element itself. > > It basically spells out to "find text of element matching(path)". Well, this will make life easier... > > Stefan > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Jan 29 05:34:26 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Jan 2011 15:34:26 +1100 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: References: Message-ID: <4D4398D2.6020509@pearwood.info> Alex Hall wrote: > I keep getting an error 403, which the api defines as a bad login > attempt. This could mean anything. Perhaps your password is wrong. Perhaps your username is wrong. Perhaps the website is sniffing the user-agent and refusing to allow Python to connect. Try setting the user-agent to the same one Firefox or Internet Explorer use: http://www.voidspace.org.uk/python/articles/urllib2.shtml#id15 -- Steven From steve at pearwood.info Sat Jan 29 05:30:58 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Jan 2011 15:30:58 +1100 Subject: [Tutor] Accessing a secured webpage In-Reply-To: <4D433B2A.4000306@free.fr> References: <4D433B2A.4000306@free.fr> Message-ID: <4D439802.1080006@pearwood.info> Karim wrote: > > Hello, > > I want to create a client to access a webpage. But when I access it > interactively there is a dialog box > which ask for login and password. You should read this: http://www.voidspace.org.uk/python/articles/authentication.shtml or this French translation: http://www.voidspace.org.uk/python/articles/authentication_francais.shtml > I want to access it in batch via python but I could only found a basic > example: > > ||#||!/bin/env|| ||python| > |#|| ||-*-|| ||coding:|| ||utf-8|| ||-*-| > > |import| urllib2 > reponse|=| > urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) > xhtmldata|=| reponse.|read|() > |for| num,ligne|in| |enumerate|(xhtmldata.|splitlines|()) : > |print| |"||%04d|| ||-|| ||%s||"||%|(num,ligne) > | I don't understand why your code has been filled with vertical pipe characters | -- Steven From smokefloat at gmail.com Sat Jan 29 06:02:32 2011 From: smokefloat at gmail.com (David Hutto) Date: Sat, 29 Jan 2011 00:02:32 -0500 Subject: [Tutor] Accessing a secured webpage In-Reply-To: <4D439802.1080006@pearwood.info> References: <4D433B2A.4000306@free.fr> <4D439802.1080006@pearwood.info> Message-ID: On Fri, Jan 28, 2011 at 11:30 PM, Steven D'Aprano wrote: > Karim wrote: >> >> Hello, >> >> I want to create a client to access a webpage. But when I access it >> interactively ?there is a dialog box >> which ask for login and password. > > You should read this: > > http://www.voidspace.org.uk/python/articles/authentication.shtml Void Space...You mean like the one between your ears...badumpchee. Apologies I couldn't resist. > > or this French translation: > http://www.voidspace.org.uk/python/articles/authentication_francais.shtml > > >> I want to access it in batch via python but I could only found a basic >> example: >> >> ||#||!/bin/env|| ?||python| >> |#|| ?||-*-|| ?||coding:|| ?||utf-8|| ?||-*-| >> >> |import| ?urllib2 >> reponse|=| >> ?urllib2.|urlopen|(|'||http||:||/||/||www||.||kernel||.||org||/||'|) >> xhtmldata|=| ?reponse.|read|() >> |for| ?num,ligne|in| ?|enumerate|(xhtmldata.|splitlines|()) : >> ? ?|print| ?|"||%04d|| ?||-|| ?||%s||"||%|(num,ligne) >> | > > I don't understand why your code has been filled with vertical pipe > characters | > > -- > Steven > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- The lawyer in me says argue...even if you're wrong. The scientist in me... says shut up, listen, and then argue. But the lawyer won on appeal, so now I have to argue due to a court order. Furthermore, if you could be a scientific celebrity, would you want einstein sitting around with you on saturday morning, while you're sitting in your undies, watching Underdog?...Or better yet, would Einstein want you to violate his Underdog time? Can you imagine Einstein sitting around in his underware? Thinking about the relativity between his pubic nardsac, and his Fruit of the Looms, while knocking a few Dorito's crumbs off his inner brilliant white thighs, and hailing E = mc**2, and licking the orangy, delicious, Doritoey crust that layered his genetically rippled fingertips? But then again, J. Edgar Hoover would want his pantyhose intertwined within the equation. However, I digress, momentarily. But Einstein gave freely, for humanity, not for gain, other than personal freedom. An equation that benefited all, and yet gain is a personal product. Also, if you can answer it, is gravity anymore than interplanetary static cling? From steve at pearwood.info Sat Jan 29 06:23:27 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Jan 2011 16:23:27 +1100 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: References: Message-ID: <4D43A44F.4080702@pearwood.info> A few more comments... Alex Hall wrote: > Hello, > I am continuing to work on that api wrapper... I never realized how > little I know about urllib/urllib2! The idea of downloading from the > api is pretty easy: give it a url and a password and it gives you the > book. Here is a quote from the api documentation: > In addition the MD5 hash of the end user password must be passed in > the request via a "X-password" HTTP header. You might like to mention where this API comes from. > Here is what I am doing. I use hashlib.md5(password).hexdigest() to > get the md5 of the password. "base" is just the base url, and > "destination" is just a local path. If it matters, this is an https > url. It may matter. urllib has some problems with https. What makes you think you should use the *hex* digest of the password, rather than some other format? > user=urllib.quote(user) #user is an email address, so make it useable in a url > req=urllib2.Request(base+"download/for/"+user+"/content/"+str(id), > None, {"X-password":password}) > try: > book=urllib2.urlopen(req) > local=open(destination+str(id), "w") #name the file You should open binary files in binary. This may not matter, depending on your OS, but it never hurts to use "rb" and "wb" even when it doesn't matter. > local.write(book.read()) #save the blob to the local file > local.close() > except urllib2.HTTPError, e: > print "HTTP error "+str(e.code) > except urllib2.URLError, e: > print "URL error: "+e.reason There is absolutely no point in catching an exception, only to print it. You should only catch exceptions if you intended to *do something* other than print the error message which would have been printed anyway. In this case, there is good useful information in the HTTP exception, but not in the URL error. I recommend you change your code to: book = urllib2.urlopen(req) local = open(destination+str(id), "wb") #name the file try: local.write(book.read()) #save the blob to the local file except urllib2.HTTPError, e: print "HTTP error:", print e.code # 403 = permission denied, 401= not found, etc. print e.msg # this may give you a clue why the request was rejected # uncomment the next line if you need more info # print e.hdrs finally: local.close() If any other exception, including URLError, happens, Python will automatically print the traceback, including the exception. But other than these quibbles, the code looks fine to me. > I keep getting an error 403, which the api defines as a bad login > attempt. I am sure my password is right, though, so while I > investigate, I thought I would check that I am not only going about > this http header thing right but also getting the binary object right. > I am following an example I found pretty closely. The HTTP standard is that error 403 is request forbidden. This *strongly* suggests that either your username or password is wrong. Or perhaps there are restrictions on how many times you can connect in a day, and you've exceeded it. Or your account has been closed. Or the website doesn't like the tool you are using to connect (Python). Or you've tried downloading too many files too quickly, and the webserver has locked you out. My suggestion is: * Double check, *triple* check, that your username and password are correct. * Write out the URL by hand (you can use Python for calculating the MD5 sum, I'm not that cruel *grins*). * Try using another commandline tool. If you're on Linux, you can use curl or wget: wget --header="X-password:" with and replaced by the correct values. curl will probably be similar. * If wget works, great, go back to trying it from Python! If not, inspect the error messages it prints. Try changing the user-agent. Try setting the referer [sic] to the website's home page. -- Steven From steve at pearwood.info Sat Jan 29 06:55:31 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Jan 2011 16:55:31 +1100 Subject: [Tutor] Accessing a secured webpage In-Reply-To: References: <4D433B2A.4000306@free.fr> <4D439802.1080006@pearwood.info> Message-ID: <4D43ABD3.10600@pearwood.info> David Hutto wrote: >> You should read this: >> >> http://www.voidspace.org.uk/python/articles/authentication.shtml > > > Void Space...You mean like the one between your ears...badumpchee. > Apologies I couldn't resist. I'm sure you really could have, if you tried *wink* Michael Foord of Voidspace is a highly respected member of the Python community. He is very big in the IronPython world, he has an active presence in the Python Developer community and on comp.lang.python, and his website has many *very* helpful guides. I can't recommend his essays enough. -- Steven From mehgcap at gmail.com Sat Jan 29 07:05:08 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 29 Jan 2011 01:05:08 -0500 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: <4D43A44F.4080702@pearwood.info> References: <4D43A44F.4080702@pearwood.info> Message-ID: On 1/29/11, Steven D'Aprano wrote: > A few more comments... > > Alex Hall wrote: >> Hello, >> I am continuing to work on that api wrapper... I never realized how >> little I know about urllib/urllib2! The idea of downloading from the >> api is pretty easy: give it a url and a password and it gives you the >> book. Here is a quote from the api documentation: >> In addition the MD5 hash of the end user password must be passed in >> the request via a "X-password" HTTP header. > > You might like to mention where this API comes from. Sorry. http://api.bookshare.org. > > >> Here is what I am doing. I use hashlib.md5(password).hexdigest() to >> get the md5 of the password. "base" is just the base url, and >> "destination" is just a local path. If it matters, this is an https >> url. > > It may matter. urllib has some problems with https. Wonderful... Time to find another package? > > What makes you think you should use the *hex* digest of the password, > rather than some other format? Honestly, it seemed the logical choice, and the api docs to not say anything except to md5Sum() the password. I have tried it with and without the hexdigest() and nothing changed. I will look to see what else hashlib provides. > > >> user=urllib.quote(user) #user is an email address, so make it useable in >> a url >> req=urllib2.Request(base+"download/for/"+user+"/content/"+str(id), >> None, {"X-password":password}) >> try: >> book=urllib2.urlopen(req) >> local=open(destination+str(id), "w") #name the file > > You should open binary files in binary. This may not matter, depending > on your OS, but it never hurts to use "rb" and "wb" even when it doesn't > matter. Great point! > >> local.write(book.read()) #save the blob to the local file >> local.close() >> except urllib2.HTTPError, e: >> print "HTTP error "+str(e.code) >> except urllib2.URLError, e: >> print "URL error: "+e.reason > > > There is absolutely no point in catching an exception, only to print it. True. Currently, I am trying to get this to work. Once it does I will better my error-handling code. Still, I suppose the traceback would help even more... > You should only catch exceptions if you intended to *do something* other > than print the error message which would have been printed anyway. > > In this case, there is good useful information in the HTTP exception, > but not in the URL error. I recommend you change your code to: > > book = urllib2.urlopen(req) > local = open(destination+str(id), "wb") #name the file > try: > local.write(book.read()) #save the blob to the local file > except urllib2.HTTPError, e: > print "HTTP error:", > print e.code # 403 = permission denied, 401= not found, etc. > print e.msg # this may give you a clue why the request was rejected > # uncomment the next line if you need more info > # print e.hdrs > finally: > local.close() Makes sense. > > If any other exception, including URLError, happens, Python will > automatically print the traceback, including the exception. > > But other than these quibbles, the code looks fine to me. > > >> I keep getting an error 403, which the api defines as a bad login >> attempt. I am sure my password is right, though, so while I >> investigate, I thought I would check that I am not only going about >> this http header thing right but also getting the binary object right. >> I am following an example I found pretty closely. > > The HTTP standard is that error 403 is request forbidden. This > *strongly* suggests that either your username or password is wrong. Could this be due to the wrong encoding, as you mentioned above? What about that urllib.quote(user) for an email address? > > Or perhaps there are restrictions on how many times you can connect in a > day, and you've exceeded it. Or your account has been closed. Or the > website doesn't like the tool you are using to connect (Python). Or > you've tried downloading too many files too quickly, and the webserver > has locked you out. I will change the useragent. The api says that each api key is limited to three requests per second, no hourly or daily limits. > > My suggestion is: > > * Double check, *triple* check, that your username and password > are correct. I am as sure as I can be about the plaintext, the encoding of the md5 and the urllib.quote() may be causing problems. > > * Write out the URL by hand (you can use Python for calculating > the MD5 sum, I'm not that cruel *grins*). The url should be right. I am now at an error 500 instead of 403, which is rather strange. I know 500=internal server error, but as far as I know the api is not down. > > * Try using another commandline tool. If you're on Linux, you can > use curl or wget: > > wget --header="X-password:" > > with and replaced by the correct values. > > curl will probably be similar. Windows... > > * If wget works, great, go back to trying it from Python! If > not, inspect the error messages it prints. Try changing the > user-agent. Try setting the referer [sic] to the website's > home page. > > > -- > Steven > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Jan 29 07:38:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 29 Jan 2011 17:38:03 +1100 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: References: <4D43A44F.4080702@pearwood.info> Message-ID: <4D43B5CB.1000601@pearwood.info> Alex Hall wrote: > Sorry. http://api.bookshare.org. Hmmm, I get: 403 Developer Inactive so that's no help to me. However, I did find this: http://developer.bookshare.org/docs/Home/ [quote] For user authenticated services, the user's username will be passed in via the for parameter in the endpoint path. The password should be derived as (Java syntax): md5sum(userPassword), where userPassword is the password of the user on whose behalf the service is being requested. [end quote] Unfortunately, that might be Java syntax (and also C syntax, Python syntax, Fortran syntax, and about a million other languages...) but there's no clue as to what the result should look like. Do they want an numeric string? In decimal or some other base? A string? >> It may matter. urllib has some problems with https. > Wonderful... Time to find another package? Not necessarily. Don't jump to conclusions. "Some problems" doesn't necessarily mean that you're seeing them. >> What makes you think you should use the *hex* digest of the password, >> rather than some other format? > Honestly, it seemed the logical choice, and the api docs to not say > anything except to md5Sum() the password. I have tried it with and > without the hexdigest() and nothing changed. I will look to see what > else hashlib provides. Try urllib.quote(hashlib.md5(password).digest()) and see if that helps. But having said that... > The url should be right. I am now at an error 500 instead of 403, > which is rather strange. I know 500=internal server error, but as far > as I know the api is not down. Sounds to me that whatever their server is using to authenticate is broken. -- Steven From mehgcap at gmail.com Sat Jan 29 20:39:38 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sat, 29 Jan 2011 14:39:38 -0500 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: <4D43B5CB.1000601@pearwood.info> References: <4D43A44F.4080702@pearwood.info> <4D43B5CB.1000601@pearwood.info> Message-ID: On 1/29/11, Steven D'Aprano wrote: > Alex Hall wrote: > >> Sorry. http://api.bookshare.org. > > Hmmm, I get: > > 403 Developer Inactive > > so that's no help to me. However, I did find this: > > http://developer.bookshare.org/docs/Home/ > > [quote] > For user authenticated services, the user's username will be passed in > via the for parameter in the endpoint path. The password should be > derived as (Java syntax): md5sum(userPassword), where userPassword is > the password of the user on whose behalf the service is being requested. > [end quote] > > Unfortunately, that might be Java syntax (and also C syntax, Python > syntax, Fortran syntax, and about a million other languages...) but > there's no clue as to what the result should look like. Do they want an > numeric string? In decimal or some other base? A string? I posted on a forum just in case (just found the forums), but it looks like they wanted urllib.quote(hex digest of password). > >>> It may matter. urllib has some problems with https. >> Wonderful... Time to find another package? > > Not necessarily. Don't jump to conclusions. "Some problems" doesn't > necessarily mean that you're seeing them. > > >>> What makes you think you should use the *hex* digest of the password, >>> rather than some other format? >> Honestly, it seemed the logical choice, and the api docs to not say >> anything except to md5Sum() the password. I have tried it with and >> without the hexdigest() and nothing changed. I will look to see what >> else hashlib provides. > > Try urllib.quote(hashlib.md5(password).digest()) and see if that helps. Almost! It did not work that way, but doing the exact same thing with hexdigest did it. Looks like I had to quote(md5(password).hexdigest()) and that is all it wanted. The default user-agent even works. Thanks! > But having said that... > >> The url should be right. I am now at an error 500 instead of 403, >> which is rather strange. I know 500=internal server error, but as far >> as I know the api is not down. > > Sounds to me that whatever their server is using to authenticate is broken. > > > > -- > Steven > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From steve at pearwood.info Sat Jan 29 23:21:43 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Jan 2011 09:21:43 +1100 Subject: [Tutor] getting binary file from website with custom header In-Reply-To: References: <4D43A44F.4080702@pearwood.info> <4D43B5CB.1000601@pearwood.info> Message-ID: <4D4492F7.9020004@pearwood.info> Alex Hall wrote: >>>> What makes you think you should use the *hex* digest of the password, >>>> rather than some other format? >>> Honestly, it seemed the logical choice, and the api docs to not say >>> anything except to md5Sum() the password. I have tried it with and >>> without the hexdigest() and nothing changed. I will look to see what >>> else hashlib provides. >> Try urllib.quote(hashlib.md5(password).digest()) and see if that helps. > Almost! It did not work that way, but doing the exact same thing with > hexdigest did it. Looks like I had to quote(md5(password).hexdigest()) > and that is all it wanted. The default user-agent even works. Thanks! That's remarkable. By definition, the hexdigest should be nothing but hex digits 0...9a...f. There shouldn't be anything there that needs quoting, or changes after quoting: >>> hashlib.md5("hello world").hexdigest() '5eb63bbbe01eeed093cb22bb8f5acdc3' >>> urllib.quote(hashlib.md5("hello world").hexdigest()) '5eb63bbbe01eeed093cb22bb8f5acdc3' I am amazed that your password works with quoting but not without it. It shouldn't make any difference. -- Steven From simplemind09 at gmail.com Sun Jan 30 07:42:33 2011 From: simplemind09 at gmail.com (walter weston) Date: Sat, 29 Jan 2011 23:42:33 -0700 Subject: [Tutor] pywin32 help Message-ID: hello I am running python 2.7 , I am trying to install pywin32 version 2.7 when I run the setup.py file a black console windows pops up displays some text and dissappears before I can read any of the text . I dont know what says so I cant give details here is the link to pywin32 : http://sourceforge.net/projects/pywin32/....... I need pywin32 for the pythoncom module which I will be using pumpmessages .why dont they make the install easier? like a more stable EXE or something instead of all these file directories they include...... they made to make this download for an average joe haha... please help this average joe out -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladymcse2000 at gmail.com Sun Jan 30 10:29:09 2011 From: ladymcse2000 at gmail.com (Becky Mcquilling) Date: Sun, 30 Jan 2011 01:29:09 -0800 Subject: [Tutor] Python and Tuples Message-ID: I'm fairly new to python and I am trying to do some math with tuples. If I have a tuple: t =( (1000, 2000), (2, 4), (25, 2)) I want to loop through and print out the results of the multiplying the two numbers like so: 1000 x 2000 2 x 4 etc. I'm not sure of the syntax for that. Any ideas? Becky -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Sun Jan 30 10:43:53 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 30 Jan 2011 09:43:53 +0000 Subject: [Tutor] pywin32 help In-Reply-To: References: Message-ID: <4D4532D9.7000001@timgolden.me.uk> On 30/01/2011 6:42 AM, walter weston wrote: > hello I am running python 2.7 , I am trying to install pywin32 version 2.7 > when I run the setup.py file a black console windows pops up displays some > text and dissappears before I can read any of the text . I dont know what > says so I cant give details here is the link to pywin32 : > http://sourceforge.net/projects/pywin32/....... I need pywin32 for the > pythoncom module which I will be using pumpmessages .why dont they make the > install easier? like a more stable EXE or something instead of all these > file directories they include...... they made to make this download for an > average joe haha... please help this average joe out Well it's not that hard, really: instead of going for the big green button which gives you the version-neutral source zip, just click on the link immediately to the right entitled "View all files". That takes you to here: http://sourceforge.net/projects/pywin32/files/ from which you work your way down through the directories, selecting the highest number which you guess will take you to the most recent build and... voila! http://sourceforge.net/projects/pywin32/files/pywin32/Build%20214/ Lots of .exe files, one for each version of Python / processor arch. Just for the record, pywin32 has had binaries available for Python 2.7 from pretty much the day after 2.6 was released (ie long before 2.7 was officially available). TJG From steve at pearwood.info Sun Jan 30 10:47:08 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 30 Jan 2011 20:47:08 +1100 Subject: [Tutor] Python and Tuples In-Reply-To: References: Message-ID: <4D45339C.7020802@pearwood.info> Becky Mcquilling wrote: > I'm fairly new to python and I am trying to do some math with tuples. > > If I have a tuple: > > t =( (1000, 2000), (2, 4), (25, 2)) > I want to loop through and print out the results of the multiplying the two Start with a basic loop through the objects in the tuple: >>> t = ( (1000, 2000), (2, 4), (25, 2) ) >>> for pair in t: ... print(pair) ... (1000, 2000) (2, 4) (25, 2) This walks through the outer tuple, grabbing each inner tuple (a pair of numbers) in turn. So we *could* (but won't -- keep reading!) write this: for pair in t: x = pair[0] # grab the first number in the pair y = pair[1] # and the second number print(x*y) and that would work, but we can do better than that. Python has "tuple unpacking" that works like this: >>> pair = (23, 42) >>> x, y = pair >>> print(x) 23 >>> print(y) 42 We can combine tuple unpacking with the for-loop to get this: >>> for x,y in t: ... print(x*y) ... 2000000 8 50 -- Steven From karim.liateni at free.fr Sun Jan 30 10:50:31 2011 From: karim.liateni at free.fr (Karim) Date: Sun, 30 Jan 2011 10:50:31 +0100 Subject: [Tutor] Python and Tuples In-Reply-To: References: Message-ID: <4D453467.1060502@free.fr> Hello, for x, y in t: print x*y Regards Karim On 01/30/2011 10:29 AM, Becky Mcquilling wrote: > I'm fairly new to python and I am trying to do some math with tuples. > > If I have a tuple: > > t =( (1000, 2000), (2, 4), (25, 2)) > I want to loop through and print out the results of the multiplying > the two numbers like so: > > 1000 x 2000 > 2 x 4 > > etc. > > I'm not sure of the syntax for that. Any ideas? > > Becky > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sun Jan 30 11:07:02 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 30 Jan 2011 10:07:02 +0000 Subject: [Tutor] Python and Tuples In-Reply-To: <4D45339C.7020802@pearwood.info> References: <4D45339C.7020802@pearwood.info> Message-ID: <428313541-1296382677-cardhu_decombobulator_blackberry.rim.net-1549354289-@b3.c12.bise7.blackberry> Nice Steve, No one does it better. Weldone. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Steven D'Aprano Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sun, 30 Jan 2011 20:47:08 To: Subject: Re: [Tutor] Python and Tuples Becky Mcquilling wrote: > I'm fairly new to python and I am trying to do some math with tuples. > > If I have a tuple: > > t =( (1000, 2000), (2, 4), (25, 2)) > I want to loop through and print out the results of the multiplying the two Start with a basic loop through the objects in the tuple: >>> t = ( (1000, 2000), (2, 4), (25, 2) ) >>> for pair in t: ... print(pair) ... (1000, 2000) (2, 4) (25, 2) This walks through the outer tuple, grabbing each inner tuple (a pair of numbers) in turn. So we *could* (but won't -- keep reading!) write this: for pair in t: x = pair[0] # grab the first number in the pair y = pair[1] # and the second number print(x*y) and that would work, but we can do better than that. Python has "tuple unpacking" that works like this: >>> pair = (23, 42) >>> x, y = pair >>> print(x) 23 >>> print(y) 42 We can combine tuple unpacking with the for-loop to get this: >>> for x,y in t: ... print(x*y) ... 2000000 8 50 -- Steven _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From delegbede at dudupay.com Sun Jan 30 11:07:59 2011 From: delegbede at dudupay.com (delegbede at dudupay.com) Date: Sun, 30 Jan 2011 10:07:59 +0000 Subject: [Tutor] Python and Tuples In-Reply-To: <4D453467.1060502@free.fr> References: <4D453467.1060502@free.fr> Message-ID: <1590828863-1296383431-cardhu_decombobulator_blackberry.rim.net-190304176-@b3.c12.bise7.blackberry> Thanks Karim. That's a way to go. Cheers. Sent from my BlackBerry wireless device from MTN -----Original Message----- From: Karim Sender: tutor-bounces+delegbede=dudupay.com at python.org Date: Sun, 30 Jan 2011 10:50:31 To: Becky Mcquilling; python mail list Subject: Re: [Tutor] Python and Tuples _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From chrysalis_reborn at yahoo.com Sun Jan 30 13:01:35 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Sun, 30 Jan 2011 04:01:35 -0800 (PST) Subject: [Tutor] pywin32 help In-Reply-To: Message-ID: <159833.27437.qm@web130224.mail.mud.yahoo.com> I'm not 100% sure, but I think the Active State version of python comes with pywin32... http://www.activestate.com/activepython/downloads ...but I could be mistaken. --- On Sun, 1/30/11, walter weston wrote: From: walter weston Subject: [Tutor] pywin32 help To: tutor at python.org Date: Sunday, January 30, 2011, 1:42 AM hello I am running python 2.7 , I am trying to install pywin32 version 2.7 when I run the setup.py file a black console windows pops up? displays some text and dissappears before I can read any of the text . I dont know what says so I cant give details here is the link to pywin32 :http://sourceforge.net/projects/pywin32/....... I need pywin32 for the pythoncom module which I will be using pumpmessages .why dont they make the install easier? like a more stable EXE or something instead of all these file directories they include...... they made to make this download for an average joe haha... please help this average joe out -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 30 15:28:14 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jan 2011 14:28:14 -0000 Subject: [Tutor] Python and Tuples References: Message-ID: "Becky Mcquilling" wrote > I'm fairly new to python and I am trying to do some math with > tuples. > > If I have a tuple: > > t =( (1000, 2000), (2, 4), (25, 2)) Thats a tuple of tuples. The pairs of numbers each make up a tuple. And the triple of pairs makes up another tuple. > I want to loop through and print out the results of the multiplying > the two > numbers like so: > > 1000 x 2000 > 2 x 4 > > etc. > > I'm not sure of the syntax for that. Any ideas? Which bit are you not clear about? How to extract the pairs of numbers? Or how to access the individual numbers in the pair? Or how to do the math? Or how to print the result? Its always good to show us what you have tried so that we can see where you are struggling. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sun Jan 30 19:54:09 2011 From: bgailer at gmail.com (bob gailer) Date: Sun, 30 Jan 2011 13:54:09 -0500 Subject: [Tutor] Python and Tuples In-Reply-To: References: Message-ID: <4D45B3D1.2080606@gmail.com> On 1/30/2011 4:29 AM, Becky Mcquilling wrote: > I'm fairly new to python and I am trying to do some math with tuples. > > If I have a tuple: > > t =( (1000, 2000), (2, 4), (25, 2)) > I want to loop through and print out the results of the multiplying > the two numbers like so: > > 1000 x 2000 > 2 x 4 The one-line version: print [x*y for x,y in t] or even better, in Python 3.x [print(x*y) for x,y in t] -- Bob Gailer 919-636-4239 Chapel Hill NC From duretn at bellsouth.net Sun Jan 30 20:19:58 2011 From: duretn at bellsouth.net (Nevins Duret) Date: Sun, 30 Jan 2011 14:19:58 -0500 Subject: [Tutor] Wrapping my head around global variables!! In-Reply-To: <917212.52814.qm@web130206.mail.mud.yahoo.com> References: <917212.52814.qm@web130206.mail.mud.yahoo.com> Message-ID: <4D45B9DE.4060507@bellsouth.net> Hello Elwin, Elwin I have no objections with you taking the idea, all I want to do is learn and connect with my some and give him something to aspire to and just plain out challenge. I purchased several python books so if you have any recommendations on others that helped you to become ,what I consider, a python guru then please send me some links. My only challenge is time and patience and sticking with. I really appreciated everyone's input in helping me understand the underlying concepts of this. It is more than appreciated. Well, Elwin, I ran the code using python2.6 and it worked perfectly. My only problem now is in trying to run it in python3. These are the steps that I've taken to resolve it: | #!/usr/bin/env python3.1 from tkinter import * import tkinter.font letters ="ABCDEFGHIJKLMNOPQRSTUVWXYZ" vowels = "AEIOU" sometimes = "Y" def changeLetter(letter): chosenLetter.configure(text = letter) if letter in vowels: message.configure(text = "IS A VOWEL") elif letter in sometimes: message.configure(text = "SOMETIMES A VOWEL") else: message.configure(text = "IS A CONSONANT") root = Tk() root.title('!!NAME MY CONSONANT/ NAME MY VOWEL!!') lgFont = tkinter.font(family = "HELVETICA", size = 200) msgFont = tkinter.font(family = "HELVETICA", size = 16) mainFrame = Frame() mainFrame.pack(padx = 10, pady = 10) letterMessage = Frame(mainFrame) chosenLetter = Label(letterMessage, width = 2, height = 1, font = lgFont, relief = 'sunken') message = Label(letterMessage, text = "CHOOSE LETTER", font = msgFont, relief = 'sunken') chosenLetter.pack(padx = 10, pady = 10, fill = 'x') message.pack(padx = 10, pady = 10, anchor = 'w', fill = 'x', ipady = 5) vowelsFound = Label(mainFrame) vowelsFound.grid(row = 7, column =1, columnspan = 5, sticky = 'W') letterMessage.grid(row = 1, column = 6, rowspan = 13) count = 1 letterButtons = dict() rowCount = 1 columnCount = 1 stopPoints = (5, 10, 15, 20, 25, 26) stopIndex = 0 #letterbutton[1] = button for letter 'A' #letterbutton[2] = button for letter 'B' for letter in letters: letterButtons[count] = Button(mainFrame, text = letter, width = 5, command = lambda arg1 = letter : changeLetter(arg1)) if count == 26: columnCount = 3 letterButtons[count].grid(row = rowCount, column = columnCount) columnCount += 1 if count == stopPoints[stopIndex] and stopIndex <= 4: rowCount += 1 columnCount = 1 stopIndex += 1 count += 1 root.mainloop()| When I try and run this code, I get the error: |Traceback (most recent call last): File "/home/neduret/pythonproj/alphabet3.py", line 21, in lgFont = tkinter.font(family = "HELVETICA", size = 200) TypeError: 'module' object is not callable| Now correct me if I'm wrong, but for whatever reason, is tkFont deprecated in Python3.1? Well, this is why I used import tkinter.font instead. However, now I am getting the error message stated above. I don't know if you know of any steps I can do to resolve this however, I'm sure it must stem from either a syntax or a module I've yet to import for Python3.1, being that I had to install tkFont to get it to run under the Python2.6 environment. I specifically admired your both complete and descriptive explanation on your reasoning for every piece of line in the code. I can't thank you enough. Best Regards, Nevins Duret On 01/29/2011 07:01 PM, Elwin Estle wrote: > I found myself rather intrigued with what I perceived to be the basic idea behind your programming attempt, so just for the heck of it, I played around further with the idea. > > Attached is what I have so far, if you are interested. It is a Tkinter GUI version with buttons for each letter and code to tell the user if it is a vowel or a consonant, or the "sometimes" vowels, y and w. It does not record letters chosen. > > It only uses the upper case letters, but I was thinking it might be interesting to use both upper and lower case. Right now, the letters are arranged in order, but with a total of 52 characters, both upper and lower, arranged in a grid, one could perhaps "scramble" the order of the buttons using the random.shuffle function. > > Python does have sound capability, depending on the platform you are running on, so it would be cool to have it play some kind of .wav file that tells the user if the letter is a vowel/consonant. You could even record the sound of each letter, then string the .wavs together so that it could say, "A is a vowel" or somesuch. I haven't messed with the sound thing, myself. > > Anyway, the attached code is heavily commented. Feel free to delete the attachment (if you feel I am "horning in" on your idea) or use/modify it for your own purposes. Writing it helped me learn a few things, like the whole "button - command" thing. It was driving me nuts, until I found out what the problem was. And it was a chance to use the code somebody on python tutor gave me for creating Tkinter widgets "on the fly" at program runtime. > > --- On Fri, 1/28/11, Nevins Duret wrote: > >> From: Nevins Duret >> Subject: [Tutor] Wrapping my head around global variables!! >> To: tutor at python.org >> Date: Friday, January 28, 2011, 10:22 AM >> Hello Python collective, >> >> I am trying to wrap my head >> around what exactly is causing me not to get any output or >> error message in the following code: >> >>> #!/usr/bin/env python3.1 >>> >>> import random >>> >>> def main(): >>> >>> def chosen_letter(): >>> >>> chosen_letter = >> Consonant() >>> chosen_letter = >> Vowel() >>> return chosen_letter >>> >>> Consonant = random.choice( [B, >> C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z] ) >>> Vowel = random.choice( [A, E, >> I, O, U, Y] ) >>> print("Choose a letter"( >> Consonant, Vowel )) >>> print("You randomly chose"( >> Consonant, Vowel )) >>> if Consonant == ( "B C D F G H >> J K L M N P Q R S T V W X Z" ): >>> print("You >> randomly chose a Consonant") >>> else: >>> print("You >> randomly chose a Vowel") >>> if Consonant: >>> >> gameStatus = "CONTINUE" >>> elif Vowel == A or Vowel == E >> or Vowel == I or Vowel == O or Vowel == U or Vowel == Y: >>> >> gameStatus = "FINISHED ALL VOWELS" >>> if gameStatus == "FINISHED ALL >> VOWELS": >>> print("FINISHED >> DISPLAYING ALL VOWELS") >>> else: >>> print("LOOKING >> FOR MORE VOWELS") >>> if __name__ == "__main__": main() >>> >> All this code is intended to do is to have a user, in this >> case my 4 year old, choose letters of the alphabet until all >> vowels are specified. For whatever reason I'm neither >> getting an error message nor am I obtaining any messages in >> the output console. Any help on this would be greatly >> appreciated. I eventually want to make this into a gui >> in order to introduce young kids to programming, by having >> the letters print out to screen as the user makes choices >> based on vowels and consonants. Again, thank you for >> any help and expertise. >> >> Best Regards, >> >> freesparks >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Jan 30 22:25:02 2011 From: davea at ieee.org (Dave Angel) Date: Sun, 30 Jan 2011 16:25:02 -0500 Subject: [Tutor] pywin32 help In-Reply-To: <159833.27437.qm@web130224.mail.mud.yahoo.com> References: <159833.27437.qm@web130224.mail.mud.yahoo.com> Message-ID: <4D45D72E.4020203@ieee.org> (please don't top-post. Insert the ">" symbol in front of whatever lines you're quoting, and put your response under the quote. Most email programs can be configured to do this easily, or even automatically.) On 01/-10/-28163 02:59 PM, Elwin Estle wrote: > I'm not 100% sure, but I think the Active State version of python comes with pywin32... > > http://www.activestate.com/activepython/downloads > > ...but I could be mistaken. > > --- On Sun, 1/30/11, walter weston wrote: > > From: walter weston > Subject: [Tutor] pywin32 help > To: tutor at python.org > Date: Sunday, January 30, 2011, 1:42 AM > > hello I am running python 2.7 , I am trying to install pywin32 version 2.7 when I run the setup.py file a black console windows pops up displays some text and dissappears before I can read any of the text . I dont know what says so I cant give details here is the link to pywin32 :http://sourceforge.net/projects/pywin32/....... I need pywin32 for the pythoncom module which I will be using pumpmessages .why dont they make the install easier? like a more stable EXE or something instead of all these file directories they include...... they made to make this download for an average joe haha... please help this average joe out > > -----Inline Attachment Follows----- > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > As Elwin points out, you can get Python + pywin32 + a few other goodies as a single bundle. That way, it's easy to be sure the versions match. As for avoiding the disappearing console, the solution is simple: In Windows, when installing something, launch the install from a DOS box. Then any error messages will still be in the console window when the program terminates. DaveA From rdmoores at gmail.com Sun Jan 30 22:43:43 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 30 Jan 2011 13:43:43 -0800 Subject: [Tutor] decimal module and precision Message-ID: Python 3.1 The decimal module continues to puzzle me from time to time. Here's one of those. I want to use Alex Martelli's factory function as much as possible. Turns out it has a problem with precision in addition and multiplication. ========================================= from decimal import Decimal as D import decimal #Alex Martelli's factory function from 'Python in a Nutshell', 2nd ed., p.373 def d(x): return decimal.Decimal(str(x)) decimal.getcontext().prec = 55 print('power') a = D('123.2345274523452345235432452345')**D('2.3') a2 = d(123.2345274523452345235432452345)**d(2.3) print('a =', a) print('a2 =', a2) print() print('addition') x = D('123.2345274523452345235432452345')+D('2.3') x2 = d(123.2345274523452345235432452345)+d(2.3) print('x =', x) print('x2 =', x2) print() print('division') y = D('123.2345274523452345235432452345')/D('2.3') y2 = d(123.2345274523452345235432452345)/d(2.3) print('y =', y) print('y2 =', y2) print() print('multiplication') z = D('123.2345274523452345235432452345')*D('2.3') z2 = d(123.2345274523452345235432452345)*d(2.3) print('z =', z) print('z2 =', z2) ================================= =============Output================ power a = 64370.15122802469152726635110412345417588163863981991324 a2 = 64370.15122760993409213289215777394902129746619501742003 addition x = 125.5345274523452345235432452345 x2 = 125.534527452 division y = 53.58022932710662370588836749326086956521739130434782609 y2 = 53.58022932695652173913043478260869565217391304347826087 multiplication z = 283.43941314039403940414946403935 z2 = 283.4394131396 =========end of Output======================= Why in the world does precision not work for addition and multiplication (see x2 and z2)? Thanks, Dick Moores From alan.gauld at btinternet.com Sun Jan 30 23:40:53 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Jan 2011 22:40:53 -0000 Subject: [Tutor] Wrapping my head around global variables!! References: <917212.52814.qm@web130206.mail.mud.yahoo.com> <4D45B9DE.4060507@bellsouth.net> Message-ID: "Nevins Duret" wrote > import tkinter.font > > When I try and run this code, I get the error: > > |Traceback (most recent call last): > File "/home/neduret/pythonproj/alphabet3.py", line 21, in > lgFont = tkinter.font(family = "HELVETICA", size = 200) > TypeError: 'module' object is not callable| > > > Now correct me if I'm wrong, but for whatever reason, is tkFont > deprecated in Python3.1? Well, this is why I used > > import tkinter.font instead. tkinter.font is a module. As the error says you cannot call the module. You need to find out what object/function *inside* the module does what you need. A case of reading the documentation I suspect. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From kbailey at howlermonkey.net Mon Jan 31 01:13:09 2011 From: kbailey at howlermonkey.net (Kirk Bailey) Date: Sun, 30 Jan 2011 19:13:09 -0500 Subject: [Tutor] print stack traces not caused by errors In-Reply-To: <4D23B614.8060603@aim.com> References: <4D23B614.8060603@aim.com> Message-ID: <4D45FE95.7070405@howlermonkey.net> test On 1/4/2011 7:06 PM, Corey Richardson wrote: > On 01/04/2011 06:59 PM, Alan Gauld wrote: >> "Alex Hall" wrote >> >>> expected at all. I tried the pdb module, but I am running a wx >>> program >>> so it is not helping. I tried: >>> python -m pdb c:\prog\solitaire\game.py >> The key to using any debugger in a GUI environment is to set break >> points on the event handlers of interest. Then when the event fires >> the debugger will stop your code at the start of the event handler >> and you can examine the stack, variables etc and step through >> the code. >> >> Single line stepping is tiresome so usually you are better off >> setting another break point within the function (just before or within >> a loop maybe? Or after reading a line from a file...). A watch point >> is even better but sadly I don't think pdb supports those. But >> the debugger in Eclipse and winPDB(?) do I think. >> >> And of course print statements work too within the console >> window. >> >> HTH, >> >> Alan G. >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > I've done almost all my debugging via print statements at crucial > points. It's a good way to go, IMO. > > ~Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- end Very Truly yours, - Kirk Bailey, Largo Florida kniht +-----+ | BOX | +-----+ think From simplemind09 at gmail.com Mon Jan 31 04:27:40 2011 From: simplemind09 at gmail.com (walter weston) Date: Sun, 30 Jan 2011 20:27:40 -0700 Subject: [Tutor] noobie question,,,error related Message-ID: I get this error when I try and load the datetime module, Traceback (most recent call last): File "C:/Python27/TIMED_PROGRAM.py", line 2, in datetime.ctime() AttributeError: 'module' object has no attribute 'ctime' why is this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Mon Jan 31 04:32:31 2011 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 30 Jan 2011 22:32:31 -0500 Subject: [Tutor] noobie question,,,error related In-Reply-To: References: Message-ID: On 1/30/11, walter weston wrote: > I get this error when I try and load the datetime module, > > Traceback (most recent call last): > File "C:/Python27/TIMED_PROGRAM.py", line 2, in > datetime.ctime() > AttributeError: 'module' object has no attribute 'ctime' > > > why is this? Did you actually import it first, as in import datetime or from datetime import ctime If not, then that is the problem. I have never used this module, so it is possible that ctime is really non-existent or is not a method, but I am not sure there. > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From timomlists at gmail.com Mon Jan 31 09:36:47 2011 From: timomlists at gmail.com (Timo) Date: Mon, 31 Jan 2011 09:36:47 +0100 Subject: [Tutor] noobie question,,,error related In-Reply-To: References: Message-ID: <4D46749F.9070400@gmail.com> On 31-01-11 04:27, walter weston wrote: > I get this error when I try and load the datetime module, > > Traceback (most recent call last): > File "C:/Python27/TIMED_PROGRAM.py", line 2, in > datetime.ctime() > AttributeError: 'module' object has no attribute 'ctime' > > > why is this? The error says why this is. The function ctime() isn't in the datetime module. You should have a look at the documentation [1] where you can see that ctime is a method for the date object [2] or the datetime object [3]. Cheers, Timo [1] http://docs.python.org/library/datetime.html#module-datetime [2] http://docs.python.org/library/datetime.html#datetime.date.ctime [3] http://docs.python.org/library/datetime.html#datetime.datetime.ctime > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Mon Jan 31 10:32:03 2011 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 31 Jan 2011 20:32:03 +1100 Subject: [Tutor] decimal module and precision In-Reply-To: References: Message-ID: <4D468193.7030508@pearwood.info> Richard D. Moores wrote: > Python 3.1 > The decimal module continues to puzzle me from time to time. Here's > one of those. I want to use Alex Martelli's factory function as much > as possible. Turns out it has a problem with precision in addition and > multiplication. > > ========================================= > from decimal import Decimal as D > import decimal > > #Alex Martelli's factory function from 'Python in a Nutshell', 2nd ed., p.373 > def d(x): > return decimal.Decimal(str(x)) I don't have the second edition of the book, only the first. Are you sure that Alex Martelli calls this a *factory* function? It doesn't look like a factory to me. > decimal.getcontext().prec = 55 > > print('power') > a = D('123.2345274523452345235432452345')**D('2.3') > a2 = d(123.2345274523452345235432452345)**d(2.3) > print('a =', a) > print('a2 =', a2) > print() And here is your problem: >>> str(123.2345274523452345235432452345) '123.234527452' Consequently: >>> D(str(123.2345274523452345235432452345)) Decimal('123.234527452') > Why in the world does precision not work for addition and > multiplication (see x2 and z2)? It does. You are misinterpreting the error. The problem is not with the addition, but with the construction *before* the addition. By the way, if you are using Python 2.7 or 3.1, you should consider using the Decimal.from_float method. -- Steven From pedrooconnell at gmail.com Mon Jan 31 12:42:36 2011 From: pedrooconnell at gmail.com (Pete O'Connell) Date: Tue, 1 Feb 2011 00:42:36 +1300 Subject: [Tutor] open linux file browser from nuke python script Message-ID: Hi, I am trying to get a python script to open up a file browser window with the location of a folder. I am using kubuntu 10.04. The string that gets created works fine if I paste it into a shell eg: 'kde-open path/to/the/sequence', but it doesn't seem to want to run from within my interpreter using either subprocess.Popen or os.system For the first argument I have tried 'kde-open', 'konqueror', and a few others that all work fine in the shell but not in my interpreter. Here is what my script looks like: #################################### import nuke import subprocess def showFolder(): subprocess.Popen(['kde-open', 'path/to/the/sequence']) showFolder() ################################################### I must to run it from a specific interpreter (Nuke, the compositing software) Anyone have any idea what I might be doing wrong? Can anyone suggest a workaround? Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From enalicho at gmail.com Mon Jan 31 12:46:33 2011 From: enalicho at gmail.com (Noah Hall) Date: Mon, 31 Jan 2011 11:46:33 +0000 Subject: [Tutor] noobie question,,,error related In-Reply-To: References: Message-ID: > I get this error when I try and load the datetime module, > > Traceback (most recent call last): > ? File "C:/Python27/TIMED_PROGRAM.py", line 2, in > ??? datetime.ctime() > AttributeError: 'module' object has no attribute 'ctime' Your problem, I guess comes from you having code like the following - >>>import datetime >>>datetime.ctime(arg) Error The problem with that is that datetime.ctime doesn't exist - it's datetime.datetime.ctime. If you want to skip the extra datetime in front, run >>>from datetime import datetime >>>datetime.ctime(arg) Success. In future, please provide us with code in order to clarify things. From rdmoores at gmail.com Mon Jan 31 13:25:35 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 31 Jan 2011 04:25:35 -0800 Subject: [Tutor] decimal module and precision In-Reply-To: <4D468193.7030508@pearwood.info> References: <4D468193.7030508@pearwood.info> Message-ID: On Mon, Jan 31, 2011 at 01:32, Steven D'Aprano wrote: > Richard D. Moores wrote: >> >> Python 3.1 >> The decimal module continues to puzzle me from time to time. Here's >> one of those. I want to use Alex Martelli's factory function as much >> as possible. Turns out it has a problem with precision in addition and >> multiplication. >> >> ========================================= >> from decimal import Decimal as D >> import decimal >> >> #Alex Martelli's factory function from 'Python in a Nutshell', 2nd ed., >> p.373 >> def d(x): >> ? ?return decimal.Decimal(str(x)) > > > I don't have the second edition of the book, only the first. Are you sure > that Alex Martelli calls this a *factory* function? It doesn't look like a > factory to me. Quoting from p. 373, just before the function d(): "... you can easily write a factory function for ease of experimentation, with decimal:" (But I should confess that I have only a very foggy idea what a factory function is.) >> decimal.getcontext().prec = 55 >> >> print('power') >> a = D('123.2345274523452345235432452345')**D('2.3') >> a2 = d(123.2345274523452345235432452345)**d(2.3) >> print('a =', a) >> print('a2 =', a2) >> print() > > And here is your problem: > >>>> str(123.2345274523452345235432452345) > '123.234527452' > > Consequently: > >>>> D(str(123.2345274523452345235432452345)) > Decimal('123.234527452') > > >> Why in the world does precision not work for addition and >> multiplication (see x2 and z2)? > > It does. You are misinterpreting the error. The problem is not with the > addition, but with the construction *before* the addition. But the same construction, d(), is used for power and division, and the precision of the outputs is correct. Or have I misunderstood you? For your reference, here's the script (with output) I originally posted about: > By the way, if you are using Python 2.7 or 3.1, you should consider using > the Decimal.from_float method. Ah, that solves my problem. See . Thanks! the precision is correct for all 4 cases. Not only that, but a, x, y, z equal a2, x2, y2, z2 , respectively. But a new (minor) question has arisen with Decimal.from_float. How could I abbreviate that to, say, D, when I don't want to use d()? >>> from decimal import Decimal.from_float as D Traceback (most recent call last): File "", line 1, in Syntax Error: from decimal import Decimal.from_float as D: , line 128 Write a function, I suppose? import decimal def D(x): return decimal.Decimal.from_float(x) decimal.getcontext().prec = 80 x = 34.56 y = 54 a = D(x)**D(y) print(a) """ OUTPUT 1.2105469158150833527405908484753780279256714499986841719510192301537218650731014E+83 """ Dick From chrysalis_reborn at yahoo.com Mon Jan 31 14:07:24 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 05:07:24 -0800 (PST) Subject: [Tutor] search list with regex Message-ID: <832803.30471.qm@web130207.mail.mud.yahoo.com> Tcl's list search command has the option to search for a list element that matches a given regex.? Is there something similar in python?? If not, it seems like it should be fairly trivial for me to write my own (just wondering if I would be re-inventing the wheel). From chrysalis_reborn at yahoo.com Mon Jan 31 14:07:53 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 05:07:53 -0800 (PST) Subject: [Tutor] Wrapping my head around global variables!! Message-ID: <104697.70805.qm@web130204.mail.mud.yahoo.com> I am no Python guru, I haven't even scratched the surface.? And to be honest, I do not know the answer to your question.? It is probably a Python 3.x thing.? I would suggest looking here: http://docs.python.org/modindex.html ...which is for --- On Sun, 1/30/11, Nevins Duret wrote: From: Nevins Duret Subject: Re: [Tutor] Wrapping my head around global variables!! To: tutor at python.org Date: Sunday, January 30, 2011, 2:19 PM Hello Elwin, ?? Elwin I have no objections with you taking the idea, all I want to do is learn and connect with my some and give him something to aspire to and just plain out challenge.? I purchased several python books so if you have any recommendations on others that helped you to become ,what I consider, a python guru then please send me some links.? My only challenge is time and patience and sticking with.? I really appreciated everyone's input in helping me understand the underlying concepts of this.? It is more than appreciated.? Well, Elwin, I ran the code using python2.6 and it worked perfectly.? My only problem now is in trying to run it in python3.? These are the steps that I've taken to resolve it: #!/usr/bin/env python3.1 from tkinter import * import tkinter.font letters ="ABCDEFGHIJKLMNOPQRSTUVWXYZ" vowels = "AEIOU" sometimes = "Y" def changeLetter(letter): ??? chosenLetter.configure(text = letter) ??? if letter in vowels: ??????? message.configure(text = "IS A VOWEL") ??? elif letter in sometimes: ??????? message.configure(text = "SOMETIMES A VOWEL") ??? else: ??????? message.configure(text = "IS A CONSONANT") root = Tk() root.title('!!NAME MY CONSONANT/ NAME MY VOWEL!!') lgFont = tkinter.font(family = "HELVETICA", size = 200) msgFont = tkinter.font(family = "HELVETICA", size = 16) mainFrame = Frame() mainFrame.pack(padx = 10, pady = 10) letterMessage = Frame(mainFrame) chosenLetter = Label(letterMessage, width = 2, height = 1, font = lgFont, relief = 'sunken') message = Label(letterMessage, text = "CHOOSE LETTER", font = msgFont, relief = 'sunken') chosenLetter.pack(padx = 10, pady = 10, fill = 'x') message.pack(padx = 10, pady = 10, anchor = 'w', fill = 'x', ipady = 5) vowelsFound = Label(mainFrame) vowelsFound.grid(row = 7, column =1, columnspan = 5, sticky = 'W') letterMessage.grid(row = 1, column = 6, rowspan = 13) count = 1 letterButtons = dict() rowCount = 1 columnCount = 1 stopPoints = (5, 10, 15, 20, 25, 26) stopIndex = 0 #letterbutton[1] = button for letter 'A' #letterbutton[2] = button for letter 'B' for letter in letters: ??? letterButtons[count] = Button(mainFrame, text = letter, width = 5, command = lambda arg1 = letter : changeLetter(arg1)) ??? if count == 26: ??????? columnCount = 3 ??? letterButtons[count].grid(row = rowCount, column = columnCount) ??? columnCount += 1 ??? if count == stopPoints[stopIndex] and stopIndex <= 4: ??????? rowCount += 1 ??????? columnCount = 1 ??????? stopIndex += 1 ? ??? count += 1 root.mainloop() When I try and? run this code, I get the error: Traceback (most recent call last): ? File "/home/neduret/pythonproj/alphabet3.py", line 21, in ??? lgFont = tkinter.font(family = "HELVETICA", size = 200) TypeError: 'module' object is not callable Now correct me if I'm wrong, but for whatever reason, is tkFont deprecated in Python3.1?? Well, this is why I used import tkinter.font instead. However, now I am getting the error message stated above.? I don't know if you know of any steps I can do to resolve this however, I'm sure it must stem from either a syntax or a module I've yet to import for Python3.1, being that I had to install tkFont to get it to run under the Python2.6 environment.? I specifically admired your both complete and descriptive explanation on your reasoning for every piece of line in the code.? I can't thank you enough. Best Regards, Nevins Duret On 01/29/2011 07:01 PM, Elwin Estle wrote: I found myself rather intrigued with what I perceived to be the basic idea behind your programming attempt, so just for the heck of it, I played around further with the idea. Attached is what I have so far, if you are interested. It is a Tkinter GUI version with buttons for each letter and code to tell the user if it is a vowel or a consonant, or the "sometimes" vowels, y and w. It does not record letters chosen. It only uses the upper case letters, but I was thinking it might be interesting to use both upper and lower case. Right now, the letters are arranged in order, but with a total of 52 characters, both upper and lower, arranged in a grid, one could perhaps "scramble" the order of the buttons using the random.shuffle function. Python does have sound capability, depending on the platform you are running on, so it would be cool to have it play some kind of .wav file that tells the user if the letter is a vowel/consonant. You could even record the sound of each letter, then string the .wavs together so that it could say, "A is a vowel" or somesuch. I haven't messed with the sound thing, myself. Anyway, the attached code is heavily commented. Feel free to delete the attachment (if you feel I am "horning in" on your idea) or use/modify it for your own purposes. Writing it helped me learn a few things, like the whole "button - command" thing. It was driving me nuts, until I found out what the problem was. And it was a chance to use the code somebody on python tutor gave me for creating Tkinter widgets "on the fly" at program runtime. --- On Fri, 1/28/11, Nevins Duret wrote: From: Nevins Duret Subject: [Tutor] Wrapping my head around global variables!! To: tutor at python.org Date: Friday, January 28, 2011, 10:22 AM Hello Python collective, ? ? ? ? I am trying to wrap my head around what exactly is causing me not to get any output or error message in the following code: #!/usr/bin/env python3.1 import random def main(): ? ???def chosen_letter(): ? ? ? ???chosen_letter = Consonant() ? ? ? ???chosen_letter = Vowel() ? ???return chosen_letter ? ???Consonant = random.choice( [B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z] ) ? ???Vowel = random.choice( [A, E, I, O, U, Y] ) ? ???print("Choose a letter"( Consonant, Vowel )) ? ???print("You randomly chose"( Consonant, Vowel )) ? ???if Consonant == ( "B C D F G H J K L M N P Q R S T V W X Z" ): ? ? ? ???print("You randomly chose a Consonant") ? ???else: ? ? ? ???print("You randomly chose a Vowel") ? ???if Consonant: ? ? ? ? ? ???gameStatus = "CONTINUE" ? ???elif Vowel == A or Vowel == E or Vowel == I or Vowel == O or Vowel == U or Vowel == Y: ? ? ? ? ? ???gameStatus = "FINISHED ALL VOWELS" ? ???if gameStatus == "FINISHED ALL VOWELS": ? ? ? ???print("FINISHED DISPLAYING ALL VOWELS") ? ???else: ? ? ? ???print("LOOKING FOR MORE VOWELS") if __name__ == "__main__": main() All this code is intended to do is to have a user, in this case my 4 year old, choose letters of the alphabet until all vowels are specified.? For whatever reason I'm neither getting an error message nor am I obtaining any messages in the output console.? Any help on this would be greatly appreciated.? I eventually want to make this into a gui in order to introduce young kids to programming, by having the letters print out to screen as the user makes choices based on vowels and consonants.? Again, thank you for any help and expertise. Best Regards, freesparks _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -----Inline Attachment Follows----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From chrysalis_reborn at yahoo.com Mon Jan 31 14:11:55 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 05:11:55 -0800 (PST) Subject: [Tutor] oops...sorry, just top posted again Message-ID: <304980.9782.qm@web130210.mail.mud.yahoo.com> ...but I have an excuse. I had the thing saved in a drafts folder and just hit send without thinking about it. ...I'll just go super glue broken glass to my hands and sprinkle itching powder all over my body. Is that penance enough? From eike.welk at gmx.net Mon Jan 31 14:24:42 2011 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 31 Jan 2011 14:24:42 +0100 Subject: [Tutor] decimal module and precision In-Reply-To: References: Message-ID: <201101311426.27525.eike.welk@gmx.net> Hello Richard! In your code: d(123.2345274523452345235432452345) you are entering the number as a `float` and you are loosing the precision already when the code is compiled. To retain the precision all constants must be entered as strings. For illustration see this part of an interactive Python session: >>> 123.123456789012345678901 123.12345678901235 The other issue with floating point is, that only very few numbers can be accurately represented. These numbers must be composed from (including negative) powers of two. Like this: 0.5 + 0.25 + 0.125 + 0.0625 ... Numbers that cant be represented accurately: >>> 0.1 0.10000000000000001 >>> 0.3 0.29999999999999999 It would probably be a good idea, if the Python compiler would issue a warning when it encounters a `float` constant with excessive precision. Eike. From david at pythontoo.com Mon Jan 31 15:56:12 2011 From: david at pythontoo.com (David Abbott) Date: Mon, 31 Jan 2011 09:56:12 -0500 Subject: [Tutor] Fwd: open linux file browser from nuke python script In-Reply-To: References: Message-ID: ---------- Forwarded message ---------- From: David Abbott Date: Mon, Jan 31, 2011 at 9:55 AM Subject: Re: [Tutor] open linux file browser from nuke python script To: Pete O'Connell On Mon, Jan 31, 2011 at 6:42 AM, Pete O'Connell wrote: > Hi, I am trying to get a python script to open up a file browser window with > the location of a folder. I am using kubuntu 10.04. > The string that gets created works fine if I paste it into a shell eg: > 'kde-open path/to/the/sequence', > but it doesn't seem to want to run from within my interpreter using either > subprocess.Popen or os.system > For the first argument I have tried 'kde-open', 'konqueror', and a few > others that all work fine in the shell but not in my interpreter. > Here is what my script looks like: > #################################### > import nuke > import subprocess > def showFolder(): > ??? subprocess.Popen(['kde-open', 'path/to/the/sequence']) > showFolder() > ################################################### > I must to run it from a specific interpreter (Nuke, the compositing > software) > Anyone have any idea what I might be doing wrong? Can anyone suggest a > workaround? > Pete Here is one way this is just an example; #!/usr/bin/python from subprocess import call def open_gedit(): ? ? ? ?app = "gedit" ? ? ? ?fname = "test.txt" ? ? ? ?call([app, fname]) def main(): ? ? ? ?open_gedit() if __name__ == "__main__": ? ? ? ?main() -- David Abbott (dabbott) Gentoo http://dev.gentoo.org/~dabbott/ From smokefloat at gmail.com Mon Jan 31 16:05:28 2011 From: smokefloat at gmail.com (David Hutto) Date: Mon, 31 Jan 2011 10:05:28 -0500 Subject: [Tutor] oops...sorry, just top posted again In-Reply-To: <304980.9782.qm@web130210.mail.mud.yahoo.com> References: <304980.9782.qm@web130210.mail.mud.yahoo.com> Message-ID: On Mon, Jan 31, 2011 at 8:11 AM, Elwin Estle wrote: > ...but I have an excuse. ?I had the thing saved in a drafts folder and just hit send without thinking about it. > > ...I'll just go super glue broken glass to my hands and sprinkle itching powder all over my body. ?Is that penance enough? > Nah, You also have to appease the Python Gods with a virgin sacrifice down at the local volcano, or canyon like abyss...your pick.. From waynejwerner at gmail.com Mon Jan 31 16:20:23 2011 From: waynejwerner at gmail.com (Wayne Werner) Date: Mon, 31 Jan 2011 09:20:23 -0600 Subject: [Tutor] search list with regex In-Reply-To: <832803.30471.qm@web130207.mail.mud.yahoo.com> References: <832803.30471.qm@web130207.mail.mud.yahoo.com> Message-ID: On Mon, Jan 31, 2011 at 7:07 AM, Elwin Estle wrote: > Tcl's list search command has the option to search for a list element that > matches a given regex. Is there something similar in python? If not, it > seems like it should be fairly trivial for me to write my own (just > wondering if I would be re-inventing the wheel). matching_items = [] for item in yourlist: result = re.search('[sS]ome expression', item) # and of course s/search/match, if you're interested in matching if result: matching_items.append(item) Or you could go for more terse syntax via list comp: matching_items = [item for item in yourlist if re.search('contains', item)] Or if you want one at a time you could change [] for () and turn it into a generator expression. However, the list itself doesn't have any method for matching. Here are its "public" methods: append count extend index insert pop remove reverse sort HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Jan 31 16:23:11 2011 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 31 Jan 2011 07:23:11 -0800 Subject: [Tutor] decimal module and precision In-Reply-To: <201101311426.27525.eike.welk@gmx.net> References: <201101311426.27525.eike.welk@gmx.net> Message-ID: On Mon, Jan 31, 2011 at 05:24, Eike Welk wrote: > Hello Richard! > > In your code: > > ? d(123.2345274523452345235432452345) > > you are entering the number as a `float` and you are loosing the precision > already when the code is compiled. To retain the precision all constants must > be entered as strings. > > For illustration see this part of an interactive Python session: > >>>> 123.123456789012345678901 > 123.12345678901235 > > The other issue with floating point is, that only very few numbers can be > accurately represented. These numbers must be composed from (including > negative) powers of two. Like this: 0.5 + 0.25 + 0.125 + 0.0625 ... > Numbers that cant be represented accurately: > >>>> 0.1 > 0.10000000000000001 >>>> 0.3 > 0.29999999999999999 So I'll try: >>> import decimal >>> from decimal import Decimal as D >>> decimal.getcontext().prec = 32 >>> print(D('23.45')**D('.34')) 2.9231329473018093516404474158812 >>> def d(x): return decimal.Decimal.from_float(x) >>> print(d(23.45)**d(.34)) 2.9231329473018095467750783681372 Which is accurate to only 16 digits; my Windows Vista calculator gives 2.9231329473018093516404474158812 for 23.45**.34 And using mpmath with Python 2.6 does exactly as poorly: >>> from mpmath import mp, mpf >>> mp.dps=32;mp.pretty=True >>> mpf(23.45)**mpf(.34) 2.9231329473018095467750783681372 So it seems I shouldn't use d(), or my revised d(), or mpmath for maximum precision, which seems to be at least 32 when using the decimal module the standard way. > It would probably be a good idea, if the Python compiler would issue a warning > when it encounters a `float` constant with excessive precision. Well, it sure would have helped me! Thanks, Eike. Dick From chrysalis_reborn at yahoo.com Mon Jan 31 17:08:24 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 08:08:24 -0800 (PST) Subject: [Tutor] search list with regex In-Reply-To: Message-ID: <261691.47525.qm@web130202.mail.mud.yahoo.com> --- On Mon, 1/31/11, Wayne Werner wrote: From: Wayne Werner Subject: Re: [Tutor] search list with regex To: "Elwin Estle" Cc: tutor at python.org Date: Monday, January 31, 2011, 10:20 AM On Mon, Jan 31, 2011 at 7:07 AM, Elwin Estle wrote: Tcl's list search command has the option to search for a list element that matches a given regex.? Is there something similar in python?? If not, it seems like it should be fairly trivial for me to write my own (just wondering if I would be re-inventing the wheel). matching_items = []for item in yourlist:?? ?result = re.search('[sS]ome expression', item) # and of course s/search/match, if you're interested in matching ?? ?if result: ?? ? ? ?matching_items.append(item)? Or you could go for more terse syntax via list comp: matching_items = [item for item in yourlist if re.search('contains', item)] Or if you want one at a time you could change [] for () and turn it into a generator expression. However, the list itself doesn't have any method for matching. Here are its "public" methods: appendcountextendindexinsertpopremovereversesort HTH,Wayne ...here I am...dutifully bottom posting... That's kinda what I figured, and the code you posted is pretty much what I had in mind.? The list I plan to use it with is pretty short, but varies in length (am parsing a file full of Vcards). One thing I notice, is that working with lists in Python is WAY faster than doing it in Tcl.? I have occasion to parse various text files and my standard method is to slurp the whole thing up into a string variable, then break it up into a list that I can then work on with various string or regex commands..?? In Tcl, I've had it take minutes to do this process, but it takes just seconds in Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chrysalis_reborn at yahoo.com Mon Jan 31 17:11:58 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 08:11:58 -0800 (PST) Subject: [Tutor] oops...sorry, just top posted again In-Reply-To: Message-ID: <241302.30118.qm@web130204.mail.mud.yahoo.com> --- On Mon, 1/31/11, David Hutto wrote: > From: David Hutto > Subject: Re: [Tutor] oops...sorry, just top posted again > To: "Elwin Estle" > Cc: tutor at python.org > Date: Monday, January 31, 2011, 10:05 AM > On Mon, Jan 31, 2011 at 8:11 AM, > Elwin Estle > wrote: > > ...but I have an excuse. ?I had the thing saved in a > drafts folder and just hit send without thinking about it. > > > > ...I'll just go super glue broken glass to my hands > and sprinkle itching powder all over my body. ?Is that > penance enough? > > > > Nah, You also have to appease the Python Gods with a virgin > sacrifice > down at the local volcano, or canyon like abyss...your > pick.. > Sorry, no volcanoes hereabouts, just cornfields. Canyon-like abysses seem to be in short supply also. Acquiring the sacrificial material might get me pepper sprayed. Do you suppose the Python Gods would take plastic? ...or donuts? From karim.liateni at free.fr Mon Jan 31 20:10:18 2011 From: karim.liateni at free.fr (Karim) Date: Mon, 31 Jan 2011 20:10:18 +0100 Subject: [Tutor] oops...sorry, just top posted again In-Reply-To: References: <304980.9782.qm@web130210.mail.mud.yahoo.com> Message-ID: <4D47091A.5050805@free.fr> Is this a SM forum ? Karim On 01/31/2011 04:05 PM, David Hutto wrote: > On Mon, Jan 31, 2011 at 8:11 AM, Elwin Estle wrote: >> ...but I have an excuse. I had the thing saved in a drafts folder and just hit send without thinking about it. >> >> ...I'll just go super glue broken glass to my hands and sprinkle itching powder all over my body. Is that penance enough? >> > Nah, You also have to appease the Python Gods with a virgin sacrifice > down at the local volcano, or canyon like abyss...your pick.. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Mon Jan 31 21:29:22 2011 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 31 Jan 2011 20:29:22 -0000 Subject: [Tutor] search list with regex References: <261691.47525.qm@web130202.mail.mud.yahoo.com> Message-ID: "Elwin Estle" wrote > parse various text files and my standard method is to > slurp the whole thing up into a string variable, then > break it up into a list that I can then work on If you read it with readlines() Python will do all of that for you... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From chrysalis_reborn at yahoo.com Mon Jan 31 21:51:38 2011 From: chrysalis_reborn at yahoo.com (Elwin Estle) Date: Mon, 31 Jan 2011 12:51:38 -0800 (PST) Subject: [Tutor] search list with regex In-Reply-To: Message-ID: <782948.28943.qm@web130224.mail.mud.yahoo.com> --- On Mon, 1/31/11, Alan Gauld wrote: > From: Alan Gauld > Subject: Re: [Tutor] search list with regex > To: tutor at python.org > Date: Monday, January 31, 2011, 3:29 PM > > "Elwin Estle" > wrote > > > parse various text files and my standard method is to > > slurp the whole thing up into a string variable, then > > break it up into a list that I can then work on > > If you read it with readlines() Python will do all of > that for you... > Yeah, I should probably give that a try. It was so abysmally slow to do it that way in Tcl that I didn't even think to try it in python. However, with the vcards, it is perhaps easier to do it the "big string" way, since each vcard is of varying length, but they all start with "BEGIN:VCARD", and end with "END:VCARD". I can just load the whole works and have it split into individual vcards using that information for the split.